Visual J++ Start Page

Welcome to this preview edition of Microsoft Visual J++, the tool that offers a high-productivity visual environment and integrated high-performance components to create, test, tune, and deploy Java code. Although not all features are enabled in this release, we encourage you to explore and try the product.

Visual J++ is a member of the Visual Studio family of development products which includes:

  • Visual Basic
  • Visual C++
  • Visual FoxPro
  • Visual InterDev
  • Visual J++
  • Visual SourceSafe
  • MSDN Library
Jump to the Visual Studio Start Page.

Copyright
Accessibility Information

Getting Started
Take just a few minutes to get familiar with Visual J++.

New Features
Find out about all the new Visual J++ features.

Readme
Check the Readme for installation notes, known limitations, and workarounds specific to this release.

Documentation Map
Become more familiar with the Visual J++ documentation.

Samples
Run our collection of samples that illustrate key technologies.

Visual J++ on the Web


Documentation Map

Below is an overview of what you'll find in the Visual J++ documentation:

  • What's New Highlights the new features in Visual J++ Technology Preview 1.

  • Getting Started Includes simple step-by-step tutorials to get you up and running with Visual J++.

  • User's Guide Explains how to use Visual J++.

  • Programmer's Guide Provides in-depth information on using the Windows Foundation Classes for Java (WFC), and discusses other advanced programming techniques.

  • Reference Contains comprehensive and detailed reference information for the WFC API and controls, the Java API, the Java Language Specification, the IntelliSense API, and more.

  • Samples Provides a rich collection of ready-to-run samples that illustrate key technologies.

Other Documentation

Located elsewhere in the MSDN Library, the following documentation sets include information that you may find useful:

  • Microsoft SDK 2.0 for Java, including the Java Package Manager

  • ActiveX Data Objects (ADO)

  • Remote Data Service (RDS)

  • Database Designer

  • Query Designer

  • VBScript

  • JScript

  • Active Server Pages (ASP) and server script

  • Microsoft Transaction Server (MTS)


What's New

What’s New in Visual J++

Microsoft Visual J++ provides an exciting, new development environment for Java programmers. We've enhanced the product with many special features:

  • Windows Foundation Classes for Java (WFC) This new application framework accesses the Microsoft Windows API, enabling you to write full-featured Windows applications with the Java programming language. WFC also wraps the Dynamic HTML object model implemented in Internet Explorer 4.0, which allows you to dynamically manipulate HTML on both the client and the server.

  • WFC Designer The Rapid Application Development (RAD) features of the Designer make it easy to create form-based applications with WFC. Using the Toolbox, you can quickly drop WFC components onto your form and configure their properties in the Properties window.

  • ActiveX Data Objects (ADO) for WFC WFC uses ADO components to retrieve data and perform simple data binding. Using the data controls in the Designer, you can quickly access and display data on a form.

  • Enhanced COM Support Creating a COM object in Java is now a simple process in Visual J++. With WFC, you can also host and create ActiveX controls.

  • Object Browser You can quickly find information about Java or COM-based components, without adding them to your project—even if you don’t have the source code for these components.

  • IntelliSense This collection of programming technologies can assist you in writing code. The Statement Completion feature displays member lists and parameter information as you type.

  • Enhance Debugging Support The integrated debugger has been enhanced with several new features, including multi-process debugging, remote debugging, integration between Java and script, and a Running Documents window for debugging script code.

  • Packaging and Deployment You can package components together from your project or solution and deploy the packaged file to the Web. This packaged .cab file can be signed for extra security.

  • Multi-Project Solutions You can group multiple projects into a single solution. Each project can have a different type; for example, you can add a Visual J++ project and a Visual InterDev project to the same solution.

  • Directory-Based Projects Visual J++ projects are structured according to the file system. Each file and folder in a project corresponds to a file and folder on the hard disk. The Project Explorer helps you manage the files and folders in your project.

  • Wizards and Builders These tools help you create and modify the files in your project:
    • The Application Wizard guides you in creating a form-based application with WFC.

    • The Class Builder modifies the classes in your existing Java source files.

    • The Data Form Wizard adds a data-bound form to your project.

    • The J/Direct Call Builder automatically inserts Java definitions for the Win32 API functions into your code.
  • Full-Featured HTML Support The HTML editor can help you insert links and bookmarks into your Web pages, create and modify HTML tables, and create scripts. The HTML editor also provides three views for working with Web pages: Source view allows you to edit the actual HTML source and tags; Design view provides a WYSIWYG environment for editing your files; and Quick view displays your Web page in a manner similar to how it will look in your browser.


Creating Applets and Applications with Visual J++

Thanks for using this pre-release version of Visual J++.

Microsoft Visual J++ is an integrated Windows-hosted development tool for Java programming. Visual J++ allows you to create Java programs, compile, modify, run, and debug them all within a single environment. You can also package your Java applications and applets for easy distribution to the Web.

If you have not developed Java programs with earlier versions of Visual J++, become acquainted with the process by following the procedures found in this Test Drive. You’ll be introduced to Visual J++ through specific tasks that explain how to create projects, files, and solutions as you learn how to use the features of the development environment. If you have Java and HTML files that you’ve used in another Java project or have taken from the Web, you may use them in many of the following procedures. If you’re starting without any files, the Test Drive will guide you through the steps to create them and more. You may find you don’t want or need to know about every task and procedure of this tour. Feel free to jump to the topics that interest you and return to the ones you’ve skipped at another time.

Note Many of the procedures in the Test Drive are built upon material presented in previous steps or sections of the documentation. You’ll find each procedure contains links to all steps and supporting topics that you may need to complete a given task.

The Test Drive provides an introduction to using Visual J++ and will give you a better understanding of what you need to do to create and package Java applets and applications. The Test Drive describes the following:

  • Applets and Applications

    Provides basic definitions for Java applets and applications.

  • Creating an Application with WFC Controls

    Includes a procedure for designing a Windows application with the WFC Designer and controls.

  • Creating a Java Console Application

    Includes procedures for creating, building, and running console applications created with Visual J++.

  • Creating Java Applets with Visual J++

    Discusses and provides jumps to procedures for creating basic types of applets using a Visual J++ template.

  • Opening an Existing Visual J++ Project

    Includes steps for opening a project previously created with the Visual J++ development environment.

  • Importing a Project Created with Visual J++ 1.1

    Discusses issues and procedures for importing a Visual J++ 1.1 project into the new version of Visual J++.

For more detailed information about using the development environment, see the Using Visual J++ section of the product’s online documentation.

For information about the Java language, refer to the online version of the Java Language Specification and the Java Application Programming Interface.

See also:

  • Creating a Visual J++ Project

  • Debugging Applications


Applets and Applications

Thanks for using this pre-release version of Visual J++.

There are two basic types of Java programs: applets and applications. Applets can be referenced by an HTML page and launched when that page is loaded by a Java-capable browser, such as Internet Explorer. Applications do not require a browser to run; they can be executed from the command line using a stand-alone interpreter.

In terms of source code, the basic differences between an applet and an application are as follows:

  • An applet must define a class derived from the Applet class. An application can do the same, but it is not required to do so.

  • An application must define a class with a method named main() that controls its execution. An applet does not use a main() method; its execution is controlled by various methods defined by the Applet class.

Use Visual J++’s project templates or the Project Wizard to create customized variations of Java applets and applications.


Creating an Application with WFC Controls

Thanks for using this pre-release version of Visual J++.

This scenario shows you how to create a basic Windows application with the Windows Foundation Classes for Java (WFC). Once you have built the application, you can run it run from the development environment or you can make it into an executable (.exe) file and run it from the command line. With the procedures in this scenario, you will be able to:

  • Create and build a WFC application

  • Run the application from the development environment

  • Build a stand-alone executable file

  • Run the executable file from the command line.


Creating and Building a WFC Application

Thanks for using this pre-release version of Visual J++.

This procedure shows you how to create a Windows application with the WFC Designer and controls. The application created populates a list box with a string whenever the application’s button is clicked. Once you’ve compiled the application cleanly, you will run it from the development environment.

Tip Before beginning the following procedure, close all open projects by clicking Close All from the File menu.

To open the WFC Designer when creating a Windows application with WFC controls

  1. On the File menu, click New Project and the New Project dialog box appears.

  2. On the New tab, expand the Visual J++ Projects folder and then the Applications folder.

    Note Expand items in the environment by either double-clicking a folder or single-clicking a “+” sign to the left of a folder.

  3. Click the Windows Application icon.

  4. In the Name text box, enter a name for your application’s project.

  5. In the Location text box, enter the path for the directory where you want to save your project

    –or–

    Click the Browse button to navigate to the folder where you want to save your project.

  6. Click Open.

    A collapsed view of your application project appears in Project Explorer.

  7. In Project Explorer, click the “+” sign next to your project’s name to expand the project’s node.

  8. Double-click the application’s Form1.java file.

    The WFC Designer appears and is ready to accept WFC controls from the Toolbox.

To add WFC controls to the WFC Designer

  1. On the Toolbox, click the WFC button to display the WFC controls available for placement on your application’s form.

  2. In the Toolbox, select the Button control.

  3. Drag the Button to the position on the form where you want it to appear, and release the mouse button.

    Note Once the control has been placed on the form, you may move it to a different location when the arrow changes to a move cursor over the control. You may adjust its size with the control’s sizing handles.

  4. With the cursor over the Button control, click the right mouse to display the shortcut menu.

  5. From the shortcut menu, select Properties and the Property Browser appears.

  6. In the Property Browser, find the Text property and change its value from “button 1” to “Add Item”.

    Now the button on the form displays the new value.

  7. In the Toolbox, select the ListBox control and drag it to a position just below the Add Item button.

    Since you’ll be displaying text in the ListBox control, adjust its size to hold several lines of text.

To add a button click event handler

  1. Double click the Button control.

    A Text editor window opens to an empty event handler for the button’s click event.

  2. Between the braces of the button1_Click() event handler, add the following code:

    listBox1.addItem(“This is a new string.”);

    When you’ve finished this step, the event handler look like this:

   private void button1_Click(Object sender, Event e)
{

listBox1.addItem(“This is a new string.”);

   }

To build a WFC application

  • From the Build menu, select Build.

    If your application has any compilation errors or messages, they will appear in the Task List. Correct the errors and rebuild your application until there are no compiler messages in the Task List.

To see the results of the code you’ve added to the Windows Application template, you will need to run the application. See Running a WFC Application from the Environment for details to run the application from within the Visual J++ environment.


Running a WFC Application from the Environment

Thanks for using this pre-release version of Visual J++.

To run a WFC application from the Visual J++ environment

  1. From the Debug menu, click Start.

    Your application runs in a separate WJVIEW window.

  2. Switch to the WJVIEW window your application’s running in.

  3. Click the Add Item button.

    A line of text appears in the list box.

  4. Continue to click the Add Item button until you’re convinced your program is behaving as you expected.

To close the application

  • Click the Close Window button located on the upper right corner of the close the application.


Building a Windows Executable File

Thanks for using this pre-release version of Visual J++.


Running a WFC .EXE File from the Command Line


Creating a Java Console Application

Thanks for using this pre-release version of Visual J++.

This topic will provide an overview for a discussion of creating console and Windows-based applications with Java. Topics to be included are:

  • Using the Console Application Template

  • Building and Running a Console Application


Using the Console Application Template

Thanks for using this pre-release version of Visual J++.

Use this procedure to create a basic Java console application. The following procedure will run the application from the development environment. To run the application from the command line, see Viewing Applications with JVIEW or Viewing Applications with WJVIEW.

Tip Before beginning the following procedure, close all open projects by clicking Close Project on the File menu for each open project.

To create a basic Java console application

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. On the New tab, click the “+” sign to the left of the Visual J++ Projects folder to display additional folders for specific types of Visual J++ projects.

    Folders for Web Pages, Applications, and Components appear.

  3. Open the Applications folder.

    Application Wizard, Console Application, and Windows Application icons appear in the rightmost pane of the New Project dialog.

  4. Click the Console Application icon.

  5. Enter a name for your application project into the Name text box.

  6. Click Open.

    A collapsed view of your application project appears in the Project Explorer.

  7. Expand the project icon by clicking the “+” sign to the left of your project’s name in the Project Explorer.

  8. To view your application’s code, highlight the application’s .java file, and click View Code on the shortcut menu.

    The application’s code appears in an interactive Text Editor where you can modify the code.

  9. Add the following code inside the main() method of your application:
    String str = "The quick brown fox jumped over the lazy yellow dog.";

System.out.println("The string is: " + str);
System.out.println("The length of the string is: " + str.length());
System.out.println("The substring from positions 10 to 20 is: +
str.substring(10,20));
System.out.println("The upper case string is: " +
str.toUpperCase());

To see the results of the code you’ve added to the template, you will need to compile and run the applet. See Building and Running a Console Application for the procedures to walk you through this process.


Building and Running a Console Application

Thanks for using this pre-release version of Visual J++.

To compile a basic Java console application

  • On the Build menu, click Build <ProjectName> where.ProjectName is the name you gave your project in the New Project dialog box.

    The Output Window appears and displays the results of the project’s compilation. Build errors are displayed on the Task List not in the Output Window. To view a list of compilation errors and warnings, see Viewing Compilation Errors and Warnings.

To run the application with an application viewer

  1. On the Debug menu, click Start.

    The Settings dialog box appears the first time you run any project. The name of your application’s class file appears in the When project runs, load text box.

Tip To modify the information in the Settings dialog box after your project runs once, select Settings on the Project menu. Click the Launch tab and enter your changes.

  2. Click OK to accept the values in the Settings dialog box.

Your application runs in WJVIEW, Visual J++’s applet and application viewer. The output from your program is displayed in the Output Window.


Creating Java Applets with Visual J++

Thanks for using this pre-release version of Visual J++.

Creating different types of applets with Visual J++ is easily accomplished through the use of project templates provided by the development environment. The topics listed below provide procedures for using these templates to create applets to meet specific programming requirements. As you become more familiar with the development environment, you will discover what you need to do to make the templates work for you to create your Java applets.

  • Creating a Java Applet with the Applet on HTML Template

  • Building and Running an Applet with an Applet Viewer

  • Viewing Compilation Errors and Warnings

  • Running an Applet from an HTML Page


Creating a Java Applet with the Applet on HTML Template

Thanks for using this pre-release version of Visual J++.

To create a Java applet using the Applet on HTML template

Use this procedure to create a basic Java™ applet. This applet can be run from the development environment or it can be called from a Web page. This procedure will run the applet from the development environment. See Running an Applet from an HTML Page for the procedure for running your applet within a browser.

Tip Before beginning the following procedure, close all open projects by clicking Close Project on the File menu for each open project.

To create a basic Java applet

  1. On the File menu, click New Project.

    The New Project dialog box appears.

  2. On the New tab, click the “+” sign to the left of the Visual J++ Projects folder to display additional folders for specific types of Visual J++ projects.

    Folders for Web Pages, Applications, and Components appear.

  3. Open the Web Pages folder.

    Applet on HTML, Code-Behind HTML, and COM Control on HTML icons appear in the rightmost pane of the New Project dialog.

  4. Click the Applet on HTML icon.

  5. Enter a name for your applet project into the Name text box.

  6. Click Open.

    A collapsed view of your applet project appears in the Project Explorer.

  7. Expand the project icon by clicking the “+” sign to the left of your project’s name in the Project Explorer.

  8. To view your applet’s code, highlight the applet’s .java file, and click View Code on the shortcut menu.

    The applet’s code appears in an interactive Code Editor where you can make modifications to the code.

  9. Add the following code for a paint() method to your applet class after the init() method:
    public void paint( Graphics g )
{
g.drawString( "Hello, World!", 50, 25 );
}

To see the results of the code you’ve added to the template, you will need to compile and run the applet. See Building and Running an Applet with an Applet Viewer for the procedures to walk you through this process.


Building and Running an Applet with an Applet Viewer

Thanks for using this pre-release version of Visual J++.

To compile a basic Java applet

  • On the Build menu, click Build <ProjectName> where.ProjectName is the name you gave your project in the New Project dialog box.

    The Output Window appears and displays the results of the project’s compilation. Build errors are displayed on the Task List not in the Output Window. To view a list of compilation errors and warnings, see Viewing Compilation Errors and Warnings.

To run the applet with an applet viewer

  1. On the Debug menu, click Start.

    The Settings dialog box appears the first time you run any project. The name of your applet appears in the When project runs, load text box.

Tip To modify the information in the Settings dialog box after your project runs once, select Settings on the Project menu. Click the Launch tab and enter your changes.

  2. Click OK to accept the values in the Settings dialog box.

    Your applet runs in WJVIEW, Visual J++’s applet and application viewer.

  3. To dismiss the applet, click the Applet button in the upper left corner of the applet, and click Quit.


Running an Applet from an HTML Page

Thanks for using this pre-release version of Visual J++.

This procedure continues to add to the applet project created in the topic, Building a Java Applet with the Applet on HTML Template. If you have not created a project with the Applet template, please do so before continuing with the next steps.

If you have a project created with the Applet on HTML template and it is not open, please open it now. See Opening an Existing Visual J++ Project for the procedure to open this project.

After you have either created a new applet project or opened an existing project, a collapsed view of your project appears in the Project Explorer.

To run your applet from an HTML page

  1. In the Project Explorer, expand the project icon.

  2. Double click your project’s .html file.

    The HTML editor opens in the Design tab with your project’s applet displayed.

  3. To run your applet in a Web browser from the HTML page, open the Settings dialog box by clicking Settings on the Project menu.

  4. Select the Launch tab.

  5. Click the Default group’s radio button.

  6. Select your project’s .html page from the When project runs, load: drop-down list box.

    Notice the Default group’s Program: text box contains IExplore.exe with appropriate settings in the Arguments: text box.

    Note To run your applet with a different browser, select the Other Executable group’s radio button and type the name of the browser and its arguments in the respective editable text boxes.

  7. Click OK.

  8. On the Debug menu, click Start.

    Your Web browser launches, loads your html page, and displays your applet.


Creating a Windows-based Application with J/Direct

Thanks for using this pre-release version of Visual J++.

This topic includes:

  • Using the Windows Application Template

  • Using J/Direct

  • Building and Running a Windows Application


Using the Windows Application Template

Thanks for using this pre-release version of Visual J++.


Building and Running a Windows Application

Thanks for using this pre-release version of Visual J++.

To compile a basic Windows-based application

  • On the Build menu, click Build <ProjectName> where.ProjectName is the name you gave your project in the New Project dialog box.

    The Output Window appears and displays the results of the project’s compilation. Build errors are displayed on the Task List not in the Output Window. To view a list of compilation errors and warnings, see Viewing Compilation Errors and Warnings.

To run the application with an application viewer

  1. On the Debug menu, click Start.

    The Settings dialog box appears the first time you run any project. The name of your application’s class file appears in the When project runs, load text box.

Tip To modify the information in the Settings dialog box after your project runs once, select Settings on the Project menu. Click the Launch tab and enter your changes.

  2. Click OK to accept the values in the Settings dialog box.

    Your application runs in WJVIEW, Visual J++’s applet and application viewer.

Note The output of this program is two message boxes, one to display the results of the GetProfileString() Windows API; the other displays the results of the GetEnvironmentVariable() API. Usually they will appear, one after the other, in front of the development environment. However, occasionally, they will be minimized on the operating system’s task bar.


Opening an Existing Visual J++ Project

Thanks for using this pre-release version of Visual J++.

To open an existing Visual J++ project or solution

  1. On the File menu, click Open Project.

    The New Project dialog box appears.

  2. Click the Existing tab.

    A list of existing projects appears.

  3. In the Look in drop-down list box, find the root directory that contains your projects.

    A list of projects in each root directory appears.

  4. Click the project you want to open.

  5. Click Open.

    The project’s file appears.

  6. Double-click on the project (.vjp) file.

    A collapsed view of your applet project appears in the Project Explorer. By default, the Project Explorer appears in the upper right corner of the Visual J++ development environment.

  7. Expand the project icon by clicking the “+” sign to the left of your project’s name in the Project Explorer.

  8. To view your applet’s code, highlight the applet’s .java file, and click View Code on the context menu.


Importing a Project Created with Visual J++ 1.1

Thanks for using this pre-release version of Visual J++.

You can open and use Java projects created with Visual J++ 1.1 in the new Visual J++ development environment. The following procedure provides the steps for converting these files.

Caution Before importing your Visual J++ 1.1 projects, it is important that you understand the new project structure, which conforms to the new specification published by Sun Microsystems and implemented in the JDK 1.1.

The new project structure is directory-based, in contrast to Visual J++ 1.1’s file-based project structure. This change in project structure means that every file that exists in the root directory of your project and all directories below the project root directory are automatically included as part of your project. You can remove files from a new or imported project with the Remove item on the Project Explorer’s shortcut menu.

To import a Visual J++ 1.1 project

  1. On the File menu, click Open Project.

    The Open Project dialog box appears.

  2. Click the Existing tab, and locate the root directory of the existing Visual J++ 1.1 project you want to import.

  3. Click the root directory of Visual J++ 1.1 project.

  4. Click the Import Project Folder button at the bottom of the Open Project dialog box.

    Your imported Visual J++ 1.1 project appears in the Project Explorer.

  5. Expand your project’s folder to view the files in your project.

Your project is now ready for you to modify, build, and run.


User's Guide

The Visual J++ User’s Guide contains the following topics:

  • Creating and Building Projects Explains how to create, manage, and build a Visual J++ project. Also shows how to import a Visual J++ 1.1 project.

  • Designing Forms Shows how to create and modify forms using the Rapid Application Development (RAD) features of the WFC Designer.

  • Editing Code Explains how to use IntelliSense features, such as Statement Completion, in the Text editor. Provides information on using the Class Builder and Class Outline to modify your code, and discusses the features of the Object Browser to view Java and COM-based components.

  • Accessing Data Shows how to use the WFC data controls and the Data Form Wizard to access data on a form.

  • Introducing Wizards and Builders Provides an overview of the Visual J++ wizards and builders.

  • Debugging Applications Discusses how to debug applications, applets, and components.

  • Packaging and Deploying Projects Shows how to package and deploy your projects.

  • Managing Projects with Source Code Control Explains how to use a source code control program, such as Microsoft Visual Source Safe, with your projects.

  • Compiling Applications with JVC Discusses how to use the JVC compiler and provides a reference for command-line options.

  • Viewing Applications with JVIEW and WJVIEW Discusses how to use the JVIEW and WJVIEW tools to view applications and applets.


Creating and Building Projects

Thanks for using this pre-release version of Visual J++.

This section will include the following topics:

  • Directory-Based Projects

  • Creating a Project with the Application Wizard

  • Creating a Project with Templates

  • Managing a Project with Project Explorer

  • Building a Project

  • Importing a Visual J++ 1.1 Project

For information about specific features that will assist you in working with projects, see the topics listed below.

Note You may find that some of the topics listed below describe features that are shared or described by other products and are not included in the Visual J++ core documentation. You will be able to navigate to these topics from within the Visual J++ documentation, however, when the documentation delivery system syncs on these topics, they will be found in a location external to the Visual J++ table of contents.

Features that support project development:

Text Editor Output Window

Shared topics that support project development:

Adding and Removing Files Creating Project Templates
Adding and Removing Projects Creating Solutions
Attaching and Detaching Processes


Directory-Based Projects

Thanks for using this pre-release version of Visual J++.


Creating a Project with the Application Wizard

Thanks for using this pre-release version of Visual J++.


Creating a Project with Templates

Thanks for using this pre-release version of Visual J++.

The types of projects that will be discussed in this topic are:

  • Creating a WFC Application

  • Creating a WFC Component

  • Creating a Console Application

  • Creating an Applet

  • Creating a Server-Side Component

  • Creating a Multi-Project Solution


Creating a WFC Application

Thanks for using this pre-release version of Visual J++.


Creating a WFC Component


Creating a Console Application

Thanks for using this pre-release version of Visual J++.

For a brief procedure describing how to create a console application with Visual J++ 98, please see Creating a Java Console Application in the Getting Started section of the product’s online documentation.


Creating an Applet

Thanks for using this pre-release version of Visual J++.

For a brief procedure describing how to create an applet with Visual J++ 98, please see Creating Java Applets with Visual J++ in the Getting Started section of the product’s online documentation.


Creating a Server-Side Component

Thanks for using this pre-release version of Visual J++.


Creating a Multi-Project Solution

Thanks for using this pre-release version of Visual J++.


Managing Projects with Project Explorer

The Project Explorer window displays the items that belong to the open project(s). In Visual J++, projects are directory-based. Each file and folder in the project corresponds to a file and folder on the hard disk. Adding a file to the project adds the file to the project directory structure on the hard disk, and vice versa. Note, however, that you can remove a file from the project without removing it from the hard disk.

Using Project Explorer, you can:

  • Choose the project view

  • Open a file

  • Add a file

  • Add a folder

  • Move or copy a file or folder

  • Rename a file or folder

  • Remove a file or folder

  • Display all files in the project directory structure

By default, Project Explorer is automatically opened when you create or open a project. To manually open Project Explorer, click Project Explorer on the View menu.


Choosing the Project View

A Java package is essentially a folder in your Java project. The hierarchy of Java packages in a project maps to a hierarchy of folders in the file system. Because of this relationship, Project Explorer provides two ways to view your Java project: directory view and package view.

Directory view, the default view, displays a hierarchical list of all project subfolders, according to the project directory structure on the hard disk. Each Java package in the project is displayed as a subfolder. Package view displays project subfolders as Java packages, in a flat list. Note that package view displays only .java files and the folders that contain .java files. Each folder that is displayed is listed by its fully-qualified package name. The project node itself is considered the default package.

The following diagram shows the same project in both directory view and package view:

Directory View | Package View

For more information about the relationship between Java packages and the file system, see Storing Packages in a File System in the Java Language Specification.

To view the project in package view

  • On the Project menu, click Package View, or click the Package View button in Project Explorer. Only the project's .java files, and the folders (packages) that contain them, are displayed. Note, however, that if a non-Java source file is currently open, then it remains displayed in Project Explorer.

To view the project in directory view

  • On the Project menu, click Directory View, or click the Directory View button in Project Explorer. All files and folders in the project are displayed.

By default, Project Explorer does not display any nonproject files and folders that reside in the project directory structure on the hard disk. However, if the project view is set to directory view, you can display these items by clicking the Show All Files button in Project Explorer. Note that in package view, this button is disabled. For more information about nonproject items that reside in the project directory structure, see Displaying All Files in the Project Directory Structure.


Opening a File

You can use Project Explorer to open the files in your Java project. Each file is associated with a source editor. If the file supports graphical editing, then it is also associated with a graphical editor.

To open a file in its source editor

  • In Project Explorer, right-click the name of the file and click View Code on the shortcut menu. You can also click the View Code button in Project Explorer.

To open a file in its graphical editor

  • If the file supports graphical editing, right-click the name of the file in Project Explorer and click View Designer on the shortcut menu. You can also click the View Designer button in Project Explorer. (If the file does not support graphical editing, neither the button nor the menu command is available.)

Tip Double-clicking the name of the file opens it in the default editor for that file type. For example, if a .java file supports graphical editing, it is opened in the Designer; otherwise, it is opened in the Text editor.

For information about adding files to your project, see Adding a File.

Miscellaneous Files

To open a file that is not part of the open project, use the Open File command on the File menu. Project Explorer lists the file under the Miscellaneous Files node. Once a nonproject file is listed under Miscellaneous Files, you can simply double-click it in Project Explorer to reopen it.

Note that if you remove a file from the project, it still resides in the project directory structure. However, you must still use the Open File command to open the file, since the file no longer belongs to the project. For information about removing files, see Removing a File or Folder.


Adding a File

When you add a file to your project, it is included in the project's build process. Adding a file to a Java project also adds the file to the project directory structure on the hard disk:

  • Creating a new file in the project creates a new file on the disk.

  • Adding a file that already exists on the disk copies the file to the appropriate location in the project directory structure.

Note Some files may reside in the project directory structure without belonging to the project. For example, removing a file from the project still leaves the file in the project directory structure. This file can be added back to the project in its same location on the disk.

You can add a file to the top-level project or to a specific folder. For information about adding folders to the project, see Adding a Folder.

To add a file to the project

  1. In Project Explorer, select the project or folder node that will contain the file.

  2. On the Project menu, click Add Item.

  3. To create a new file, click the New tab in the Add Item dialog box.
    • In the left pane of the dialog box, select a file category. In the right pane, select the type of file you want to add, based on the selection in the left pane.

    • In the Name box, type a name for the file. For information about valid Java file names, see Identifiers in the Java Language Specification.

    • Click Open. Note that when you add a new .java file, Visual J++ automatically inserts the proper package statement into the file. (If you add a .java file to the project node itself, no package statement is inserted, since the project node is considered the default package.)
  4. To add an existing file, click the Existing tab in the Add Item dialog box.
    • Find and select the file you want to add. You can select multiple files from the same folder by using the SHIFT or CTRL keys.

    • Click Open. Note that when you add an existing .java file, you must manually change its package statement to reference the new package. (Note that the project node itself is considered the default package.) If a file's package statement does not map to the folder it resides in, the output directory structure will not match the source directory structure when you build the project. For more information about building your project, see Building a Project.

When a single file is added to the project through Project Explorer, it is automatically opened in its default editor. When multiple files are added at the same time, no file is opened. For information about opening files, see Opening a File.

Note If a file is added to the project directory structure through the file system, it is automatically added to the project if its file type is specified in the project filter. The file is then displayed in Project Explorer, but not opened. For more information about the project filter, see Displaying All Files in the Project Directory Structure.

Adding a File that Resides in the Project Directory Structure

If a file does not belong to the project, but it already exists in the project directory structure, you can simply add it to the project in that same location.

To add a file that already resides in the project directory structure

  1. Set the project view to directory view by clicking the Directory View button in Project Explorer. Only directory view allows you to see the nonproject files that reside in the project directory structure. For more information about views, see Choosing the Project View.

  2. If the nonproject files are not currently displayed, click the Show All Files button in Project Explorer to show all files in the project directory structure.

  3. Right-click the name of the file that you want to add to the project. Note that you cannot add a file if its folder is not in the project. For information about adding the folder, see Adding a Folder that Resides in the Project Directory Structure.

  4. On the shortcut menu, click Add To Project. The file is added to the project, but not opened. For information about opening files, see Opening a File.

  5. To hide any remaining nonproject files, click the Show All Files button again.

For more information about nonproject files that reside in the project directory structure, see Displaying All Files in the Project Directory Structure.


Adding a Folder

When you add a new folder to your project, a corresponding folder is created on the hard disk. In a Java project, a folder is essentially a Java package. In Project Explorer's directory view, all packages are displayed as project subfolders. In package view, subfolders are displayed as Java packages. For more information about views, see Choosing the Project View.

Note A folder may reside in the project directory structure without belonging to the project. For example, removing a folder from the project still leaves the folder in the project directory structure. This folder can be added back to the project in its same location on the disk.

To add a new folder (package) to the project

  1. In Project Explorer, right-click the project or folder node that will contain the new folder.

  2. On the shortcut menu, click New Folder.

  3. In the Add Package/Folder dialog box, type the name of the new folder. This name must be a valid Java package name. For information about valid names, see Identifiers in the Java Language Specification.

  4. Click OK.

Once you have created a folder, you can add files to it. For information about adding files, see Adding a File.

Note If a folder is added to the project directory structure through the file system, it is automatically added to the project and displayed in Project Explorer. All files in the folder, whose types are specified in the project filter, are added to the project as well. For more information about the project filter, see Displaying All Files in the Project Directory Structure.

Adding a Folder that Resides in the Project Directory Structure

If a folder does not belong to the project, but it already exists in the project directory structure, you can simply add it to the project in that same location.

To add a folder that already resides in the project directory structure

  1. Set the project view to directory view by clicking the Directory View button in Project Explorer. Only directory view allows you to see the nonproject items that reside in the project directory structure. For more information about views, see Choosing the Project View.

  2. If the nonproject items are not currently displayed, click the Show All Files button in Project Explorer to show all files and folders in the project directory structure.

  3. Right-click the name of the folder that you want to add to the project.

  4. On the shortcut menu, click Add To Project. The folder and all subfolders and files contained within the folder are added to the project. (Only those files whose types are specified in the project filter are added.)

  5. To hide any remaining nonproject items, click the Show All Files button again.

For more information about the project filter and about nonproject items that reside in the project directory structure, see Displaying All Files in the Project Directory Structure.


Moving or Copying a File or Folder

When you move or copy a file or folder in your Java project, the file or folder on the hard disk is also moved or copied. Moving or copying a folder also moves or copies all project files in the folder.

Important When moving or copying a .java file to a different folder, you must manually change its package statement to reference the new package. (Note that the project node itself is considered the default package.) Similarly, if you move a folder within the project, you must manually change the package statement of each .java file in the folder. If a file's package statement does not map to the folder it resides in, the output directory structure will not match the source directory structure when you build the project. For more information about building your project, see Building a Project.

When moving or copying items, Project Explorer follows the rules of the file system. For example, you cannot move a folder into any of its subfolders.

To move or copy a file or folder in the project

  1. In Project Explorer, right-click the name of the file or folder to be moved or copied.

  2. To move the item, click Cut on the shortcut menu; to copy the item, click Copy.

  3. Right-click the new folder or the project node that will contain the file or folder.

  4. On the shortcut menu, click Paste.

Note If a file or folder is moved or copied through the file system, it is automatically moved or copied within Project Explorer. However, you must still ensure that the package statements in the .java files are correct.

You can also copy files and folders by dragging them in Project Explorer. Note that drag-and-drop operations in Project Explorer only copy the source items. In directory view, you can drag either a single folder or any set of files. In package view, you can only drag files. For more information about views, see Choosing the Project View.


Renaming a File or Folder

When you rename a file or folder in your Java project, the file or folder on the hard disk is also renamed.

Important When renaming an item in your project, you must be careful to manually change all references to the old name. For example, Java requires a public class to have the same name as its source file. Therefore, if you rename a .java file, you must also rename the associated public class, and vice versa.

Note that if you rename a folder, you must change the package statement of each .java file in the folder. If a file's package statement does not map to the folder it resides in, the output directory structure will not match the project directory structure when you build the project. For more information about building your project, see Building a Project.

To rename a file or folder in the project

  1. In Project Explorer, right-click the name of the file or folder to be renamed.

  2. On the shortcut menu, click Rename.

  3. Type the new name and press Enter. This name must be a valid file or package name. For information about valid names, see Identifiers in the Java Language Specification.

Note If a file or folder is renamed through the file system, it is automatically renamed in Project Explorer. However, you must still change all references to the old name.


Removing a File or Folder

When you remove a file from your Java project, the file is no longer built with the project; however, the file still remains in the project directory structure on the hard disk. When you remove a folder, the folder and all of its files are removed from the project, but they are still left on the hard disk.

You can also to choose to actually delete the file or folder from both the project and the hard disk.

Note Removing or deleting a .java file does not automatically remove or delete the associated .class file (if it exists). However, you can display the .class file in Project Explorer and then manually remove or delete it.

To remove a file or folder from the project

  1. In Project Explorer, right-click the name of the file or folder to be removed.

  2. On the shortcut menu, click Remove From Project.

To delete a file or folder from the project and the hard disk

  1. In Project Explorer, right-click the name of the file or folder to be deleted.

  2. On the shortcut menu, click Delete.

Note If an item is deleted through the file system, it is automatically deleted from the project and removed from Project Explorer.

Project Explorer provides the option of displaying the items you have removed from your project. For more information, see Displaying All Files in the Project Directory Structure. For information about adding a removed file or folder back to the project, see Adding a File and Adding a Folder, respectively.


Displaying All Files in the Project Directory Structure

Files and folders may reside in the project directory structure without belonging to your project:

  • Removing a file or folder from a Java project still leaves it on the hard disk.

  • Files whose types are not in the project filter may not be added to the project. For more information, see The Project Filter.

In Project Explorer's directory view, you have the option of displaying all files and folders that reside in the project directory structure, even if they do not belong to the project. The icon for each item denotes whether it currently belongs to the project.

To toggle the display of nonproject items in the project directory structure

  1. Set the project view to directory view by clicking the Directory View button in Project Explorer. Only directory view allows you to see the nonproject items that reside in the project directory structure. For more information about views, see Choosing the Project View.

  2. Click the Show All Files button in Project Explorer.

For information about adding a nonproject file or folder to the project, see Adding a File and Adding a Folder, respectively.

The Project Filter

Visual J++ uses a project filter to determine which types of files typically belong to a Java project. The project filter is an inclusive filter, meaning that the extensions in the filter identify valid project files. The following extensions are included in the project filter:

  • .java

  • .asp, .htm, .html

  • .bmp, .gif, .ico, .jpeg, .jpg

  • .avi, .au, .wav

  • .doc, .rtf, .txt, .ppt, .wri, .xls

  • .bat, .cur, .reg, .snd, .tlb, .url

When a file is added to the project directory structure from outside the Visual J++ environment, the project filter is used to determine whether the file actually belongs to the project.

Important When you add a file within the Visual J++ environment, the file is always added to the project, regardless of its file type.


Building a Project

Thanks for using this pre-release version of Visual J++.

This section will include the following topics:

  • Setting Launch Options

  • Setting Compiler Options

  • Creating Custom Build Rules

  • Setting the Classpath

  • Setting COM Classes


Setting Launch Options

Thanks for using this pre-release version of Visual J++.


Setting Compiler Options

Thanks for using this pre-release version of Visual J++.


Creating Custom Build Rules

Thanks for using this pre-release version of Visual J++.


Setting the Classpath

Thanks for using this pre-release version of Visual J++.


Setting COM Classes

Thanks for using this pre-release version of Visual J++.


Importing a Visual J++ 1.1 Project

Thanks for using this pre-release version of Visual J++.

For a brief procedure describing how to import Visual J++ 1.1 projects, see Importing a Project Created with Visual J++ 1.1 in the Getting Started section of the product’s online documentation.


Designing Forms

The Form Designer provides you with a dynamic way to visually create forms for your applications, turning a two-dimensional form into source code which is based on the Windows Foundation Classes (WFC). The Form Designer contains RAD features, such as Code Generation and code completion which provides quick syntax analysis, debugging information, and other tools for:

  • Creating a form and specifying the alignment and formatting without having to write Java code.

  • Writing or modifying Java codefor a form and viewing the results in the Form Designer.

  • Adding controls to a form by dragging WFC and ActiveX controls onto it. The Form Designer generates the appropriate Java source code.

  • Setting properties with the Properties window without having to write Java code. Properties include form elements such as color, size, position and font.

  • Creating menus for your form through the addition of a single WFC control.

  • Formatting forms to position and size your forms and controls by dragging their handles and objects visually without having to write Java code.

  • Managing the Toolbox containing WFC, ActiveX, and custom controls.

  • Authoring WFC controls


Creating a Form

A form is added to your application through the Project menu.

Objects can be dragged from the Toolbox to the form. The form is persisted as a block of source code that defines an instance of the WFC Form class. The default Form class contains:

  • A constructor that invokes the initForm method.

  • A set of instance variables, one for each item on the form.

  • An initForm method that specifies the default properties for the items. These defaults can be changed by setting item properties.

The Form Designer generates this code based on values set in the Properties window for each control and the form itself. Caution should be taken when modifying the initForm method since the Form Designer also reads this code when displaying the form. Conditionals such as if, while, and switch statements should be avoided, as should component methods. If you modify the initForm code, restrict changes to properties that begin with set and restrict values to constants. Do not use variables to set values.

For example:

Correct Use | setSize(10,100);
Incorrect Use | x=10; y = 100; setSize(x,y);

To create a form

  1. If you do not have a project open, select one from the Projects template dialog box. If you select a Windows Application template, a form template is already included.

  2. On the Project menu, click Add Item or Add Form.

    The Add Item dialog box appears with the form templates.

  3. In the Add Item dialog box, you can select either the New or Existing tab. For this example, select the New tab.

  4. On the right side of the Add Item dialog box are the various templates you can use. Click Form for this example. This template creates a class capable of hosting controls.

  5. By default, the name of the class file is Form1.java. If you wish, you can edit the name of the class file in the Name text box to match your project.(such as MyForm1.java).

  6. Click Open.

    The form window is displayed, showing the form surface.

The form is automatically opened in design mode if you are creating a new form from a template. If the Form Designer is not currently active, follow the below procedure to open the Form Designer.

To view the form in the Form Designer

  • On the View menu, click Designer.

    -or-

  • Double-click the node in the Project Explorer or right-click the form file name and use the context menu to select View Designer. Your form now appears in the Form Designer.

By default, controls are aligned to the grid. The grid options can be set through the Tools/Options dialog box for Forms.

The Toolbox contains WFC Controls and may include other tabs containing ActiveX and custom controls.

Once you have the basic form template, you are ready to add controls to it.


Managing the Toolbox

The Form Designer includes a Toolbox of default controls. You can add custom tabs to the Toolbox for your convenience. Custom controls can also be added to any of the tabs.

Each Toolbox tab has a default group of controls. These controls may be reorganized for your convenience. Any tab may contain any type of control.

To add objects to the Toolbox

  • On the Tools menu, click Customize Toolbox.

    -or-

  • Paste an item that has been copied to the Clipboard onto the Toolbox.

    -or-

  • Drag selected scraps of code or text from the Text editor into the Toolbox and then drag it into other files or windows where you want to use it.

Note Only components that extend wfc.core.Component and have the ShowInToolbox attribute set are displayed. ShowInToolbox is an attribute returned from IClassInfo.getAttributes. The Component class, by default, doesn't return this; the Control class by default, does.

To organize your tools, you can:

  • Copy a Toolbox item from one tab to another tab by pressing CTRL and dragging the selected item to the new tab.

  • Move a Toolbox item from one tab to another tab by dragging the selected item to the new tab.

    Note If you try to move a nonremovable item, dragging it to a new tab will copy it to the new tab instead of moving it.

You can add and customize Toolbox tabs by:

  • Selecting Add Tab from the context menu when you right-click the Toolbox to create tabs for customized groupings.

  • Rearranging items on a tab and rearranging the tabs by dragging them to the location you want.

  • Clicking on the tab label and typing the new name description text of items or by using the Rename Item context menu item.

To view Toolbox objects as a list

  • Right-click the Toolbox to display the context menu, and then select List View. This displays the contents of the active tab in the Toolbox in a list format. This list contains the icons and descriptive information associated with the active Toolbox tab.

To view Toolbox objects as icons

  • Right-click the Toolbox to display the context menu, and then deselect the List View check box. This displays the contents of the active tab in the Toolbox as icons only.

To delete objects from the Toolbox

  • Select the item to be deleted and press DEL.

To recover a deleted control

  1. Right-click the Toolbox to display the context menu, and then select Customize Toolbox.

  2. On the Customize Toolbox dialog box, click the WFC Controls tab.

  3. On the WFC Controls tab, click the check box for the control you wish to add.


Adding Controls to a Form

You can add controls to your form in design mode by selecting them from the Toolbox.

To add a control

  • On the Toolbox, click the control you want to add to your form. Hold down the mouse button and drag the control onto your form. The control appears on your form in its default size.

    -or-

  • On the Toolbox, double-click the control to add it to the center of your form. The control appears on your form in its default size.

    Click the control and drag it to the desired location.

To resize a control

  • Highlight the control you want to resize (if it is not already highlighted), and resize it with the sizing handles.

Note You can also use keyboard arrows to move the control. Use SHIFT+ Arrow keys to size the control.

To add event handler templates to a control

  • Double-click a form or control to generate a method for the default event of the form or control. The event handler method is created in the Form class.

You can also add event handlers through the Event View of the Properties window.


Formatting Forms

Objects placed on a form can be aligned and grouped using the location properties for the form, the grid options from the Tools menu, and from the Format menu.

To set grid options

  1. On the Tools menu, click Options.

    The Options dialog box appears.

  2. In the Options dialog box tree-view area of your project, double-click Forms, and then select WFC. The forms Options page for the Toolbox window appears.

You can use this dialog box to set the defaults for displaying the grid, the grid height and width in pixels, and to toggle alignment to the grid.

To change location properties

  1. Select the control you wish to change

  2. On the View menu, click Properties window.

    The Properties window opens.

  3. In the Properties window, double-click the Location property to expand the node. You can enter the x and y coordinate properties for your control. You can also change the location programmatically by setting the x and y location properties.

To format controls on a form, you can use the options on the Format menu to manage your controls. You can:

  • Align controls

  • Make multiple controls the same size

  • Size to grid

  • Adjust horizontal and vertical spacing

  • Adjust the front to back order

  • Lock controls in place

To align two controls on a form

  1. Click the first control (this control becomes the reference), then press the CTRL key and click the second control.

  2. On the Format menu, click Align and select Lefts from the cascading menu.

    The second control aligns with the left edge of the first control.

    Note that controls can be stacked on top of each other.

Modifying the Form Layout Behavior

With the Form Designer, you can define the behaviors of controls that are placed on your form. For example, you can anchor a label control at the top of the form using the anchor property.

To anchor the control within the form

  1. Place the control on the form.

  2. Click the control so that the control's properties appear in the Properties window.

  3. Double-click the Anchor property in the Properties window.

    The Anchor position editor appears.

  4. Click on the cross bars in the editor to enable and disable anchoring behavior between the control and the form edge.

To modify docking behavior

  1. Place the control on the form.

  2. Click the control so that the control's properties appear in the Properties window.

  3. Double-click the Dock property in the Properties window.

    The Dock editor appears.

  4. Click on the bars in the editor to enable and disable docking behavior for the control. Click None to disable the docking behavior.

Note The control is automatically resized to fit the boundaries of the docked edge.

Most controls can be docked to the edges of a form or can be made to fill the entire form.


Setting Properties with the Properties Window

Properties are attributes that define how a control appears and runs at run time. Each form and each control has an associated custom property page. Modifying the properties in the page (the Properties window) affects the code that is generated for the control in initForm. Properties include the appearance, behavior, and position for the control. The background color, enable and disable state, show state, font, default size and position, and so forth, may be set in the Properties window for the form. Properties vary depending on the class for the container (or Form class).

Some properties are inherited, such as Font, background color, and foreground color.

To edit the properties of a control or form

  1. On the form, select the control you wish to edit; or, to edit the form, click the form itself.

    The properties page associated with the selected control is displayed in the Properties Window.

  2. Select the property that you wish to modify for the control from the Properties window. For example, you might choose the Font property to change the font style for the name on a button control.

Note Multi-selection of controls results in a custom properties page which displays only the common properties.

Complex properties use common dialogs and editors for:

  • Text input – size and strings (in-place string edit changes appear in real-time

  • Combo box selection – cursors, enums and booleans

  • Font picker – common dialog box for selecting font characteristics

  • Color picker – common dialog box with a palette for color selection

  • List items – window for creating initial list items

  • Anchor and Dock editors – for setting position behavior

Click the node of compound properties to access sub-properties.


Creating Menus for Forms

Main menus and context menus are created through the use of the menu controls.

  • Adding and Modifying a Menu

  • Adding a Context Menu


Adding and Modifying a Menu

If you want your application to provide a set of commands to users, menus offer a convenient and consistent way to group commands and an easy way for users to access them. The menu bar appears immediately below the title bar on the form and contains one or more menu titles. When you click a menu title (such as File), a menu containing a list of menu items appears. Menu items can include commands (such as New and Exit), separator bars, and submenu titles. Each menu item the user sees corresponds to a menu control property you define. Multiple menus can be added to one form.

To add a menu to your form

  1. On the Toolbox, under the WFC tab, double-click the MainMenu control.

Note You can also highlight the MainMenu control on the Toolbox and, holding down the left mouse button, drag the control onto your form.

The MainMenu control is inserted onto your form, and the default location for the first item on the menu bar is displayed. Two visual markers (Type Here) appear directly to the right and below to signify the next available editing locations.

Note By default, the MainMenu property for the form is set to MainMenu1.

  2. Type the name of your first menu caption in the default location text box. (For example, type File to add the File menu item.) The menu caption is added to your menu, and the default location text box moves to the next menu caption location. Continue typing your menu captions until all your captions are complete.

Forms may have several menus, such as File/Save and File/SaveAs. You can switch menus by changing the Menu property for the form to a different menu name, for example, mainMenu2.

To add access keys to a menu

  1. Click the menu caption in which you want to add an access key.

  2. Place the mouse cursor immediately before the letter in the caption box that you want to be your access key letter and type an ampersand (&). For example, on the File menu, click File, placing your cursor before the "F" in File and then type an ampersand. You can also edit the caption title through the Text property for the menu item.

To add shortcut (action) keys to a menu item

  1. Click the menu item caption in which you want to add a shortcut key.

  2. Select a function key or key combination in the Shortcut box which is located in the Properties window.

  3. Set the showShort property to true.

To remove a shortcut key

  • Set the shortcut property to "none."

To enable check marks on a menu

  • On the Properties window, select the Checked property to add a check mark next to the menu caption.

To move a menu

  • Place the mouse over the desired menu item caption. Hold down the left mouse button and drag the menu caption to the new position.

    The actual menu caption moves and snaps to place. Other menu captions that are affected by this change are moved as appropriate.

Note Moving top-level menu captions will move all child members, as well. Child members are not displayed during the move.

To modify a menu

  • Click the menu caption you want to modify. In the text box containing the menu caption, make any necessary changes.

To create a menu separator bar

  1. Click the menu caption that is above the location where you want to add a separator bar.

  2. Press the Dash (–) key and then press ENTER.

    A separator bar appears directly below your menu caption.

    -or-

  • Click the right mouse button, and select Insert Separator from the context menu.

Separator bars may be moved and deleted in the same manner as regular menu captions.

To delete a menu item from your form

  • Right-click the menu item caption you want to delete, and select Delete from the context menu.

Note To delete the entire menu, highlight each menu caption and press DELETE, or click the MainMenu1 control and select Delete from the context menu.

Confirmation on deletion only occurs on menu captions with sub-menus.


Context Menus

Adding Context Menus

Context menus can be associated with controls on your form. These menus appear when the user right-button clicks on the control.

To add a context menu to a form

  1. On the Toolbox, under the WFC Controls tab, double-click the ContextMenu control.

Note Any of the methods used to add a control to a form may be used. You can also highlight the ContextMenu control on the Toolbox and, holding down the left mouse button, drag the control onto your form.

The ContextMenu control is inserted onto your form.

  2. To enter design mode, double-click the ContextMenu control.

Context menu controls can be edited in the same way as MainMenu controls.

To assign a context menu to a control

  • Select the control you want to assign a context menu to and add the name of the context menu to the contextMenu property, using Properties window. By default, the first context menu is named contextMenu1.

To add access keys to a menu

  1. Click the menu caption in which you want to add an access key.

  2. Place the mouse cursor immediately before the letter in the caption that you want to be your access letter and type an ampersand (&). For example, on the File menu, click File and place the mouse cursor at the beginning of the word. Then type an ampersand before the "F."

    -or-

  • On the Properties window, select the Show Shortcut property to specify an action key (CTRL+<somecharacter>.

To enable check marks on a menu

  • On the Properties window, select the Checked property to add a check mark next to the menu caption.

To move a menu

  • Place the mouse over the desired menu item caption. Hold down the left mouse button and drag the menu caption to the new position.

    The actual menu caption moves and snaps into place. Other menu captions that are affected by this change are moved as appropriate.

Note Moving top-level menu captions will move all child members, as well. Child members will not be displayed during the move.

To modify a menu

  • Click the menu caption you want to modify. In the text box containing the menu caption, make any necessary changes.

To create a menu separator bar

  1. Click the menu caption that is above the location where you want to add a separator bar.

  2. Press the Dash (-) key and then press ENTER.

    A separator bar appears directly below your menu caption.

    -or-

  • Click the right mouse button, and then Insert Separator from the context menu.

Separator bars may be moved and deleted in the same manner as regular menu captions.

To delete a menu item from your form

  • Right-click the menu item caption you want to delete, and select Delete from the context menu.

Note To delete the entire menu, highlight each menu caption and press DELETE, or click the ContextMenu1 control and use Ctrl+Delete from the context menu.

Confirmation on deletion only occurs on menu captions with sub-menus.


Code Completion

Code Generation

Visual J++ synchronizes Visual representation of code changes and form views (code generation from visual layout) in both directions. Information about which methods (and classes) that are being modified is formatted into the source code. Similarly, modifications to the source code is sent to the Form Designer.

The two-way editing does not simultaneously modify source code and visual layout. The code that is used to create the visual layout is disabled while the Form Designer is in use. The layout is stored as code when the designer window is closed or the form is saved. Editing of the entire initForm function is locked until the Form Designer window is closed.

Edits in the Forms editor are not serialized as code until you click Save on the File menu, or when the forms editor is closed.

You can use the Form Designer to edit classes that adhere to the following syntax:

class isEditable extends [UserControl, Form, Design Page] {
   Container components = new Container(this);
   private void initForm() {
      [form initialization code goes here]
}
}

The initialization code must adhere to certain parsing rules:

  • Initialization code must reside in the initForm function.

  • No conditional code will be parsed (no if, while, or switch statements).


Editing Code

Visual J++ provides several ways to create, modify, and manage your project's code. The topics and procedures in this section give you hands-on experience to help you explore the Text editor, Class Builder, Class Outline, and Object Browser.

Use the following table to learn more about the ways you can work with the files of a Visual J++ project. Select a feature you'd like to know more about from the left column. Clicking the link in the corresponding right column takes you to the supporting topics and procedures.

To | See
Discover IntelliSense features of the integrated Text editor. Procedures in this topic include building statements with Word Completion, Parameter Info, and dynamic syntax checking. | Managing Files with the Text Editor
Modify classes in existing files with Class Builder. Procedures in this topic include changing class attributes, choosing a superclass and the interfaces to be implemented, and managing the member variables, methods, properties, and events. | Modifying Code with Class Builder
Manage your Java source files with Class Outline. Procedures in this topic include navigating to a definition, adding a new declaration, deleting a definition, and moving and copying a definition. | Managing Code with Class Outline
Browse the contents of Java packages and COM libraries. Procedures in this topic include selecting the packages and libraries to be browsed, viewing classes and members, and filtering and grouping classes and members. | Browsing Packages and Libraries with the Object Browser


Managing Files with the Text Editor

The development environment includes an integrated Text editor to manage, edit, and print source files. Most of the procedures for using the editor will seem familiar if you have used other Windows-based text editors. In addition, Visual J++ has enhanced the Text editor with several new timesaving features such as statement completion, dynamic syntax checking, and two-way interaction between the Text editor and Class Outline — these are just a few of the services IntelliSense provides for Visual J++ developers. For more information and step-by-step procedures describing these features, see:

  • Writing Code with Statement Completion

  • Finding Errors with Dynamic Syntax Checking

  • Updating Class Outline from the Text Editor

Most of the functionality of the environment's Text editor is the same regardless of the product you are using or type of project you're editing. Use the following table to determine what you want to do with the Text editor and then click the link to go to the related topics and procedures.

! WARNING Several topics in the following table refer to features and procedures applicable to more than one product and are not included in the Visual J++ online documentation. This will not prevent you from viewing these cross-product topics, however, when the location of these topics is displayed, they'll appear outside the Visual J++ table of contents.

If you want to | See
Manage the Text editor's open windows Splitting a Window in the Text Editor

Viewing a File in Full-Screen Mode
Find and replace text in a single file or multiple files Finding and Replacing Text in a Single File

Finding Text in Multiple Files
Customize the Text editor's features to support the way you like to work Setting Options in the Code Editor

Displaying Margins and Scrollbars

Setting Tabs and Indentations

Formatting Braces, Operands, and Parameters

Add Comments to the Task List
Navigate through project files Enable Virtual Spaces

Finding Matching Delimiters

Navigating with Bookmarks
Highlight lines, multiple lines, or columns of text | Selecting a Box of Text
Change the syntax coloring, and the font styles and sizes for your project's files | Font and Color Options(Text Editor — Options Dialog Box)
Drag-and-drop text between editor windows and other environment windows General Options (Text Editor — Options Dialog Box)

Using the Code Editor
Use the Text editor's keyboard shortcuts Text Editor Window Navigation Keyboard Shortcuts

Statement Completion Keyboard Shortcuts

Text Editor Window Editing Keyboard Shortcuts


Writing Code with Statement Completion

Visual J++'s Statement Completion saves you time by doing the reference look-up work for you. Statement Completion automatically displays member lists and parameter information that gives you a list of classes, members, and method signatures, that are relevant within the context of the current .java source file.

To introduce you to the Statement Completion features, this scenario will show you how to build statement(s) with the java.lang.String and java.lang.System classes. After you've built your project and run the application, the program will display a message in the console window provided by JVIEW. This scenario includes the following procedures:

  • Enabling/Disabling Statement Completion Options in the Text Editor

  • Creating Statements with Word Completion

  • Selecting an Overloaded Method

  • Selecting Methods from a Member List

  • Building an Argument List with Parameter Info

Note This scenario was created with the Visual J++ Console Application template. You may complete the following procedures with any .java source code file in any Visual J++ project. If you would like to create a console application to complete this scenario, please see Using the Console Application Template and follow the steps to create and open a project before proceeding.


Finding Errors with Dynamic Syntax Checking

Visual J++ also provides dynamic syntax checking to assist you when you're writing code within the Text editor. In addition to the information Statement Completion provides, you receive visual clues in the form of red squiggly lines and error tips as you build your program's statements.

As you begin typing within a .java file, red squiggly lines appear under code elements, such as class names, member names, and symbols. When you see a red squiggly line, IntelliSense is telling you your code, as it is currently written, has syntactic errors. As you continue typing, the red squiggly lines may disappear as you finish the statement — depending upon the correctness of the completed statement.

For each syntax error marked with a red squiggly line, a task related to the syntax error will appear in the Task List. This provides a list of items that you'll need to correct before you compile your program.

To get error tips and error help from a red squiggly line

  1. Rest the cursor over the red squiggly line.

    IntelliSense displays an Error Tip that best suits the context of your source code. On occasion, the tip will simply be "Syntax Error."

Tip If you do not see a red squiggly line under obvious syntax errors, make sure you've enabled the options that support dynamic syntax checking.

  2. While resting the cursor over a red squiggly line, click the right mouse button to access the shortcut menu.

  3. From the shortcut menu, select Error Help to get online help for the error identified by the red squiggly line.

See Creating Statements with Word Completion for an example that demonstrates the use of red squiggly lines.


Updating Class Outline from the Text Editor

In addition to being able to modify your code with Class Builder, Visual J++ uses IntelliSense to dynamically update the Class Outline tree view of your file whenever you add a method, member variable, or class to an existing .java source file from the Text editor. If you wish to add a Javadoc comment to your code, IntelliSense creates a comment block and then displays the comment in Class Outline's Javadoc pane. For procedures that illustrate these features, see:

  • Adding Items to Class Outline from the Text Editor

  • Adding Javadoc Comments to Source Files


Modifying Code with Class Builder

The Class Builder is a tool that assists you in modifying the classes in your Java source files. Using Class Builder, you can:

  • Modify the general attributes of a class

  • Add a new class to your file

  • Choose the superclass and override its methods

  • Choose the interfaces implemented by the class

  • Manage the member variables, methods, properties, and events in the class

You can also set various Class Builder options to customize its functionality.

Important Class Builder inserts @builder comment tags into your code. Because these comments are needed by Class Builder, you should avoid deleting them.

For more information about the wizards and builders included with Visual J++, see Introducing Wizards and Builders.

Starting Class Builder

To open Class Builder, you can:

  • Select the .java file in Project Explorer that identifies the class you want to modify. On the View menu, point to Other Windows and click Class Builder.

-or-

  • Right-click the name of the class in Class Outline and click Class Builder on the shortcut menu.

  • When Class Builder is open, the Class Name box on the General tab displays the name of the class that will be modified. The following procedure shows how to change the selected class:

To change the selected class in Class Builder

  1. On the General tab, click Select Class.

  2. In the Select Class dialog box, select whether you want to view your classes in Project View or Class View. Project view displays a hierarchical list of the .java files in your solution, where each file node lists the names of the classes contained in that file. Class view displays a hierarchical list of class names.

  3. Once you have chosen a view, select the name of the class you want to modify with Class Builder.

  4. Click OK.


Modifying Class Attributes

Using Class Builder, you can easily modify the general attributes of a class.

To modify class attributes

  1. Start Class Builder and make sure the class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the General tab in Class Builder.

  3. Select an access modifier from the Access drop-down list. Nested (or inner) classes can be declared as public, protected, private, or default (package). Non-nested classes can be declared as public or default. For information about nested classes, see Inner Classes in the Java Language Specification.

  4. Select additional modifiers, such as abstract, final, or static. (Only nested classes can be declared as static.)

  5. To insert Javadoc comments for the class, enter the comment text in the Javadoc comment box.

  6. If you are exposing your class as a WFC control, select Include ClassInfo to insert a ClassInfo class into your class. (This option is only available for non-nested classes.) ClassInfo is used to describe the properties and events of the control.

  7. To expose your class as a COM object, select COM Class. When this option is selected, Class Builder inserts the @com.register tag to register your class as a COM class, making it accessible to other languages that support COM. (The COM Class option is only available for non-nested classes.)

  8. To add Microsoft Transaction Server support to your class, select Enabled under MTS Support. (This option is only available for non-nested classes.) Note that because transaction support is only valid for COM classes, enabling MTS support also selects the COM Class option. You can then select one of the following options from the drop-down list:
    • Required The component requires an MTS transaction for its work.

    • RequiresNew The component requires a new MTS transaction for its work. (A new transaction is created, even if one already exists.)

    • Supported The component works regardless of whether a transaction is provided by MTS.

    • NotSupported The component supports neither MTS transactions nor the MTS API.

    Class Builder automatically inserts the @com.register and @com.transaction tags, and adds the com.ms.mtx.IObjectControl interface to the list of implemented interfaces (if this interface is on the classpath). For more information about Microsoft Transaction Server, see Getting Started with Microsoft Transaction Server.


Adding a New Class

  • You can use Class Builder to add a new class definition to an existing .java file.

To add a new class

  1. Start Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the General tab in Class Builder.

  3. Click Add Class.

  4. In the Add Class dialog box, enter the information for the class:
    • Enter the name of the class in the Class Name box.

    • To make this class a nested (or inner) class of the class that is selected in the General tab of Class Builder, select the Create a nested class option. For information about nested classes, see Inner Classes in the Java Language Specification.

    • Select an access modifier from the Access drop-down list. Nested classes can be declared as public, protected, private, or default (package). Non-nested classes can be declared as public or default.

    • Select additional modifiers, such as abstract, final, or static. (Only nested classes can be declared as static.)

    • To insert Javadoc comments for the class, enter the comment text in the Javadoc comment box.

    • To display this class as the selected class in the General tab of Class Builder, select Display new class in Class Builder.
  5. Click Add to add the class declaration to your file.


Choosing the Superclass

You can use Class Builder to choose a superclass for your class and override the superclass methods.

To choose the superclass

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Extends tab in Class Builder.

  3. The Superclass Name box displays the current superclass. To specify a different superclass, click Select Superclass.

  4. In the Select Superclass dialog box, select a superclass from the drop-down list. If the class you want to derive from is not listed, enter the name of the class in the edit box portion of the list. Note, however, that this class is not added to the list for subsequent use.

  5. Click OK.

To override a superclass method

  1. On the Extends tab in Class Builder, select a method from the Inherited Methods list. This list displays all methods inherited from the superclass.

  2. Click the right arrow button to move the method to the Local Overrides list. A declaration for the method is then inserted into your class, where you can add your implementation. (Note that if you select a superclass method that cannot be overridden, the right arrow button is disabled.)

  3. The Local Overrides list displays all superclass methods that your class has overridden. To remove an overridden method, select the method from the Local Overrides list and click the left arrow button. Any associated code is removed from your source file.


Choosing the Implemented Interfaces

Using Class Builder, you can choose which interfaces are implemented by your class. When you add an interface to the list of implemented interfaces, Class Builder inserts declarations into your class for each interface method.

To implement an interface

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Implements tab in Class Builder. The Implemented Interfaces list displays all interfaces that are currently implemented by your class.

  3. To add an interface to the list, click Add.
    • In the Select Interface dialog box, select an interface from the drop-down list. If the interface you want to implement is not listed, enter the name of the interface in the edit box portion of the list. Note, however, that this class is not added to the list for subsequent use.

    • Click OK. Class Builder inserts declarations for all interface methods into your class, where you can add your implementation.
  4. When an interface is selected from the Implemented Interfaces list, the Interface Methods list displays all methods that are defined by that interface.

  5. To remove an implemented interface, select the interface from the Implemented Interfaces list and click Remove. Any interface methods that were inserted into your file may or may not be removed. For more information, see Setting Class Builder Options.


Managing the Member Variables in a Class

Using Class Builder, you can easily manage the member variables defined by your class. Class Builder assists you in adding a new member variable, adding a member variable based on an existing definition, modifying a member variable, and deleting a member variable.

To display the member variables in your class

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Member Variables tab in Class Builder. The Member Variables list displays the member variables that are currently defined by your class. (Depending on the current settings for Class Builder, this list may be filtered. For more information, see Setting Class Builder Options.)

To add a new member variable

  1. Click Add. In the Add Member Variable dialog box, enter the information for the member variable:
    • Enter the name of the member variable in the Member Variable Name box.

    • Select a data type from the Data Type drop-down list or enter your own data type.

    • Select an access modifier from the Access drop-down list. Member variables can be declared as public, protected, private, or default (package).

    • Select additional modifiers, such as static, final, volatile, or transient.

    • To initialize the member variable, enter a value in the Initial Value box.

    • To insert Javadoc comments for the member variable, enter the comment text in the Javadoc comment box.
  2. Click Add.

To add a member variable based on an existing definition

  1. Select a member variable from the Member Variables list and click Clone. The Clone Member Variable dialog box displays the information for the selected member variable, which is the basis for the new member variable.

  2. Replace the name in the Member Variable Name box with the name of the new member variable. Modify the remaining selections as needed.

  3. Click Add.

To modify an existing member variable definition

  1. Select the member variable from the Member Variables list and click Modify.

  2. In the Modify Member Variable dialog box, modify the information for the member variable and then click Modify.

To delete a member variable that has already been declared

  • Select the member variable from the Member Variables list and click Delete.


Managing the Methods in a Class

Using Class Builder, you can easily manage the methods defined by your class. Class Builder assists you in adding a new method, adding a method based on an existing definition, modifying a method, and deleting a method.

To display the methods in your class

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Methods tab in Class Builder. The Methods list displays the methods that are currently defined by your class. (Depending on the current settings for Class Builder, this list may be filtered. For more information, see Setting Class Builder Options.)

To add a new method

  1. Click Add. In the Add Method dialog box, enter the information for the method:
    • Enter the name of the method in the Method Name box.

    • Select a return type from the Return Type drop-down list or enter your own return type.

    • In the Parameters grid, specify the method parameters. In the left column of the grid, select a parameter type from the drop-down list or enter your own type. In the right column, enter the name of the parameter.

    • Select an access modifier from the Access drop-down list. Methods can be declared as public, protected, private, or default (package).

    • Select additional modifiers, such as abstract, final, static, synchronized, or native.

    • To insert Javadoc comments for the method, enter the comment text in the Javadoc comment box.
  2. Click Add.

To add a method based on an existing definition

  1. Select a method from the Member Methods list and click Clone. The Clone Method dialog box displays the information for the selected method, which is the basis for the new method.

  2. Replace the name in the Method Name box with the name of the new method. Modify the remaining selections as needed.

  3. Click Add.

To modify an existing method definition

  1. Select the method from the Member Methods list and click Modify.

  2. In the Modify Method dialog box, modify the information for the method and then click Modify.

To delete a method that has already been declared

  • Select the method from the Member Methods list and click Delete.


Managing the Properties in a Class

If you are exposing your class as a WFC control, you can use Class Builder to manage the properties defined by your class. Class Builder assists you in adding a new property, adding a property based on an existing definition, modifying a property, and deleting a property.

To display the properties in your class

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Properties tab in Class Builder. The WFC Properties list displays the properties that are currently defined by your class.

To add a new property

  1. Click Add. In the Add Property dialog box, enter the information for the property:
    • Enter the name of the property in the Property Name box.

    • Select a data type from the Data Type drop-down list or enter your own data type.

    • Select a category from the Category drop-down list. Categories allow you to group related properties; for example, you can categorize properties in the Properties window. Category names cannot contain any spaces.

    • To assign a default value to the property, enter a value in the Default Value box. Note that the data type of the default value should match the data type you selected from the Data Type drop-down list.

    • To provide a description for the property, enter the description text in the Description box. Property descriptions are displayed in the Properties window.

    • Each property is associated with a member variable to hold the current property value. The Associated Member Variable box displays the suggested name for this member variable. To specify a different name, edit the text in this box.
  2. Click Add.

To add a property based on an existing property

  1. Select a property from the WFC Properties list and click Clone. The Clone Property dialog box displays the information for the selected property, which is the basis for the new property.

  2. Replace the name in the Property Name box with the name of the new property. Modify the remaining selections as needed.

  3. Click Add.

To modify an existing property definition

  1. Select the property from the WFC Properties list and click Modify.

  2. In the Modify Property dialog box, modify the information for the property and click then Modify. (Note that the Associated Member Variable box is disabled.)

To delete a property that you have already declared

  • Select the property from the WFC Properties list and click Delete.


Managing the Events in a Class

If you are exposing your class as a WFC control, you can use Class Builder to manage the events defined by your class. Class Builder assists you in adding a new event, adding an event based on an existing definition, modifying an event, and deleting an event.

To display the events in your class

  1. Start Class Builder and make sure your class is selected by Class Builder. For information on how to do this, see Starting Class Builder.

  2. Click the Events tab in Class Builder. The WFC Events list displays all events that are currently defined by your class.

To add a new event

  1. Click Add. In the Add Event dialog box, enter the information for the event:
    • Enter the name of the event in the Name box.

    • Select an event type from the Type drop-down list or enter your own event type.

    • Select a category from the Category drop-down list. Categories allow you to group related events; for example, you can categorize events in the Properties window. Category names cannot contain any spaces.

    • To provide a description for the event, enter the description text in the Description box. Event descriptions are displayed in the Properties window.
  2. Click Add.

To add an event based on an existing event

  1. Select an event from the WFC Events list and click Clone. The Clone Event dialog box displays the information for the selected event, which is the basis for the new event.

  2. Replace the name in the Event Name box with the name of the new event. Modify the remaining selections as needed.

  3. Click Add.

To modify an existing event definition

  1. Select the event from the WFC Events list and click Modify.

  2. In the Modify Event dialog box, modify the information for the event and then click Modify.

To delete an event that has already been declared

  • Select the event from the WFC Events list and click Delete.


Setting Class Builder Options

Visual J++ allows you to set various options to customize the functionality of Class Builder.

To set Class Builder options

  1. On the Tools menu, click Class Builder Options.

  2. In the Class Builder Options dialog box, select or clear the following options:
    Option | Description
    Filter list box entries Selected by default. Class Builder does not display the following types of methods and member variables:
    • On the Extends tab, the inherited methods that have been overridden. The Inherited Methods list no longer displays those methods that have been added to the Local Overrides list.

    • On the Methods tab, the inherited methods that have not been overriden, the methods associated with properties and events, and the initForm method that was inserted by the Designer.

    • On the Member Variables tab, the member variables associated with properties and events, and with any controls on the form.
    Include call to super in overrides | Selected by default. When you override an inherited method, a call to the superclass method is automatically added to the definition.
    Include TODO comments in new methods | Selected by default. //TODO comments are inserted into method definitions to indicate where you need to add some code.
    Add interface methods in abstract classes | Selected by default. When an abstract class implements an interface, all interface methods are added to the class. (Abstract classes are not required to provide definitions for the methods of implemented interfaces.)
    Remove interface methods when removing an interface | Cleared by default. If your class implements an interface and you later remove this interface, the interface methods will not be removed; these methods will remain as methods defined by your class.
    Automatically update ClassInfo when superclass changes | Selected by default. If you are exposing your class as a WFC control and you specify a different superclass, the ClassInfo is automatically updated with the new superclass information.

  3. Click OK to save your settings.


Managing Code with Class Outline

The Class Outline window lists all classes, interfaces, and delegates defined in a .java source file. All imported classes, and all classes that are contained within the file’s package, are also listed. Whenever you open a .java file in the Text editor, Class Outline automatically displays the information for that file.

Class Outline shows the following details for each class:

  • The superclass, as well as all other classes in the inheritance hierarchy

  • The members that are inherited from the superclass, as well as from the other classes in the inheritance hierarchy

  • Any interfaces that the class implements

  • Any initializer blocks defined in the class

  • Any nested or member classes contained within the class

  • Any nested interfaces contained within the class

  • The methods and member variables defined by the class

When an item is selected in Class Outline, any associated Javadoc comments are displayed in the lower pane of Class Outline.

Using Class Outline, you can:

  • Navigate to a definition in the source file

  • Modify a class definition in the source file

  • Add a new declaration to the source file

  • Delete a definition from the source file

  • Move or copy a definition in the source file

  • Override a method inherited from the superclass

  • Set a breakpoint on a method

Class Outline is available whenever you open a .java file in the Text editor, and by default, it is tab-linked with the Toolbox. If you close Class Outline, you can later reopen it by pointing to Other Windows on the View menu and clicking Document Outline.

Refreshing Class Outline

In most cases, the items displayed by Class Outline are automatically synchronized with the associated declarations in the source file; for example, if you change the name of a method in your class, the method name is immediately updated in Class Outline. However, you must manually refresh Class Outline if you change the declaration of an inherited method. Class Outline does not automatically update the list of inherited members.

To refresh Class Outline, right-click the Class Outline window and click Refresh on the shortcut menu.


Navigating to a Definition

You can use Class Outline to quickly move the insertion point to a specific definition in your source file. If the definition resides in another .java file (such as the definition of an inherited method), and if that source file is available on your computer, then the file is opened and the insertion point is moved to the definition. If the source file is not available, then the Object Browser is opened.

To navigate to a definition

  1. In Class Outline, right-click the item whose definition you want to navigate to.

  2. On the shortcut menu, click Go to definition.

-or-

  • Double-click the item in Class Outline.

Note When you use the Text editor to move the insertion point in the source file, Class Outline does not indicate which definition has been navigated to. To synchronize Class Outline with the source file, right-click the declaration in the Text editor and click Sync Class Outline on the shortcut menu.


Modifying a Class Definition

You can use Class Outline to launch the Class Builder to modify a class definition.

To modify a class definition

  1. In Class Outline, right-click the name of the class you want to modify.

  2. On the shortcut menu, click Class Builder. For information about modifying your class with Class Builder, see Modifying Code with Class Builder.

Note If you use the Text editor to modify a class definition, Class Outline is automatically updated to show the changes.


Adding a New Declaration

You can use Class Outline to add a method or member variable to a class, or to add a new class to your .java file.

To add a new declaration

  1. Right-click the name of a class in Class Outline to add a method or member variable.

    -or-

    Right-click the Class Outline window to add another class to the file.

  2. On the shortcut menu, click Add Class, Add Member Variable, or Add Method.

  3. If you are adding a class, enter the class information in the Add Class dialog box:
    • Enter the name of the class in the Class Name box.

    • To make this class a nested (or inner) class of the class that is currently selected in Class Outline, select the Create a Nested Class option. For information about nested classes, see Inner Classes in the Java Language Specification.

    • Select an access modifier from the Access drop-down list. Nested classes can be declared as public, protected, private, or default (package). Non-nested classes can be declared as public or default.

    • Select additional modifiers, such as abstract, final, or static. (Only nested classes can be declared as static.)

    • To insert Javadoc comments for the class, enter the comment text in the Javadoc Comment box.

    • To display this class as the selected class in Class Builder, click Display new class in Class Builder. (Class Builder is automatically opened if it is not currently open.)

    • Click Add.
  4. If you are adding a member variable, enter the member variable information in the Add Member Variable dialog box:
    • Enter the name of the member variable in the Member Variable Name box.

    • Select a data type from the Data Type drop-down list or enter your own data type.

    • Select an access modifier from the Access drop-down list. Member variables can be declared as public, protected, private, or default (package).

    • Select additional modifiers, such as static, final, volatile, or transient.

    • To initialize the member variable, enter a value in the Initial Value box.

    • To insert Javadoc comments for the member variable, enter the comment text in the Javadoc Comment box.

    • Click Add.
  5. If you are adding a method, enter the method information in the Add Method dialog box:
    • Enter the name of the method in the Method Name box.

    • Select a return type from the Return Type drop-down list or enter your own return type.

    • In the Parameters grid, specify the method parameters. In the left column of the grid, select a parameter type from the drop-down list or enter your own type. In the right column, enter the name of the parameter.

    • Select an access modifier from the Access drop-down list. Methods can be declared as public, protected, private, or default (package).

    • Select additional modifiers, such as abstract, final, static, synchronized, or native.

    • To insert Javadoc comments for the method, enter the comment text in the Javadoc Comment box.

    • Click Add.

The new declaration is inserted into the .java file, where you can add your implementation. Class Outline is automatically updated to display the new item.

Note If you use the Text editor to add a declaration, the item is automatically added to Class Outline.

For more information about adding and modifying declarations, see Modifying Code with Class Builder and Creating Files with Class Wizard.


Deleting a Definition

Using Class Outline, you can quickly delete a definition from your .java file.

To delete a definition

  1. In Class Outline, right-click the item to be deleted.

  2. On the shortcut menu, click Delete. The definition is removed from the source file.

Note If you use the Text editor to delete a definition, the associated item in Class Outline is automatically removed.


Moving or Copying a Definition

Using Class Outline, you can easily move or copy the definition of a method, member variable, or class.

To move or copy a definition

  1. In Class Outline, right-click the name of the item that you want to move or copy.

  2. To move the item, click Cut on the shortcut menu; to copy the item, click Copy.

  3. Right-click the item that indicates where you want to insert the definition:
    • To insert a method or member variable definition at the end of a class, right-click the name of the class.

    • To insert a method or member variable definition before another item within a class, right-click the name of that item.

    • To insert a class definition, right-click the name of another class in the file before which you want to insert the definition.
  4. On the shortcut menu, click Paste.

Note If you use the Text editor to move or copy a definition, the associated item in Class Outline is automatically moved or copied.


Overriding a Method

Class Outline displays all the methods that a class inherits from its superclass as well as from the other classes in the inheritance hierarchy. Using Class Outline, you can quickly add a definition to override an inherited method.

Note You cannot override a method that is marked as static or final.

To override an inherited method

  1. In Class Outline, expand the Inherited Members node of the class. This node displays both methods and member variables; however, only methods can be overridden.

  2. Right-click the method that you want to override. On the shortcut menu, click Override method.

  3. A declaration for the method is inserted into the .java file, where you can add your implementation.


Setting a Breakpoint

You can use Class Outline to quickly set a breakpoint on a method for use in the integrated debugger.

To set a breakpoint

  1. In Class Outline, right-click the method that you want to set a breakpoint on.

  2. On the shortcut menu, click Insert Breakpoint. To verify that a breakpoint was set, double-click the method in Class Outline to go to the definition in the source file. Observe that a breakpoint glyph appears in the margin.

  3. To clear the breakpoint, right-click the method and click Remove Breakpoint on the shortcut menu.

For more information about breakpoints and debugging, see Debugging Applications.


Browsing Packages and Libraries with the Object Browser

The Object Browser provides a convenient way to view the contents of Java packages and COM libraries. You can quickly browse Java or COM-based components without actually adding them to your project, even if you don't have the source code for these components.

Using the Object Browser, you can:

  • View the classes and members contained in the packages and libraries

  • Select the packages and libraries to be browsed

  • Filter the classes and members

  • Group and sort the classes and members

To open the Object Browser, point to Other Windows on the View menu and click Object Browser.


Viewing Classes and Members

The Object Browser provides two lists for viewing the classes and members in a package or library. The primary list can display either classes or members (or both). When a class is selected from the primary list, its members are displayed in the dependent list; when a member is selected from the primary list, all classes containing that member are displayed in the dependent list.

To set the Object Browser view

  1. To toggle whether classes are displayed in the primary list, right-click the Object Browser and click Show Classes on the shortcut menu. You can also click the Show Classes button on the Object Browser's command bar.

  2. To toggle whether members are displayed in the primary list, right-click the Object Browser and click Show Members on the shortcut menu. You can also click the Show Members button on the command bar.

To help distinguish classes from members, classes appear in bold. Note that by default, the Object Browser groups the items in the primary list into their respective packages or libraries, which also appear in bold. To toggle whether these items are grouped by packages and libraries, right-click the Object Browser and click Group by Packages/Libraries on the shortcut menu. You can also click the Group by Packages/Libraries button on the command bar.

Viewing Class and Member Information

You can use the Object Browser to obtain specific information about the classes and members in a package or library:

  • When a class or member is selected in the Object Browser, the lower description pane displays information about the item and supports hyperlinking to other classes, packages, and libraries.

  • When a class node is expanded, the following subnodes are displayed (when applicable):
    • Implemented Interfaces, which lists all interfaces implemented by the class.

    • Subclasses, which lists all classes that extend the class.

    • Superclasses, which lists all classes in the inheritance hierarchy.
  • When a Java method is displayed in the dependent list, its signature is included. (The signatures for COM methods are not displayed.)

Viewing Definitions

If the source code for a package or library is available on your computer, you can navigate to a class or member definition from the Object Browser. Select the item and then right-click the Object Browser. On the shortcut menu, click View Definition.

Viewing Hidden Members

The Object Browser can show any hidden members of COM libraries. To toggle the display of hidden members, right-click the Object Browser and click Show Hidden Members on the shortcut menu. Hidden members appear in gray text.


Selecting Packages and Libraries

By default, the Object Browser only displays the packages and libraries that can be referenced from the current solution, which include all packages in the solution, the packages installed by the Java Package Manager (JPM), and the packages on the classpath. You can also add additional packages and libraries to the Object Browser.

To select the packages and libraries to be browsed

  1. Right-click the Object Browser and click Select Current Packages/Libraries on the shortcut menu. You can also click the Select Current Packages/Libraries button on the Object Browser's command bar.

  2. The Select Packages/Libraries dialog box shows the packages and libraries that are available for browsing. The Solution node lists the Java projects that belong to your solution. The Other Libraries and Packages node contains the following subnodes:
    • COM Libraries, which lists all COM components and type libraries that are available for browsing.

    • Java Installed Packages, which lists all packages that are on the classpath or have been installed by the JPM.

    • Other Java Packages, which lists other packages that are available for browsing but are not on the classpath and have not been installed by the JPM.
  3. Select the packages and libraries that you want displayed in the Object Browser, and clear the items that you want removed. A package or library will be displayed in the Object Browser only if all of its parent nodes are also selected. (By default, selecting an item automatically selects all parent nodes.) A node that is selected with a gray checkmark indicates that some—but not all—of its child items are selected.

    Tip The easiest way to identify which packages and libraries will be displayed in the Object Browser is that these items appear in bold.

  4. To add items to the COM Libraries and Other Java Packages nodes, click Add.
    • To add COM components and libraries, click the COM Libraries tab in the Add New Packages/Libraries dialog box. All components and libraries that are currently registered on your computer are listed. (To register another component or library and add it to the list, click Browse to locate the file.) Select the components and libraries you want to add and click OK.

    • To add other Java packages, click the Other Java Packages tab in the Add New Packages/Libraries dialog box. Click Browse to locate the file containing the package. After the package has been added to the list, click OK.

      Important Adding COM components or other Java packages to the Object Browser simply allows you to browse the components or packages. To actually use a COM component in your project, you must import it. For information on how to do this, see Importing a COM Object.

      To use a Java package from your project, you must add it to the classpath. For information about the classpath, see CLASSPATH Environment Variable and Setting the Classpath.

  5. Click OK to apply your selections.

The items that you select for browsing in the Select Packages/Libraries dialog box may persist after you close the Object Browser:

  • The packages and libraries that you select under the Other Libraries and Packages node will persist per user, per computer. For example, if you create a new solution on the same computer, the same selected set of packages and libraries under Other Libraries and Packages will be displayed by the Object Browser. However, if another user logs onto the computer, a different set of packages and libraries may be initially selected.

  • The projects that you select under the Solution node will not persist after you close the solution. The next time you reopen the solution, all Java projects in the solution will be selected by default.


Grouping and Sorting Classes and Members

The Object Browser allows you to group or sort classes and members by access or by type. By default, no grouping or sorting is applied.

To group or sort classes and members

  1. Right-click the Object Browser and click Grouping and Sorting on the shortcut menu. You can also click the Grouping and Sorting button on the Object Browser's command bar.

  2. To group or sort classes, select a group category from the drop-down list in the Classes section:
    • To group classes by their access level, select Group by Class Access. Public classes are grouped into the Public Types category; nonpublic classes are grouped into the Package Types category, since they are only accessible from the packages they belong to.

    • To group classes by their types, select Group by Class Type.

    • To remove class groupings, select <No Grouping>.
  3. If classes are grouped, you can change the order of the group categories. Select a category from the list and click the up arrow button or the down arrow button.

  4. To group or sort members, select a group category from the drop-down list in the Members section:
    • To group members by their access level, select Group by Member Access.

    • To group members by their types, select Group by Member Type.

    • To remove member groupings, select <No Grouping>.
  5. If members are grouped, you can change the order of the group categories. Select a category from the list and click the up arrow button or the down arrow button.

  6. To display the names of the group categories in the Object Browser, select Group with headers in main list.

    Note The group headers only apply to the primary list in the Object Browser. For example, suppose you have grouped members but the Object Browser is viewing only classes in the primary list. When a class is selected and its members are displayed in the dependent list, the members are grouped but the actual group headers are not included. For information about viewing classes and members in the primary and dependent lists, see Viewing Classes and Members.

  7. Click OK.


Accessing Data

Using the design tools and wizards, you can easily access data in Visual J++. By adding the WFC data controls to your form in the Designer, you can quickly configure how data is retrieved and displayed. You can also run the Data Form Wizard to automatically generate a data-bound form.

Visual J++ provides controls to access data through ActiveX Data Objects (ADO), the data programming model for WFC applications. The core ADO components include the Connection, Command, and Recordset components, which allow you to connect to a database and retrieve a set of records. ADO also provides the DataSource component, which combines the functionality of the Connection, Command, and Recordset components.

Note The Toolbox in the WFC Designer only provides a DataSource control; the Connection, Command, and Recordset components can only be used in code. For information about programming with the ADO components, see the ADO Tutorial (VJ++).

ADO supports simple data binding through the DataBinder component. This component binds a field from a Recordset or DataSource component to the property of a WFC control. Visual J++ also provides complex data-bound controls, such as the DataGrid and DataNavigator controls, that interact directly with a recordset. For more information about data binding, see Data Binding in WFC.

To access data on a form, you can either run the Data Form Wizard or perform the following steps in the Designer:

  • Add the data controls to the Toolbox

  • Retrieve a set of records

  • Display the data on a form

  • Navigate the records

For more information about ADO, see What’s New in ADO 2.0 and Getting Started with ADO 2.0. For information about the COM-based data access options available with Visual Studio, see Choosing the Right Data Access Technology.


Running the Data Form Wizard

Using the Data Form Wizard, you can automatically generate a form that is bound to the fields in a database. The Data Form Wizard supports Microsoft Access .mdb files and databases that can be accessed through ODBC.

Currently, the Data Form Wizard only binds data from a single table or query. Any boolean-valued field is bound to a Checkbox control on the form; all other types of fields are bound to Edit controls.

Note The Data Form Wizard cannot bind fields whose data type is an OLE object.

To launch the Data Form Wizard

  1. To add a data-bound form to your application with the Data Form Wizard, right-click the project or folder node in Project Explorer that will contain the form.
    • On the shortcut menu, point to Add and then click Add Form.

    • In the Add Item dialog box, select Data Form Wizard and click Open.

    Note The Data Form Wizard is also launched when you create a new, data-based application with the Application Wizard.

  2. In the Introduction step, you can choose a profile from the drop-down list. (If the profile you want to use is not listed, click the ellipses button (...) to open that profile.) For more information about profiles, see Introducing Wizards and Builders.

Click Next to specify the database type.


Database Type Step

In the Database Type step of the Data Form Wizard, you specify the format of your database.

To specify the database format:

  1. Select the Access option for any Microsoft Access .mdb file. Click Next to specify the database file.

  2. Select the Remote(ODBC) option to access a database through ODBC, such as an ISAM database (dBase, FoxPro, or Paradox) or a remote data source (SQL Server or Oracle). Click Next to specify the ODBC connection information.

    Note Although you can use the Microsoft Access ODBC driver to connect to an Access database, selecting the Access option will provide better performance.


Database Step

If you selected the Access format in the Database Type step of the Data Form Wizard, then the Database step allows you to specify the .mdb file.

To specify the .mdb file

  1. In the Database name box, enter the full path and name of the .mdb file, or click Browse to locate the file.

  2. Under Choose from, select whether you want to access data from tables or queries (or both).

Click Next to specify details about the form to be created.


Connect Information Step

If you selected the Remote(ODBC) format in the Database Type step of the Data Form Wizard, then the Connect Information step allows you to specify the ODBC information, such as a data source name (DSN), database, and driver.

The following procedures show different ways of connecting to a database through ODBC.

To connect to a database using a DSN that you have created

  1. From the DSN drop-down list, select the name of your ODBC data source. (To create a data source, use the ODBC icon in the Windows Control Panel.)

  2. If a user ID and password are associated with this data source, enter the information in the UID and PWD boxes, respectively.

To connect to a database using a generic DSN

  1. From the DSN drop-down list, select the name of the generic data source, such as FoxPro Files.

  2. In the Database box, enter the full path and name of the database file.

To connect to a database using a specified driver

  1. In the Database box, enter the full path and name of the database file.

  2. From the Driver drop-down list, select the driver you want to use, such as Microsoft FoxPro Driver (*.dbf).

To connect to a full server database

  1. In the UID and PWD boxes, enter the associated user ID and password, respectively.

  2. In the Database box, enter the name of the database.

  3. From the Driver drop-down list, select the driver you want to use, such as SQL Server or Oracle.

  4. In the Server box, enter the name of the server.

Click Next to specify details about the form to be created.


Form Step

In the Form step of the Data Form Wizard, you specify the name of the data-bound form as well as the layout of the form.

To specify form details

  1. In the Form name box, enter the name of the form. By default, the form name is based on the name of your database.

  2. Under Form layout, select how the form will be laid out:
    • Single record The form displays one record at a time. Each non-Boolean field in the database is bound to an Edit control; Boolean fields are bound to Checkbox controls. A Label control is associated with each bound control, and displays the name of the field.

    • Grid Currently not available.

    • Master/Detail Currently not available.

Click Next to specify the record source for the bound controls.


Record Source Step

In the Record Source step of the Data Form Wizard, you choose the fields that you want to bind to the controls on the form.

To specify the bound fields

  1. From the Record source drop-down list, select the name of a table or query that contains the fields you want to bind.

  2. The Available fields list contains the fields in the specified table or query. The Selected fields list contains the fields that will be bound to your form, in the order they are listed. Use the following buttons to move fields between the two lists:
    Button Description
    > Moves the selected field in the Available Fields list to the Selected Fields list. The selected field will be bound to a control on the form.
    >> Moves all fields from the Available Fields list to the Selected Fields list. All fields will be bound to controls on the form.
    < Moves the selected field in the Selected Fields list to the Available Fields list. The selected field will not be bound to a control on the form.
    << Moves all fields from the Selected Fields list to the Available Fields list. No field will be bound to a control on the form.

    Note The Data Form Wizard will add a single-column list of bound controls to the form, based on the order of the fields in the Selected Fields list. To change the order of a field, select the field in the list and click the up arrow button or the down arrow button.

  3. To sort the data that will be displayed by the form, select a field from the Column to sort by drop-down list.

Click Next to add additional controls to the form.


Control Selection Step

In the Control Selection step of the Data Form Wizard, you can select the additional controls that you want to appear on the form. Any code that is required by these controls is automatically added to your form.

To add additional controls

  • Under Available controls, select the controls you want to add:
    Control | Description
    Add button | Allows the user to add new records to the database.
    Delete button | Allows the user to delete records from the database.
    Update button | Updates the database with the changes that have been made on the form.
    Refresh button | Refreshes the form with the latest data from the database.
    Close button | Allows the user to close the form.
    Data navigator | Allows the user to navigate through the records.

Click Next to view the summary for the form.


Summary Step

In the Summary step of the Data Form Wizard, you can save and review your wizard settings.

To save and review the wizard settings

  1. To save your settings to an existing profile, select the profile from the drop-down list. To save your settings to a new profile, click the ellipses button (...) to specify a file name. (For more information about profiles, see Introducing Wizards and Builders.)

  2. To review your settings, click View Report. To save the report, click Save in the View Report dialog box.

  3. Click Finish to add the form to your project.

The Data Form Wizard provides a quick start to creating a form with controls bound to the fields in a database. You can later add additional bindings with the DataBinder control. For information on how to do this, see Binding Data.


Adding the Data Controls to the Toolbox

In order to use the data controls in the Designer, they must appear in the Toolbox.

To add the data controls to the Toolbox

  1. If the Toolbox is not already displayed, click Toolbox on the View menu.

  2. On the Tools menu, click Customize Toolbox.

  3. In the Customize Toolbox dialog box, click the WFC Controls tab. Select the following controls: DataBinder, DataGrid, DataNavigator, and DataSource.

  4. Click OK. The data controls now appear in the Toolbox.

For information about adding these controls to a form, see:

  • Retrieving a set of records

  • Displaying data on a form

  • Navigating records

For more information about the Toolbox, see Managing the Toolbox.


Retrieving a Set of Records

Visual J++ provides the DataSource control to access data in the Designer. This control allows you to connect to and query a database to retrieve a set of records.

Note To retrieve a recordset in code, you can also use the Connection, Command, and Recordset components. The Designer, however, only supports the DataSource component. For information about programming with the ADO components, see the ADO Tutorial (VJ++).

The following steps show how to use the DataSource control in the Designer. (You must have already added this control to the Toolbox.)

To retrieve data with the DataSource control

  1. Add a DataSource control to your form. (For information about adding controls to a form, see Adding Controls to a Form.)

    Note Because the DataSource control only retrieves data and does not display it, the control is not visible when you run your form.

  2. To connect to the database, you set the connectionString property of the DataSource control. (For information about setting properties, see Setting Properties with the Properties Window.)
    • To access an ODBC data source, you typically set the connectionString property as follows:

      DSN=dataSourceName;UID=userID;PWD=password;

      If no user ID and password are associated with this data source, you can omit the UID and PWD tags. Note that you can also specify this string with OLEDB tags:

      Data Source=dataSourceName;User ID=userID;Password=password;

    • To directly access a Microsoft Access .mdb file without using ODBC, set the connectionString property as follows:

      Provider=Microsoft.Jet.OLEDB.3.51;Data Source=fileName;User ID=userID;Password=password;

      In the previous string, fileName specifies the full path and name of the .mdb file. If no users have been created, you can omit the User ID and Password tags.

  3. To query the database, set the queryString property of the DataSource control to an SQL string. For example, to retrieve all records from a table called Products, enter Select * from Products.

Now that you have retrieved a set of records, you must bind the data to display it on the form.


Displaying Data on a Form

To display data on a form, you first use the DataSource control to retrieve the data. Next, you bind the data using either the DataBinder control or the DataGrid control. The DataBinder control binds the fields from a recordset to the properties of WFC controls. The DataGrid control directly displays the data from the fields that it binds in a grid format.

For more information about using these controls, see Binding Data with the DataBinder Control and Populating the DataGrid Control.


Binding Data with the DataBinder Control

The DataBinder control binds a field from a recordset to the property of another control. When a property is bound, it is automatically set to the value of the field in the current record.

The following steps show how to use the DataBinder control in the Designer. (You must have already added the data controls to the Toolbox.) This example binds the text property of an Edit control.

To bind a data field to a property with the DataBinder control

  1. Add a DataSource control to the form to retrieve the data. For information on how to do this, see Retrieving a Set of Records.

  2. Add an Edit control and a DataBinder control to the form.

    Note Like the DataSource control, the DataBinder control is not displayed when the form is run, since it only manages the binding and does not actually display data.

  3. To associate the recordset from the DataSource control with the DataBinder control, set the DataBinder control’s the dataSource property. From the drop-down list, select the name of the DataSource control.

  4. The bindings property of the DataBinder control identifies the bindings that have been currently defined. To set this property, right-click the DataBinder control and click Properties on the shortcut menu. (You can also click the Properties button in the Properties window.) Use the control’s design page to define the bindings:
    • From the Data Field drop-down list, select the name of the data field to be bound.

    • From the Control drop-down list, select the name of the Edit control.

    • From the Property drop-down list, select the text property.

    • Click Add. The text property is now bound to the data field.

    • To add other bindings, repeat the process. Click OK when all bindings have been added.

You can now add a DataNavigator control to the form to navigate through the records of data. For more information about the DataBinder control and for related programming examples, see DataBinder Component.


Populating the DataGrid Control

The DataGrid control binds fields from a recordset and displays the data in a series of rows and columns. The control is automatically populated when you set its dataSource property to the name of your DataSource control.

Note The cursor and lock types of the recordset determine whether its data dynamically reflects the data in the database, and whether its data can be changed. If the recordset allows data to be changed, you can set properties of the DataGrid control to determine whether the user can change the data via the grid. The data in the recordset is always synchronized with the data that is displayed in the DataGrid control, and vice versa.

The following steps show how to populate the DataGrid control in the Designer. (You must have already added the data controls to the Toolbox.)

To populate the DataGrid control with data

  1. Add a DataSource control to the form to retrieve the data. For information on how to do this, see Retrieving a Set of Records.

  2. Add a DataGrid control to the form.

  3. To associate the recordset from the DataSource control with the DataGrid control, set the DataGrid control’s the dataSource property. From the drop-down list, select the name of the DataSource control.

When the data from the recordset is displayed in the grid, the current record is identified by a marker in the corresponding row’s header. To quickly navigate through the rows in the grid, you can add a DataNavigator control to the form.


Navigating Records

The DataNavigator control allows you to change the current record in a recordset. Use the DataNavigator control in conjunction with another data-bound control, such as the DataBinder control. The DataBinder control binds a property of another control to a field in a recordset. This property obtains data from the recordset’s current record, which is initially the first record. To move to another record, use a DataNavigator control that is bound to the same recordset.

The following steps show how to use the DataNavigator control in the Designer. (You must have already added the data controls to the Toolbox.)

To navigate a recordset with the DataNavigator control

  1. Add a DataSource control to the form to retrieve the data. For information on how to do this, see Retrieving a Set of Records.

  2. Use a DataBinder control to bind data from the recordset associated with the DataSource control. For information on how to do this, see Binding Data with the DataBinder Control.

  3. Add a DataNavigator control to the form.

  4. To associate the recordset from the DataSource control with the DataNavigator control, set the DataNavigator control’s the dataSource property. From the drop-down list, select the name of the DataSource control.

  5. Use the buttons on the DataNavigator control to navigate the data:
    Button Navigation Direction
    << Move to the first record.
    < Move to the previous record.
    > Move to the next record.
    >> Move to the last record.


Introducing Wizards and Builders

Visual J++ provides several wizards and builders to help you develop your applications. A wizard adds a new file to your project by guiding you through a series of steps. Each step contains Back and Next buttons to navigate through the steps. The Cancel button cancels all settings you’ve made and closes the wizard. The Finish button accepts the selections you’ve currently entered and uses the default settings for any remaining steps. (The Finish button is available once you make enough choices for the wizard to complete the task.)

Note When you run a wizard, you can typically save your settings to a profile. The next time you run the wizard, you can load this profile to reuse the settings.

While a wizard creates a new file through a step-by-step process, a builder assists you in modifying the existing files in your project. Visual J++ provides the following wizards and builders:

Wizard or Builder | Description
Application Wizard | Automatically creates a WFC application containing a form. You have the option of binding the form to the fields in a database.
Class Builder | Modifies the class definitions in your Java source files.
Data Form Wizard | Automatically generates a form that is bound to the fields in a database. The Data Form Wizard supports Microsoft Access .mdb files and databases that can be accessed through ODBC.
J/Direct Call Builder | Inserts Java definitions for the Win32 API functions into your code, along with the appropriate @dll.import tags.


Debugging Applications

Thanks for using this pre-release version of Visual J++.

Sometimes errors can occur within your code; this type of error is often referred to as a bug. The process of locating and fixing bugs in your application is known as debugging. Minor bugs — for example, incorrect results in an accumulator — can be frustrating or inconvenient. More severe bugs can cause an application to stop responding to commands, possibly requiring the user to restart the application, losing any work that hasn’t been saved.

See Basic Debugging Procedures to learn more about using the integrated debugger with Visual J++ projects. These procedures show you how to set breakpoints, step through code, view run-time values of member variables, and much more. For more information about the general features the integrated debugger shares with other products, see the tables in The Debugging Process. When you are in a debugging session and having problems that are not specifically addressed in a debugging procedure, you may find the help you need in Trouble-Shooting Tips for Debugging an Application.

The online documentation also provides scenarios that have been created to show you how to use the debugger’s features with specific types of Visual J++ projects. Details for recreating example projects can be found throughout the procedures in the following scenarios:

  • Debugging a WFC Application

  • Debugging a WFC Component

  • Debugging a Console Application

  • Debugging Multithreaded Applications

  • Debugging a Java COM Object

  • Debugging a Java Applet

  • Debugging a Server-side Component


The Debugging Process

Thanks for using this pre-release version of Visual J++.

The process of finding and fixing errors in your application is known as debugging. Visual J++ debugging support includes breakpoints, break expressions, watch expressions, thread control, and exception handling. You also have the ability to step through your code one statement or method at a time and view the values of variables and properties.

There are no magic tricks to debugging, and there is no fixed sequence of steps that works every time. Basically, debugging helps you understand what’s happening when your application runs. Debugging tools give you a snapshot of the current state of your application, including:

  • The appearance of your application’s user interface

  • Values of member variables, expressions, and properties

  • Active method calls

The topics listed below provide general information about the debugger’s features that will assist you in debugging your Visual J++ projects:

Note Several topics in the following tables refer to features and procedures applicable to more than one product and are not written specifically for Visual J++. This will not prevent you from viewing these cross-product topics, however, when the location of these topics is displayed, they'll appear outside the Visual J++ table of contents.

General debugging topics:

Debugging Basics Continuing After an Error
Tips for Debugging Attaching and Detaching Processes
Pausing Application Execution with Breakpoints Setting Exception Handling Rules
Stepping Through Code to Trace Execution Ending a Debugging Session
Entering Break Mode at a Problem Statement Just-in-Time (JIT) Debugging

The integrated debugger’s windows:

Viewing Information in the Immediate Window Viewing Messages or Results in the Output Window
Viewing Information in the Locals Window Viewing Information in the Threads Window
Viewing Information in the Auto Window Viewing the Call Stack
Viewing Information in the Watch Window Viewing a List of Running Documents

Visual InterDev debugging topics:

Debugging Your Pages Debugging Script
Debugging Client Script The Script Debugging Process
Debugging Server Script Debugging Remotely
Debugging Mixed Client and Server Scripts Debugging Stored Procedures and Triggers
Debugging a Global.asa File


Basic Debugging Procedures

Thanks for using this pre-release version of Visual J++.

After you have debugged several applicatations, you'll find certain tasks may apply to debugging almost any program.The following general debugging topics provide step-by-step procedures for:

  • Entering Command-line Arguments

  • Displaying the Debug Toolbar

  • Setting Breakpoints

  • Examining Information with Debug Windows

  • Stepping Through the Code

  • Handling Java Exceptions

See Debugging Basics for an overview of basic debugging strategies.


Entering Command-line Arguments

Thanks for using this pre-release version of Visual J++.

You have finished writing the code for your application and have finally gotten it to compile without any warnings or errors. But, before it can run, your application needs information passed to it from the command line. You can choose to enter this information from a console window or from within the development environment. The following procedure explains how to use the Custom options in the environment’s Launch tab of the project’s Properties dialog box. The Properties dialog box for an open project can be accessed from the Project menu.

To enter command-line arguments

  1. From Project Explorer, double-click a .java file to load it into the Text editor.

  2. On the Project menu, click <Project name> properties to display the Properties dialog box.

  3. On the Launch tab, click the Custom radio button.

    The Custom options on this tab provide a place to enter the command line arguments for your application.

  4. In the Arguments text box type the information you want to pass to your program.

    For example, if your program accepted a date in the format of MM DD YY, July 10, 1997 would be entered as 7 10 1997.

Note The Arguments text box may have some viewer options displayed. If you have a specific reason to change these preset options, do so now and enter the date after them.

Now you are ready to debug your application. Setting a breakpoint before starting the integrated debugger is one way to start this process.


Displaying the Debug Toolbar

You may want to use the Debug Toolbar for quick access to the debugger’s most commonly used commands and windows.

To display the Debug Toolbar

  • On the View menu click Toolbars and then select Debug.


Setting Breakpoints

Thanks for using this pre-release version of Visual J++.

This topic includes procedures for:

  • Setting a Breakpoint Before Starting the Debugger

  • Setting a Breakpoint from the Breakpoints Dialog Box

  • Entering Break Mode at a Problem Statement


Examining Information with Debug Windows

Thanks for using this pre-release version of Visual J++.

  • The following topics discuss the debug windows separately and include the purpose of each window. In these topics you will also find specific procedures for accessing and using each debug window:
    • Displaying the Debug Toolbar

    • Viewing Information in the Auto Window

    • Viewing Information in the Locals Window

    • Viewing Information in the Watch Window

    • Viewing Information in the Immediate Window

    • Viewing Information in the Threads Window

    • Viewing Information in the Call Stack Window

    • Viewing Information in the Running Documents Window

    • Viewing Results in the Output Window

After you’ve a chance to see the state of your application’s member variables, you may want to step through your code to get a better idea of what is really happening in your application.


Stepping Through the Code

The application example for this scenario accepts a date passed from the command line and converts it to a Julian calendar date. The application used in this scenario was built in Creating a Console. If you’d like to create this project to complete the following exercises, do so now.

You have entered a date for conversion, stopped on a breakpoint you’ve set, and used the debug windows to examine some of your program’s variables. You have an idea of what the problem may be, but you’d like to step through the statements of your code to get a better understanding of what’s really happening. The following procedure shows you how to trace through your program’s execution.

To step through your program when in break mode

  1. Place the cursor in the margin next on the line of code where you would like to begin stepping through your code.

    Tip Choose a line that will be executed before the application ends.

  2. If you are following the scenario for debugging a Console application, place the cursor next to the following code:
      for(int nCount=1; nCount < m_nMonth; nCount++)
  3. Click in the margin.

    A red dot appears in the margin indicating the line on which the breakpoint was set.

  4. Press F5 and the debugger runs your application and breaks on your new breakpoint.

    The yellow arrow in the margin points to the next instruction to be processed.

  5. Continue to step through your program by pressing F11, paying attention to the line of code being executed and information displayed in any open debugging windows.

    In the open debug windows, values for member variables display in red whenever these values change. If you’re following the debugging scenario for a Console application, continue stepping through your application’s source code until the values for m_nDayOfYear and nCount change to red in the open debug windows.

    For more information about stepping through your program’s code with the debugger, see Stepping Through Code to Trace Execution,

To terminate the debugging session:

  • On the Debug menu, click End.

    For more ways to stop a debugging session, see Ending a Debugging Session.

When you’re program enters break mode, you may want to set another breakpoint or examine one or more Debug Windows to view the values of your program’s member variables.

See Basic Debugging Procedures for additional information on using the features of the integrated debugger.


Handling Java Exceptions

Thanks for using this pre-release version of Visual J++.

This topic will include the following:

  • Discuss first and second chance exception handling

  • Break into the debugger on all exceptions

  • Break into the debugging on specific types of exceptions

See Setting Exception Handling Rules for more information about the elements of the Java Exceptions dialog box.


Debugging a WFC Application

Thanks for using this pre-release version of Visual J++.

If you’ve created a Windows Foundation Classes for Java (WFC) application and noticed peculiar behavior when it runs, these procedures will help you debug your application.

Note The application example for this scenario was built in Creating a WFC Application. If you’d like to create this project to complete the following exercises, do so now.

The application in this scenario accepts a calendar date and converts it to a Julian date. Once the date’s been entered, you’ll set a breakpoint and start debugging the application. You’ll also examine the value of some member variables with the debugger’s windows. Although there may be references to specific code statements in the Julian Date Conversion application, you can substitute code from your application and still find the procedures in this scenario helpful.

After you’ve entered the date you want converted to a Julian date, go to Setting a Breakpoint Before Starting the Debugger to begin the debugging session.

When execution of your application stops on a break point, view current values for your application’s member variables in the Auto, Locals, Watch, and Immediate debug windows. This gives you a snapshot of what’s happening with your program up to the place where it entered break mode.

Now that you’ve had a chance to look at the state of your program up to where it entered break mode, you may want to set another breakpoint, and then continue Stepping Through the Code.

This concludes the scenario for debugging a WFC application. See Basic Debugging Procedures for additional information on using the features of the integrated debugger.


Debugging a WFC Component

Thanks for using this pre-release version of Visual J++.


Debugging a Console Application

Thanks for using this pre-release version of Visual J++.

If you’ve created a Java console application and noticed peculiar behavior when it runs, these procedures will help you debug your application.

Note The application example for this scenario was built in Creating a Console Application. If you’d like to create this project to complete the following exercises, do so now.

The application in this scenario accepts a calendar date passed from the command line and converts it to a Julian date. Once the date’s been entered, you’ll set a breakpoint and start debugging the application. You’ll also examine the value of some member variables with the debug windows. Although there may be references to specific code statements in the Julian Date Conversion application, you can substitute code and member variables from any application and still find the procedures in this scenario helpful.

Running the application requires that a date be entered from the command line before this program runs. The steps in the procedure for Entering Command-line Arguments shows you how to pass this information to the application from the development environment’s Launch tab. After you’ve entered command-line arguments for your program, go to Setting a Breakpoint Before Starting the Debugger to begin the debugging session.

When execution of your application stops on a break point, view current values for your application’s member variables in the Auto, Locals, Watch, and Immediate debug windows. This gives you a snapshot of what’s happening with your program up to the place where it entered break mode.

Now that you’ve had a chance look at the state of your program up to where it entered break mode, you may want to set another breakpoint, and then continue Stepping Through the Code.

This concludes the scenario for debugging a console application using the Julian Date Conversion application. See Basic Debugging Procedures for additional information on using the features of the integrated debugger.


Debugging a Multithreaded Application

A process is a collection of virtual memory space, code, data, and system resources, while a thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each 32-bit application has at least one process and one thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution.

If you have created a multithreaded application or component and noticed peculiar behavior when it runs, you may need to debug the code running on a specific thread to find the source of the problem. The procedures is this scenario are designed to show you how to use the debug Threads window in conjunction with setting breakpoints and viewing information in other debug windows:

If you do not have an application that supports multiple threads and would like to walk through the following procedures, complete the procedures in Multithreaded Beverages Application that create a multithreaded console application.


Multithreaded Beverages Application

The following scenario creates an console application that supports two threads. The application consists of three classes: Class1, Coffee, and Tea. Class1 contains the application’s main()method and code to start two threads — one to run the code for the Coffee class and one for the Tea class.

To create a multithreaded console application

  1. On the File menu, click New Project to display the New Project dialog box.

  2. Expand the folders for Visual J++ Projects and then Applications.

  3. Single-click the Console Application icon.

  4. In the Name text box, type a unique name for your project.

  5. In the Location text box, enter or Browse to the location where you want to save your project.

  6. Click Open and your project appears in Project Explorer.

  7. In Project Explorer, expand your project’s icon and double-click on the Class1.java file.

    Your .java file is now loaded in the Text editor and ready for modifications.

To add the Coffee and Tea classes to Class1.java file

  1. At the end of the file, after Class1’s closing brace, “{“, enter the code found in Coffee and Tea Source Code.

  2. Between the braces of Class1’s main() method, insert the following code:
      Coffee m_Coffee = new Coffee();  //creates Coffee object
      m_Coffee.start();                 //creates thread for Coffee object
      new Tea().start();              //creates Tea object and its thread


Debugging a Multi-Process Application

A process is a collection of virtual memory space, code, data, and system resources, while a thread is code that is to be serially executed within a process. A processor executes threads, not processes, so each 32-bit application has at least one process and one thread. Prior to the introduction of multiple threads of execution, applications were all designed to run on a single thread of execution. Processes communicate with one another through messages, using RPC to pass information between processes. There is no difference to the caller in a call coming from a process on a remote machine, and a call from another process on the same machine.

When you are debugging an application that requires more than one process to run, you may want to watch activity across all processes. The following procedure shows you how to select a different process when your are debugging your application.

To select a process from the Threads debug window

  1. Open the Threads debug window.

  2. From the drop-down list box at the top of the Threads window, select the process you want to observe.

Note

Once you have selected a process to debug see Basic Debugging Procedures for specific procedures for:

  • Displaying the Debug Toolbar

  • Setting Breakpoints

  • Examining Information with Debug Windows

  • Stepping Through the Code

  • Debugging a Multithreaded Application


Debugging a COM Object

Thanks for using this pre-release version of Visual J++.


Debugging a Java Applet

Thanks for using this pre-release version of Visual J++.

Once you have decided how you want to debug your applet, use the following procedures to set up the environment for:

  • Debugging an Applet Running in JVIEW

  • Debugging an Applet Running in Internet Explorer

Once you have started your applet in JVIEW or the Internet Explorer, see Basic Debugging Procedures for specific procedures to follow during your debugging session.


Debugging an Applet Running in JVIEW

Thanks for using this pre-release version of Visual J++.

The environment and your project are now ready for you to continue debugging your applet with the debugger’s windows and general features for setting breakpoints, stepping through code, continuing after an error, and handling exceptions. See the topics in Basic Debugging Procedures and the tables in The Debugging Process for a list of these features and their supporting documentation.


Debugging an Applet Running in Internet Explorer

Thanks for using this pre-release version of Visual J++.

The environment and your project are now ready for you to continue debugging your applet with the debugger’s windows and general features for setting breakpoints, stepping through code, continuing after an error, and handling exceptions. See the topics in Basic Debugging Procedures and the tables in The Debugging Process for a list of these features and their supporting documentation.


Debugging a Server-Side Component

Thanks for using this pre-release version of Visual J++.

Once you’ve created, built, and deployed your server-side component, you may find it doesn’t behave exactly as you expected. This is when you’ll want to debug your project to find the errors in your scripting and Java code. The following scenario takes you through the steps for setting up your environment to enable debugging of your Java server-side component. For more detailed instructions about debugging script, see the Visual InterDev topic, The Script Debugging Process.

Before you can begin to debug a server-side component, make sure you have:

  • Created an .asp page to run your server-side component

  • Microsoft Internet Information Server (IIS) installed on your computer or on a Web server

  • Deployed your component to IIS

  • Internet Explorer (version 4.0 or later)

This scenario uses the project built in Creating a Server-Side Component. However, the following procedures provide information you’ll need to prepare any server-side component for debugging:

  • Configuring Internet Information Server (IIS) for Debugging a Java Server-Side Component

  • Preparing the Environment for Debugging a Java Server-Side Component

  • Starting a Java Server-Side Component Debugging Session


Configuring Internet Information Server (IIS) for Debugging a Java Server-Side Component

Thanks for using this pre-release version of Visual J++.

After you have configured IIS, you'll need to prepare the Visual J++ environment before you can begin to debug your Java server-side component.

Preparing the Environment for Debugging a Java Server-Side Component

Thanks for using this pre-release version of Visual J++.

To prepare the environment for debugging a Java server-side component

  1. On the Tools menu, click Options and highlight the Debugger node in the tree view of the Options dialog box.

    The property page for Debugger options appears.

  2. In the Java and Script sections of this property page, select the option to Attach to running program.

  3. Reboot your machine to enable these options.

  4. Start Internet Explorer and point the browser to your project’s .asp page at the http:// server location where you’ve deployed your Java server-side component.

    The contents of your .asp page appear in the Web browser.

After you have configured IIS and prepared the Visual J++ environment, you are now ready to begin the debugging of your Java server-side component.


Starting a Java Server-Side Component Debugging Session

Thanks for using this pre-release version of Visual J++.

To debug a Java server-side component

  1. Start Visual J++.

  2. On the File menu, click Open Project.

  3. On the Existing tab of the Open Project dialog box, select your server-side component project.

  4. In Project Explorer, expand your project’s node, and double-click your component’s .java file to load it into the Text editor.

  5. On the Debug menu, click Processes to display the Processes dialog box.

  6. In the Processes section of the dialog box, select Microsoft Active Server Pages.

  7. Click Attach.

    This puts your project in run mode and loads the debugger.

  8. From within the Text editor, set a breakpoint within a public method of your component’s class.

  9. From Internet Explorer, set a breakpoint after the script calls the server-side component in your .asp page.

  10. From Internet Explorer, click Refresh.

    The scripting code calls the component and breaks on the line where you’ve set the breakpoint.

The environment and your project are now ready for you to continue debugging your component with the debugger’s windows and general features for setting breakpoints, stepping through code, continuing after an error, and handling exceptions. See the topics in Basic Debugging Procedures and the tables in The Debugging Process for a list of these features and their supporting documentation.


Trouble-Shooting Tips for Debugging an Application

Thanks for using this pre-release version of Visual J++.


Packaging and Deploying Projects

Thanks for using this pre-release version of Visual J++.


Managing Projects with Source Code Control

Thanks for using this pre-release version of Visual J++.


Compiling Applications with JVC

JVC.EXE (JVC) is the Microsoft compiler for Java. By default, the compiler produces (.class) files that run on any Virtual Machine (VM). However, JVC also builds applications optimized for the Windows platform. See Writing Windows-Based Applications with J/Direct for more information about creating Windows applications with Visual J++.

You may select your project’s compiler options on the Compile tab of the project’s Properties dialog box; options may also be typed into the Additional compiler options text box of the same tab. Access the Compile tab from the Project menu’s Properties dialog box. Each of the options on the Compile tab is described in Setting Compiler Options.

For an alphabetic reference of the JVC command-line options, see JVC Command-Line Options. For more information about using JVC to compile your Java programs, see:

  • Description of JVC Syntax

  • Compiling with JVC.EXE


Description of JVC Syntax

The JVC.EXE (JVC) command line uses the following syntax:

JVC [options] <filename>

The following table describes input to the JVC command.

Entry | Meaning
option One or more JVC options. See Setting a Project’s Build Options and JVC Command-Line Options for more information.

Note All options apply to all specified source files.
filename | The name of one or more source files. For more information about valid filenames, see Filename Syntax below.

You can specify any number of options and filenames, as long as the number of characters on the command line does not exceed 1024 or the limit dictated by the operating system.

Note There is no guarantee that future releases of Microsoft Windows NT (version 4.0 and later) and Microsoft Windows 95 will have the same input limit of 1024 characters for the command line.

Any options you wish to pass to JVC must be supplied before the name of the .java file(s).

Filename Syntax

JVC recognizes the following filename syntax:

  • JVC accepts files with names that follow FAT or NTFS naming conventions.

  • Any filename can include a full or partial path.

    A full path includes a drive name and one or more directory names. JVC accepts filenames separated either by backslashes (\) or forward slashes (/).

    A partial path omits the drive name, which JVC assumes to be the current drive. If you don’t specify a path, JVC assumes the file is in the current directory.

Note If a filename does not have an extension, JVC assumes the extension of .java when it reads the file.


Compiling with JVC.EXE

You can use JVC.EXE (JVC) to compile specified .java source files into .class files that are run by the Virtual Machine (VM) for Java. To check your code for syntax errors only, without producing .class files, use the /nowrite option.

You can specify JVC options on the command line, or in the development environment. If you are compiling your Java project from within the development environment, specify the JVC options you wish to use in the Compile tab’s Additional compiler options. Access the Compile tab from the Project menu’s Settings dialog box.

If you are compiling your Java project from the command line, place the JVC options before the name of the .java file or files on the command line. For more information about using JVC.EXE, see:

  • JVC Command Files

  • CLASSPATH Environment Variable

  • JVC Command-Line Options

  • Conditional Compilation

Order of JVC Options

Command-line options must appear before .java source file names on the JVC.EXE (JVC) command line. JVC reads the command line from left to right processing options in the order it encounters them. Each option applies to all files on the command line. If JVC encounters conflicting options, it uses the rightmost option.


JVC Command Files

A command file, also referred to as a response file, is a text file that contains a list of filenames you would otherwise type on the command line. JVC accepts a command file as an argument on the command line. The command file allows you to compile multiple source files.

The criteria listed below should be followed when using command files:

  • A command file may contain only filenames.

  • A command file must not invoke the JVC command.

  • A command file must not contain any JVC compiler options.

A command file is specified by an “at” sign (@) followed by a filename; the filename can specify an absolute or relative path.


CLASSPATH Environment Variable

The CLASSPATH environment variable specifies the system’s default location for .class files. Java compilers (JVC), application viewers ( JVIEW and WJVIEW), and virtual machines ( Virtual Machine (VM) for Java) use the information stored in the CLASSPATH environment variable when compiling and running Java programs. When compiling from the command line, use the /cp:p and /cp:a to add information to the CLASSPATH environment variable.

Note The option settings for JVC, JVIEW, and WJVIEW apply only to the current compilation and must be entered each time these tools run.

Setting the CLASSPATH environment variable from the command line changes it permanently until the system shuts down. However, the /cp, /cp:p, and /cp:a options of JVC, JVIEW, and WJVIEW can replace or modify the CLASSPATH environment variable when compiling and viewing your Java programs.

Note The directories in the CLASSPATH environment variable are separated by semicolons on a Microsoft Windows system.

The following syntax sets the CLASSPATH environment variable from the command line:

SET CLASSPATH = <path>

CLASSPATH and the Java Package Manager (JPM)

When the VM installs, it registers information about all Java packages with the Java Package Manager (JPM) and enters the following CLASSPATH values into the HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\Classpath registry key:

Windows 95 | C:\WIN95\java\classes\classes.zip; C:\WIN95\java\classes;.;
Window NT | C:\WINNT\java\classes\classes.zip; C:\WINNT\java\classes;.;

When a Java programs runs, the VM searches for .class files by gathering information from the following sources in the order listed:

  1. Command-line provided paths

    Note Use the /cp, /cp:p, and /cp:a options to specify CLASSPATH information when running JVC, JVIEW, and WJVIEW.

  2. The DevClasspath registry key

    Note The DevClasspath registry key allows developers who are working on packages to supercede packages that may be installed in the Java Package Manager’s (JPM) database. With this key, developers can build their packages into a specified directory and JPM’s installed packages will not shadow it. For more information about the Java Package Manager, see Package Manager in the SDK for Java 2.0 at http://www.microsoft.com/java/sdk/20/default.htm.

  3. Java Package Manager (JPM) database

    Note When your program runs from within the Visual J++ development environment, the VM includes the information entered into the Java Packages tab of Settings dialog box when searching for .class files. Access the Java Packages tab from the Project menu’s Settings dialog box. For more information on using the Java Package Manager, see Package Manager in the Microsoft SDK for Java Version 2.0 located at http://www.microsoft.com/java/sdk/20/default.htm.

  4. The TrustedClasspath, TrustedLibsDirectory, Classpath, and LibsDirectory registry keys

  5. The CLASSPATH environment variable


JVC Command-Line Options

This topic is an alphabetic reference to all the JVC command-line options. These options are listed in the following table.

If a command-line option can take one or more arguments, its syntax is shown under a Syntax heading before its description. Click any option in the following table for information on that option.

JVC Options Set from the Command Line

/cp — Set CLASSPATH Option | /g — Generate Debugging Information Option | /nowrite — Compile Only Option | /verbose — Display Compiler Messages Option
/cp:o — Display CLASSPATH Option | /g:l — Generate Line Number Information Option | /O — Enable Optimizations Option | /w — Set Warning Level Option
/cp:p — Prepend CLASSPATH Option | /g:t — Generate Debug Tables Option | /O:I — Inline Methods Optimization Option | /x — Disable Language Extensions Option
/d — Output Directory Option | /nologo — Suppress Copyright Banner | /O:J — Optimize Bytecode Jumps Option | /? — Online Help Option
/D — Define Conditional Compilation Symbol | /nowarn — Suppress Warning Messages | /ref — Recompile Referenced Classes |

All options listed in this table may be typed into the Compile tab’s Additional compiler options text box. Access the Compile tab from the Project menu’s Settings dialog box. These options can also be used typed onto the command line before the source filenames.


/cp -- Set CLASSPATH Option (JVC)

/cp — Set CLASSPATH Option (JVC)

Syntax

/cp classpath

Use the /cp option to set the CLASSPATH information for the current compilation. Using this option specifies the path where the JVC can find system and user-defined classes. The Virtual Machine (VM) for Java uses the CLASSPATH environment variable and the Java Package Manager to find system classes. . For more information on using the Java Package Manager, see Package Manager in the Microsoft SDK for Java Version 2.0 located at http://www.microsoft.com/java/sdk/20/default.htm.

Note The directories in the CLASSPATH environment variable are separated by semicolons on a Microsoft Windows system.

Example

When compiling myClass.java on Windows NT (version 4.0 or later), the class path might be:

JVC /cp x:.;x:\java\classes myClass.java

In this example JVC searches in and beneath the current directory and the x:\java\classes directory for system and user-defined classes.


/cp:o -- Display CLASSPATH Option (JVC)

/cp:o — Display CLASSPATH Option (JVC)

This option prints the class path to standard output. This option is especially useful for troubleshooting errors, such as “class not found,” when compiling from the command line.

Example

The following example prints the class path to the screen:

JVC /cp:o


/cp:p -- Prepend CLASSPATH Option (JVC)

/cp:p — Prepend CLASSPATH Option (JVC)

Syntax

/cp:p path

This option prepends the information found in the CLASSPATH environment variable and inserts a semicolon between directory paths. When multiple /cp:p options are entered, the paths are concatenated.

Note The CLASSPATH environment variable or the /cp option supply the location of the .class files. For a full description of the CLASSPATH environment variable, see CLASSPATH Environment Variable.

Example

The following command prepends the directory of myproj to the existing class path:

JVC /cp:p myproj

The following commands concatenate the directories, myproj1 and myproj2, and prepends the resulting path to the existing CLASSPATH information:

JVC /cp:p myproj1 /cp:p myproj2


/d -- Output Directory Option (JVC)

/d — Output Directory Option (JVC)

Syntax

/d directory

When compiling .java files, use the /d option to specify an output directory other than the current directory for the .class files. If the directory does not exist, JVC will create it. If this option is not specified, JVC will write the .class files to the directory containing the corresponding .java files.

Example

The following command compiles the myClass.java file into a myClass.class file and writes this file into the classdir directory:

JVC /d c:\classdir myClass.java

CAUTION The Virtual Machine (VM) for Java depends upon specific directory locations for .java classes based on the names of the Java packages that contain the .class files. Using this option could cause execution to fail if the VM can’t find the classes it needs to run a Java program. For an explanation of how the VM searches for .class files, see CLASSPATH Environment Variable.


/g -- Generate Debugging Information Option (JVC)

/g — Generate Debugging Information Option (JVC)

Syntax

/g[-]

The /g option generates all debugging information. No debugging options are set by default. The effect of using the /g option is the same as using the following options together:

Option | Action
/g:l | Generate line number information
/g:t | Generate debug tables

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following command creates a .class file called myClass.class that contains debugging information:

JVC /g myClass.java


/g:l -- Generate Line Number Information Option (JVC)

/g:l — Generate Line Number Information Option (JVC)

Syntax

/g:l[-]

This option generates line numbers that are used when debugging a program. No debugging options are set by default.

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following command instructs JVC to generate line-number information for the resulting myClass.class file:

JVC /g:l myClass.java


/g:t -- Generate Debug Tables Option (JVC)

/g:t — Generate Debug Tables Option (JVC)

Syntax

/g:t[-]

This option generates debug tables that are used when debugging a program. No debugging options are set by default.

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following command instructs JVC to generate debug-table information for the resulting myClass.class file:

JVC /g:t myClass.java


/nowrite -- Compile Only Option (JVC)

/nowrite — Compile Only Option (JVC)

Syntax

/nowrite

The /nowrite option tells JVC to compile a .java file and to suppress the writing of the .class file. This option is useful for checking your source code for syntax errors only, without producing .class files.

Example

The myClass.java file is compiled, errors and warnings are reported, but no corresponding myClass.class file is produced:

JVC /nowrite myClass.java


/O -- Enable Optimizations Option (JVC)

/O — Enable Optimizations Option (JVC)

Syntax

/O

The /O option combines optimizing options to produce a more efficient program. The effect of using this option is the same as using the following options together:

Option | Action
/O:I | Optimize by inlining methods when appropriate.
/O:J | Optimize bytecode jumps. Default optimization setting.

Note To disable any optimization option, use a dash (–) after the option on the command line.

Example

The following command fully optimizes the code for the myClass.class file that is produced:

JVC /O myClass.java


/O:I -- Inline Methods Optimization Option (JVC)

/O:I — Inline Methods Optimization Option (JVC)

Syntax

/O:I

The /O:I option tells the compiler it may inline methods to produce more efficient code. Code that is inlined does not have the overhead associated with a method call. Since there is no mechanism in the Java language to request inlining of methods, use this option when you want the compiler to inline your code.

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following example evaluates the source code in the myClass.java file and inlines methods where possible. The resulting myClass.class file contains the optimized code:

JVC /O:I myClass.java


/O:J -- Optimize Bytecode Jumps Option (JVC)

/O:J — Optimize Bytecode Jumps Option (JVC)

Syntax

/O:J

The /O:J option causes JVC to optimize the bytecode jumps in the compiled .class file. This option tells the compiler to generate code that jumps to another place in the code. This option is the compiler’s default optimization setting.

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following example evaluates the source code in the myClass.java file and optimizes the bytecode jumps to produce more efficient code. The resulting myClass.class file contains the optimized code:

JVC /O:J myClass.java


/verbose -- Display Compiler Messages Option (JVC)

/verbose — Display Compiler Messages Option (JVC)

Syntax

/verbose

This option instructs JVC to display all messages while compiling a file or project. These messages give useful information about the progress of the compilation.


/w -- Set Warning Level Option (JVC)

/w — Set Warning Level Option (JVC)

Syntax

/w0

/w1

/w2

/w3

/w4

/wx

These options control the output of warning messages produced by the compiler. The compiler determines which warnings to display based upon their severity. They affect only source files named on the command line.

Compiler warning message numbers begin with J5. The documentation describes the warnings, indicates each warning’s level, and indicates potential problems (rather than actual coding errors) with statements that may not compile as you intend.

The meaning of these options is as follows:

Option | Description
/w0 | Turns off all warning messages.
/w1 | Displays severe warning messages.
/w2 | Displays a less severe level of warning message than /w1. This is the default warning level setting.
/w3 | Displays a less severe level of warning than /w2, including use of methods with no declared return type, failure to put return statements in methods with non-void return types, and data conversions that would cause loss of data or precision.
/w4 | Displays the least severe level of warning messages.
/wx | Forces warnings to errors. Any warning will cause the compiler to emit an error and fail the compilation. This option can be combined with one of the warning level options above.

For additional information, see Warning Level Options.


/x -- Disable Language Extensions Option (JVC)

/x — Disable Language Extensions Option (JVC)

Syntax

/x[-]

The Visual J++ compiler supports the Java language specification. In addition, it may offer a number of features beyond those required by this specification. These features are available by default, but are not available when the /x option is specified.

Use the /x option if you plan to port your program to other environments. The /x option tells the compiler to treat extended keywords as simple identifiers and to disable the other Microsoft extensions.

Note To disable this option, use a dash (–) after the option on the command line.

Example

The following command ignores any Visual J++ extensions used in the myClass.class file:

JVC /x myClass.java


/? -- Online Help Option (JVC)

/? — Online Help Option (JVC)

Syntax

/?

This option displays a listing of compiler options to standard output.


Viewing Applications with JVIEW

JVIEW.EXE (JVIEW) is a tool used to view Java applications and applets. JVIEW provides console window where your Java programs can run. JVIEW supports both debug and retail versions of your applications and applets.

If your Java project is an application, that is, has a public static void main(String args[]) method, JVIEW will run the application in JVIEW’s console window without additional command-line options. If your Java project is an applet, that is, has an public void init() method, use JVIEW’s /a option.

For an alphabetic reference of the JVIEW options see JVIEW Command-Line Options.

For more information about using JVIEW to view your Java window-based programs, see:

  • Description of JVIEW Syntax

  • Running JVIEW.EXE


Description of JVIEW Syntax

The JVIEW.EXE (JVIEW) command line uses the following syntax:

JVIEW [options] <classname> [arguments]

The following table describes input to the JVIEW command.

Entry | Meaning
Options | One or more JVIEW options JVIEW Command-Line Options for more information.
Classname | The name of the class to execute. Do not include the .class extension of this filename. For example, use HelloWorldApp and not HelloWorldApp.class. Note You may also specify a fully-qualified class name, without the .class extension, such as, C:\My Documents\Visual Studio Projects\HelloWorldApp\ HelloWorldApp.
Arguments | Command-line arguments to be passed to the class identified by classname.

Note Any options that you wish to supply to JVIEW must be supplied before the name of the .class file or they will be interpreted as command-line arguments to the . class file.


Running JVIEW.EXE

You can specify JVIEW.EXE (JVIEW) options on the command line or in the development environment. By default, Visual J++ chooses WJVIEW as its application and applet viewer. Within Visual J++, to run JVIEW without specifying additional command-line options, select the Launch as a console application check box in the Default group box of the Launch tab. Access the Launch tab from the Project menu’s Settings dialog box.

You can pass more than the default options to JVEIW if you are running your program from the command line or from within the development environment.

To pass more than the default options to JVIEW from within Visual J++:

  1. From the Project menu, select Settings.

  2. From the Launch tab on the Settings dialog box, select the Other executables group box.

  3. Type JVIEW.EXE in the Other executables group’s Program text box.

  4. Type the JVIEW options for your program into the Other executables group’s Arguments text box.

When you run JVIEW from the command line, enter the options you wish to pass to JVIEW before the name of your class file(s) on the command line. See JVIEW Command-Line Options for details about specific options.


JVIEW Command-Line Options

This section is an alphabetic reference of the JVIEW command-line options. These options are listed in the following table.

If a command-line option can take one or more arguments, its syntax is shown under a Syntax heading before its description. Click any option in the following table for information on that option.

JVIEW Command-line Options

/a — Applet Viewer Option | /cp:p — Prepend CLASSPATH Option | /v — Class Verification Option
/cp — Set CLASSPATH Option | /d: — System Property Option | /? — Online Help Option
/cp:a — Append CLASSPATH Option | /p — Pause Viewer Option |

See Running JVIEW.EXE for information on how to specify these options from within the development environment or on the command line.


/a -- Applet Viewer Option (JVIEW/WJVIEW)

/a — Applet Viewer Option (JVIEW/WJVIEW)

Use the /a option to invoke an applet viewer — a browserless environment for viewing applets. Applets that are run within the applet viewer behave in the same manner as those hosted within a browser, including loading, sound, and security. The applet viewer accepts applet parameters and class names, in addition to URLs and HTML filenames.

The /a option directs JVIEW or WJVIEW to run an applet and requires your Java project to have an public void init() method. If your Java project has a public static void main(String args[]) method, use JVIEW or WJVIEW without the /a option to run it as an application. For more information, see Applets and Applications.

Note When the /a option is used, any remaining command-line tokens become parameters for the applet viewer.

Example

The following command-line statements run the HelloWorld applet in an applet viewer for JVIEW or WJVIEW, respectively:

JVIEW /a HelloWorld

-or-

WJVIEW /a HelloWorld

You can load an applet either by using an HTML file to specify parameters, or by loading parameters directly from the command line. The following example shows how to load the HelloWorld applet from an HTML source file with the applet tag:

<applet code=MyApplet.class width=100 height=200>
               <param name=SomeName value=SomeValue></applet>

The same HelloWorld applet can run in JVIEW or WJVIEW with the following command-line information:

JVIEW /a width=100 height=200 SomeName=SomeValue HelloWorld

-or-

WJVIEW /a width=100 height=200 SomeName=SomeValue HelloWorld

The following examples show how to run more than one applet at a time from the command line:

JVIEW /a width=200 height=400 HelloWorld height=300 SpinningWorld

-or-

WJVIEW /a width=200 height=400 HelloWorld height=300 SpinningWorld

The results of the previous commands display the HelloWorld applet in a 200 x 400 frame and the SpinningWorld applet in a 200 x 300 frame.

Note If no height and width are specified, the applets’s default size is one-third the size of the screen.

Any parameter, including HTML files, will be loaded from directory and .zip file locations specified by CLASSPATH information and the Java Package Manager (JPM) database. For example:

JVIEW /a /cp \src\bvt\HelloWorld.html

-or-

WJVIEW /a /cp \src\bvt\HelloWorld.html


/cp -- Set CLASSPATH Option (JVIEW/WJVIEW)

/cp — Set CLASSPATH Option (JVIEW/WJVIEW)

Syntax

/cp classpath

Use the /cp option to set the CLASSPATH environment variable for the current compilation. Using this option specifies the path where JVIEW and WJVIEW can find system and user-defined .class files. The Virtual Machine (VM) for Java uses a platform-dependent default location, the CLASSPATH Environment Variable, and the Java Package Manager (JPM) database to find system classes. For more information on using the Java Package Manager, see Package Manager in the Microsoft SDK for Java Version 2.0 located at http://www.microsoft.com/java/sdk/20/default.htm.

Note The directories in the CLASSPATH environment variable are separated by semicolons on a Microsoft Windows system.

Example

On Windows NT, the following commands provide CLASSPATH information for JVIEW and WJVIEW:

JVIEW /cp X:.;X:\WINNT\java\classes\classes.zip;X:\WINNT\java\classes\

-or-

WJVIEW /cp X:.;X:\WINNT\java\classes\classes.zip;X:\WINNT\java\classes\

In this example JVIEW and WJVIEW search in and beneath the current directory and the x:\java\classes directory for system and user-defined classes.

Note In the previous examples, X: designates the drive letter where the class or .zip files reside.


/cp:a -- Append CLASSPATH Option (JVIEW/WJVIEW)

/cp:a — Append CLASSPATH Option (JVIEW/WJVIEW)

Syntax

/cp:a path

The /cp:a option appends the path entered to the end of the CLASSPATH information and inserts a semicolon between the directories. When multiple /cp:a options are entered, the paths are concatenated.

Note The CLASSPATH environment variable or the /cp option supply the location of the .class file and .zip file directories. The Virtual Machine (VM) for Java uses a platform-dependent default location, the CLASSPATH Environment Variable, and the Java Package Manager (JPM) database to find system classes. See the documentation for the Java Package Manager in the SDK for Java 2.0 for more information about working with the JPM.

Example

The following commands append the directory of myproj to the existing CLASSPATH information:

JVIEW /cp:a myproj

-or-

WJVIEW /cp:a myproj

The following commands concatenate the directories, myproj1 and myproj2, and append the resulting path to the existing CLASSPATH information:

JVIEW /cp:a myproj1 /cp:a myproj2

-or-

WJVIEW /cp:a myproj1 /cp:a myproj2


/cp:p -- Prepend CLASSPATH Option (JVIEW/WJVIEW)

/cp:p — Prepend CLASSPATH Option (JVIEW/WJVIEW)

Syntax

/cp:p path

The /cp:p option prepends the path entered to the beginning of the CLASSPATH information and inserts a semicolon between the directories. When multiple /cp:p options are entered, the paths are concatenated.

Note The CLASSPATH environment variable or the /cp option supply the location of the .class file and .zip file directories. The Virtual Machine (VM) for Java uses a platform-dependent default location, the CLASSPATH Environment Variable, and the Java Package Manager (JPM) database to find system classes. For more information on using the Java Package Manager, see Package Manager in the Microsoft SDK for Java Version 2.0 located at http://www.microsoft.com/java/sdk/20/default.htm.

Example

The following commands prepend the directory of myproj to the existing CLASSPATH information:

JVIEW /cp:p myproj

-or-

WJVIEW /cp:p myproj

The following commands concatenate the directories, myproj1 and myproj2, and prepend the resulting path to the existing CLASSPATH information:

JVIEW /cp:p myproj1 /cp:p myproj2

-or-

WJVIEW /cp:p myproj1 /cp:p myproj2


/d: -- System Property Option (JVIEW/WJVIEW)

/d: — System Property Option (JVIEW/WJVIEW)

Syntax

/d:property=string value

Use the /d: option to set a system property for a Java program. Java programs can read system properties by using the Java.lang.System.getProperties methods. See these methods’ documentation for descriptions of system properties.

Example

The following commands set the user.dir property to some arbitrary value:

JVIEW /d:user.dir=c:\java\test HelloWorld.

-or-

WJVIEW /d:user.dir=c:\java\test HelloWorld.

You can also set user-defined properties. The following commands set the property called “myprop”:

JVIEW /d:myprop=12 HelloWorld

-or-

WJVIEW /d:myprop=12 HelloWorld


/p -- Pause Viewer Option (JVIEW/WJVIEW)

/p — Pause Viewer Option (JVIEW/WJVIEW)

The /p option to forces JVIEW and WJVIEW to pause before exiting if an error occurs. You can use this command-line option to determine the user interface state just prior to the error when debugging an application.

Example

Use the following commands to pause before exiting JVIEW or WJVIEW if an error occurs in the HelloWorld application:

JVIEW /p HelloWorld

-or-

WJVIEW /p HelloWorld


/v -- Class Verification Option (JVIEW/WJVIEW)

/v — Class Verification Option (JVIEW/WJVIEW)

The /v option causes JVIEW and WJVIEW to verify all invoked methods. Without this option, only methods from untrusted loaders are verified. Verification is a process applied to the bytecode loaded from the .class files to ensure that it does not pose a security threat. Verification enforces this so that if one of your .class files attempts to do anything that violates the security model, that file is rejected.

Note On Microsoft’s Virtual Machine (VM) for Java only a subset of the total functionality of this option is possible with the bytecode language for .class files that are loaded remotely.

For performance reasons, the local system classes are not normally verified. The /v option forces the verifier to process these files. You can use this option to ensure that a set of .class files will pass the verifier.

Example

Use the following JVIEW or WJVIEW command to insure the .class files of the SpinningWorld application do not pose a security problem:

JVIEW /v SpinningWorld

-or-

WJVIEW /v SpinningWorld


/? -- Online Help Option (JVIEW/WJVIEW)

/? — Online Help Option (JVIEW/WJVIEW)

Syntax

/?

This option displays a listing of command-line options for JVIEW and WJVIEW.

Example

Use the following commands to display online help for JVIEW or WJVIEW, respectively:

JVIEW /?

-or-

WJVIEW /?


Viewing Applications with WJVIEW

WJVIEW.EXE (WJVIEW) is a tool used to view window-based Java applications from the command line. Unlike JVIEW, WJVIEW spawns a separate window process. WJVIEW provides an environment where your window-based programs can run and supports both debug and retail versions of your applications.

Note Use WJVIEW to run window-based Java applications. WJVIEW has the same functionality and command-line options as JVIEW. WJVIEW runs your window-based Java application in a separate graphical user interface (GUI) process and does not use or require a console window. Consequently, do not use WJVIEW for Java applications that require output to or input from the console window.

For an alphabetic reference to the WJVIEW options, see WJVIEW Command-Line Options.

For more information about using WJVIEW to view your Java window-based programs, see:

  • Description of WJVIEW Syntax

  • Running WJVIEW.EXE


Description of WJVIEW Syntax

The WJVIEW.EXE (WJVIEW) command line uses the following syntax:

WJVIEW [options] <classname> [arguments]

The following table describes input to the WJVIEW command.

Entry | Meaning
Options | One or more WJVIEW options. See WJVIEW Command-Line Options for more information.
Classname | The name of the class to execute. Do not include the .class extension of this filename. For example, use HelloWorldApp and not HelloWorldApp.class. Note You may also specify a fully-qualified class name, without the .class extension, such as, C:\My Documents\Visual Studio Projects\HelloWorldApp\ HelloWorldApp.
Arguments | Command-line arguments to be passed to the class identified by classname.

Note Any options that you wish to supply to WJVIEW must be supplied before the name of the class file or they will be interpreted as command-line arguments to the class file.


Running WJVIEW.EXE

You can specify WJVIEW.EXE (WJVIEW) options on the command line or in the development environment. By default, Visual J++ chooses WJVIEW as its application and applet viewer.

You can pass more than the default options to WJVEIW if you are running your program from the command line or from within the development environment.

To pass more than the default options to WJVIEW from within Visual J++:

  1. From the Project menu, select Settings.

  2. From the Launch tab on the Settings dialog box, select the Other executables group box.

  3. Type WJVIEW.EXE in the Other executables group’s Program text box.

  4. Type the WJVIEW options for your program into the Other executables group’s Arguments text box.

When you run WJVIEW from the command line, enter the options you wish to supply to WJVIEW before the name of your class file on the command line. See WJVIEW Command-Line Options for details about specific options.


WJVIEW Command-Line Options

This section is an alphabetic reference to the WJVIEW command-line options. These options are listed in the following table.

If a command-line option can take one or more arguments, its syntax is shown under a Syntax heading before its description. Click any option in the following table for information on the option.

WJVIEW Command-line Options

/a — Applet Viewer Option | /cp:p — Prepend CLASSPATH Option | /v — Class Verification Option
/cp — Set CLASSPATH Option | /d: — System Property Option | /? — Online Help Option
/cp:a — Append CLASSPATH Option | /p — Pause Viewer Option |

See Running WJVIEW.EXE for information on how to specify these options from within the development environment or on the command line.


Programmer's Guide

The Visual J++ Programmer’s Guide contains the following topics:

  • Introduction to WFC Programming Provides an overview of the Windows Foundation Classes for Java (WFC).

  • WFC Fundamental Programming Concepts

  • Programming Dynamic HTML in Java Explains how WFC supports Dynamic HTML.

  • Data Binding in WFC Explains how WFC supports data binding.

  • Overview of WFC Controls

  • Windows Graphical Services

  • Working with ActiveX Controls

  • Authoring WFC Controls

  • Creating Localizable Applications

  • Writing Windows-Based Applications with J/Direct Explains how to access Win32 API functions with J/Direct, including how to use the J/Direct Call Builder. Also discusses security issues and error messages, and provides several troubleshooting tips.

  • Advanced Windows Programming Techniques

  • Integrating Java and COM

  • Writing High-Performance Java Code

  • Visual J++ Extensibility Overview Describes the extensibility object model for extending the development environment.


Introduction to WFC Programming

Windows Foundation Classes for Java (WFC) is a set of class libraries combined with a Rapid Access Development (RAD) tool that makes it easy to build fast and powerful applications and components for the Microsoft platform using the Java language. WFC brings the Java language to the Win32 platform and the Dynamic HTML (DHTML) object model of Internet Explorer 4.0. This means you can use Java to solve real problems today and know that you have a smooth migration path into the future.

A goal of WFC is to provide complete and compelling component and programming models for Java. Because Java provides a unique set of advantages in terms of language features, it is the first language of choice for developing Windows and DHTML applications using this new programming model.

WFC enables developers to quickly build rich Win32 applications and ActiveX controls in Java by using the Visual J++ Designer to drag and drop controls onto a form, set properties, and generate event handlers. Developers can also easily access data on a server from their applications and deploy their applications as Windows .EXE files or Internet URLs. Moreover, they can build their own WFC components by using the designer or writing code directly in the editor. Finally, developers can access the DHTML object model using Java classes.

The rich application model takes advantage of the J/Direct technology to access the Win32 API. However, it makes it much easier to program by taking care of details like Window message-handling procedures, message pumps, messages, window handles, and so forth. The application model is open, so experienced Win32 programmers can intermix J/Direct calls with WFC classes to add any functionality available on the Win32 platform.

If you are looking for a quick “hands-on” introduction to using Visual J++ to develop a WFC application, take a few minutes and walk through the test drive, Creating an Application with WFC Controls. This tutorial steps you through building and running a simple WFC application.

To view the WFC API reference, see Windows Foundation Classes for Java.


Getting Started with Controls and Templates

One of the strengths of the WFC component model is that the Visual J++ development environment provides most of the components, forms, menus, and dialog boxes that you typically need. These components can either be extended for your own needs or you canauthor your own controls. Because Visual J++ provides controls typically used in the Win32 environment, you’ll feel at home with the visual components available from the Visual J++ design environment.

Because the Visual J++ development environment is tightly integrated with the WFC classes, most of what you need to know to get started using controls, forms, and menus can be found in the section of the documentation on using Visual J++. For help using Visual J++ to create the visual components of your application, see the following topics:

  • Creating and Building Projects

  • Designing Forms

  • Editing Code


Starting with a Form

Most windows are represented in WFC programming as forms. A form is used wherever you want a separate overlapping, graphical component, such as a main application window or dialog box. Forms act as containers for controls, allowing you to visually composes applications. Forms have their own properties, which can be set in the Properties dialog box. Syntactically, a form is a Java class derived from the Form class. The Form class extends the Control class, as do the controls that you place on a form.

When you create a new project, and then choose Windows Application, a form is automatically created for you. You can add other forms by choosing either Add Item or Add Form from the Project menu.

Once a form is added to your project, the form can be viewed either in the design mode or in the code editor. You can use the Designer to size it and set properties by choosing View Designer from the shortcut menu of the form in Project Explorer. Each form belongs to a nonvisual Application object that contains the main thread of the application. Forms and controls represent the visual Windows components. This is handled completely by the framework of WFC.

When you open the code editor on the a new form, you'll see the template-based class created for you that contains the necessary syntax of the form class, including a constructor and a main() method with code that instantiates your form. When you work in design mode, adding controls, setting properties, and so forth, the Designer inserts and modifies a section of this class (this area is delineated in the code editor and should not be edited by hand).

For information on creating a form see Designing Forms.


Adding Controls

Controls are added by dragging them from the Toolbox onto the form, sizing them, and setting their properties in the Property dialog box. You can drag and drop both ActiveX and WFC controls onto your forms in Visual J++. For details about adding controls to a form, see Adding Components to a Form.

WFC controls can be grouped into three categories:

  • Intrinsic controls. The basic Windows controls such as buttons, check boxes, edit boxes, list boxes, and so on.

  • Common controls. The Win32 common controls found in comctl32.dll. These include controls such as animations, toolbars, tabs, status bars, and Tree view controls, to name a few.

  • WFC controls. Custom controls written specifically for the WFC framework.

All existing WFC controls are Java classes found in the package wfc.ui. For a reference of all of the packages and classes in WFC, see the Windows Foundation Classes for Java.

If you want, you can create your own controls using the WFC packages, either by extending existing controls or writing your own from scratch, and add them to the Toolbox. The WFC component model makes it easy to expose information about your control's properties and events, enabling your control to work seemlessly with the Visual J++ Designer. See Managing the Toolbox to learn how to add your own controls to the toolbox.


Adding Menus

Although technically not controls, menus are added in a manner similar to controls. To add a menu, you drag the MainMenu control from the Toolbox onto the form. Once the menu is enabled on the form, the menu designer lets you add submenus and menu items by simply typing them in. Each menu item has an event handler that can be hooked up in the coding phase of development. And, as with controls, all implementation code for the menus and menu items is created automatically for you as you visually create the menu. To learn how to add menus and work with the menu editor, see Creating Menus.

For more information on handling menu item click events, see Adding Code.


Adding Code

The form and menu designers help you to create your initial form class from the design environment and even provide much of the skeleton code for things like event handlers. However, at some point you need to actually write code to make your application do what you want it to.

Event handler methods are called when an event is triggered from a user-interface element on the form, such as a mouse click on a control. The Designer creates skeleton code for these, so it's mostly a matter of filling in the code you want run when the event occurs. For other events, the WFC component model employs a new delegate keyword in the Visual J++ compiler that lets you map event handlers to custom events and provide event handlers for any controls that you write yourself.

In addition to controls and event handlers, there are many other parts of the WFC library that you will find useful.

  • Graphics support. Several classes in the wfc.ui package, including the Graphics class, provide support for accessing Windows graphical services.

  • Dynamic HTML support. The wfc.html package provides an extensive set of classes that provide access to the DHTML object model implemented by Internet Explorer (versions 4.0 and later). For an overview of the classes in the wfc.html, see Programming Dynamic HTML in Java. For reference information on this package, see Windows Foundation Classes for Java.

  • Data binding support. WFC is designed to use the ActiveX Data Objects (ADO) components to support both simple and complex data binding. Using the DataBinder component, you can bind a field from a recordset to the property of any WFC component. WFC also provides other complex-bound components that interact directly with a recordset. For more information, see Data Binding in WFC.

  • Localization support. WFC provides several classes in the wfc.ui package that make localizing your code much easier by letting you to store your resource elements, such as strings, in a resource file and accessing them by resource identifiers. This greatly simplifies the job of translating user interfaces for multiple languages.

  • Direct Win32 API support. The J/Direct technology provided with Visual J++ enables you to call any dynamic-link library (DLL) from your Java code. WFC is built upon a layer of J/Direct calls to Win32 libraries (implemented in the wfc.Win32 and wfc.OLE32 packages). Consequently, if you are comfortable with standard Windows programming and want to access those libraries directly, WFC provides the underlying elements (such as device contexts and window handles) to give you ultimate control. While this may be desirable for some specialized applications, most programmers will find the basic services of WFC sufficient. (For information on using J/Direct to access the Win32 API, see Writing Windows-Based Applications with J/Direct).

For more information on the WFC component model and many of the features of WFC, see the Visual J++ readme file (ReadMeVJ.htm).


Debugging Your Application

Thanks for using this prerelease version of Visual J++.


Deploying Your Application

Thanks for using this prerelease version of Visual J++.


A WFC Example Application

For a walkthrough of a WFC example application, see the Visual J++ readme file (ReadMeVJ.htm).


WFC Fundamental Programming Concepts

Thanks for using this pre-release version of Visual J++.


Programming Dynamic HTML in Java

With Microsoft Internet Explorer 4.0, Microsoft introduced its implementation of a revolutionary HTML object model that allows content providers to effectively manipulate HTML properties on the fly. Until now, this object model has mostly been accessed using script technology. The wfc.html package of the Windows Foundation Classes for Java framework now lets you access the power of Dynamic HTML (DHTML) on a Web page directly from a Java class.

The following topics are covered in this section:

  • Introduction to the wfc.html Package

  • Elements

  • Containers

  • Events

  • Styles

  • Tables

  • Using the HTML Package on the Server


Quick Start

To help you get up and running using the wfc.html package to implement Java and DHTML, here is a thumbnail sketch of the steps you might perform to write a simple DHTML sample. While this is by no means the entire story, it should help set the stage before reading the rest of this topic or jumping into the samples. There are seven basic steps when creating a Java applet that uses the HTML package:

  1. Derive your own class from the DhModule class.

  2. Override the DhModule.documentLoad() method, and implement steps 3, 4, 5, and 6 in that method.

  3. Obtain a reference to the current document by calling getDocument().

  4. Create some elements (such as DhButton) or use findElement to access existing elements in the document.

  5. Hook an event handler into one of your elements.

  6. Add the elements to the document using the DhDocument.add() method.

  7. Write the event handler method you hooked up in step 5.

Your code should look something like this:

    // Step 1: Derive from DhModule
    public class MyClass extends DhModule
    {
        // Step 2: override the loader method
        public void documentLoad(Object sender, DhEvent p)
        {
            // Step 3: get a document
            DhDocument doc = getDocument();

            // Step 4: create an element
            DhButton button1 = new DhButton("Say hello");

            // Step 5: wire in an event handler
            button1.addOnClick( new DhEventHandler(this.onButton1Click) );

            // Step 6: add it to the document
            doc.add(button1);
        }

        // Step 7: Actually implement the event handler
        public void onButton1Click( Object sender, DhEvent e )
        {
           DhDocument doc = getDocument();
           DhText t = new DhText("Hello!");
           doc.newLine();
           doc.add(t);
        }
    }

The Java portion of the exercise is done. Now you actually write the HTML. Thanks to the advent of Java URL moniker support in Internet Explorer 4.0 (which recognizes classid=java:classname ) this step is easy. Make sure your HTML includes the following syntax (substitute “MyClass” with the name of your class if it’s different from the above example):

    <HTML><BODY>
    <OBJECT classid="java:MyClass" HEIGHT=0 WIDTH=0></OBJECT>
    </HTML></BODY>

Open Internet Explorer 4.0, point it at your HTML file, and you can see your application run.


The DhElement Class

Elements are objects derived from DhElement, which is the superclass of all user interface elements in the wfc.html package. There is a certain consistency you can count on when using any object derived from DhElement:

  • Every element has an empty constructor. This means you can instantiate any element with simply a new and then set properties, hook event handlers, and call methods in a very consistent way.

  • Elements are stateless. In other words, setting properties or calling methods always works and is not conditional on some external state or circumstance.

  • Every container has an add() method that takes the type-safe element that is appropriate for it.

  • In the browser environment, an element does not become visible to the end-user until you add it (or the topmost container element in its parentage) to the document. However, this is merely an artifact and not part of the programming model. You don't have to change the way you program to elements as they work the same way whether they are live or not.

If an element is already on the page when the documentLoad() method is called, then you can call the document's findElement() method and start programming to that element. The searching routine used by findElement assumes that the element you are looking to find has an ID attribute set to a particular name. You can also enumerate all the elements in the document until you find the one you are interested in.


Working with Containers

Containers are elements that can hold other elements. A basic example is the <DIV> element, which can contain any other HTML item. More complex examples include table cells, one-dimensional (1D) and two-dimensional (2D) regions, and, of course, the document itself. In most cases, containers can be arbitrarily nested, such as having a 2D region inside a 1D region inside a 1D region.

Containers are like other elements. They are created with a new statement, and many can be positioned and sized on the page. When you have a 2D region, known as a DhPanel in this library, you can position and size elements within it and set up their z-order relationships. One of the powerful features of DHTML is that you can then change any of these attributes in your code. You can also create regular 1D regions using the DhSection object. A DhSection represents an area in which regular 1D HTML layout rules are followed (that is, inline flow within the area). In addition, the area can be sized and positioned within a page or another container.

Once you have created a container element, you can add elements to it using the add() method. This mechanism follows the regular pattern of parent-child relationships: the elements, which can also be other containers, added to the container become its children. None is actually attached to the document until the topmost container, which is not a part of any other container, is added to the document.

You can position and size a container using its SetBounds() method. If the container is a 2D container, you can size and position any elements you place within it using the element’s SetBounds() methods.

For example, to create a 2D container, type:

    DhPanel myPanel = new DhPanel();

You can then set various attributes on the panel, including the ToolTip that is shown when the mouse hovers over the panel:

   myPanel.setToolTip("This text appears when the mouse hovers");
   myPanel.setFont("Arial", 10);
   myPanel.setBackgroundColor(Color.RED);
   myPanel.setBounds(5, 5, 100, 100);

Finally, you can add the panel you've just created to the document in the usual way:

   document.add(myPanel);

When adding elements to the panel, you can specify where they go in the z-order using one of a set of constants provided by the wfc.html package. Elements are added with a default size and position. Therefore, you should always call setBounds() on them before adding them to the container.

   DhText myText = new DhText("I'm adding this in 2D space");
   DhText myOtherText = new DhText("This, too!");
   myText.setBounds(10, 10, 50, 50);
   myOtherText.setBounds(10, 15, 50, 50);
   myPanel.add(myText, null, DhInsertEnum.INSERT_BEGINNING);
   myPanel.add(myOtherText, myText, DhInsertEnum.INSERT_BEFORE);

You can also use the setZIndex() method after the elements are added to move the elements around in the z-order. For example, the following syntax does not explicitly set a z-order on the added element but uses the default z-order (that is, on top of all other elements):

   myPanel.add(myText);

You can set this explicitly as follows, where num is an integer representing the relative z-order of the element within its container:

   myText.setZIndex(num);

The element with the lowest number is at the bottom of the z-order (that is, everything else covers it). The element with the highest number is at the top (that is, it covers everything else).


Handling Events

Many elements in a DHTML program can fire events. A button is the obvious example. For example, one of the actions you'd probably like to know about in your code is when the person viewing a page clicks a button. And you'll also want to know which button was clicked. Here's how:

   DhButton myButton = new DhButton();
   .
   .
   .
   document.add(myButton);
   myButton.addOnClick(new DhEventHandler(this.myButtonClick));
   .
   .
   .
   void myButtonClick(Object sender, DhEvent e)
   {
      myButton.setText("I've been clicked");
   }

This code says that, for the button called myButton, call myButtonClick whenever the button fires the OnClick event (that is, when it is clicked). The code inside the myButtonClick() event handler does very little in this example. It just sets the caption on the button to some new text.

Events are fired all the way up a containment tree; this means that the OnClick event can equally be seen by the button's container as by the button itself. Although typically programmers handle events in the container closest to the event, this event bubbling model can be useful in special cases, giving the programmer the flexibility to decide the best place to code the event handlers.

Many different events can be fired by elements in DHTML, and you can catch them all in the same way. For example, to catch the OnMouseOver event on a button:

    DhButton myButton = new DhButton();
    .
    .
    .
    document.add(myButton);
    myButton.addOnMouseOver(new DhEventHandler(this.myButtonMouseOver));
    .
    .
    .
    void myButtonMouseOver(Object sender, DhEvent e)
    {
        myButton.setText("I can feel that mouse");
    }

All the events that can be fired (and caught) are defined in the DhEvents class.


Dynamic Styles

You can think of a style object as a freestanding collection of properties. The term style is borrowed from the word processing world where the editing of a style sheet is independent of the documents to which you apply it. The same is true for using and applying style objects in this library.

As an example, consider that your boss tells you that the new corporate color is red and you need to change the color of elements of your HTML pages. You can, of course, set properties directly on elements if you like, which is the traditional model of GUI framework programming:

       // old way of doing things...
       DhText t1 = new DhText();
       DhText t2 = new DhText();
       t1.setColor( DhColors.RED );
       t1.setFont( "arial", 10 );
       t2.setColor( Color.RED );
       t2.setFont( "arial", 10 );

You might be drawn toward using derivation to save yourself some time. For example, you might consider improving this with some code like the following:

       // old way of doing things a little better...
       public class MyText extends DhText
       {
          public MyText()
          {
              setColor( Color.RED );
              setFont( "arial", 10 );
          }

This works fine until you decide you also want those settings for buttons, labels, tabs, documents, panels, and so on. And you’ll find yourself with even more work when you want to apply these to another part of your program or to another program.

The answer to this problem is a style object. While using this library, you can at any point instantiate a style object and set its properties:

       // STEP 1: Create style objects.

       DhStyle myStyle = new DhStyle();

       // STEP 2: Set properties on style objects

       myStyle.setColor( Color.RED );
       myStyle.setFont( "arial", 10 );

Then, at any other time in the code, you can apply that style to any number of elements:

       DhText t1 = new DhText();
       DhText t2 = new DhText();

       // STEP 3: Apply styles using the setStyle method.

       t1.setStyle( myStyle );
       t2.setStyle( myStyle );

When it's time to keep up with the dynamic nature of high-level policy setting at your corporation, the following line will set all instances of all elements with myStyle set on them to change color:

       myStyle.setColor( Color.BLUE );

Here is the really powerful part: all this is available during runtime. Every time you make a change to the style object, the DHTML runtime will dynamically reach back and update all elements to which that style object is applied.

For more information, see:

  • Style Inheritance


Style Inheritance

It is worth noting how the HTML rendering engine determines what to use if conflicting styles are set on any given element. For example, take the case of color:

If an element has the color property set directly on it (DhElement.setColor), then the color defined by the color property is used. Otherwise, if an element has a style object on it (DhElement.setStyle) and that object has the color property set, then that value is used. Failing to find a color or a style, the same process is used with the element's container (DhElement.getParent), and failing that, with the container of that container and so on. The process continues up to the document. If the document doesn't have a color property set on it anywhere, the environment (either browser settings or some other environment settings) determine the color to use.

This process is called cascading styles because the properties cascade down the containment hierarchy.


Dynamic Tables

Working with tables is actually no different from any other part of the library; the principles and programming model apply to tables as they do to any other type of element. A table, however, is such a powerful and popular element that it is worth discussing.

To use a table you create a DhTable object, add DhRow objects to that and then add DhCell objects to the rows. Here are the rules regarding table usage:

  • You can add only DhRow objects to a DhTable object.

  • You can add only DhCell objects to a DhRow object.

  • You can add any kind of element to a DhCell object.

While this may seem restrictive, you can easily do a simplistic container that emulates a gridbag with the following code:

        import com.ms.wd.html.*;

        public class GridBag extends DhTable
        {
            int   cols;
            int   currCol;
            DhRow currRow;

            public GridBag(int cols)
            {
                this.cols = cols;
                this.currCol = cols;
            }

            public void add(DhElement e)
            {
                if( ++this.currCol >= cols )
                {
                    this.currRow = new DhRow();
                    super.add(currRow);
                    this.currCol = 0;
                }
                DhCell c = new DhCell();
                c.add(e);
                this.currRow.add( c );
            }

        }

One of the most powerful uses of the library is the combination of tables and style objects. This combination allows you to create powerful, well looking, and easy to code custom report generators.


Using the wfc.html Package on a Server

The wfc.html package can also be used on the server to provide a programmatic model for generating HTML and sending it to the client page. Although it is created using the dynamic HTML package, this model is actually static because the server Java class has no interaction with the client document. Instead, the server composes HTML elements and sends them off sequentially to the client. While relatively static in terms of an associated client document, the power of dynamic HTML is still evident on the server. For example, you can apply DhStyle attributes to all parts of some template HTML code and then generate vastly different looking pages by just changing the DhStyle attributes, rather than having to programmatically generate all the individual style changes. Another advantage comes from the fact that you can use the same model for generating dynamic HTML for both client and server applications, thereby making the HTML generation easier to learn and remember.

There are currently two modes of generating HTML on the server. Both use Active Server Pages (ASP) scripting and a class based on the wfc.html classes. The first is the "bare-bones" approach that relies more on the ASP script and does not require registering the class file. The uses registration and is much closer to the model that you use on the client because it places more control inside the class than in the script.

Unregistered Method

This method uses two ASP methods on the server page: getObject() and Response.Write(). The getObject() method is used to instantiate a class based on the WFC wfc.html classes; the Response.Write() method writes the generated HTML string to the client. The wfc.html.DhElement class provides a generateHTML() method that creates the HTML string; this string is then sent to the client page using the ASP Response.Write() method.

For example, say you have a class called MyServer that extends DhSection and incorporates some HTML elements. In your ASP script, you would call getObject("java:MyServer") to create a DHTML object. You can then perform whatever actions you want on the object (for example, setting properties) from your ASP script. When you have finished, you would call the object's generateHTML() method to generate the string and pass that result to the ASP Response.Write()method to send the HTML to the client. The following code fragments show the relevant ASP script and Java code for creating a DhEdit control in HTML and sending it to the client.

ASP SCRIPT

Dim f,x
set f = getObject( "java:dhFactory" )
set x= f.createEdit
x.setText( "I'm an edit!" )
Response.Write( x.generateHTML() )
Response.Write( f.createBreak().generateHTML() )
.
.
.

JAVA CODE

public class dhFactory implements DhColors, DhUnits{
public dhFactory(){ }
public DhBreak createBreak() {
      return new DhBreak(); }
public DhEdit createEdit(){
      return new DhEdit(); }
.
.
.
}

Registered Method

This registered method is slightly more sophisticated and closer to client model. In this method you follow these steps:

  1. Create your server Java class (extending from DhModule).

  2. Override the DhModule documentLoad() method as you would with a client application.

  3. Register the class using the javareg utility. For example, for the MyClass example, type:
    Javareg /register /class:myClass /prodid:MyClass

  4.
Call the ASP  Server.CreateObject() method, passing it the name of your WFC html server class.
    5.

At run time, the framework recognizes that your wfc.html-based class is running on a server and acts accordingly.

Once instantiated, all the sending of HTML is performed when you call the DhModule.write() method in your derived class. The write() method in a server class is similar to the add() method in a client class; however, instead of adding the element to the document, it is sent to the client in a serial stream (in fact, if write() is called from a client class, add() is automatically called).

[NEED SAMPLE CODE HERE]
Besides using the write() method instead of the add() method, there are very few other differences between the interpretation of server and client HTML classes. One important difference, however, is that in a server class, elements, once written (sent to the client), cannot be modified afterwards as they can be on a client document. For example, the DhCantModifyElement exception, which is relevant only for server applications, is thrown after a write() has been performed on an element if an attempt is made to modify that element again. This underscores the fact that there is no real interoperation between the server Java class and the client document as there is on the client between the Java class and the document: from the server's standpoint, once written, the element is essentially gone.

Finally, it should be pointed out that the wfc.html package is still in development and there are features of server Java programming that are still to come. The most important of these is the implementation of a template model of server programming which will allow you to provide an HTML template embedded with attributes that are recognized by wfc.html classes. The server class can then parse the HTML, pull out the HTML that is appropriately tagged, compose it, and send  it to the client.


Data Binding in WFC

To access data from your Java project, you typically use the ActiveX Data Objects (ADO) components, which define the data programming model for WFC applications. The core ADO components include the Connection, Command, and Recordset components.

The Connection component allows you to connect to a database. Once a connection is established, you can query the database to retrieve a set of records. The Recordset component represents the records returned from a query. You can use either an SQL string or a Command component to specify the query.

ADO also provides the DataSource component, which combines the functionality of the Connection, Command, and Recordset components. For information about programming with the ADO components, see the ADO Tutorial (VJ++). The ADO components are defined in the wfc.data and wfc.data.ui packages.

Note The Toolbox in the WFC Designer only provides a DataSource control; the Connection, Command, and Recordset components can only be used in code.

Once a recordset has been retrieved, either through a Recordset component or a DataSource component, you can bind the recordset to a WFC component. WFC supports both simple and complex data binding, described as follows:

Type of Binding | Description
Simple | Refers to the relationship between a field in a recordset and the property of a WFC component. The binding is called simple because the component does not need explicit knowledge about the data protocol or data provider.
Complex | Refers to the direct relationship between a recordset and a WFC component.

Note that the recordset’s cursor and lock types determine whether the data in the recordset dynamically reflects the data in the database, and whether the data in the recordset can be changed.

For more information about ADO, see What’s New in ADO 2.0 and Getting Started with ADO 2.0.


Simple Data Binding

Simple data binding refers to the relationship between a field in a recordset and the property of a WFC component. When a property is bound, data is automatically transferred between the field and the property:

  • If the value of the field changes, the new value is propagated to the property.

  • If a new row in the recordset is navigated to, the current field value is propagated to the property.

  • If the value of the property changes and the component supports a property change notification, the new value is propagated to the field in the recordset. Note that the recordset is immediately updated when the property changes (unlike the Visual Basic simple data binding model, which postpones all property change notifications until a new row is navigated to).

    Note If an attempt is made to update a read-only recordset, the recordset will generate an ADO exception. You can then catch this exception and set the bound property back to its previous value; otherwise, the value of the property and the value of the field will be inconsistent.

Bindable Properties

Simple data binding in WFC is performed by the DataBinder component. This component creates and manages the binding between the field and the property. The DataBinder component can bind any property that is accessible through methods matching the following design patterns:

public <PropertyType> get<PropertyName>()
public void set<PropertyName>(<PropertyType>)

If a property is marked with the NotBindable attribute, then it is not enumerated in the DataBinder component’s design page and cannot be bound within the Designer; however, you can still bind the property programmatically. The NotBindable attribute is specified in the component’s ClassInfo. Typically, the name property is marked as NotBindable.

Note The DataBinder component does not support indexed properties. The DataBinder component will not enumerate indexed properties in its design page, and will generate a Java exception if you attempt to bind an indexed property programmatically.

Property Change Requests and Notifications

The component of a bound property can provide events that signal when a property is about to be changed (a request) and when the property has been changed (a notification):

  • To support a property change request, the component provides a <PropertyName>Changing event. This event is triggered before the property is actually changed, and can be canceled to prevent the change.

  • To support a property change notification, the component provides a <PropertyName>Changed event. This event is triggered after the property has been changed, and causes the associated field in the recordset to be updated with the new value.

    Note By default, no data validation is performed before the recordset is updated. However, you can use the Changing events on the recordset to validate the new property value.


DataBinder Component

ADO defines the DataBinder component to perform simple data binding. This component creates and manages the bindings between the fields in a recordset and the bindable properties of WFC components. For more information about whether a property can be bound, see Bindable Properties.

Although a single DataBinder component can manage multiple bindings, it is associated with only one recordset. To bind the fields of a second recordset, you must use another DataBinder component. Additionally, a DataBinder component can only bind to components that exist on the same design surface as itself; for example, a DataBinder component cannot bind to a component that exists on a different form.

If the component of a bound property supports a change notification for that property, the field in the recordset is automatically updated when the property changes. Note that the DataBinder component provides no mechanism for validating the change made to the property’s value. For more information, see Property Change Requests and Notifications.

Example

The following example shows how to programmatically perform simple data binding with the DataBinder component. Note that the DataBinder component uses an array of DataBinding objects to manage the bindings.

import wfc.data.*;
import wfc.data.ui.*;
import wfc.ui.*;

/* Use the Connection and Recordset components to
   connect to a database and retrieve a recordset. */
Connection c = new Connection();
c.setConnectionString(“dsn=myDSN;uid=myUID;pwd=myPWD”);
c.open();

Recordset rs = new Recordset();
rs.setActiveConnection(c);
rs.setSource(“select * from authors”);
rs.open();

/* Create a DataBinder component. To associate this
   component with rs, set the dataSource property. */
DataBinder db = new DataBinder();
db.setDataSource(rs);

/* Create the components whose properties will be bound. */
Edit edit1 = new Edit();
Edit edit2 = new Edit();

/* Set the DataBinder component’s bindings property to
   an array of DataBinding objects. This array defines
   the bindings between the text property of each Edit
   component and the fields in the recordset. */
db.setBindings(new DataBinding[] {
      new DataBinding(edit1, “text”, “firstName”),
      new DataBinding(edit2, “text”, “lastName”) } );

}

For more information about the DataBinder component’s dataSource property, see Complex Data Binding. For information about using the DataBinder component in the Designer, see Accessing Data.


Complex Data Binding

Complex data binding refers to components that interact directly with a recordset. A complex data-bound component provides dataSource and dataMember properties that identify the recordset it is bound to. Note that the properties of complex bound components can still be simple bound via the DataBinder component.

dataSource and dataMember Properties

The dataSource property identifies an object that implements the IDataSource interface. This object exposes one or more recordsets. The dataMember property then specifies the name of the recordset that is currently bound to the component. For example:

/* Bind the component to the recordset named “Products”,
   which is exposed by the data source, ds. */
dbComponent.setDataSource(ds);
dbComponent.setDataMember(“Products”);

If you do not set the dataMember property, then the data source’s default recordset will be bound. (You can explicitly specify the default recordset by setting the dataMember property to null.)

/* Bind the component to the default recordset
   exposed by the data source, ds. */
dbComponent.setDataSource(ds);
dbComponent.setDataMember(null);  /* This line is optional. */

Note that the Recordset and DataSource components already implement the IDataSource interface. Therefore, you can set the dataSource property directly to one of these components. In this case, you do not have to set the dataMember property:

/* Set the dataSource property directly to the Recordset
   component,rs, without setting the dataMember property. */
dbComponent.setDataSource(rs);

Complex Bound Components in Visual J++

Visual J++ provides the following complex data-bound components:

Component | Description
DataBinder | Binds a field from a recordset to the property of a WFC component. (Although the DataBinder component is used to perform simple binding, the component itself exposes dataSource and dataMember properties.)
DataGrid | Binds multiple fields from a recordset and displays the data in a grid format.
DataNavigator | Allows the user to change the current record in a recordset. Any other component that is bound to the same recordset is then updated to reflect the new current row.

For information about using these components in the Designer, see Accessing Data.


Overview of WFC Controls

Thanks for using this pre-release version of Visual J++.


Windows Graphical Services

Thanks for using this pre-release version of Visual J++.


Working with ActiveX Controls

Thanks for using this pre-release version of Visual J++.


Authoring WFC Controls

Thanks for using this pre-release version of Visual J++.


Creating Localizable Applications

Thanks for using this pre-release version of Visual J++.


Writing Windows-Based Applications with J/Direct

J/Direct is a new feature of Microsoft Visual J++ that provides easy access to Microsoft Windows dynamic-link libraries (DLLs). Using J/Direct, you can make direct calls to standard Win32 system DLLs (such as KERNEL32 and USER32) and third-party DLLs. J/Direct is far simpler to use than the older Raw Native Interface or the Java Native Interface (known as RNI and JNI, respectively), both of which require you to write a specialized wrapper DLL and perform all non-trivial data type translations yourself. With J/Direct, the vast majority of pre-existing DLL functions can be invoked by simply declaring the function and calling it. J/Direct uses the @dll.import directive, which is similar to Visual Basic's DECLARE facility.

To use J/Direct, you need to have installed Microsoft Visual J++ and Microsoft Internet Explorer, version 4.0 or higher. To quickly build applications that take advantage of the native power of J/Direct, use the J/Direct Call Builder, which is a part of the Visual J++ development environment.

This section explains how to use the @dll.import directive to invoke a DLL function from Java. It also offers details about how each data type is passed and received, and describes how the @dll.struct directive is used to pass and receive structures from DLL methods.

For more information on writing Windows-based applications with J/Direct, see:

  • Message Box Example

  • J/Direct Call Builder

  • Quick Syntax Reference

  • How Data Types are Marshaled

  • Invoking OLE API Functions

  • Aliasing (Method Renaming)

  • Linking by Ordinal

  • Specifying @dll.import for an Entire Class

  • How the VM Chooses Between ANSI and Unicode

  • Obtaining the Error Code Set By a DLL Function

  • Dynamically Loading and Invoking DLLs

  • Comparing J/Direct to Raw Native Interface

  • Security Issues

  • Error Messages

  • Troubleshooting Tips


Message Box Example

This topic provides a message box application that uses the @dll.import directive.

Using J/Direct to call Win32 DLLs from Java code is straightforward. The following is a short Java application that displays a message box:

class ShowMsgBox {
   public static void main(String args[])
   {
      MessageBox(0, "It worked!",
                 "This messagebox brought to you using J/Direct", 0);
   }

   /** @dll.import("USER32") */
   private static native int MessageBox(int hwndOwner, String text,
                                        String title, int fuStyle);
}

The @dll.import directive tells the compiler that the MessageBox method will link to the Win32 USER32.DLL using the J/Direct protocol rather than the Raw Native Interface (RNI) protocol supported in previous versions. In addition, the Microsoft Virtual Machine (VM) for Java provides automatic type marshaling from String objects to the null-terminated strings expected by C.

It is not necessary to indicate whether the ANSI MessageBox (MessageBoxA) function or the Unicode MessageBox function (MessageBoxW) should be called. In the above example, the ANSI version is always called. How the VM Chooses Between ANSI and Unicode explains how to use the auto modifier to call the optimal version of the function, depending on the version of Microsoft® Windows® that is hosting the application.


J/Direct Call Builder

Using the J/Direct Call Builder, you can quickly create J/Direct calls to the Win32 API. The J/Direct Call Builder automatically inserts Java definitions for the Win32 API elements into your code, along with the appropriate @dll.import tags.

To access the Win32 API with the J/Direct Call Builder

  1. To open the J/Direct Call Builder, point to Other Windows on the View menu and click J/Direct Call Builder.

  2. By default, the J/Direct Call Builder displays elements defined in the following Win32 DLLs: advapi32.dll, gdi32.dll, kernel32.dll, shell32.dll, spoolss.dll, user32.dll, and winmm.dll. (These DLLs are specified by the WIN32.TXT file, which is selected under Source.)

  3. The Target box identifies the class to contain the J/Direct calls. By default, a class named Win32 will be added to your project and will contain these calls. (If your solution contains multiple Java projects, the Win32 class is added to the first project.)

    To specify a different target class, click the ellipses button (...).

    • In the Select Class dialog box, select whether you want to view your classes in Project View or Class View. Project view displays a hierarchical list of the .java files in your solution, where each file node lists the names of the classes contained in that file. Class view displays a hierarchical list of class names.

    • Once you have chosen a view, select the name of the class to contain the J/Direct calls. (To copy the calls to the Windows Clipboard instead of to a class, select Clipboard.)

    • Click OK.
  4. To filter the display of Win32 methods, structs, and constants, select or clear the Methods, Structs, and Constants options.

  5. Now select the method, struct, or constant that you want to insert. (You can select multiple items using the SHIFT and CTRL keys.) Note that a Win32 struct will be added as a nested class inside your class.

    Note To search for an item by its initial characters, type the characters into the Find box. The first item that matches these characters is automatically selected.

  6. To insert the associated Java definition into your class, click Copy To Target. (You can also double-click the method, struct, or constant to insert it into your class.)

When a Win32 API element is selected in the J/Direct Call Builder, the lower preview pane displays the associated Java definition. You can copy and paste this text into any file. To quickly find the online reference information for a Win32 API element, right-click the item and click Display API Help on the shortcut menu.

For information about the default settings for this builder, see Setting J/Direct Call Builder Options.


Setting J/Direct Call Builder Options

Visual J++ allows you to set two options to customize the functionality of the J/Direct Call Builder.

To set J/Direct Call Builder options

  7. On the Tools menu, click J/Direct Call Builder Options.

  8. In the J/Direct Call Builder Options dialog box, select or clear the following options:
    Option | Description
    Show Target window when copy to target | Selected by default. When you insert a J/Direct call into your class, the builder automatically opens the .java file in the Text editor, if it is not already opened.
    Disable stack crawl security check Cleared by default. The VM will initiate a stack-based security check for each J/Direct call. If any of the callers on the stack are not fully trusted, then a security exception is thrown and the J/Direct call will not be invoked. This mainly affects Java code deployed on Web pages.

    When you select this option to disable the security checks, the @security(checkDllCalls=off) tag is automatically added to your class the next time you insert a J/Direct call. (If you later clear this option, any existing occurrences of the @security tag remain in your files, but no new instances will be added.)

  9. Click OK to save your settings.


Quick Syntax Reference

The following topics give a quick reference to the @dll.import, @dll.struct, and @dll.structmap directives. For each directive, the required syntax is shown and explained.

  • Syntax for @dll.import

  • Syntax for @dll.struct

  • Syntax for @dll.structmap


Syntax for @dll.import

The @dll.import directive should be placed just above the method declaration. The syntax of the directive is:

  /**@dll.import("LibName",<Modifier>)*/
  ...method declaration...;

LibName is the name of the DLL that contains the function you want to invoke. Modifier is optional, and the value that you should supply for it varies depending on your needs. In the method declaration, you can use the function name that the DLL uses, or you can give the method a different name by using aliasing. For information on aliasing, see Aliasing (Method Renaming). The Java data types that you choose for the parameters and for the return value of the method should be types that map to the types of the DLL function parameters and return value. See How Data Types are Marshaled for more information about how Java data types map to native types.

The following table presents the @dll.import syntax for several situations that are described in this section.

Situation Required Syntax Explanation
Calling Win32 DLLs
/**@dll.import("Libname")*/
Calling OLE APIs
/**@dll.import("Libname", ole)*/
Aliasing
/**@dll.import("Libname", entrypoint="DLLFunctionName")*/
 In the method declaration, use the Java name that you selected.
Linking by Ordinal
/**@dll.import("Libname", entrypoint="#ordinal")*/
 "ordinal" is a 16-bit integer, specified in decimal, that indicates the DLL function that you are importing.


Syntax for @dll.struct

The @dll.struct directive is placed just above the class declaration. The syntax of @dll.struct is:

  /**@dll.struct(<LinkTypeModifier>,<pack=n>)*/
  ...class declaration...;

LinkTypeModifier tells the compiler whether fields of type String and char represent ANSI or Unicode characters in native format. LinkTypeModifier can be ansi, unicode, or auto. If you do not specify LinkTypeModifier, ansi is used by default. See How the VM Chooses Between ANSI and Unicode to help you learn more about the values to use for LinkTypeModifier.

You can also specify pack=n to tell the compiler to set the packing size of the structure to either 1, 2, 4, or 8, depending on the value you specify for n. If you omit the pack=n modifier, the packing size is set to 8 by default. See Structure Packing for more information on setting the packing size.

Within the class declaration, you need to supply fields whose Java types map to the types of the fields in the native structure, in the order they occur in the native structure. See Correspondence Between Types Inside Structures for information about choosing the data types of the fields.

The following table describes the syntax for several situations in which you might use the @dll.struct directive.

Situation Required Syntax Explanation
Declare a structure
/**@dll.struct()*/
 When you do not specify LinkTypeModifier, char or String fields are assumed to represent ANSI characters.
Set a structure's packing size
/**@dll.struct(pack=n)*/
 n can be 1,2,4, or 8.
Declare a structure that has a field of type char
/**@dll.struct(ansi)*/
 The character field represents an ANSI character.
Declare a structure with a field of type string and set the packing size
/**@dll.struct(unicode,pack=n)*/
 The String fields will be in Unicode format, and the packing size is set to 1,2,4, or 8, depending on the value of n.


Syntax for @dll.structmap

The @dll.structmap directive is used to declare fixed-size strings and arrays embedded in structures. It should be placed within a structure that is declared with @dll.struct, and directly above the declaration of the fixed-size string or array field. For more information on how to use @dll.structmap, see Fixed-size Strings Embedded within Structures and Fixed-size Scalar Arrays Embedded within Structures.

The following table presents the syntax of the @dll.structmap directive.

Situation | Required Syntax | Explanation
Structure that contains a fixed-size string. | /**@dll.structmap([type=TCHAR[Size]])*/ | Size is a decimal integer that indicates the number of characters in the string, including space for the null terminator.
Structure that contains a fixed-size array. | /**@dll.structmap([type=FIXEDARRAY,size=n])*/ | n is a decimal integer that represents the size of the array.


How Data Types are Marshaled

Simply put, the Microsoft VM evaluates Java arguments, then converts them to native C++ types. The Microsoft VM infers the native type of each parameter and the return value from the declared (compile-time) Java type of the parameter. For example, a parameter declared as a Java integer is passed as a 32-bit integer; a parameter declared as a Java String object is passed as a null-terminated string, and so forth. There are no invisible attributes that provide information about the native types. In Java, what you see is what you get.

The following topics describe in detail how the Java data types map to native data types:

  • Quick Reference Provides tables that list the Java type that maps to each native type.

  • Basic Scalar Types Describes the mappings for int, byte, short, long, float, and double.

  • Chars Explains the mapping of the char data type.

  • Booleans Explains the mapping of the boolean data type.

  • Strings Explains how to pass and receive strings.

  • Arrays Explains how to pass arrays of scalars.

  • Structures Explains how to use the @dll.struct directive to pass and receive structures and how to use @dll.structmap to embed fixed-sized arrays within structures.

  • Pointers Explains how to handle DLLs that have multiple return values and how to read and write data through raw pointers.

  • Polymorphic Parameters Explains how to simulate polymorphic parameters.

  • Callbacks Explains how to declare and invoke a DLL function that takes a Callback parameter and how to embed a Callback inside a structure.


Quick Reference

The following two tables list the native type that corresponds to each Java type. The first table describes the mappings for parameters and return values, and the second table shows the mappings that are used with the @dll.struct directive.

Parameter and Return Value Mappings

Java | Native | Notes/Restrictions
byte | BYTE or CHAR |
short | SHORT or WORD |
int | INT, UINT, LONG, ULONG, or DWORD |
char | TCHAR |
long | __int64 |
float | float |
double | double |
boolean | BOOL |
String | LPCTSTR | Not allowed as return value, except in ole mode. In ole mode, String maps to LPWSTR. The Microsoft VM frees the string by using CoTaskMemFree.
StringBuffer | LPTSTR | Not allowed as return value. Set the StringBuffer capacity large enough to hold the largest string that the DLL function can generate.
byte[] | BYTE* |
short[] | WORD* |
char[] | TCHAR* |
int[] | DWORD* |
float[] | float* |
double[] | double* |
long[] | __int64* |
boolean[] | BOOL[] |
Object | pointer to struct | In ole mode, an IUnknown* is passed instead.
Interface | COM interface | Use jactivex or similar tool to generate interface file.
com.ms.com.SafeArray | SAFEARRAY* | Not allowed as return value.
com.ms.com._Guid | GUID,IID,CLSID |
com.ms.com.Variant | VARIANT* |
@dll.struct classes | pointer to struct |
@com.struct classes | pointer to struct |
void | VOID | As return value only.
com.ms.dll.Callback | function pointer | As parameter only.

Mappings used with @dll.struct

Java | Native
byte | BYTE or CHAR
char | TCHAR
short | SHORT or WORD
int | INT, UINT, LONG, ULONG or DWORD
float | __int64
long | float
double | double
boolean | BOOL[]
Java | Native
String | Pointer to a string, or an embedded fixed-size string
Class marked with @dll.struct | Nested structure
char[] | Nested array of TCHAR
byte[] | Nested array of BYTE
short[] | Nested array of SHORT
int[] | Nested array of LONG
long[] | Nested array of __int64
float[] | Nested array of floats
double[] | Nested array of doubles


Basic Scalar Types

The basic scalar types are mapped as follows:

Java type | DLL
int | signed 32-bit integer
byte | signed 8-bit integer
short | signed 16-bit integer
long | signed 64-bit integer
float | 32-bit float
double | 64-bit double

Note that there is no direct representation of unsigned integer types in Java. Since Java has no unsigned types, use the Java type which is the same size as the integer type you want. For example, the Java int type can be used without loss of representation for the common DWORD (unsigned 32-bit) type.


Chars

The Java char type becomes a CHAR (an 8-bit ANSI character) unless the unicode or ole @dll.struct modifier is in effect, in which case it becomes a WCHAR (a 16-bit Unicode character).


Booleans

The Java boolean type maps to the Win32 BOOL type, which is a 32-bit type. As a parameter, the Java true maps to 1, and false maps to 0. As a return value, all non-zero values map to true.

Note that BOOL and VARIANT_BOOL (the internal boolean type in Microsoft Visual Basic®) are not interchangeable. To pass a VARIANT_BOOL to a Visual Basic DLL, you must use the Java short type and use –1 for VARIANT_TRUE, and 0 for VARIANT_FALSE.


Strings

This section explains how you can pass a string in ANSI or Unicode format to a DLL function. It also discusses two ways to return a string from a DLL function.

  • Passing a String to a DLL Function

  • Receiving a String from a DLL Function


Arrays

J/Direct automatically handles arrays of scalars. The following Java array types translate directly into native pointer types:

Java | Native | # bytes per element
byte[] | BYTE* | 1
short[] | SHORT* | 2
int[] | DWORD* | 4
float[] | FLOAT* | 4
double[] | DOUBLE* | 8
long[] | __int64* | 8
boolean[] | BOOL* | 4

The char[] array type maps to CHAR* unless the unicode modifier is in effect, in which case it maps to WCHAR*.

All scalar array parameters can be modified by the caller (such as [in, out] parameters).

Array types cannot be used as return types. There is no support for arrays of objects or strings.

Typically, this facility is used by OLE functions to return values. (OLE functions reserve the "function" return value to return the HRESULT error code.) See Invoking OLE API Functions to learn how to obtain the return value for OLE functions.


Structures

The Java language does not directly support the concept of a structure. Although Java classes containing fields can be used to emulate the concept of a structure within the Java language, ordinary Java objects cannot be used to simulate structures in native DLL calls. This is because the Java language does not guarantee the layout of the fields and because the garbage collector is free to move the object around in memory.

Therefore, to pass and receive structures from DLL methods, you need to use the @dll.struct compiler directive. When applied to a Java class definition, this directive causes all instances of the class to be allocated in a memory block that will not move during garbage collection. In addition, the layout of the fields in memory can be controlled using the pack modifier (see Structure Packing). For example, the Win32 SYSTEMTIME structure has the following definition in the C programming language:

typedef struct {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME;

The correct declaration of this structure in Java is as follows:

/** @dll.struct() */
class SYSTEMTIME {
  public short wYear;
  public short wMonth;
  public short wDayOfWeek;
  public short wDay;
  public short wHour;
  public short wMinute;
  public short wSecond;
  public short wMilliseconds;
}

The following example uses the SYSTEMTIME structure in a DLL method call:

class ShowStruct {
    /** @dll.import("KERNEL32") */
    static native void GetSystemTime(SYSTEMTIME pst);
    public static void main(String args[])
    {
      SYSTEMTIME systemtime = new SYSTEMTIME();
      GetSystemTime(systemtime);
      System.out.println("Year is " + systemtime.wYear);
      System.out.println("Month is " + systemtime.wMonth);
      // etc.
    }
}

Note Classes declared with @dll.struct are considered unsafe and therefore cannot be used by untrusted applets.

For more information, see:

  • Correspondence Between Types Inside Structures

  • Nested Structures

  • Fixed-size Strings Embedded Within Structures

  • Fixed-size Scalar Arrays Embedded within Structures

  • Structure Packing

  • The Relationship Between @dll.struct and @com.struct


Pointers

Java does not support a pointer data type. However, instead of passing a pointer, you can pass a one-element array. You can store pointers in Java integers, and you can read and write data from raw pointers.

For more information, see:

  • Return Value Pointers

  • Raw Pointers


Polymorphic Parameters

Some Win32 functions declare a parameter whose type depends on the value of another parameter. For example, the WinHelp function is declared as follows:

BOOL WinHelp(int hwnd, LPCTSTR szHelpFile, UINT cmd, DWORD dwData);

The innocent-looking dwData parameter can actually be any one of the following: a pointer to a string, a pointer to a MULTIKEYHELP structure, a pointer to a HELPWININFO, or a plain integer, depending on the value of the cmd parameter.

J/Direct offers two ways to declare such a parameter:

  • Declare the parameter as type Object.

  • Use overloading to declare a separate method for each possible type.

For a comparison, see Comparison Between the Two Methods.


Callbacks

Several Win32 APIs require your programs to provide Windows with the address of a callback function. You can write callbacks in Java by extending the system class com.ms.dll.Callback.

For more information, see:

  • Declaring a Method that Takes a Callback

  • Invoking a Function that Takes a Callback

  • Restrictions on Types Accepted by the Callback Method

  • Associating Data with a Callback

  • The Lifetime of a Callback

  • Embedding a Callback Inside a Structure


Invoking OLE API Functions

For information on invoking OLE API functions, see:

  • OLE Mode Syntax

  • How Win32 Functions Compare with OLE Functions

  • Comparing Win32 Code to OLE Code

  • Invoking OLE Functions

  • How OLE Mode Works

  • Passing and Receiving Strings from OLE Functions

  • Passing GUIDs (and IIDs and CLSIDs)

  • Passing VARIANTs

  • Passing COM Interface Pointers


OLE Mode Syntax

The @dll.import directive includes a special mode tailored for importing OLE API functions. To use this mode, simply include the ole modifier as in the following example:

/** @dll.import("OLE32", ole) */
  public class OLE32 {
    ...
  }


Comparison of Win32 Functions with OLE Functions

In theory, the functions exported out of OLE32.DLL and OLEAUT32.DLL are no different from any other DLL function. In practice, the OLE functions follow a consistent calling style of their own. OLE functions differ from Win32 functions in the following ways:

  • OLE functions only come in Unicode. There are no ANSI OLE functions.

  • Virtually all OLE functions return a 32-bit status code known as an HRESULT through the normal function return value. The high-bit indicates whether the function succeeded (hi-bit off) or failed (hi-bit on). A few functions return multiple success values (typically S_OK and S_FALSE) but most return only one success value (S_OK).

  • If an OLE function returns some value other than the status code, it does so by having the caller supply a pointer to a variable that will receive the value on exit. This return value pointer is, by convention, the last parameter.

  • The Win32 style of returning strings is to fill in a caller-allocated buffer. OLE functions typically return strings by allocating them using CoTaskMemAlloc and expecting the caller to free them using CoTaskMemFree.


Comparing Win32 Code to OLE Code

The code for a simple Add function would look like this in the Win32 style of coding:

  int sum;
  sum = Add(10, 20);

In OLE style, the Add function would be written the following way:

HRESULT hr;
  int sum;
  hr = Add(10, 20, &sum);
  if (FAILED(hr)) {
    ...handle error..
  }


Invoking OLE Functions

The ole mode takes advantage of a consistent coding style to provide a Java-friendly way to call OLE functions. Invoking an OLE-style Add function from Java looks much like invoking a more traditional Win32-style function:

/** dll.import("OLELIKEMATHDLL", ole) */
  private native static int Add(int x, int y);
  int sum = Add(10, 20);
  // if we got here, Add succeeded.


How OLE Mode Works

Because of the ole modifier, the Microsoft VM automatically assumes that the native Add function returns an HRESULT. The VM notices that the Add function returns an integer. When invoking Add, the VM automatically allocates a temporary variable of type int and inserts a pointer to it as a third parameter. After the native Add function returns, the VM automatically checks the HRESULT and if it indicates a failure (high-bit on), a Java exception of type com.ms.com.ComFailException is thrown. If the HRESULT does not indicate a failure, the VM retrieves the Add function's true return value from the temporary variable it created, and it returns that value.

Unlike Java/COM integration, a return value of S_FALSE does not cause a ComSuccessException to be thrown. If you need to distinguish between success results, you need to use normal DLL calling mode and treat the HRESULT as an integer return value.

To summarize, ole mode alters the semantics of DLL calling as follows:

  1. All strings and characters are assumed to be Unicode.

  2. The function return value of the native function is presumed to be an HRESULT. The Microsoft VM throws a ComFailException if the returned HRESULT indicates failure.

  3. If the Java method return type is not void, the Microsoft VM will assume that the native function returns an additional result through a pointer, which is the final argument to the function. The VM will supply this pointer argument and dereference it after the call to obtain the additional return value. This value will be returned as the value of the Java method.


Passing and Receiving Strings from OLE Functions

Declaring a parameter as type String on an ole mode function passes a LPCOLESTR. The Microsoft VM also includes a preceding length prefix so the string can also be treated as a BSTR.

Declaring a return value as type String in ole mode causes the Microsoft VM to pass a pointer to an uninitialized LPCOLESTR*. When the native function returns, the Microsoft VM will convert the returned LPCOLESTR to a Java String, and then call CoTaskMemFree to free the string.


Passing GUIDs (and IIDs and CLSIDs)

The system class com.ms.com._Guid is used to represent GUIDs. Passing a _Guid object as a parameter passes a pointer to a GUID to the native function. Declaring a return type of _Guid causes the Microsoft VM to pass a pointer to an uninitialized GUID that the function fills in (in ole mode only).

For example, OLE32 exports the functions CLSIDFromProgID and ProgIDFromCLSID to map between CLSIDs and the human-readable names used by the Visual Basic function CreateObject.

These methods have the following prototypes:

HRESULT CLSIDFromProgID(LPCOLESTR szProgID, LPCLSID pclsid);
HRESULT ProgIDFromCLSID(REFCLSID clsid, LPOLESTR *lpszProgId);

In Java, these methods are declared in the following way:

import com.ms.com._Guid;
  class OLE {
    /** @dll.import("OLE32", ole) */
    public static native _Guid CLSIDFromProgID(String szProgID);

    /** @dll.import("OLE32", ole) */
    public static native String ProgIDFromCLSID(_Guid clsid);
  }

Note Note that com.ms.com._Guid supercedes com.ms.com.Guid (with no underscore).


Passing VARIANTs

Declaring a parameter to be type com.ms.com.Variant passes a pointer to a VARIANT to the native function. Declaring a return value to be type com.ms.com.Variant (ole-mode only) passes a pointer to an uninitialized Variant for the native function to fill in.


Passing COM Interface Pointers

To pass a COM interface pointer, you must generate a Java/COM interface class using a tool such as jactivex.exe. You can then pass or receive COM interfaces by declaring a parameter to be of that interface type.

For example, the system class com.ms.com.IStream is a Java/COM interface that represents the Structured Storage IStream* interface. The OLE32 function CreateStreamOnHGlobal could be declared as follows:

import com.ms.com.*;
/** @dll.import("OLE32", ole) */
public static native IStream CreateStreamOnHGlobal(int hGlobal,
                                     boolean fDeleteOnRelease);

Java/COM integration is a complex topic and a full discussion is beyond the scope of this documentation. For more information, see Integrating Java and COM.


Aliasing (Method Renaming)

Sometimes you want to use a name for the Java method that is different from the name that the DLL uses when it exports the function. For example, you might want to have the Java name start with a lowercase letter so that it conforms to Java naming conventions. To do so, just use the @dll.import directive with the entrypoint modifier as in the following example:

/** @dll.import("USER32", entrypoint="GetSysColor") */
  static native int getSysColor(int nIndex);

You do not need to use aliasing to perform the ANSI/Unicode suffixing done by the Win32 APIs. The Microsoft VM automatically takes care of this (see How the VM Chooses Between ANSI and Unicode). Aliasing is also unnecessary when accessing functions that have been exported by a .def file. Such names are typically exported using "stdcall mangling." That is, a method such as the following sample method would be renamed to _sample@8 (where 8 denotes the number of parameter bytes accepted by the function):

extern "C"
  __declspec(dllexport)
  VOID sample(int x, int y){
    ...
  }

J/Direct automatically binds to stdcall-mangled names without an explicit entrypoint.

The Microsoft VM automatically provides aliases for the following KERNEL32 API functions.

Kernel32 Function | Alias
CopyMemory | RtlMoveMemory
MoveMemory | RtlMoveMemory
FillMemory | RtlFillMemory
ZeroMemory | RtlZeroMemory


Linking by Ordinal

Some DLLs export functions by ordinal (16-bit integer) rather than by name. To call such DLLs, you will need to use a method-level @dll.import directive to specify the ordinal. The syntax for ordinal linking is:

/** @dll.import("Libname", entrypoint="#ordinal") */

Note that ordinal is specified in decimal.

For example, to link a function exported as ordinal 82 in DLL "MyDll.DLL", you would write the following code:

/** @dll.import("MyDll", entrypoint="#82") */
  public static native void MySample();


Specifying @dll.import for an Entire Class

The @dll.import directive can also be used prior to the class definition to set a library name for all native methods declared in that class. The following declaration uses @dll.import for an entire class:

/** @dll.import("KERNEL32") */
class EnvironmentStrings
{
  public static native int GetEnvironmentStrings();
  public static native int GetEnvironmentVariable(String name,
                            StringBuffer value, int ccbValue);
  public static native boolean SetEnvironmentVariable(String name,
                                                    String value);
}

It is equivalent to specifying @dll.import for each method, as in the following example:

class EnvironmentStrings
{
  /** @dll.import("KERNEL32") */
  public static native int GetEnvironmentStrings();

  /** @dll.import("KERNEL32") */
  public static native int GetEnvironmentVariable(String name,
                              StringBuffer value, int ccbValue);

  /** @dll.import("KERNEL32") */
  public static native boolean SetEnvironmentVariable(String name,
                                                    String value);
}

Using the @dll.import directive at the class level saves space in the .class file and eliminates redundant information. However, class-level @dll.import directives are not inherited by subclasses.


How the VM Chooses Between ANSI and Unicode

Regarding the MessageBox example shown in the J/Direct topic Getting Started, a subtle, but important fact is that USER32 does not export a function named MessageBox. Because the MessageBox function takes a string, it (like all Win32 functions that deal with strings) must exist in two versions: an ANSI version and a Unicode version (named MessageBoxA and MessageBoxW, respectively). When you code a call to MessageBox in C or C++, the MessageBox "function" you call is actually a macro that expands to either MessageBoxA or MessageBoxW, depending on whether the UNICODE macro is defined.

For more information, see:

  • Calling the ANSI Version of a DLL Function

  • Calling the Unicode Version of a DLL Function

  • Calling the Optimal Version of a DLL Function


Calling the ANSI Version of a DLL Function

By default, the Microsoft VM assumes that the ANSI version of the MessageBox function is the one that is needed. If you import the MessageBox function using @dll.import (without a modifier) as follows:

/** @dll.import("USER32") */
  static native int MessageBox(int hwnd, String text,
                               String title, int style);

the Microsoft VM will go through the following steps:

  1. The strings "text" and "title" are converted to ANSI null-terminated strings.

  2. The VM attempts to find an export named MessageBox in USER32.DLL.

  3. This attempt fails. The VM then appends an "A" onto the name and looks for an export named MessageBoxA.

  4. This attempt succeeds, and the VM invokes the MessageBoxA function.


Calling the Unicode Version of a DLL Function

Suppose that instead of calling the ANSI version of the MessageBox function, you want to call the Unicode version. You can do this by using the unicode modifier with the @dll.import directive:

/** @dll.import("USER32",unicode) */
  static native int MessageBox(int hwnd, String text, String title,
                               int style);

Since the unicode modifier is present, the Microsoft VM will go through the following steps:

  1. The strings "text" and "title" are converted to Unicode null-terminated strings.

  2. The VM attempts to find an export named MessageBox in USER32.DLL.

  3. This attempt fails. The VM appends a "W" onto the name and looks for an export named MessageBoxW.

  4. This attempt succeeds, and the VM invokes the MessageBoxW function.


Calling the Optimal Version of a DLL Function

Unfortunately, neither calling the ANSI version or the Unicode version of a DLL function is an ideal way to invoke the Win32 functions. Using the default ANSI mode allows your code to run on any Win32 platform, but causes unnecessary performance penalties on fully Unicode systems such as Microsoft Windows® NT. Using the unicode modifier removes the performance penalty but restricts you to running on systems that implement the Unicode API. Fortunately, you can use the auto modifier with the @dll.import directive to call the optimal version of a DLL function based on the host operating system.

Using the auto modifier gives you the best of both worlds. The following example shows how to call the optimal version of the MessageBox function:

/** @dll.import("USER32",auto) */
  static native int MessageBox(int hwnd, String text, String title,
                               int style);

When the auto modifier is present, the Microsoft VM determines at run time whether the underlying platform supports the Unicode APIs. If Unicode is supported, the VM acts as if the unicode modifier had been specified. Otherwise, the VM behaves as if the ansi modifier had been specified. Thus, the auto modifier allows you to generate a single binary which runs well on both ANSI and Unicode Windows systems using the optimal API set available on the given platform.

In general, the auto modifier should be used whenever you call Windows API functions. If you are calling your own DLLs, select either ansi (the default) or unicode depending on your needs.

The following list provides details of how the VM decides whether to use ANSI or Unicode when you use the auto modifier:

  1. The VM opens the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM and looks for the DWORD-named value DllImportDefaultType. This value can be one of the following:

    2 – ANSI: Uses the ANSI version always.

    3 – Unicode: Uses the UNICODE version always.

    4 – Platform: Uses ANSI or Unicode depending on the platform.

  2. If the key does not exist, or if it is set to 4 (indicating platform), the VM calls the Win32 GetVersion function and examines the high bit to determine whether the underlying platform is Microsoft Windows® 95 or Microsoft Windows NT. If the platform is Windows 95, ANSI mode is used. Otherwise, Unicode mode is used.

It is not necessary to set the DllImportDefaultType registry key yourself. It exists primarily so that the installation program can set the appropriate choice on future Windows platforms. You can programmatically query the preferred mode on your platform by reading the com.ms.dll.DllLib.systemDefaultCharSize field. This field will be set to 1 on ANSI systems, 2 on Unicode systems.

The ansi, unicode, and auto modifiers can also be used with the @dll.struct directive.


Obtaining the Error Code Set by a DLL Function

Do not invoke the Win32 function GetLastError to obtain an error code set by another DLL call. Because the Microsoft VM may execute function calls of its own in the process of executing Java code, the error code may have been overwritten by the time you get to it.

To reliably access the error code set by a DLL function, you must use the setLastError modifier to instruct the VM to capture the error code immediately after invoking that method. For performance reasons, this is not done by default. You can then invoke the com.ms.dll.DllLib.getLastWin32Error method to retrieve the error code. Each Java thread maintains separate storage for this value.

For example, the FindNextFile function returns status information through the error code. FindNextFile would be declared as follows:

/** @dll.import("KERNEL32",setLastError) */
  static native boolean FindNextFile(int hFindFile,
                              WIN32_FIND_DATA wfd);

A typical call would appear as:

import com.ms.dll.DllLib;

boolean f = FindNextFile(hFindFile, wfd);
if (!f) {
  int errorcode = DllLib.getLastWin32Error();
}


Dynamically Loading and Invoking DLLs

There may be times when you need more control over the loading and linking process than the @dll.import directive normally provides. For instance, your requirements might include:

  • Loading a library whose name or path must be computed at run time or generated from user input.

  • Freeing a library prior to process termination.

  • Executing a function whose name or ordinal must be computed at run time.

The Win32 APIs have always provided the ability to control loading and linking. The LoadLibrary, LoadLibraryEx, and FreeLibrary functions allow you to have explicit control over the loading and freeing of DLLs. The GetProcAddress function allows you to link to a specific export. The GetProcAddress function returns a function pointer, so any language that can call through a function pointer can implement dynamic invocation without a problem.

J/Direct allows Java programmers to declare the requisite functions in the following way:

Note If you are using the com.ms.win32 package, these declarations also appear in the Kernel32 class.

/** @dll.import("KERNEL32",auto) */
public native static int LoadLibrary(String lpLibFileName);

/** @dll.import("KERNEL32",auto) */
public native static int LoadLibraryEx(String lpLibFileName,
                                       int hFile, int dwFlags);

/** @dll.import("KERNEL32",auto) */
public native static boolean FreeLibrary(int hLibModule);

/** @dll.import("KERNEL32",ansi) */
public native static int GetProcAddress(int hModule, String lpProcName);

Notice that GetProcAddress is declared with the ansi modifier, not auto. This is because GetProcAddress is one of the few Windows functions without a Unicode equivalent. If we were to use the auto modifier, this function would fail on Microsoft Windows NT systems.

That only leaves the problem of invoking a function obtained by GetProcAddress. For your convenience, msjava.dll, (the DLL that implements the Microsoft VM) exports a special function named call. The call function's first argument is a pointer to a second function. All call does is invoke the second function, passing it the remaining arguments.

The following is an example of how an application could load a DLL and call AFunction exported by the DLL:

BOOL AFunction(LPCSTR argument);

  /** @dll.import("msjava") */
  static native boolean call(int funcptr,String argument);

  int hmod = LoadLibrary("...");
  int funcaddr = GetProcAddress(hmod, "AFunction");
  boolean result = call(funcaddr, "Hello");
  FreeLibrary(hmod);


Comparing J/Direct to Raw Native Interface

J/Direct and Raw Native Interface (RNI) are complementary technologies. Using RNI requires that DLL functions adhere to a strict naming convention, and it requires that the DLL functions work harmoniously with the Java garbage collector. That is, RNI functions must be sure to call GCEnable and GCDisable around code that is time-consuming, code that could yield, code that could block on another thread, and code that blocks while waiting for user input. RNI functions must be specially designed to operate in the Java environment. In return, RNI functions benefit from fast access to Java object internals and the Java class loader.

J/Direct links Java with existing code such as the Win32 API functions, which were not designed to deal with the Java garbage collector and the other subtleties of the Java runtime environment. However, J/Direct automatically calls GCEnable on your behalf so that you can call functions that block or perform UI without having a detrimental effect on the garbage collector. In addition, J/Direct automatically translates common data types such as strings and structures to the forms that C functions normally expect, so you don't need to write lengthy glue code and wrapper DLLs. The tradeoff is that DLL functions cannot access fields and methods of arbitrary Java objects. In this release, they can only access fields and methods of objects that are declared using the @dll.struct directive. Another limitation of J/Direct is that RNI functions cannot be invoked from DLL functions that have been called using J/Direct. The reason for this restriction is that garbage collection can run concurrently with your DLL functions. Therefore, any object handles returned by RNI functions or manipulated by DLL functions are inherently unstable.

Fortunately, you can use either RNI or J/Direct (or both). The compiler and the Microsoft VM allow you to mix and match J/Direct and RNI within the same class as your needs dictate.


Security Issues

Although J/Direct is a very powerful feature for stand-alone Java applications and trusted intranet Web applications, it is clearly too powerful to be used by normal Java applets on the Web. This section describes how J/Direct works with the security system of the Microsoft VM to prevent untrusted code from abusing the power provided by J/Direct.

For security issues, see:

  • Trusted Versus Untrusted Classes

  • Security Checkpoints for J/Direct Method Calls

  • Security Checkpoints for J/Direct Structures

  • Security and the com.ms.win32 Class


Trusted Versus Untrusted Classes

J/Direct divides all loaded Java classes into one of two categories:

  1. Fully trusted (indicating maximum permissions).

  2. Untrusted.

Only fully trusted classes are allowed to use J/Direct. A Java class is considered fully trusted if one of the following statements is true:

  • The class is digitally signed indicating full trust. An example of such a class would be a signed applet.

  • The class is installed on the target computer's CLASSPATH or installed by the package manager. A downloadable, digitally signed library designed to be shared among multiple applets could meet this criterion.

  • The class is running as a non-browser application using the JVIEW or the WJVIEW application.

An unsigned applet on the Web, on the other hand, constitutes untrusted Java code.


Security Checkpoints for J/Direct Method Calls

The Microsoft VM applies security checks to J/Direct methods at three different times:

  1. At link time.

  2. Upon first invocation.

  3. Upon every invocation.

An attempted J/Direct call takes place only if each of the three security checks passes or is explicitly disabled.


Security Checkpoints for J/Direct Structures

J/Direct also imposes security restrictions on classes that are marked using the @dll.struct directive. Because structures only become unsafe when they are instantiated, these security checks are more efficient than the checks used for J/Direct methods. The following two security checks are performed on @dll.struct classes:

Load time | Classes marked with the @dll.struct directive will load only if the context indicates full trust.
Link time | Code that is not fully trusted cannot link to classes declared using the @dll.struct directive. The Microsoft VM will throw a NoClassDefFoundError if such an attempt is made.


Security and the com.ms.win32 Classes

For maximum security, the J/Direct methods defined in the com.ms.win32 package do perform the call stack check on each invocation. If you are using these classes for a Java application (running under JVIEW or WJVIEW), the performance overhead will be negligible. If you are using com.ms.win32 classes from a trusted class and require maximum performance, you should copy the required J/Direct declarations into your own classes and disable the per-invocation security check. See Security Checks upon Every Invocation for more information on disabling the per-invocation security check.


Error Messages

There are several types of exceptions that might be thrown by the Microsoft VM when you are using J/Direct. For each of the following run-time errors, possible causes and solutions are explained:

  • java.lang.SecurityException [class.method]

  • java.lang.IllegalAccessError

  • java.lang.SecurityException

  • java.lang.NoClassDefFoundError

  • com.ms.security.SecurityExceptionEx


java.lang.SecurityException [class.method]

Exception Class | java.lang.SecurityException
Message | class.method: Only fully trusted classes can have native methods as members.
Possible Causes | The native keyword has been used on a method that is a member of a class that is not loaded with full permissions (for example, an unsigned applet). This exception is thrown only if an attempt is made to invoke the native method.
Possible Solutions | Digitally sign your applet requesting full permissions.


java.lang.IllegalAccessError

Exception Class | java.lang.IllegalAccessError
Message | Class has been marked as nonpublic to untrusted code.
Possible Causes An untrusted class has attempted to refer to a field or method of another class that has been marked for trusted use only. Many of the system classes in the com.ms.com and com.ms.dll packages have been marked this way. A class can be marked as nonpublic to untrusted code using the @security directive in the following way:
  /** @security(checkClassLinking=on) */
  public class ForTrustedUseOnly{
   ...
  }
Possible Solutions | Digitally sign your applet requesting full permissions.


java.lang.SecurityException

Exception Class | java.lang.SecurityException
Message | J/Direct method has not been authorized for use on behalf of an untrusted caller.
Possible Causes | An untrusted class has invoked a trusted method that attempts to make a J/Direct call. Even if the class making the actual J/Direct call is trusted, the security manager will throw a SecurityException if any of the methods in the call stack belong to an untrusted class.
Possible Solutions Digitally sign your applet requesting full permissions. Or, you can disable the security check by marking the class that attempts the J/Direct call with the @security directive, as shown in the following example:
/** @security(checkDllCalls=off) */
  public class SafeDllCalls{
   ...
  }

Note Disabling this security check transfers responsibility for security from the Microsoft VM for Java to you. Remember that even with this security check disabled, you will still have to digitally sign the class for maximum trust. If you use the @security directive, you should ensure that the following statements are true:

  • All J/Direct methods are declared private.

  • Your class exposes only the functionality needed by the client.

  • Your class guards all access to these capabilities with appropriate security checks.


java.lang.NoClassDefFoundError

Exception Class | java.lang.NoClassDefFoundError
Message | None.
Possible Causes | An untrusted class has attempted to load either a class marked with the @dll.struct directive or a class generated using the jactivex tool. Although this is really a security violation (not a class loader error), a NoClassDefFoundError is thrown for backward compatibility purposes.
Possible Solutions | Digitally sign your applet requesting full permissions.


com.ms.security.SecurityExceptionEx

Exception Class | com.ms.security.SecurityExceptionEx
Message | [host] J/Direct method has not been authorized for use on behalf of an untrusted caller.
Possible Causes | A J/Direct call was attempted from the init, start, stop, or destroy method of an applet. To make J/Direct calls during these methods, the applet must assert permissions even if the applet has been signed.
Possible Solutions Execute the following code to assert permissions:
import com.ms.security.*;
    ...
  PolicyEngine.assertPermission(PermissionID.SYSTEM);


Troubleshooting Tips

The following topics describe problems that you may encounter when using J/Direct. For each situation, possible solutions are provided:

  • UnsatisifiedLinkError When Calling a Method

  • Getting SecurityException When Calling a DLL Method or Using an @dll.struct Class

  • StringBuffers Truncated on Return From DLL Function

  • Syntax Errors Within @dll Directives

  • Compiler Cannot Find the com.ms.dll Package

  • @dll Directives Do Not Work on Applets

  • Using J/Direct Makes Class Unusable

  • J/Direct Throws a ParameterCountMismatchError After Calling a Native Function

  • J/Direct Does Not Unload a DLL


UnsatisifiedLinkError When Calling a Method

  • Check your version of the compiler to see that it's current with this release of Microsoft Visual J++. If your compiler does not support J/Direct, the Microsoft VM will attempt to link native methods using the Raw Native Interface (and will not succeed).

  • Make sure your DLL is visible on the system path. DLLs are searched for in the following locations (in order):
    1. The directory from which the application (typically JVIEW) loaded.

    2. The current directory.

    3. The Windows system directory.

    4. The Windows directory.

    5. The directories listed in the PATH environment variable.

    The Microsoft VM will not attempt to load the DLL until a method requiring it is actually called. Therefore, do not assume that the DLL load was successful simply because the Java class loaded successfully.

  • Check the method qualifiers. Methods declared with the @dll.import directive must be native and static. They can have any level of access (public, private, and so on) supported by the Java language.

  • Make sure that your method name matches the DLL export name exactly, including capitalization. The DLL linking mechanism in Win32 is case-sensitive.

  • If you still have trouble linking to a method, use a utility such as dumpbin/exports (Visual C++) to verify that the DLL exports the method by the name you are using. Some DLLs may require you to link to exports by ordinal (an integer) rather than a name. In such a case, use the entrypoint override on the method using the "#ordinal" syntax as shown in the following example:
      // This method is exported as ordinal #34.
  /** @dll.import("MyDll",entrypoint="#34") */
  public static native void MySample();
  • Be aware that some so-called functions are actually C macros and the actual DLL export name may be quite different from the name of the macro.


Getting SecurityException When Calling a DLL Method or Using an @dll.struct Class

DLL calling and the use of @dll.struct classes is restricted to Java applications and signed Java applets.


StringBuffers Truncated on Return From DLL Function

You must ensure that the StringBuffer's capacity is sufficient to contain the string you need before you invoke the DLL function. You can specify the capacity in the StringBuffer's constructor, and you can use the StringBuffer.ensureCapacity method to guarantee a minimum capacity prior to the DLL call.


Syntax Errors Within @dll Directives

Extra white space within @dll.import and @dll.struct directives can cause syntax errors. Avoid using white space inside @dll constructs.


Compiler Cannot Find the com.ms.dll Package

An older version of Classes.zip is being used. Try renaming all older versions of Classes.zip on your disk drive and follow the instructions under Compiler Cannot Find Basic System Packages for creating a new Classes.zip file.


@dll Directives Do Not Work on Applets (or Only Works Within the Microsoft Visual J++ Environment)

Because the use of J/Direct can compromise security, its use is restricted to Java applications and signed Java applets.


Using J/Direct Makes Class Unusable

Using J/Direct Makes Class Untrusted

Any use of J/Direct within a class marks that class as unsafe and unusable by untrusted code, even if the J/Direct methods are not actually invoked.


J/Direct Throws a ParameterCountMismatchError After Calling a Native Function

The ParameterCountMismatchError exception alerts you to the fact that the called function consumed (popped off the stack) more or fewer parameters than was passed by J/Direct. This error normally indicates that the parameters in the Java method declaration do not match up with the parameters expected by the DLL function.

If the function pops off no arguments, it is assumed to be using the cdecl calling convention and an exception is not thrown, even if the Java method declares a non-zero number of arguments.

CAUTION You should not attempt to catch and deal with the ParameterCountMismatchError exception. This exception was designed to assist developers in catching errors during the development stage. For performance reasons, parameter count checking is performed only when the application is running under a Java debugger. It is also important to note that J/Direct performs this check after the function call has been completed. Because this exception indicates that one or more invalid parameters might have been passed to the function call, it cannot be guaranteed that the process can recover.


J/Direct Does Not Unload a DLL

J/Direct unloads a DLL when the Microsoft VM discards the Java class that imported the DLL. For a Java application running under JVIEW, this does not occur until the process exits. For a trusted Java applet, this happens at some undetermined time after the browser has left the page containing the applet. The Microsoft VM attempts to keep Java classes loaded for several pages afterward in order to optimize applet refresh time in case the page is revisited.

If you need explicit control over the loading and unloading of DLLs, you need to call the Windows loader explicitly and use the call entrypoint to invoke functions dynamically. For more information on how to do this, see Dynamically Loading and Invoking DLLs.


Advanced Windows Programming Techniques

Thanks for using this pre-release version of Visual J++.


Integrating Java and COM

Thanks for using this pre-release version of Visual J++.


Creating an COM Object with Java

Thanks for using this pre-release version of Visual J++.


Exposing a Java Class as a COM Class

Thanks for using this pre-release version of Visual J++.


Calling a COM Object from Java

Thanks for using this pre-release version of Visual J++.


Importing a COM Object

Thanks for using this pre-release version of Visual J++.


Distributing Java Applications Containing COM Components

Thanks for using this pre-release version of Visual J++.


Handling Security Issues for Java and COM

Thanks for using this pre-release version of Visual J++.


Converting JavaBeans to ActiveX Components

Thanks for using this pre-release version of Visual J++.


Writing High-Performance Java Code

While writing high-performance Java code is a lofty goal to pursue, the term itself is ambiguous. By definition, program optimization is “ the process of producing more efficient (smaller and/or faster) programs through selection and design of data structures, algorithms, and instruction sequences.” This section provides several topics that discuss various ways you can speed up your Java code.

Sections:

Optimization Guidelines

Optimizing for Speed

Optimizing for Size

Optimizing Tools at Your Disposal

Things to Avoid


Visual J++ Extensibility Overview

Extensibility is a means of enabling key functionality via wizards and add-ins. It has proved to be a powerful way of adding new functionality without requiring work in the core code base.

The Visual J++ extensibility model derives from and extends the Visual Studio core extensibility object model. This model operates in the design-time mode to give access to the functionality available to the user of the development environment.

See also:

  • Extensibility Overview

  • Extensibility in Visual Studio

  • What is an Add-In?

  • The Extensibility Object Model

  • Using the AddIn Manager

  • Extensibility in Visual J++


Reference

The Visual J++ Reference contains the following topics:

  • Windows Foundation Classes for Java (WFC)

  • Java API

  • IntelliSense API

  • Extensibility in Visual J++

  • Conditional Compilation

  • Java Language Specification

  • Reserved Words, A-L

  • Reserved Words, M-Z


 Windows Foundation Classes for Java

Windows Foundation Classes for Java

The following packages are included in the Windows Foundation Classes for Java.

Note: Use the Object Browser to explore classes and packages that do not have associated reference topics in this Technical Preview Edition of Visual J++. To open the Object Browser, from the View menu, click Other Windows, and then click Object Browser.

Package wfc.app (Reference not yet available)
Provides classes that encapsulate Windows application operations, such as threads, messaging, and access to the Clipboard and registry.
Package wfc.ax (Reference not yet available)
Provides classes that represent the ActiveX interfaces used internally by WFC components.
Package wfc.core
Provides core component model classes.
Package wfc.data.ui (Reference not yet available)
Represents the classes used to implement data-bound controls.
Package wfc.html
Provides classes for accessing Dynamic HTML.
Package wfc.io (Reference not yet available)
Provides classes and interfaces for creating and working with data streams.
Package wfc.ole32 (Reference not yet available)
Provides Java wrapper classes and interfaces for OLE services used internally by WFC components.
Package wfc.ui
Provides user interface component classes.
Package wfc.util (Reference not yet available)
Provides miscellaneous utility classes.
Package wfc.win32 (Reference not yet available)
Provides Java wrapper classes for the Win32 API used internally by WFC components.


 Package wfc.core

Package wfc.core

The wfc.core package provides support for building Windows Foundation Classes controls and components.


 About wfc.core

About wfc.core

The wfc.core package provides support for building Windows Foundation Classes controls and components.

Classes

Class CancelEvent
Represents an event fired by components to enable you to cancel a particular operation.
Class CategoryAttribute
Defines a category for a member.
Class ClassInfo
Represents the base class implementation of IClassInfo, which is used to describe a component so that it is compatible with the Visual J++ designer.
Class Component
Represents a base class implementation of IComponent.
Class ComponentInfo
Contains information about a component including its properties, events, and attributes.
Class ComponentManager
Implements an easy way to browse properties and events for a component.
Class ConstructorArg
Represents objects that are returned by the classes that implement the IConstructable.getConstructorArgs method.
Class Container
Provides a base class implementation of the IContainer interface.
Class Customizer
Provides a base class implementation of the ICustomizer interface.
Class CustomizerVerb
The CustomizerVerb class represents a verb that can be run by a component's customizer.
Class DefaultValueAttribute
Holds the default value for a property.
Class DescriptionAttribute
Holds the description string for a member (property, method or event).
Class DesignForm
Implements a DesignForm object.
Class DesignPage
Defines a base implementation for IDesignPage.
Class Enum
Represents the base enumerator class.
Class Event
Represents the base class for all events.
Class EventInfo
Topic under construction.
Class ExtenderInfo
ExtenderInfos wrap extender properties...
Class LocalizableAttribute
Topic under construction.
Class MemberAttribute
Represents a base class for describing aspects of a member (property, method, or event).
Class MemberInfo
Topic under construction.
Class Multicast
The Multicast class implements a multicast-enabled Closure.
Class NonBrowsableAttribute
Implements a nonbrowsable attribute.
Class PropertyInfo
Describes a property.
Class ResourceManager
Manages resource data.
Class ResourceReader
Reads a binary resources stream into a HashTable that contains property names and values.
Class ResourceWriter
The ResourceWriter is responsible for persisting resource data to disk.
Class SubProperty
Topic under construction.
Class Sys
Retrieves named localized resources for various data types.
Class ValueEditor
Represents a standard implementation of the IValueEditor interface.
Class ValueEditorAttribute
Holds the class name of the value editor that should be used to edit a specific property.

Interfaces

Interface IAttributes
Represents a callback interface that is used in implementations of the getAttributes() method of the IClassInfo interface.
Interface IClassInfo
Provides meta-information for a component that cannot be determined from the component itself.
Interface IComponent
The IComponent interface represents a component.
Interface IConstructable
Allows for immutable objects to indicate what constructor arguments would result in an equivalent object.
Interface IContainer
Represents a container object that provides sites for components.
Interface ICustomizer
The ICustomizer interface represents the implementation of a customizer for a particular component.
Interface IDesignPage
Defines a design page, which is a page of a dialog box that allows for changing design time settings.
Interface IDesignPageSite
This interface defines a site for an IDesignPage.
Interface IDropDown
Service interface for implementing custom drop-down behavior in a value editor.
Interface IEvents
The IEvents interface is a callback interface that is used in implementations of the getEvents() method of the IClassInfo interface.
Interface IExtenderProvider
A component extends IExtenderProvider when it wants to provide extender properties for other components in a container.
Interface IExtenders
The IExtenders interface is a callback interface that is used in implementations of the getExtenderProperties() method of the IClassInfo interface.
Interface IPersistable
Allows an object to be persisted to a stream and depersisted from a stream.
Interface IProperties
The IProperties interface is a callback interface that is used in implementations of the getProperties() method of the IClassInfo interface.
Interface IRequireBegin
Any object that implements this method requires the begin method to be called before the object is usable.
Interface IResourceLoader
IResourceLoader represents a component that supports retrieving a resource from that component's namespace.
Interface IResourceReader
Interface that allows an object to depersist resource data from a binary resource file.
Interface IResourceWriter
Allows an object to participate in the storing of resource- based properties.
Interface ISite
Topic under construction.
Interface IValueAccess
Topic under construction.
Interface IValueEditor
The IValueEditor interface represents the implementation of an editor for values of a given type.


 CancelEvent Class

CancelEvent Class

This Package | All Packages

Event
  |
  +--CancelEvent
public class CancelEvent
extends Event

Represents an event fired by components to enable you to cancel a particular operation. The cancel field lets you specify true or false as to whether the event should be cancelled. [true means cancel, false means don't]

Fields
Name | Description
cancel | Indicates, on return, whether or not the operation should be cancelled or not.

Constructors
Name | Description
CancelEvent(boolean cancel) | Creates a CancelEvent object.
CancelEvent(boolean cancel) | Creates a new CancelEvent object.

Fields

CancelEvent.cancel

Syntax
public boolean cancel;
Description
Indicates, on return, whether or not the operation should be cancelled or not. Cancel if true, otherwise do not cancel.

Constructors

CancelEvent.CancelEvent

Syntax 1
public CancelEvent( boolean cancel );
Parameters
cancel
Set to true to cancel the event. This sets the CancelEvent.cancel member.
Description

Creates a CancelEvent object.

Syntax 2
public CancelEvent( boolean cancel );
Description

Creates a new CancelEvent object. The default value for the cancel field is false.


 CategoryAttribute Class

CategoryAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--CategoryAttribute
public class CategoryAttribute
extends MemberAttribute

Defines a category for a member. Category attributes are used to drive development tool features like property browsers that present categories such as "Data", "Position", and so on.

Fields
Name | Description
Action | Topic under construction.
Appearance | Topic under construction.
Behavior | Topic under construction.
category | Topic under construction.
Data | Topic under construction.
DragDrop | Topic under construction.
Focus | Topic under construction.
Key | Topic under construction.
Mouse | Topic under construction.
Position | Topic under construction.

Constructors
Name | Description
CategoryAttribute(String category) | Topic under construction.

Methods
Name | Description
getCategory() | Topic under construction.

Fields

CategoryAttribute.Action

Syntax
public static final CategoryAttribute Action;
Description
Topic under construction.

CategoryAttribute.Appearance

Syntax
public static final CategoryAttribute Appearance;
Description
Topic under construction.

CategoryAttribute.Behavior

Syntax
public static final CategoryAttribute Behavior;
Description
Topic under construction.

CategoryAttribute.category

Syntax
public final String category;
Description
Topic under construction.

CategoryAttribute.Data

Syntax
public static final CategoryAttribute Data;
Description
Topic under construction.

CategoryAttribute.DragDrop

Syntax
public static final CategoryAttribute DragDrop;
Description
Topic under construction.

CategoryAttribute.Focus

Syntax
public static final CategoryAttribute Focus;
Description
Topic under construction.

CategoryAttribute.Key

Syntax
public static final CategoryAttribute Key;
Description
Topic under construction.

CategoryAttribute.Mouse

Syntax
public static final CategoryAttribute Mouse;
Description
Topic under construction.

CategoryAttribute.Position

Syntax
public static final CategoryAttribute Position;
Description
Topic under construction.

Constructors

CategoryAttribute.CategoryAttribute

Syntax
public CategoryAttribute( String category );
Description

Topic under construction.

Methods

CategoryAttribute.getCategory

Syntax
public String getCategory();
Description

Topic under construction.


 ClassInfo Class

ClassInfo Class

This Package | All Packages

public class ClassInfo
implements IClassInfo

Represents the base class implementation of IClassInfo, which is used to describe a component so that it is compatible with the Visual J++ designer.

Methods
Name | Description
getAttributes(IAttributes attributes) | Specifies the attributes of the associated class by calling the add() method of the specified IAttributes callback interface.
getCustomizer(Object component) | Retrieves a customizer for the specified component.
getDefaultEventName() | Retrieves the name of the default event for the associated component class.
getDefaultPropertyName() | Retrieves the name of the default property for the associated component class.
getEvents(IEvents events) | Specifies the events of the associated class by calling the add() method of the specified IEvents callback interface.
getExtenders(IExtenders extenders) | Specifies the properties of the associated class by calling the appropriate add() methods of the specified IProperties callback interface.
getProperties(IProperties props) | Specifies the properties of the associated class by calling the appropriate add() methods of the specified IProperties callback interface.
getToolboxBitmap() | Retrieves an image that contains a 16x16 pixel icon used to represent the component in toolboxes, list views, and so on.

Methods

ClassInfo.getAttributes

Syntax
public void getAttributes( IAttributes attributes );
Parameters
attributes
An IAttributes interface that functions as a callback for the attribute list.
Description

Specifies the attributes of the associated class by calling the add() method of the specified IAttributes callback interface.

See Also
wfc.core.IAttributes, getAttributes

ClassInfo.getCustomizer

Syntax
public ICustomizer getCustomizer( Object component );
Parameters
component
Topic under construction.
Return Value

Returns the customizer.

Description

Retrieves a customizer for the specified component.

See Also
getCustomizer

ClassInfo.getDefaultEventName

Syntax
public String getDefaultEventName();
Return Value

Returns the default event name.

Description

Retrieves the name of the default event for the associated component class.

See Also
getDefaultEventName

ClassInfo.getDefaultPropertyName

Syntax
public String getDefaultPropertyName();
Description

Retrieves the name of the default property for the associated component class.

See Also
getDefaultPropertyName

ClassInfo.getEvents

Syntax
public void getEvents( IEvents events );
Parameters
events
An IEvents interface that functions as a callback for the event list.
Description

Specifies the events of the associated class by calling the add() method of the specified IEvents callback interface.

See Also
wfc.core.IEvents, getEvents

ClassInfo.getExtenders

Syntax
public void getExtenders( IExtenders extenders );
Parameters
extenders
Topic under construction.
Description

Specifies the properties of the associated class by calling the appropriate add() methods of the specified IProperties callback interface.

See Also
getExtenders

ClassInfo.getProperties

Syntax
public void getProperties( IProperties props );
Parameters
props
Topic under construction.
Description

Specifies the properties of the associated class by calling the appropriate add() methods of the specified IProperties callback interface.

See Also
getProperties

ClassInfo.getToolboxBitmap

Syntax
public Bitmap getToolboxBitmap();
Return Value

Returns the icon bitmap.

Description

Retrieves an image that contains a 16x16 pixel icon used to represent the component in toolboxes, list views, and so on.

See Also
getToolboxBitmap


 Component Class

Component Class

This Package | All Packages

public class Component
implements IComponent, IResourceLoader

Represents a base class implementation of IComponent.

Constructors
Name | Description
Component() | Creates a Component object.

Methods
Name | Description
addEventHandler(Object key, Delegate handler) | Adds an event handler for a specified key in the event list.
addOnDispose(EventHandler value) | Adds an OnDispose event handler.
componentChanged() | Calls the ISite.componentChanged method if the component is sited in a container.
dispose() | Removes this component from the container if it is sited.
fireEvent(Object key, Event e) | Fires an event from this component.
getChildOf(IComponent component) | Checks if this component is a child of the specified component.
getContainer() | Returns the container to which this component is sited if there is one.
getDesignMode() | Determines if the component is currently in design mode.
getDisposing() | Determines if the component is currently being disposed.
getEventHandler(Object key) | Retrieves a specified event handler.
getName() | Retrieves the component name as maintained by the component's site.
getResource(String name) | Retrieves a named resource.
getService(Class service) | Retrieves the service provided by the site.
getSite() | Retrieves the site of this component.
onDispose(Event e) | Calls an event handler when being disposed.
removeEventHandler(Object key, Delegate handler) | Removes an OnDispose event handler.
removeEventHandlers() | Removes all event handlers from this component.
removeOnDispose(EventHandler value) | Removes an OnDispose event handler.
setName(String value) | Sets the name of the component held by the site.
setSite(ISite value) | Sets the site of this component.

Constructors

Component.Component

Syntax
public Component();
Description

Creates a Component object.

Methods

Component.addEventHandler

Syntax
protected void addEventHandler( Object key, Delegate handler );
Parameters
key
The object in the event list to add the handler to.
handler
The delegate that references the event handler for the key object.
Description

Adds an event handler for a specified key in the event list.

Component.addOnDispose

Syntax
public void addOnDispose( EventHandler value );
Description

Adds an OnDispose event handler.

See Also
addOnDispose

Component.componentChanged

Syntax
public void componentChanged();
Description

Calls the ISite.componentChanged method if the component is sited in a container.

Component.dispose

Syntax
public void dispose();
Description

Removes this component from the container if it is sited.

See Also
dispose

Component.fireEvent

Syntax
protected void fireEvent( Object key, Event e );
Description

Fires an event from this component.

Component.getChildOf

Syntax
public boolean getChildOf( IComponent component );
Description

Checks if this component is a child of the specified component.

See Also
getChildOf

Component.getContainer

Syntax
public IContainer getContainer();
Description

Returns the container to which this component is sited if there is one.

Component.getDesignMode

Syntax
public boolean getDesignMode();
Description

Determines if the component is currently in design mode.

Component.getDisposing

Syntax
public boolean getDisposing();
Description

Determines if the component is currently being disposed.

Component.getEventHandler

Syntax
protected Delegate getEventHandler( Object key );
Parameters
key
The object in the event list.
Description

Retrieves a specified event handler.

Component.getName

Syntax
public String getName();
Return Value

Returns the Site.name string, or returns null if the component is not sited.

Description

Retrieves the component name as maintained by the component's site.

Component.getResource

Syntax
public IDataStream getResource( String name );
Description

Retrieves a named resource.

Component.getService

Syntax
public Object getService( Class service );
Return Value

Returns null currently.

Description

Retrieves the service provided by the site.

Component.getSite

Syntax
public ISite getSite();
Return Value

Returns the site of this component.

Description

Retrieves the site of this component.

See Also
IComponent.getSite, wfc.core.ISite

Component.onDispose

Syntax
protected void onDispose( Event e );
Description

Calls an event handler when being disposed.

See Also
onDispose

Component.removeEventHandler

Syntax
protected void removeEventHandler( Object key, Delegate handler );
Description

Removes an OnDispose event handler.

Component.removeEventHandlers

Syntax
protected void removeEventHandlers();
Description

Removes all event handlers from this component.

Component.removeOnDispose

Syntax
public void removeOnDispose( EventHandler value );
Description

Removes an OnDispose event handler.

See Also
removeOnDispose

Component.setName

Syntax
public void setName( String value );
Parameters
value
The new name of the component.
Description

Sets the name of the component held by the site.

Component.setSite

Syntax
public void setSite( ISite value );
Parameters
value
The site of this component.
Description

Sets the site of this component.

See Also
IComponent.setSite, wfc.core.ISite


 ComponentInfo Class

ComponentInfo Class

This Package | All Packages

public final class ComponentInfo

Contains information about a component including its properties, events, and attributes.

Methods
Name | Description
getAttributes() | Topic under construction.
getClassInfo() | Topic under construction.
getComponentClass() | Topic under construction.
getDefaultEventName() | Topic under construction.
getDefaultPropertyName() | Topic under construction.
getEvents() | Topic under construction.
getExtenders() | Topic under construction.
getProperties() | Topic under construction.

Methods

ComponentInfo.getAttributes

Syntax
public MemberAttribute[] getAttributes();
Description

Topic under construction.

ComponentInfo.getClassInfo

Syntax
public IClassInfo getClassInfo();
Description

Topic under construction.

ComponentInfo.getComponentClass

Syntax
public Class getComponentClass();
Description

Topic under construction.

ComponentInfo.getDefaultEventName

Syntax
public String getDefaultEventName();
Description

Topic under construction.

ComponentInfo.getDefaultPropertyName

Syntax
public String getDefaultPropertyName();
Description

Topic under construction.

ComponentInfo.getEvents

Syntax
public EventInfo[] getEvents();
Description

Topic under construction.

ComponentInfo.getExtenders

Syntax
public ExtenderInfo[] getExtenders();
Description

Topic under construction.

ComponentInfo.getProperties

Syntax
public PropertyInfo[] getProperties();
Description

Topic under construction.


 ComponentManager Class

ComponentManager Class

This Package | All Packages

public final class ComponentManager

Implements an easy way to browse properties and events for a component.

Methods
Name | Description
classForName(Class cls, String name) throws ClassNotFoundException | Loads a class given its name.
createClassInfo(Class classInfoClass) | Topic under construction.
createValueEditor( Class valueEditorClass) | Topic under construction.
getComponentInfo( Class componentClass) | Topic under construction.
getValueEditor(Class type) | Topic under construction.
registerValueEditorClass(Class type, Class valueEditorClass) | Topic under construction.

Methods

ComponentManager.classForName

Syntax
public static Class classForName( Class cls, String name ) throws ClassNotFoundException;
Parameters
cls
A class that was loaded with the same namespace (class loader) as the class you want to find.
name
The name of the class to load.
Return Value

Returns a java.lang.Class for the given class name.

Description

Loads a class given its name. This loads the class using the class loader of the given site.

Exceptions

Throws a java.lang.ClassNotFoundException on failure.

ComponentManager.createClassInfo

Syntax
public static IClassInfo createClassInfo( Class classInfoClass );
Description

Topic under construction.

ComponentManager.createValueEditor

Syntax
public static IValueEditor createValueEditor( Class valueEditorClass );
Description

Topic under construction.

ComponentManager.getComponentInfo

Syntax
public static ComponentInfo getComponentInfo( Class componentClass );
Description

Topic under construction.

ComponentManager.getValueEditor

Syntax
public static IValueEditor getValueEditor( Class type );
Description

Topic under construction.

ComponentManager.registerValueEditorClass

Syntax
public static void registerValueEditorClass( Class type, Class valueEditorClass );
Description

Topic under construction.


 ConstructorArg Class

ConstructorArg Class

This Package | All Packages

public class ConstructorArg

Represents objects that are returned by the classes that implement the IConstructable.getConstructorArgs method. This encapsulates an (Object value, Class type) pair that can be used as an argument for a constructor. This class is primarily used by controls to persist the object at design time.

Constructors
Name | Description
ConstructorArg(Object value, Class type) | Creates a ConstructorArg object.

Methods
Name | Description
getType() | Retrieves the type of the ConstrutorArg object.
getValue() | Retrieves the value of the ConstrutorArg object.

Constructors

ConstructorArg.ConstructorArg

Syntax
public ConstructorArg( Object value, Class type );
Parameters
value
The value expressed (cast) as the appropriate class object. For example,
Integer(entry.weight)

.

type
The class pertaining to the type. For example,
Integer.TYPE

.

Description

Creates a ConstructorArg object. The following code sample demonstrates creating a ConstructorArg array for a Point object.

    public ConstructorArg[] getConstructorArgs() {
      return new ConstructorArg[] {
        new ConstructorArg(new Integer(x), Integer.TYPE),
        new ConstructorArg(new Integer(y), Integer.TYPE)
      };

Methods

ConstructorArg.getType

Syntax
public Class getType();
Description

Retrieves the type of the ConstrutorArg object. This is a class, such as Integer or Boolean.

ConstructorArg.getValue

Syntax
public Object getValue();
Description

Retrieves the value of the ConstrutorArg object.


 Container Class

Container Class

This Package | All Packages

public class Container
implements IContainer

Provides a base class implementation of the IContainer interface.

Constructors
Name | Description
Container() | Creates a Container object.

Methods
Name | Description
add(IComponent component) | Adds a component to the container.
add(IComponent component, String name) | Adds a component to the container.
dispose() | Removes all components from a container.
getComponent(String name) | Retreives a named component from the container.
getComponents() | Retreives an array of all components from the container.
remove(IComponent component) | Removes a component from the container.

Constructors

Container.Container

Syntax
public Container();
Description

Creates a Container object.

Methods

Container.add

Syntax 1
public void add( IComponent component );
Parameters
component
The component object to add.
Description

Adds a component to the container.

Syntax 2
public void add( IComponent component, String name );
Parameters
component
The component object to add.
name
The name of the component being added.
Description

Adds a component to the container.

Container.dispose

Syntax
public void dispose();
Description

Removes all components from a container.

Container.getComponent

Syntax
public IComponent getComponent( String name );
Parameters
name
The name of the component to retrieve.
Return Value

Returns the component requested, or null if this component is not found.

Description

Retreives a named component from the container.

Container.getComponents

Syntax
public IComponent[] getComponents();
Return Value

Returns all components currently sited in this container.

Description

Retreives an array of all components from the container.

Container.remove

Syntax
public void remove( IComponent component );
Parameters
component
The component to remove.
Description

Removes a component from the container.


 Customizer Class

Customizer Class

This Package | All Packages

public class Customizer
implements ICustomizer

Provides a base class implementation of the ICustomizer interface.

Methods
Name | Description
edit() | Edits the component associated with the customizer.
getDesignFilter() | Allows your component to support a design time user interface.
getDesignPages() | Returns an array of of classes for each design page that this component utilizes.
getVerbs() | Retrieves the design-time verbs supported by the component associated with the customizer.
performVerb(CustomizerVerb verb) | Performs the action associated with the given verb on the component associated with the customizer.

Methods

Customizer.edit

Syntax
public void edit();
Description

Edits the component associated with the customizer.

See Also
edit

Customizer.getDesignFilter

Syntax
public IDesignFilter getDesignFilter();
Return Value

Returns an IDesignFilter object if your component requires design time message filtering; otherwise, returns null.

Description

Allows your component to support a design time user interface.

See Also
getDesignFilter

Customizer.getDesignPages

Syntax
public Class [] getDesignPages();
Description

Returns an array of of classes for each design page that this component utilizes.

See Also
getDesignPages

Customizer.getVerbs

Syntax
public CustomizerVerb[] getVerbs();
Return Value

Returns an array of verbs supported by the component.

Description

Retrieves the design-time verbs supported by the component associated with the customizer.

See Also
getVerbs

Customizer.performVerb

Syntax
public void performVerb( CustomizerVerb verb );
Parameters
verb
Action to be performed. Use the getVerbs() method to retrieve possible verbs.
Description

Performs the action associated with the given verb on the component associated with the customizer.

See Also
performVerb


 CustomizerVerb Class

CustomizerVerb Class

This Package | All Packages

public class CustomizerVerb

The CustomizerVerb class represents a verb that can be run by a component's customizer.

Constructors
Name | Description
CustomizerVerb(int id, String text) | Creates a customizer verb with the given ID and description.

Methods
Name | Description
getID() | Retrieves the user-defined ID of the verb.
getText() | Retrieves the text description of the verb.

Constructors

CustomizerVerb.CustomizerVerb

Syntax
public CustomizerVerb( int id, String text );
Description

Creates a customizer verb with the given ID and description. Customizer verbs are created by the getVerbs() method of the ICustomizer interface. The meaning of the id parameter is entirely determined by the particular customizer; it is typically used in a switch statement in the implementation of the performVerb() method.

Methods

CustomizerVerb.getID

Syntax
public int getID();
Description

Retrieves the user-defined ID of the verb.

CustomizerVerb.getText

Syntax
public String getText();
Description

Retrieves the text description of the verb.


 DefaultValueAttribute Class

DefaultValueAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--DefaultValueAttribute
public class DefaultValueAttribute
extends MemberAttribute

Holds the default value for a property.

Fields
Name | Description
value | The default property value.

Constructors
Name | Description
DefaultValueAttribute(Object value) | Creates a DefaultValueAttribute object.

Fields

DefaultValueAttribute.value

Syntax
public final Object value;
Description
The default property value.

Constructors

DefaultValueAttribute.DefaultValueAttribute

Syntax
public DefaultValueAttribute( Object value );
Parameters
value
The default property value.
Description

Creates a DefaultValueAttribute object.


 DescriptionAttribute Class

DescriptionAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--DescriptionAttribute
public class DescriptionAttribute
extends MemberAttribute

Holds the description string for a member (property, method or event).

Fields
Name | Description
description | The member description string.

Constructors
Name | Description
DescriptionAttribute(String description) | Creates a DescriptionAttribute object.

Methods
Name | Description
getDescription() | Retrieves the member description.

Fields

DescriptionAttribute.description

Syntax
public final String description;
Description
The member description string.

Constructors

DescriptionAttribute.DescriptionAttribute

Syntax
public DescriptionAttribute( String description );
Parameters
The member description string.
Description

Creates a DescriptionAttribute object.

Methods

DescriptionAttribute.getDescription

Syntax
public String getDescription();
Return Value

Returns the member description string.

Description

Retrieves the member description.


 DesignForm Class

DesignForm Class

This Package | All Packages

Form
  |
  +--DesignForm
public class DesignForm
extends Form

Implements a DesignForm object. A DesignForm extends wfc.ui.Form and shows a tabbed view of available design pages. Design pages are objects that implement IDesignPage. DesignPage is a stock implementation of a design page.

Constructors
Name | Description
DesignForm(Object [] ObjectList) | Creates a new DesignForm object.

Methods
Name | Description
getPage(int index) | Returns the requested design page.
getPageCount() | Returns the number of design pages on this form.
preProcessMessage(MSG msg) | This method is called by the application's message loop to preprocess input messages before they are dispatched.
showForm() | Displays the design form.
showForm(int page) | Displays the design form.
showForm(Form owner) | Displays the design form.
showForm(Form owner, int page) | Displays the design form.

Constructors

DesignForm.DesignForm

Syntax
public DesignForm( Object [] ObjectList );
Parameters
ObjectList
A list of objects for which the design form should show properties. The design form finds the common DesignPages for all the objects.
Description

Creates a new DesignForm object.

Methods

DesignForm.getPage

Syntax
public IDesignPage getPage( int index );
Parameters
Index
The index of the page to return.
Return Value

Returns an IDesignPage interface for the page.

Description

Returns the requested design page.

DesignForm.getPageCount

Syntax
public int getPageCount();
Return Value

Returns the number of design pages.

Description

Returns the number of design pages on this form.

DesignForm.preProcessMessage

Syntax
public boolean preProcessMessage( MSG msg );
Description

This method is called by the application's message loop to preprocess input messages before they are dispatched. This method forwards IDesignPage messages as necessary.

DesignForm.showForm

Syntax 1
public int showForm();
Return Value

Returns the dialog return code.

Description

Displays the design form. The form has no owner window.

Syntax 2
public int showForm( int page );
Parameters
Page
The index of the page to display.
Return Value

Returns the dialog return code.

Description

Displays the design form. The form has no owner window.

Syntax 3
public int showForm( Form owner );
Parameters
Owner
The form that owns the form to be displayed.
Return Value

Returns the dialog return code.

Description

Displays the design form.

Syntax 4
public int showForm( Form owner, int page );
Parameters
Owner
The form that owns the form to be displayed.
Page
Index of the page to display.
Return Value

Returns the dialog return code.

Description

Displays the design form.


 DesignPage Class

DesignPage Class

This Package | All Packages

Form
  |
  +--DesignPage
public class DesignPage
extends Form
implements IDesignPage

Defines a base implementation for IDesignPage. With this class, you receive a complete implementation for a design page that consists of an empty window. Extend this page to add your own controls.

Also see wfc.core.IDesignPage

Fields
Name | Description
NULLVALUE | Indicates a property value of null.

Constructors
Name | Description
DesignPage() | Creates a DesignPage object.

Methods
Name | Description
activate() | Activates and displays the page.
apply() | Applies changes to all objects in this page's object list.
deactivate() | Deactivates the page.
getControl() | Returns the control that represents the window for this page.
getCreateParams() | Returns the creation parameters for this control Return Value: Returns a wfc.ui.CreateParams object.
getPageMessage(MSG msg) | Gives the design page an opportunity to process messages before the caller uses them.
getSize() | Retrieves the width and height of this page.
getTitle() | Retrieves the title of the design page.
onReadProperty(String name) | Called when necessary to read a property from the property page and store it in an object.
onWriteProperty(String name, Object value) | Called when a property value needs to be written to a page's user interface.
setDirty() | Called by an extending object's UI to mark this page as dirty.
setObjects(Object [] objects) | Called before activation to set up the array of objects that this page is modifying properties for.
setSite(IDesignPageSite site) | Called before this page is activated to set up the site used to notify the caller of changes.
setSize(Point size) | Called to enlarge the size of this page.
supportsHelp() | Determines whether the Help icon should be shown at the top of the dialog box.

Fields

DesignPage.NULLVALUE

Syntax
public static final Object NULLVALUE;
Description
Indicates a property value of null.

Constructors

DesignPage.DesignPage

Syntax
public DesignPage();
Description

Creates a DesignPage object.

Methods

DesignPage.activate

Syntax
public void activate();
Description

Activates and displays the page.

See Also
wfc.core.IDesignPage

DesignPage.apply

Syntax
public void apply();
Description

Applies changes to all objects in this page's object list.

See Also
wfc.core.IDesignPage

DesignPage.deactivate

Syntax
public void deactivate();
Description

Deactivates the page. A page can be deactivated and later reactivated.

See Also
wfc.core.IDesignPage

DesignPage.getControl

Syntax
public Control getControl();
Return Value

Returns a Control object.

Description

Returns the control that represents the window for this page.

DesignPage.getCreateParams

Syntax
protected CreateParams getCreateParams();
Return Value

Returns a wfc.ui.CreateParams object.

Description

Returns the creation parameters for this control

See Also
wfc.ui.Control

DesignPage.getPageMessage

Syntax
public boolean getPageMessage( MSG msg );
Parameters
msg
The message to process.
Return Value

Returns true if this page processed the message; otherwise, returns false. If getPageMessage returns true, the message is disregarded. Otherwise, the caller will continue to process the message.

Description

Gives the design page an opportunity to process messages before the caller uses them.

See Also
wfc.core.IDesignPage

DesignPage.getSize

Syntax
public Point getSize();
Return Value

Returns the size of the page.

Description

Retrieves the width and height of this page. The caller can use this to size the page appropriately.

See Also
wfc.core.IDesignPage

DesignPage.getTitle

Syntax
public String getTitle();
Return Value

Returns the title of the page.

Description

Retrieves the title of the design page. The caller can use this to show the name of this page before displaying the page.

See Also
wfc.core.IDesignPage

DesignPage.onReadProperty

Syntax
protected Object onReadProperty( String name );
Parameters
name
The name of the property to read.
Return Value

Returns an object that reflects what the UI currently contains for the property. If the UI doesn't support the property, or if the UI contains the original default value for the property, this should return null. If the value from the object truly is null, use DesignPage.NULLVALUE.

Description

Called when necessary to read a property from the property page and store it in an object.

DesignPage.onWriteProperty

Syntax
protected void onWriteProperty( String name, Object value );
Parameters
name
The name of the property to write.
value
The value of the property. This will be null if several objects are in the object list and they have inconsistent values for the property. The UI should show an indeterminate state for this property. If the object's value is truly null, this will contain the value DesignPage.NULLVALUE.
Description

Called when a property value needs to be written to a page's user interface.

DesignPage.setDirty

Syntax
protected void setDirty();
Description

Called by an extending object's UI to mark this page as dirty.

DesignPage.setObjects

Syntax
public void setObjects( Object [] objects );
Parameters
objects
The array of objects this page is to modify.
Description

Called before activation to set up the array of objects that this page is modifying properties for. The objects are not guaranteed to be of any particular type; their only commonality is that they have all specified that they use this design page class.

See Also
wfc.core.IDesignPage

DesignPage.setSite

Syntax
public void setSite( IDesignPageSite site );
Parameters
site
The design page site to which this page is attached.
Description

Called before this page is activated to set up the site used to notify the caller of changes.

See Also
wfc.core.IDesignPage

DesignPage.setSize

Syntax
public void setSize( Point size );
Parameters
size
The new size.
Description

Called to enlarge the size of this page. This is done after the caller has determined the sizes of all pages. If this page supports resizing to a larger size, it should do so. A design page will never be requested to size smaller than its default size.

See Also
wfc.core.IDesignPage

DesignPage.supportsHelp

Syntax
public boolean supportsHelp();
Return Value

Returns true if the Help icon is enabled for this page; otherwise, returns false.

Description

Determines whether the Help icon should be shown at the top of the dialog box. If one or more pages supports the icon, the icon is displayed. For pages that do not support Help, the icon is dimmed.

See Also
wfc.core.IDesignPage


 Enum Class

Enum Class

This Package | All Packages

public class Enum

Represents the base enumerator class. This is used so that the Property Browser recognizes your constants. To create your own enumerator class, list the public static final integers that make up your enumerator. To associate a property with this enumerator, register the property as the enumerator type in your ClassInfo inner class (even though technically the property is of type int). The Property Browser displays a drop-down list with the choices.

The following is sample code:

class Alignment extends Enum {

  public static final int NONE = 0;
  public static final int LEFT = 1;
  public static final int CENTER = 2;
  public static final int RIGHT = 3;
}

foo.setAlignment(Alignment.LEFT);


 Event Class

Event Class

This Package | All Packages

public class Event

Represents the base class for all events. This class is used without modification for events without parameters and is extended for events with parameters.

Fields
Name | Description
EMPTY | Represents an event.

Constructors
Name | Description
Event() | Creates an Event object.

Fields

Event.EMPTY

Syntax
public static final Event EMPTY;
Description
Represents an event.

Constructors

Event.Event

Syntax
public Event();
Description

Creates an Event object.


 EventInfo Class

EventInfo Class

This Package | All Packages

MemberInfo
  |
  +--EventInfo
public final class EventInfo
extends MemberInfo

Topic under construction.

Fields
Name | Description
type | Topic under construction.

Constructors
Name | Description
EventInfo(Class componentClass, String name, Class type, MemberAttribute[] attributes) | Topic under construction.
EventInfo(Class componentClass, String name, Class type) | Topic under construction.
EventInfo(Class componentClass, String name, Class type, MemberAttribute a1) | Topic under construction.
EventInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2) | Topic under construction.
EventInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3) | Topic under construction.
EventInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4) | Topic under construction.

Methods
Name | Description
addEventHandler(Object component, Delegate value) | Topic under construction.
getAddMethod() | Topic under construction.
getMulticast() | Topic under construction.
getRemoveMethod() | Topic under construction.
getType() | Topic under construction.
removeEventHandler(Object component, Delegate value) | Topic under construction.

Fields

EventInfo.type

Syntax
public Class type;
Description
Topic under construction.

Constructors

EventInfo.EventInfo

Syntax 1
public EventInfo( Class componentClass, String name, Class type, MemberAttribute[] attributes );
Description

Topic under construction.

Syntax 2
public EventInfo( Class componentClass, String name, Class type );
Description

Topic under construction.

Syntax 3
public EventInfo( Class componentClass, String name, Class type, MemberAttribute a1 );
Description

Topic under construction.

Syntax 4
public EventInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2 );
Description

Topic under construction.

Syntax 5
public EventInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3 );
Description

Topic under construction.

Syntax 6
public EventInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4 );
Description

Topic under construction.

Methods

EventInfo.addEventHandler

Syntax
public void addEventHandler( Object component, Delegate value );
Description

Topic under construction.

EventInfo.getAddMethod

Syntax
public Method getAddMethod();
Description

Topic under construction.

EventInfo.getMulticast

Syntax
public boolean getMulticast();
Description

Topic under construction.

EventInfo.getRemoveMethod

Syntax
public Method getRemoveMethod();
Description

Topic under construction.

EventInfo.getType

Syntax
public Class getType();
Description

Topic under construction.

EventInfo.removeEventHandler

Syntax
public void removeEventHandler( Object component, Delegate value );
Description

Topic under construction.


 ExtenderInfo Class

ExtenderInfo Class

This Package | All Packages

MemberInfo
  |
  +--ExtenderInfo
public class ExtenderInfo
extends MemberInfo

ExtenderInfos wrap extender properties... They are extended versions of regular properties that let objects handle properties for other properties... given extender property foo that extends to objects of type Bar to handle property type Baz, the code looks like...

     void setFoo(Bar target, Baz value);
     Baz getFoo(Bar target);
     boolean changedFoo(Bar target);
     void resetFoo(Bar target);

Fields
Name | Description
extendeeType | Topic under construction.
propertyType | Topic under construction.

Constructors
Name | Description
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute[] attributes) | Topic under construction.
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType) | Topic under construction.
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1) | Topic under construction.
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2) | Topic under construction.
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3) | Topic under construction.
ExtenderInfo(Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4) | Topic under construction.

Methods
Name | Description
changedValue(Object extender, Object extendee) | Topic under construction.
getChangedAccessor() | Topic under construction.
getExtendeeType() | Topic under construction.
getGetAccessor() | Topic under construction.
getResetAccessor() | Topic under construction.
getSetAccessor() | Topic under construction.
getType() | Topic under construction.
getValue(Object extender, Object extendee) | Topic under construction.
getValueEditor() | Topic under construction.
resetValue(Object extender, Object extendee) | Topic under construction.
setValue(Object extender, Object extendee, Object value) | Topic under construction.

Fields

ExtenderInfo.extendeeType

Syntax
public Class extendeeType;
Description
Topic under construction.

ExtenderInfo.propertyType

Syntax
public Class propertyType;
Description
Topic under construction.

Constructors

ExtenderInfo.ExtenderInfo

Syntax 1
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute[] attributes );
Description

Topic under construction.

Syntax 2
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType );
Description

Topic under construction.

Syntax 3
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1 );
Description

Topic under construction.

Syntax 4
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2 );
Description

Topic under construction.

Syntax 5
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3 );
Description

Topic under construction.

Syntax 6
public ExtenderInfo( Class extenderClass, String propertyName, Class extendeeType, Class propertyType, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4 );
Description

Topic under construction.

Methods

ExtenderInfo.changedValue

Syntax
public boolean changedValue( Object extender, Object extendee );
Description

Topic under construction.

ExtenderInfo.getChangedAccessor

Syntax
public Method getChangedAccessor();
Description

Topic under construction.

ExtenderInfo.getExtendeeType

Syntax
public Class getExtendeeType();
Description

Topic under construction.

ExtenderInfo.getGetAccessor

Syntax
public Method getGetAccessor();
Description

Topic under construction.

ExtenderInfo.getResetAccessor

Syntax
public Method getResetAccessor();
Description

Topic under construction.

ExtenderInfo.getSetAccessor

Syntax
public Method getSetAccessor();
Description

Topic under construction.

ExtenderInfo.getType

Syntax
public Class getType();
Description

Topic under construction.

ExtenderInfo.getValue

Syntax
public Object getValue( Object extender, Object extendee );
Description

Topic under construction.

ExtenderInfo.getValueEditor

Syntax
public IValueEditor getValueEditor();
Description

Topic under construction.

ExtenderInfo.resetValue

Syntax
public void resetValue( Object extender, Object extendee );
Description

Topic under construction.

ExtenderInfo.setValue

Syntax
public void setValue( Object extender, Object extendee, Object value );
Description

Topic under construction.


 LocalizableAttribute Class

LocalizableAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--LocalizableAttribute
public class LocalizableAttribute
extends MemberAttribute

Topic under construction.

Constructors
Name | Description
LocalizableAttribute() | Creates a LocalizableAttribute object.

Constructors

LocalizableAttribute.LocalizableAttribute

Syntax
public LocalizableAttribute();
Description

Creates a LocalizableAttribute object.


 MemberAttribute Class

MemberAttribute Class

This Package | All Packages

public abstract class MemberAttribute

Represents a base class for describing aspects of a member (property, method, or event).


 MemberInfo Class

MemberInfo Class

This Package | All Packages

public class MemberInfo

Topic under construction.

Fields
Name | Description
attributes | Topic under construction.
name | Topic under construction.

Constructors
Name | Description
MemberInfo(String name, MemberAttribute[] attributes) | Topic under construction.

Methods
Name | Description
getAttribute(Class attributeClass) | Topic under construction.
getAttributes() | Topic under construction.
getCategory() | Topic under construction.
getDescription() | Topic under construction.
getName() | Topic under construction.

Fields

MemberInfo.attributes

Syntax
public MemberAttribute[] attributes;
Description
Topic under construction.

MemberInfo.name

Syntax
public String name;
Description
Topic under construction.

Constructors

MemberInfo.MemberInfo

Syntax
public MemberInfo( String name, MemberAttribute[] attributes );
Description

Topic under construction.

Methods

MemberInfo.getAttribute

Syntax
public MemberAttribute getAttribute( Class attributeClass );
Description

Topic under construction.

MemberInfo.getAttributes

Syntax
public MemberAttribute[] getAttributes();
Description

Topic under construction.

MemberInfo.getCategory

Syntax
public String getCategory();
Description

Topic under construction.

MemberInfo.getDescription

Syntax
public String getDescription();
Description

Topic under construction.

MemberInfo.getName

Syntax
public String getName();
Description

Topic under construction.


 Multicast Class

Multicast Class

This Package | All Packages

Closure
  |
  +--Multicast
public abstract class Multicast
extends Closure

The Multicast class implements a multicast-enabled Closure. By inheriting from Multicast instead of Closure, a closure type can support multicasting. A Multicast descendant differs from a Closure descendant only slightly. It requires an extra statement in its implementation of the "invoke" method. An example of a Multicast subclass follows:

  public final class MouseEventHandler extends Multicast
  {
    public MouseEventHandler(Object target, String methodName)
    {
      super(target, methodName);
    }

    public void invoke(int x, int y)
    {
      if (next != null) ((MouseEventHandler)next).invoke(x, y);
      invokeMethod(new Object[] {new Integer(x), new Integer(y)});
    }
  }

Notice the extra statement that calls the "invoke" of the next closure if one is present. For correct invocation order to be preserved, this statement must be written BEFORE the call to "invokeMethod". Although it rarely makes sense, it is possible for closures that return function results to also be multicast. In such cases, the return value of a call to the closure's "invoke" method becomes the return value of the last method in the closure's invocation list. The return values of any methods before the last method in the invocation list are discarded. An example of a multicast closure with a function result follows:

  public final class HitTestEventHandler extends Multicast
  {
    public HitTestEventHandler(Object target, String methodName)
    {
      super(target, methodName);
    }

    public boolean invoke(int x, int y)
    {
      if (next != null) ((HitTestEventHandler)next).invoke(x, y);
      return ((Boolean)invokeMethod(new Object[] {new Integer(x),
        new Integer(y)})).booleanValue();
    }
  }

Notice that the function result of the call to "invoke" of the next closure is discarded.

Methods
Name | Description
getInvocationList() | Topic under construction.

Methods

Multicast.getInvocationList

Syntax
public Closure[] getInvocationList();
Description

Topic under construction.


 NonBrowsableAttribute Class

NonBrowsableAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--NonBrowsableAttribute
public class NonBrowsableAttribute
extends MemberAttribute

Implements a nonbrowsable attribute. Properties decorated with this attribute should not be shown in value-oriented property browsers.

Constructors
Name | Description
NonBrowsableAttribute() | Creates a NonBrowsableAttribute object.

Constructors

NonBrowsableAttribute.NonBrowsableAttribute

Syntax
public NonBrowsableAttribute();
Description

Creates a NonBrowsableAttribute object.


 PropertyInfo Class

PropertyInfo Class

This Package | All Packages

MemberInfo
  |
  +--PropertyInfo
public class PropertyInfo
extends MemberInfo

Describes a property.

Fields
Name | Description
type | Topic under construction.

Constructors
Name | Description
PropertyInfo(Class componentClass, String name, Class type, MemberAttribute[] attributes) | Creates a PropertyInfo object.
PropertyInfo(Class componentClass, String name, Class type) | Creates a PropertyInfo object.
PropertyInfo(Class componentClass, String name, Class type, MemberAttribute a1) | Creates a PropertyInfo object.
PropertyInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2) | Creates a PropertyInfo object.
PropertyInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3) | Creates a PropertyInfo object.
PropertyInfo(Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4) | Creates a PropertyInfo object.

Methods
Name | Description
changedValue(Object component) | Topic under construction.
getChangedMethod() | Topic under construction.
getGetMethod() | Topic under construction.
getResetMethod() | Topic under construction.
getSetMethod() | Topic under construction.
getType() | Topic under construction.
getValue(Object component) | Topic under construction.
getValueEditor() | Topic under construction.
resetValue(Object component) | Topic under construction.
setValue(Object component, Object value) | Topic under construction.

Fields

PropertyInfo.type

Syntax
public Class type;
Description
Topic under construction.

Constructors

PropertyInfo.PropertyInfo

Syntax 1
public PropertyInfo( Class componentClass, String name, Class type, MemberAttribute[] attributes );
Description

Creates a PropertyInfo object.

Syntax 2
public PropertyInfo( Class componentClass, String name, Class type );
Description

Creates a PropertyInfo object.

Syntax 3
public PropertyInfo( Class componentClass, String name, Class type, MemberAttribute a1 );
Description

Creates a PropertyInfo object.

Syntax 4
public PropertyInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2 );
Description

Creates a PropertyInfo object.

Syntax 5
public PropertyInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3 );
Description

Creates a PropertyInfo object.

Syntax 6
public PropertyInfo( Class componentClass, String name, Class type, MemberAttribute a1, MemberAttribute a2, MemberAttribute a3, MemberAttribute a4 );
Description

Creates a PropertyInfo object.

Methods

PropertyInfo.changedValue

Syntax
public boolean changedValue( Object component );
Description

Topic under construction.

PropertyInfo.getChangedMethod

Syntax
public Method getChangedMethod();
Description

Topic under construction.

PropertyInfo.getGetMethod

Syntax
public Method getGetMethod();
Description

Topic under construction.

PropertyInfo.getResetMethod

Syntax
public Method getResetMethod();
Description

Topic under construction.

PropertyInfo.getSetMethod

Syntax
public Method getSetMethod();
Description

Topic under construction.

PropertyInfo.getType

Syntax
public Class getType();
Description

Topic under construction.

PropertyInfo.getValue

Syntax
public Object getValue( Object component );
Description

Topic under construction.

PropertyInfo.getValueEditor

Syntax
public IValueEditor getValueEditor();
Description

Topic under construction.

PropertyInfo.resetValue

Syntax
public void resetValue( Object component );
Description

Topic under construction.

PropertyInfo.setValue

Syntax
public void setValue( Object component, Object value );
Description

Topic under construction.


 ResourceManager Class

ResourceManager Class

This Package | All Packages

public final class ResourceManager

Manages resource data. Resource data can be stored and retrieved in a locale- specific manner. This enables the creation of localizable applications.

Fields
Name | Description
EXTENSION | Extension given to all resource files.

Constructors
Name | Description
ResourceManager(IResourceLoader loader, String baseName) | Creates a ResourceManager.

Methods
Name | Description
flush() | Releases any cached resource data.
getBoolean(String name) | Retrieves a boolean for the specified property that is valid for the current locale.
getBoolean(Locale locale, String name) | Retrieves the boolean for the specified property that is valid for the specified locale.
getByte(String name) | Retrieves a byte for the specified property that is valid for the current locale.
getByte(Locale locale, String name) | Retrieves the byte for the specified property that is valid for the specified locale.
getChar(String name) | Retrieves a character for the specified property that is valid for the current locale.
getChar(Locale locale, String name) | Retrieves the character for the specified property that is valid for the specified locale.
getDouble(String name) | Retrieves a double for the specified property that is valid for the current locale.
getDouble(Locale locale, String name) | Retrieves the double for the specified property that is valid for the specified locale.
getFloat(String name) | Retrieves a float for the specified property that is valid for the current locale.
getFloat(Locale locale, String name) | Retrieves the float for the specified property that is valid for the specified locale.
getInt(String name) | Retrieves a integer for the specified property that is valid for the current locale.
getInt(Locale locale, String name) | Retrieves the integer for the specified property that is valid for the specified locale.
getLocaleFileName(Locale locale) | Retrieves the file name for the specified locale.
getLocaleFileNameFromBase(Locale locale, String baseName) | Computes the localized file name given the specified locale and baseName.
getLong(String name) | Retrieves a long for the specified property that is valid for the current locale.
getLong(Locale locale, String name) | Retrieves the long for the specified property that is valid for the specified locale.
getNames() | Retrieves all the property names for the current locale.
getNames(Locale locale) | Retrieves all the property names for the specified locale.
getObject(String name) | Retrieves an object for the specified property that is valid for the current locale.
getObject(Locale locale, String name) | Retrieves the object for the specified property that is valid for the specified locale.
getObjects() | Retrieves all the property values for the current locale.
getObjects(Locale locale) | Retrieves all the property values for the current locale.
getShort(String name) | Retrieves a short for the specified property that is valid for the current locale.
getShort(Locale locale, String name) | Retrieves the short for the specified property that is valid for the specified locale.
getString(String name) | Retrieves a string for the specified property that is valid for the current locale.
getString(Locale locale, String name) | Retrieves the string for the specified property that is valid for the specified locale.
getValidData(Object value) | Retrieves true if the specified value can be stored as a resource property.
loadResourceAsStream(Class src, String name) | Loads an arbitrary binary resource file for the specified class.
setBoolean(Locale locale, String name, boolean value) | Sets the value for a property for the specified locale.
setByte(Locale locale, String name, byte value) | Sets the value for a property for the specified locale.
setChar(Locale locale, String name, char value) | Sets the value for a property for the specified locale.
setDouble(Locale locale, String name, double value) | Sets the value for a property for the specified locale.
setFloat(Locale locale, String name, float value) | Sets the value for a property for the specified locale.
setInt(Locale locale, String name, int value) | Sets the value for a property for the specified locale.
setLong(Locale locale, String name, long value) | Sets the value for a property for the specified locale.
setObject(Locale locale, String name, Object value) | Sets the value for a property for the specified locale.
setShort(Locale locale, String name, short value) | Sets the value for a property for the specified locale.
setString(Locale locale, String name, String value) | Sets the value for a property for the specified locale.

Fields

ResourceManager.EXTENSION

Syntax
public static final String EXTENSION;
Description
Extension given to all resource files.

Constructors

ResourceManager.ResourceManager

Syntax
public ResourceManager( IResourceLoader loader, String baseName );
Parameters
component
The component to get resources for.
baseName
The base file name.
Description

Creates a ResourceManager. The resource manager gets data relative to the specified component that has the baseName specified. The baseName should be the root name of the resource files. For example, the base name for the files "MyResource_enu.resources" and "MyResource_jpn.resources" is "MyResource".

Methods

ResourceManager.flush

Syntax
public void flush();
Description

Releases any cached resource data.

ResourceManager.getBoolean

Syntax 1
public boolean getBoolean( String name );
Parameters
name
the name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a boolean for the specified property that is valid for the current locale.

Syntax 2
public boolean getBoolean( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the boolean for the specified property that is valid for the specified locale.

ResourceManager.getByte

Syntax 1
public byte getByte( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a byte for the specified property that is valid for the current locale.

Syntax 2
public byte getByte( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the byte for the specified property that is valid for the specified locale.

ResourceManager.getChar

Syntax 1
public char getChar( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a character for the specified property that is valid for the current locale.

Syntax 2
public char getChar( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The Name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the character for the specified property that is valid for the specified locale.

ResourceManager.getDouble

Syntax 1
public double getDouble( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a double for the specified property that is valid for the current locale.

Syntax 2
public double getDouble( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the double for the specified property that is valid for the specified locale.

ResourceManager.getFloat

Syntax 1
public float getFloat( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a float for the specified property that is valid for the current locale.

Syntax 2
public float getFloat( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the float for the specified property that is valid for the specified locale.

ResourceManager.getInt

Syntax 1
public int getInt( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a integer for the specified property that is valid for the current locale.

Syntax 2
public int getInt( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns property value.

Description

Retrieves the integer for the specified property that is valid for the specified locale.

ResourceManager.getLocaleFileName

Syntax
public String getLocaleFileName( Locale locale );
Parameters
locale
The locale to use.
Return Value

Returns the localized file name.

Description

Retrieves the file name for the specified locale.

ResourceManager.getLocaleFileNameFromBase

Syntax
public static String getLocaleFileNameFromBase( Locale locale, String baseName );
Parameters
locale
The locale to use.
baseName
The base resource file name.
Return Value

Returns the localized file name.

Description

Computes the localized file name given the specified locale and baseName.

ResourceManager.getLong

Syntax 1
public long getLong( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a long for the specified property that is valid for the current locale.

Syntax 2
public long getLong( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the long for the specified property that is valid for the specified locale.

ResourceManager.getNames

Syntax 1
public String[] getNames();
Return Value

Returns a string array containing all the names for properties.

Description

Retrieves all the property names for the current locale.

Syntax 2
public String[] getNames( Locale locale );
Parameters
locale
The locale to retrieve names for.
Return Value

Returns a string array containing all the names for properties.

Description

Retrieves all the property names for the specified locale.

ResourceManager.getObject

Syntax 1
public Object getObject( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves an object for the specified property that is valid for the current locale.

Syntax 2
public Object getObject( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the object for the specified property that is valid for the specified locale.

ResourceManager.getObjects

Syntax 1
public Object[] getObjects();
Return Value

Returns an object array containing all the values for properties.

Description

Retrieves all the property values for the current locale.

Syntax 2
public Object[] getObjects( Locale locale );
Parameters
locale
The locale to retrieve values for.
Return Value

Returns an object array containing all the values for properties.

Description

Retrieves all the property values for the current locale.

ResourceManager.getShort

Syntax 1
public short getShort( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a short for the specified property that is valid for the current locale.

Syntax 2
public short getShort( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
the name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the short for the specified property that is valid for the specified locale.

ResourceManager.getString

Syntax 1
public String getString( String name );
Parameters
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves a string for the specified property that is valid for the current locale.

Syntax 2
public String getString( Locale locale, String name );
Parameters
locale
The locale to get the property for.
name
The name of the property to retrieve.
Return Value

Returns the property value.

Description

Retrieves the string for the specified property that is valid for the specified locale.

ResourceManager.getValidData

Syntax
public static boolean getValidData( Object value );
Parameters
value
The value to check.
Return Value

Returns true if the value can be stored in a resource file.

Description

Retrieves true if the specified value can be stored as a resource property.

ResourceManager.loadResourceAsStream

Syntax
public static IDataStream loadResourceAsStream( Class src, String name );
Parameters
src
The class to load the resource for.
name
The name of the resource to load.
Return Value

Returns the IDataStream for the specified resource.

Description

Loads an arbitrary binary resource file for the specified class. This does not load a resource property file. It is a standalone binary file that is a resource for the specified class.

ResourceManager.setBoolean

Syntax
public void setBoolean( Locale locale, String name, boolean value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setByte

Syntax
public void setByte( Locale locale, String name, byte value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setChar

Syntax
public void setChar( Locale locale, String name, char value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setDouble

Syntax
public void setDouble( Locale locale, String name, double value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setFloat

Syntax
public void setFloat( Locale locale, String name, float value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setInt

Syntax
public void setInt( Locale locale, String name, int value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setLong

Syntax
public void setLong( Locale locale, String name, long value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setObject

Syntax
public void setObject( Locale locale, String name, Object value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setShort

Syntax
public void setShort( Locale locale, String name, short value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.

ResourceManager.setString

Syntax
public void setString( Locale locale, String name, String value );
Parameters
locale
The locale the property is for.
name
The name of the property.
value
The value to assign to that property.
Description

Sets the value for a property for the specified locale.


 ResourceReader Class

ResourceReader Class

This Package | All Packages

public final class ResourceReader
implements IResourceReader

Reads a binary resources stream into a HashTable that contains property names and values.

Methods
Name | Description
depersistProperties( IDataStream stream) | Depersists all properties from the stream into a HashTable that contains the property values, with the keys set to the property name.

Methods

ResourceReader.depersistProperties

Syntax
public synchronized HashTable depersistProperties( IDataStream stream );
Parameters
stream
IDataStream containing the resource data.
Return Value

Returns HashTable containing the properties.

Description

Depersists all properties from the stream into a HashTable that contains the property values, with the keys set to the property name.


 ResourceWriter Class

ResourceWriter Class

This Package | All Packages

public final class ResourceWriter
implements IResourceWriter

The ResourceWriter is responsible for persisting resource data to disk. This can either be done by persisting out data from an existing ResourceManager or creating a new ResourceWriter and using the setXXX methods.

Constructors
Name | Description
ResourceWriter() | Creates a ResourceWriter.
ResourceWriter(ResourceManager manager) | Creates a ResourceWriter.

Methods
Name | Description
persistProperties() | Forces all properties to be written to disk.
setBoolean(Locale locale, String name, boolean value) | Sets the root directory and baseName for the files.
setByte(Locale locale, String name, byte value) | Sets the root directory and baseName for the files.
setChar(Locale locale, String name, char value) | Sets the root directory and baseName for the files.
setDouble(Locale locale, String name, double value) | Sets the root directory and baseName for the files.
setFileLocation(String rootDirectory, String baseName) | Sets the root directory and baseName for the files.
setFloat(Locale locale, String name, float value) | Sets the root directory and baseName for the files.
setInt(Locale locale, String name, int value) | Sets the root directory and baseName for the files.
setLong(Locale locale, String name, long value) | Sets the root directory and baseName for the files.
setObject(Locale locale, String name, Object value) | Sets the root directory and baseName for the files.
setShort(Locale locale, String name, short value) | Sets the root directory and baseName for the files.
setString(Locale locale, String name, String value) | Sets the root directory and baseName for the files.

Constructors

ResourceWriter.ResourceWriter

Syntax 1
public ResourceWriter();
Description

Creates a ResourceWriter.

Syntax 2
public ResourceWriter( ResourceManager manager );
Parameters
manager
The ResourceManager to get data from.
Description

Creates a ResourceWriter. The created writer gets data from the specified ResourceManager.

Methods

ResourceWriter.persistProperties

Syntax
public void persistProperties();
Description

Forces all properties to be written to disk.

ResourceWriter.setBoolean

Syntax
public void setBoolean( Locale locale, String name, boolean value );
Parameters
rootDirectory
he directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setByte

Syntax
public void setByte( Locale locale, String name, byte value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setChar

Syntax
public void setChar( Locale locale, String name, char value );
Parameters
rootDirectory
he directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setDouble

Syntax
public void setDouble( Locale locale, String name, double value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setFileLocation

Syntax
public void setFileLocation( String rootDirectory, String baseName );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setFloat

Syntax
public void setFloat( Locale locale, String name, float value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setInt

Syntax
public void setInt( Locale locale, String name, int value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setLong

Syntax
public void setLong( Locale locale, String name, long value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setObject

Syntax
public void setObject( Locale locale, String name, Object value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setShort

Syntax
public void setShort( Locale locale, String name, short value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

ResourceWriter.setString

Syntax
public void setString( Locale locale, String name, String value );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.


 SubProperty Class

SubProperty Class

This Package | All Packages

public class SubProperty

Topic under construction.

Constructors
Name | Description
SubProperty(String name, Class type, Object value, Class valueEditorClass) | Topic under construction.
SubProperty(String name, Class type, Object value) | Topic under construction.

Methods
Name | Description
getName() | Topic under construction.
getType() | Topic under construction.
getValue() | Topic under construction.
getValueEditorClass() | Topic under construction.

Constructors

SubProperty.SubProperty

Syntax 1
public SubProperty( String name, Class type, Object value, Class valueEditorClass );
Description

Topic under construction.

Syntax 2
public SubProperty( String name, Class type, Object value );
Description

Topic under construction.

Methods

SubProperty.getName

Syntax
public String getName();
Description

Topic under construction.

SubProperty.getType

Syntax
public Class getType();
Description

Topic under construction.

SubProperty.getValue

Syntax
public Object getValue();
Description

Topic under construction.

SubProperty.getValueEditorClass

Syntax
public Class getValueEditorClass();
Description

Topic under construction.


 Sys Class

Sys Class

This Package | All Packages

StaticResourceManager
  |
  +--Sys
public class Sys
extends StaticResourceManager

Retrieves named localized resources for various data types.

Methods
Name | Description
getBoolean(String name) | Retrieves a localized boolean value.
getBoolean(Locale locale, String name) | Retrieves a localized boolean value.
getByte(String name) | Retrieves a localized byte value.
getByte(Locale locale, String name) | Retrieves a localized byte value.
getChar(String name) | Retrieves a localized character value.
getChar(Locale locale, String name) | Retrieves a localized character value.
getDouble(String name) | Retrieves a localized double value.
getDouble(Locale locale, String name) | Retrieves a localized double value.
getFloat(String name) | Retrieves a localized float value.
getFloat(Locale locale, String name) | Retrieves a localized float value.
getInt(String name) | Retrieves a localized integer value.
getInt(Locale locale, String name) | Retrieves a localized integer value.
getLong(String name) | Retrieves a localized long value.
getLong(Locale locale, String name) | Retrieves a localized long value.
getObject(String name) | Retrieves a localized object.
getObject(Locale locale, String name) | Retrieves a localized object.
getShort(String name) | Retrieves a localized short value.
getShort(Locale locale, String name) | Retrieves a localized short value.
getString(String name, String arg1) | Retrieves a localized string.
getString(Locale locale, String name, String arg1) | Retrieves a localized string.
getString(String name, String arg1, String arg2) | Retrieves a localized string.
getString(Locale locale, String name, String arg1, String arg2) | Retrieves a localized string.
getString(String name, String arg1, String arg2, String arg3) | Retrieves a localized string.
getString(Locale locale, String name, String arg1, String arg2, String arg3) | Retrieves a localized string.
getString(String name, String arg1, String arg2, String arg3, String arg4) | Retrieves a localized string.
getString(Locale locale, String name, String arg1, String arg2, String arg3, String arg4) | Retrieves a localized string.
getString(String name, String arg1, String arg2, String arg3, String arg4, String arg5) | Retrieves a localized string.
getString(Locale locale, String name, String arg1, String arg2, String arg3, String arg4, String arg5) | Retrieves a localized string.
getString(String name, String[] args) | Retrieves a localized string.
getString(Locale locale, String name, String[] args) | Retrieves a localized string.
getString(String name) | Retrieves a localized string.
getString(Locale locale, String name) | Retrieves a localized string.

Methods

Sys.getBoolean

Syntax 1
public static boolean getBoolean( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named boolean value from a resource.

Description

Retrieves a localized boolean value. This method uses the default application locale.

Syntax 2
public static boolean getBoolean( Locale locale, String name );
Parameters
local
The local of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named boolean value from a resource.

Description

Retrieves a localized boolean value.

Sys.getByte

Syntax 1
public static byte getByte( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named byte value from a resource.

Description

Retrieves a localized byte value. This method uses the default application locale.

Syntax 2
public static byte getByte( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named byte value from a resource.

Description

Retrieves a localized byte value.

Sys.getChar

Syntax 1
public static char getChar( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named character value from a resource.

Description

Retrieves a localized character value. This method uses the default application locale.

Syntax 2
public static char getChar( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
Return Value

Returns a named character value from a resource.

Description

Retrieves a localized character value.

Sys.getDouble

Syntax 1
public static double getDouble( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named double value from a resource.

Description

Retrieves a localized double value. This method uses the default application locale.

Syntax 2
public static double getDouble( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named double value from a resource.

Description

Retrieves a localized double value.

Sys.getFloat

Syntax 1
public static float getFloat( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named float value from a resource.

Description

Retrieves a localized float value. This method uses the default application locale.

Syntax 2
public static float getFloat( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named float value from a resource.

Description

Retrieves a localized float value.

Sys.getInt

Syntax 1
public static int getInt( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named integer value from a resource.

Description

Retrieves a localized integer value. This method uses the default application locale.

Syntax 2
public static int getInt( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named integer value from a resource.

Description

Retrieves a localized integer value.

Sys.getLong

Syntax 1
public static long getLong( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named long value from a resource.

Description

Retrieves a localized long value. This method uses the default application locale.

Syntax 2
public static long getLong( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named long value from a resource.

Description

Retrieves a localized long value.

Sys.getObject

Syntax 1
public static Object getObject( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named object from a resource.

Description

Retrieves a localized object. This method uses the default application locale.

Syntax 2
public static Object getObject( Locale locale, String name );
Parameters
locale
The locale of the object to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named object from a resource.

Description

Retrieves a localized object.

Sys.getShort

Syntax 1
public static short getShort( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named short value from a resource.

Description

Retrieves a localized short value. This method uses the default application locale.

Syntax 2
public static short getShort( Locale locale, String name );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named short value from a resource.

Description

Retrieves a localized short value.

Sys.getString

Syntax 1
public static String getString( String name, String arg1 );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. The default application locale is used.

Syntax 2
public static String getString( Locale locale, String name, String arg1 );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 3
public static String getString( String name, String arg1, String arg2 );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 4
public static String getString( Locale locale, String name, String arg1, String arg2 );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 5
public static String getString( String name, String arg1, String arg2, String arg3 );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 6
public static String getString( Locale locale, String name, String arg1, String arg2, String arg3 );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 7
public static String getString( String name, String arg1, String arg2, String arg3, String arg4 );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 8
public static String getString( Locale locale, String name, String arg1, String arg2, String arg3, String arg4 );
Parameters
locale
The locale of the value to retrieve.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 9
public static String getString( String name, String arg1, String arg2, String arg3, String arg4, String arg5 );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 10
public static String getString( Locale locale, String name, String arg1, String arg2, String arg3, String arg4, String arg5 );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 11
public static String getString( String name, String[] args );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 12
public static String getString( Locale locale, String name, String[] args );
Parameters
locale
The locale of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.

Syntax 13
public static String getString( String name );
Parameters
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string. This method uses the default application locale.

Syntax 14
public static String getString( Locale locale, String name );
Parameters
local
The local of the value to retrieve.
name
The key name assigned to the element.
Return Value

Returns a named string from a resource.

Description

Retrieves a localized string.


 ValueEditor Class

ValueEditor Class

This Package | All Packages

public class ValueEditor
implements IValueEditor

Represents a standard implementation of the IValueEditor interface.

Methods
Name | Description
editValue(IValueAccess valueAccess) | Topic under construction.
getConstantName(Object value) | Returns the fully qualified name of a constant that represents the given value, or returns null if there is no constant for the value.
getStyle() | Returns the style flags for the value editor.
getSubProperties(Object value) | Returns the subproperties to be displayed under the object.
getTextFromValue(Object value) | Converts the given value to a text string.
getValueFromText(String text) | Converts the given text string to a value.
getValues() | Returns a list of possible values for the value editor's type.
paintValue(Object value, Graphics g, Rectangle rect) | Paints a representation of the given value in the given Rectangle of the given Graphics.

Methods

ValueEditor.editValue

Syntax
public void editValue( IValueAccess valueAccess );
Description

Topic under construction.

ValueEditor.getConstantName

Syntax
public String getConstantName( Object value );
Description

Returns the fully qualified name of a constant that represents the given value, or returns null if there is no constant for the value.

ValueEditor.getStyle

Syntax
public int getStyle();
Description

Returns the style flags for the value editor. The returned value must be a combination of the STYLE_XXX bit masks defined in this interface.

ValueEditor.getSubProperties

Syntax
public SubProperty[] getSubProperties( Object value );
Description

Returns the subproperties to be displayed under the object.

ValueEditor.getTextFromValue

Syntax
public String getTextFromValue( Object value );
Description

Converts the given value to a text string. The return value may be null if the value cannot be converted to a text string.

ValueEditor.getValueFromText

Syntax
public Object getValueFromText( String text );
Description

Converts the given text string to a value. This method is not called if the value editor specifies the STYLE_NOVALUEFROMTEXT style.

ValueEditor.getValues

Syntax
public Object[] getValues();
Description

Returns a list of possible values for the value editor's type. To display these values in a drop-down list, a property editor typically calls getTextFromValue() for each of the values in the list.

ValueEditor.paintValue

Syntax
public void paintValue( Object value, Graphics g, Rectangle rect );
Description

Paints a representation of the given value in the given Rectangle of the given Graphics. This method is called only if the value editor specifies the STYLE_PAINTVALUE style.


 ValueEditorAttribute Class

ValueEditorAttribute Class

This Package | All Packages

MemberAttribute
  |
  +--ValueEditorAttribute
public class ValueEditorAttribute
extends MemberAttribute

Holds the class name of the value editor that should be used to edit a specific property.

Fields
Name | Description
valueEditorType | Topic under construction.

Constructors
Name | Description
ValueEditorAttribute(Class valueEditorType) | Topic under construction.

Methods
Name | Description
getValueEditorType() | Topic under construction.

Fields

ValueEditorAttribute.valueEditorType

Syntax
public final Class valueEditorType;
Description
Topic under construction.

Constructors

ValueEditorAttribute.ValueEditorAttribute

Syntax
public ValueEditorAttribute( Class valueEditorType );
Description

Topic under construction.

Methods

ValueEditorAttribute.getValueEditorType

Syntax
public Class getValueEditorType();
Description

Topic under construction.


 IAttributes Interface

IAttributes Interface

This Package | All Packages

public interface IAttributes

Represents a callback interface that is used in implementations of the getAttributes() method of the IClassInfo interface. An implementation of IClassInfo.getAttributes() is provided an instance of the IAttributes interface and is responsible for calling the add() method to enumerate the attributes of the associated component class.

Methods
Name | Description
add(MemberAttribute a) | Defines an attribute.
remove(MemberAttribute a) | Removes an attribute.

Methods

IAttributes.add

Syntax
public void add( MemberAttribute a );
Parameters
a
The MemberAttribute to define.
Description

Defines an attribute.

IAttributes.remove

Syntax
public void remove( MemberAttribute a );
Parameters
a
The MemberAttribute to remove.
Description

Removes an attribute.


 IClassInfo Interface

IClassInfo Interface

This Package | All Packages

public interface IClassInfo

Provides meta-information for a component that cannot be determined from the component itself. Examples of such meta-information include a component's set of properties, its icon, and so on.

A component never implements the IClassInfo interface directly. Rather, the component implements a public static inner class named "ClassInfo," which in turn implements the IClassInfo interface. This implementation method allows the meta-information to be separated from the class itself in situations where the it is not required (such as when the component is deployed). The following example shows a base class called Window and its associated ClassInfo implementation:

  public class Window
  {
    // Members of class Window

    public static class ClassInfo implements IClassInfo
    {
      // Implementations of all methods of the IClassInfo interface
    }
  }

For a component class that is a descendant of another component class, the ClassInfo of the descendant component class typically extends the ClassInfo of the base component class. For example:

  public class Button extends Window
  {
    // Members of class Button

    public static class ClassInfo extends Window.ClassInfo
    {
      // Overrides of methods of the IClassInfo interface
    }
  }

Even though a descendant component's ClassInfo typically inherits from the base component's ClassInfo, it isn't required to do so. Indeed, a descendant component's ClassInfo can be implemented from scratch or can inherit from a ClassInfo higher up in the component hierarchy. This is useful in situations where a component wants to omit properties that were introduced by a base class.

Compilation of a component class with an inner ClassInfo class produces two class files that follow the naming pattern XXX.class and XXX$ClassInfo.class, where XXX is the name of the component class. The Windows Foundation Classes for Java component manager uses this pattern to identify classes that support meta-information.

Methods
Name | Description
getAttributes(IAttributes attributes) | Specifies the attributes of the associated class by calling the add() method of the given IAttributes callback interface.
getCustomizer(Object component) | Retrieves a customizer for the given component.
getDefaultEventName() | Retrieves the name of the "default" event for the associated component class.
getDefaultPropertyName() | Retrieves the name of the "default" property for the associated component class.
getEvents(IEvents events) | Specifies the events of the associated class by calling the add() method of the given IEvents callback interface.
getExtenders(IExtenders extenders) | Specifies the extenders of the associated class by calling the add() method of the given IExtenders callback interface.
getProperties(IProperties props) | Specifies the properties of the associated class by calling the appropriate add() methods of the given IProperties callback interface.
getToolboxBitmap() | Retrieves an image that contains a 16x16 pixel icon used to represent the component in toolboxes, list views, and so forth.

Methods

IClassInfo.getAttributes

Syntax
public void getAttributes( IAttributes attributes );
Parameters
Attributes
An IAttributes interface that functions as a callback for the attribute list.
Description

Specifies the attributes of the associated class by calling the add() method of the given IAttributes callback interface.

See Also
wfc.core.IAttributes

IClassInfo.getCustomizer

Syntax
public ICustomizer getCustomizer( Object component );
Description

Retrieves a customizer for the given component. The component parameter is guaranteed to be an instance of the ClassInfo's associated component class (or a subclass thereof). The return value may be null if the component doesn't support a customizer. For further details on component customizers, see the comments for the ICustomizer interface.

IClassInfo.getDefaultEventName

Syntax
public String getDefaultEventName();
Description

Retrieves the name of the "default" event for the associated component class. The exact implications of being a default event are defined by the tool that is editing the component, but it could, for example, mean that the handler method of the event is shown in the code window when a user double-clicks the component in the design environment.

IClassInfo.getDefaultPropertyName

Syntax
public String getDefaultPropertyName();
Description

Retrieves the name of the "default" property for the associated component class. The exact implications of being a default property are defined by the tool that is editing the component, but it could, for example, mean that the edit() method of the property's associated value editor is invoked when a user double-clicks the component in the design environment.

IClassInfo.getEvents

Syntax
public void getEvents( IEvents events );
Parameters
Events
An IEvents interface that functions as a callback for the event list.
Description

Specifies the events of the associated class by calling the add() method of the given IEvents callback interface.

See Also
wfc.core.IEvents

IClassInfo.getExtenders

Syntax
public void getExtenders( IExtenders extenders );
Parameters
Extenders
An IExtenders interface that functions as a callback for the extender list.
Description

Specifies the extenders of the associated class by calling the add() method of the given IExtenders callback interface.

See Also
wfc.core.IExtenders

IClassInfo.getProperties

Syntax
public void getProperties( IProperties props );
Parameters
Props
An IProperties interface that functions as a callback for the property list.
Description

Specifies the properties of the associated class by calling the appropriate add() methods of the given IProperties callback interface. Note that events are treated as properties whose types are descendants of the system-provided Closure class. In other words, the getProperties() method reports both the properties and the events of its associated component class. For a component class that is a descendant of another component class, the getProperties() method typically calls super.getProperties() before adding the properties that are particular to the descendant class. An example of an implementation of the getProperties() method follows.

  public class Edit extends Window
  {
    // Members of class Edit

    public static class ClassInfo extends Window.ClassInfo
    {
      public getProperties(IProperties properties)
      {
        super.getProperties(properties);
        properties.add("ReadOnly", boolean.class, new Boolean(false));
        properties.add("MaxLength", int.class, new Integer(0));
        properties.add("OnChange", EventHandler.class);
      }
    }
  }

Each call to properties.add() defines a new property or hides an already defined property of the same name. A call to add() must always specify the property's name and type and can optionally specify a default value and a value editor. For a property named XXX of type YYY, the associated component class is required to implement two methods of the following form:

  public YYY getXXX();
  public void setXXX(YYY value);

If the property type is boolean, the getXXX() method can optionally be named isXXX(). The component class can optionally implement to additional methods of the following form:

  public boolean hasDefaultXXX();
  public void resetXXX();

These methods control a property's default value. The hasDefaultXXX() method returns true if the current value of the XXX property is equal to the default value of the property. The resetXXX() method resets the XXX property to its default value. If the call to properties.add() that defines a particular property includes the default value of the property, the hasDefaultXXX() and resetXXX() methods are ignored. Otherwise, these methods are used to determine if a property is different from its default and to reset the property to its default.

If the call to properties.add() that defines a particular property includes a reference to a value editor, that value editor is used to edit the property. Otherwise, a system-provided value editor is used, as described in the comments for the IValueEditor interface.

For more information on implementing the getProperties() method, see the descriptions of the methods of the IProperties interface.

See Also
wfc.core.IProperties

IClassInfo.getToolboxBitmap

Syntax
public Bitmap getToolboxBitmap();
Return Value

Returns a Bitmap object that contains an iconic representation of the component. May return NULL if no such icon exists.

Description

Retrieves an image that contains a 16x16 pixel icon used to represent the component in toolboxes, list views, and so forth.


 IComponent Interface

IComponent Interface

This Package | All Packages

public interface IComponent

The IComponent interface represents a component. To be a component, a class must implement IComponent. Components can be hosted in containers. For each component in a container, the container creates a site that acts as a binding link between the component and the container.

Methods
Name | Description
addOnDispose(EventHandler value) | Adds an OnDispose event handler.
dispose() | Disposes a component.
getChildOf(IComponent component) | Checks if this component is a child of the specified component.
getSite() | Returns the site of this component.
removeOnDispose(EventHandler value) | Removes an OnDispose event handler.
setSite(ISite value) | Sets the site of this component.

Methods

IComponent.addOnDispose

Syntax
public void addOnDispose( EventHandler value );
Description

Adds an OnDispose event handler. The OnDispose event is fired when the component's dispose() method is called. Components that maintain references to other components can register OnDispose event handlers for the referenced components so that the references can be cleared when the components are disposed.

IComponent.dispose

Syntax
public void dispose();
Description

Disposes a component. A call to dispose() indicates that the user of the component has no further need for the component. An implementation of dispose() must:

  1. Remove any references the component is holding to other components. This is typically accomplished by assigning null to any fields that contain references to other components.
  2. Release any system resources that are associated with the component, such as file handles, window handles, or database connections.
  3. Dispose any child components, such as child windows or submenu items, by calling the dispose() method of those components. The isChildOf() method of the components that are disposed in this fashion must return true when passed this component.
  4. Remove the component from its container. If the component has a site, it must execute "site.getContainer().removeComponent(this)", where "site" is the current (non-null) site.
  5. Fire an OnDispose event to any event handlers that have been registered through the addOnDispose() method.

Ideally, a call to dispose() will revert a component to the state it was in immediately after it was created. This is, however, not a requirement. Following a call to dispose(), a component is permitted to raise exceptions for operations that cannot meaningfully be performed.

IComponent.getChildOf

Syntax
public boolean getChildOf( IComponent component );
Description

Checks if this component is a child of the specified component. A component is considered a child of a specified parent component if the parent component's implementation of the dispose() method also disposes the child component. Examples of child components are child windows and submenus.

IComponent.getSite

Syntax
public ISite getSite();
Description

Returns the site of this component. The value returned must be the value that was passed to the most recent call to setSite(), or null if no calls have been made to setSite().

IComponent.removeOnDispose

Syntax
public void removeOnDispose( EventHandler value );
Description

Removes an OnDispose event handler.

IComponent.setSite

Syntax
public void setSite( ISite value );
Description

Sets the site of this component. A non-null value indicates that the component has been added to a container; a null value indicates that the component is being removed from a container. An implementation of setSite() is required to store the specified value and return the same value from subsequent calls to getSite().


 IConstructable Interface

IConstructable Interface

This Package | All Packages

public interface IConstructable

Allows for immutable objects to indicate what constructor arguments would result in an equivalent object. A constructable object is one that can be persisted in a simple and automatic way by asking it for the constructor arguments that can be used to reconstruct the object. Failing to provide a constructor that maps to what getConstructorArgs returns prevents the object from being persisted properly.

Methods
Name | Description
getConstructorArgs() | Return Value: Returns an array of ConstructorArg objects, which have a current value and type.

Methods

IConstructable.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Return Value

Returns an array of ConstructorArg objects, which have a current value and type.

Description


 IContainer Interface

IContainer Interface

This Package | All Packages

public interface IContainer

Represents a container object that provides sites for components.

Methods
Name | Description
add(IComponent component) | Adds a component to the container.
add(IComponent component, String name) | Adds a component to the container.
dispose() | Removes all components from a container.
getComponent(String name) | Retreives a named component from the container.
getComponents() | Retreives an array of all components from the container.
remove(IComponent component) | Removes a component from the container.

Methods

IContainer.add

Syntax 1
public void add( IComponent component );
Parameters
component
The component object to add.
Description

Adds a component to the container.

Syntax 2
public void add( IComponent component, String name );
Parameters
component
The component object to add.
name
The name of the component being added.
Description

Adds a component to the container.

IContainer.dispose

Syntax
public void dispose();
Description

Removes all components from a container.

IContainer.getComponent

Syntax
public IComponent getComponent( String name );
Parameters
name
The name of the component to retrieve.
Return Value

Returns the component requested, or null if this component is not found.

Description

Retreives a named component from the container.

IContainer.getComponents

Syntax
public IComponent[] getComponents();
Return Value

Returns all components currently sited in this container.

Description

Retreives an array of all components from the container.

IContainer.remove

Syntax
public void remove( IComponent component );
Parameters
component
The component to remove.
Description

Removes a component from the container.


 ICustomizer Interface

ICustomizer Interface

This Package | All Packages

public interface ICustomizer

The ICustomizer interface represents the implementation of a customizer for a particular component. A customizer implements the ability to create a set of property pages for a component, to get a list of design-time verbs for the component, and to execute those verbs. Instances of objects that implement the ICustomizer interface are created by the getCustomizer() method of the IClassInfo interface.

Methods
Name | Description
edit() | Edits the component associated with the customizer.
getDesignFilter() | Allows your component to support a design time user interface.
getDesignPages() | Returns an array of of classes for each design page that this component utilizes.
getVerbs() | Returns the design-time verbs supported by the component associated with the customizer.
performVerb(CustomizerVerb verb) | Performs the action associated with the given verb on the component associated with the customizer.

Methods

ICustomizer.edit

Syntax
public void edit();
Description

Edits the component associated with the customizer. This method should perform the default editing action for the component. The method is typically invoked when the user double-clicks the component in the design- time environment.

ICustomizer.getDesignFilter

Syntax
public IDesignFilter getDesignFilter();
Return Value

Returns an IDesignFilter object if your component requires design time message filtering; otherwise, returns null.

Description

Allows your component to support a design time user interface. A TabStrip control, for example, has a design time user interface that allows the user to click the tabs to change tabs. To implement this, TabStrip has a design filter that allows mouse and keyboard messages to be sent to the tabs.

ICustomizer.getDesignPages

Syntax
public Class[] getDesignPages();
Description

Returns an array of of classes for each design page that this component utilizes. Each returning class must implement IDesignPage.

ICustomizer.getVerbs

Syntax
public CustomizerVerb[] getVerbs();
Description

Returns the design-time verbs supported by the component associated with the customizer. The verbs returned by this method are typically displayed in a right-click menu by the design-time environment. The return value may be null if the component has no design-time verbs. When a user selects one of the verbs, the performVerb() method is invoked with the the corresponding CustomizerVerb object. Note: A design-time environment typically provides a "Properties..." entry on a component's right-click menu. Therefore, the getVerbs() method should not include such an entry in the returned list of verbs.

ICustomizer.performVerb

Syntax
public void performVerb( CustomizerVerb verb );
Description

Performs the action associated with the given verb on the component associated with the customizer. The verb parameter is one of the verbs previously returned by a call to the getVerbs() method.


 IDesignPage Interface

IDesignPage Interface

This Package | All Packages

public interface IDesignPage

Defines a design page, which is a page of a dialog box that allows for changing design time settings. A form package typically shows this in one tab of a tabbed dialog box, but that is only one possible implementation. There are two important interfaces to consider:

There is one IDesignPageSite interface for each design page. This provides a window for the design page to parent itself in. Also, the page will notify that it is dirty through this interface. DesignForm is a stock implementation of IDesignPageSite.

The IDesignPage interface represents the page itself. This typically displays UI for setting a component's design time properties that cannot easily be set through a typical property sheet. A page may be asked to size itself larger than its default size to unify the look of multiple pages in the same dialog box but will never be asked to become smaller than its default. Pages should support dynamic resizing, but it is not a requirement. DesignPage is a stock implementation of IDesignPage.

Also see wfc.core.IDesignPageSite

Methods
Name | Description
activate() | Activates and displays the page.
apply() | Applies changes to all the objects in this page's object list.
deactivate() | Deactivates the page.
getControl() | Retrieves the control that represents the window for this page.
getPageMessage(MSG msg) | Gives the design page a chance to process messages before the caller uses them.
getSize() | Retrieves the width and height of this page.
getTitle() | Retrieves the title of the design page.
setObjects(Object [] objects) | Called before activation to set up the array of objects that this page is modifying properties for.
setSite(IDesignPageSite site) | Called before this page is activated to set up the site used to notify the caller of changes.
setSize(Point size) | Called to enlarge the size of this page.
supportsHelp() | Called to determine whether the Help icon should be shown at the top of the dialog box.

Methods

IDesignPage.activate

Syntax
public void activate();
Description

Activates and displays the page.

IDesignPage.apply

Syntax
public void apply();
Description

Applies changes to all the objects in this page's object list.

IDesignPage.deactivate

Syntax
public void deactivate();
Description

Deactivates the page. A page can be deactivated and later reactivated.

IDesignPage.getControl

Syntax
public Control getControl();
Return Value

Returns a Control object.

Description

Retrieves the control that represents the window for this page.

IDesignPage.getPageMessage

Syntax
public boolean getPageMessage( MSG msg );
Parameters
The
msg wfc.win32.MSG to process.
Return Value

Returns true if this page processed the message, or false otherwise. If this returns true, the message is discarded. Otherwise, the caller continues to process the message.

Description

Gives the design page a chance to process messages before the caller uses them.

IDesignPage.getSize

Syntax
public Point getSize();
Return Value

Returns the size of the page.

Description

Retrieves the width and height of this page. The caller can use this to size its UI appropriately.

IDesignPage.getTitle

Syntax
public String getTitle();
Return Value

Returns the title of page.

Description

Retrieves the title of the design page. The caller can use this to show the name of this page before it is actually activated.

IDesignPage.setObjects

Syntax
public void setObjects( Object [] objects );
Parameters
objects
The array of objects this page is to modify.
Description

Called before activation to set up the array of objects that this page is modifying properties for. The objects are not guaranteed to be of any particular type; their only commonality is that they have all specified that they use this design page class.

IDesignPage.setSite

Syntax
public void setSite( IDesignPageSite site );
Parameters
site
The IDesignPageSite to which this page is attached.
Description

Called before this page is activated to set up the site used to notify the caller of changes.

IDesignPage.setSize

Syntax
public void setSize( Point size );
Parameters
size
The new size.
Description

Called to enlarge the size of this page. This is done after the caller has determined the sizes of all pages. If this page supports resizing to a larger size, it should do so. A design page will never be requested to size smaller than its default size.

IDesignPage.supportsHelp

Syntax
public boolean supportsHelp();
Return Value

Returns true to enable the Help icon for this page, or returns false to disable it.

Description

Called to determine whether the Help icon should be shown at the top of the dialog box. If one or more pages supports the icon, it will appear. It will be dimmed for pages that do not support Help.


 IDesignPageSite Interface

IDesignPageSite Interface

This Package | All Packages

public interface IDesignPageSite

This interface defines a site for an IDesignPage. A site is a logical living space for the page and provides services for that page. DesignForm is a stock implementation of IDesignPageSite.

Methods
Name | Description
getControl() | Called by a page to retrieve a parenting control for the page.
setDirty() | Called by a page to mark its contents as dirty.

Methods

IDesignPageSite.getControl

Syntax
public Control getControl();
Return Value

Returns the parenting control object for the page.

Description

Called by a page to retrieve a parenting control for the page.

IDesignPageSite.setDirty

Syntax
public void setDirty();
Description

Called by a page to mark its contents as dirty. This may be used to enable a parenting form's Apply button.


 IDropDown Interface

IDropDown Interface

This Package | All Packages

public interface IDropDown

Service interface for implementing custom drop-down behavior in a value editor. This interface is accessed through getService() on a component's site at design-time.

Methods
Name | Description
dropDownComponent(Component comp) | Topic under construction.
dropDownDone() | Topic under construction.

Methods

IDropDown.dropDownComponent

Syntax
public void dropDownComponent( Component comp );
Description

Topic under construction.

IDropDown.dropDownDone

Syntax
public void dropDownDone();
Description

Topic under construction.


 IEvents Interface

IEvents Interface

This Package | All Packages

public interface IEvents

The IEvents interface is a callback interface that is used in implementations of the getEvents() method of the IClassInfo interface. An implementation of IClassInfo.getEvents() is provided an instance of the IEvents interface and is responsible for calling the add() method to enumerate the events of the associated component class.

Methods
Name | Description
add(EventInfo e) | Defines an event.
remove(EventInfo e) | Removes an event.

Methods

IEvents.add

Syntax
public void add( EventInfo e );
Description

Defines an event.

IEvents.remove

Syntax
public void remove( EventInfo e );
Description

Removes an event.


 IExtenderProvider Interface

IExtenderProvider Interface

This Package | All Packages

public interface IExtenderProvider

A component extends IExtenderProvider when it wants to provide extender properties for other components in a container.

Methods
Name | Description
canExtend(Object target) | Determines if the extender properties are to be made visible.

Methods

IExtenderProvider.canExtend

Syntax
public boolean canExtend( Object target );
Return Value

Returns true if extender properties found in ClassInfo should be shown for this target if the type matches.

Description

Determines if the extender properties are to be made visible.


 IExtenders Interface

IExtenders Interface

This Package | All Packages

public interface IExtenders

The IExtenders interface is a callback interface that is used in implementations of the getExtenderProperties() method of the IClassInfo interface. An implementation of IClassInfo.getExtenderProperties() is provided an instance of the IExtenders interface and is responsible for calling the add() method to enumerate the Extenders of the associated component class.

Methods
Name | Description
add(ExtenderInfo e) | Defines an extender property.
remove(ExtenderInfo e) | Removes an extender property.

Methods

IExtenders.add

Syntax
public void add( ExtenderInfo e );
Description

Defines an extender property.

IExtenders.remove

Syntax
public void remove( ExtenderInfo e );
Description

Removes an extender property.


 IPersistable Interface

IPersistable Interface

This Package | All Packages

public interface IPersistable

Allows an object to be persisted to a stream and depersisted from a stream. You must implement a constructor that takes an IDataStream to implement IPersistable correctly.

Methods
Name | Description
getExtension() | Retrieves the extension for the file name for the stream.
save(IDataStream stream) | Persists the object.

Methods

IPersistable.getExtension

Syntax
public String getExtension();
Return Value

Returns a string containing the file name extension, such as bmp, or wav, or null if there is no extension.

Description

Retrieves the extension for the file name for the stream.

IPersistable.save

Syntax
public void save( IDataStream stream );
Description

Persists the object. This method takes a stream into which it can save itself. It can return an extension (bmp,wav) if the stream is saved to a file, or it can return null.


 IProperties Interface

IProperties Interface

This Package | All Packages

public interface IProperties

The IProperties interface is a callback interface that is used in implementations of the getProperties() method of the IClassInfo interface. An implementation of IClassInfo.getProperties() is provided an instance of the IProperties interface and is responsible for calling the add() method to enumerate the properties of the associated component class.

Methods
Name | Description
add(PropertyInfo p) | Defines a property.
remove(PropertyInfo p) | Removes a property.

Methods

IProperties.add

Syntax
public void add( PropertyInfo p );
Description

Defines a property.

IProperties.remove

Syntax
public void remove( PropertyInfo p );
Description

Removes a property.


 IRequireBegin Interface

IRequireBegin Interface

This Package | All Packages

public interface IRequireBegin

Any object that implements this method requires the begin method to be called before the object is usable. Once the begin method is called the component becomes active and can assume that all peers are loaded, and all property sets are complete. WFC code generation will add a call to begin for all IRequireBegin components at the end of initForm().

Methods
Name | Description
begin() | Signals the object that loading of all peer components and property sets are complete.

Methods

IRequireBegin.begin

Syntax
public void begin();
Description

Signals the object that loading of all peer components and property sets are complete.


 IResourceLoader Interface

IResourceLoader Interface

This Package | All Packages

public interface IResourceLoader

IResourceLoader represents a component that supports retrieving a resource from that component's namespace.

Methods
Name | Description
getResource(String resource) | Retrieves an IDataStream for the resource with the given name.

Methods

IResourceLoader.getResource

Syntax
public IDataStream getResource( String resource );
Parameters
resource
The resource to retrieve.
Return Value

Returns the IDataStream for the resource.

Description

Retrieves an IDataStream for the resource with the given name.


 IResourceReader Interface

IResourceReader Interface

This Package | All Packages

public interface IResourceReader

Interface that allows an object to depersist resource data from a binary resource file. The file will be stored by something that supports IResourceWriter.

Methods
Name | Description
depersistProperties(IDataStream stream) | Depersist all properties from the stream into a HashTable that contains the property values, with the keys set to the property name.

Methods

IResourceReader.depersistProperties

Syntax
public HashTable depersistProperties( IDataStream stream );
Parameters
stream
IDataStream containing the resource data.
Return Value

Returns a HashTable containing the properties.

Description

Depersist all properties from the stream into a HashTable that contains the property values, with the keys set to the property name.


 IResourceWriter Interface

IResourceWriter Interface

This Package | All Packages

public interface IResourceWriter

Allows an object to participate in the storing of resource- based properties.

Methods
Name | Description
persistProperties() | Forces all properties to be written to disk.
setBoolean(Locale locale, String name, boolean value) | Sets the value of a given property for a specific locale.
setByte(Locale locale, String name, byte value) | Sets the value of a given property for a specific locale.
setChar(Locale locale, String name, char value) | Sets the value of a given property for a specific locale.
setDouble(Locale locale, String name, double value) | Sets the value of a given property for a specific locale.
setFileLocation(String rootDirectory, String baseName) | Sets the root directory and baseName for the files.
setFloat(Locale locale, String name, float value) | Sets the value of a given property for a specific locale.
setInt(Locale locale, String name, int value) | Sets the value of a given property for a specific locale.
setLong(Locale locale, String name, long value) | Sets the value of a given property for a specific locale.
setObject(Locale locale, String name, Object value) | Sets the value of a given property for a specific locale.
setShort(Locale locale, String name, short value) | Sets the value of a given property for a specific locale.
setString(Locale locale, String name, String value) | Sets the value of a given property for a specific locale.

Methods

IResourceWriter.persistProperties

Syntax
public void persistProperties();
Description

Forces all properties to be written to disk.

IResourceWriter.setBoolean

Syntax
public void setBoolean( Locale locale, String name, boolean value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setByte

Syntax
public void setByte( Locale locale, String name, byte value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setChar

Syntax
public void setChar( Locale locale, String name, char value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setDouble

Syntax
public void setDouble( Locale locale, String name, double value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setFileLocation

Syntax
public void setFileLocation( String rootDirectory, String baseName );
Parameters
rootDirectory
The directory to create resource files in.
baseName
Base file name. The locale information and resource extension will be postpended onto this name.
Description

Sets the root directory and baseName for the files.

IResourceWriter.setFloat

Syntax
public void setFloat( Locale locale, String name, float value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setInt

Syntax
public void setInt( Locale locale, String name, int value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setLong

Syntax
public void setLong( Locale locale, String name, long value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setObject

Syntax
public void setObject( Locale locale, String name, Object value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setShort

Syntax
public void setShort( Locale locale, String name, short value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.

IResourceWriter.setString

Syntax
public void setString( Locale locale, String name, String value );
Parameters
locale
The locale to store data for.
name
The name of resource.
value
The value to store.
Description

Sets the value of a given property for a specific locale. If the locale is null, the data is assumed to be for any locale and should be stored in the default resource file.


 ISite Interface

ISite Interface

This Package | All Packages

public interface ISite

Topic under construction.

Methods
Name | Description
componentChanged() | Topic under construction.
getComponent() | Topic under construction.
getContainer() | Topic under construction.
getDesignMode() | Topic under construction.
getDisposing() | Topic under construction.
getName() | Topic under construction.
getService(Class service) | Topic under construction.
setName(String value) | Topic under construction.

Methods

ISite.componentChanged

Syntax
public void componentChanged();
Description

Topic under construction.

ISite.getComponent

Syntax
public IComponent getComponent();
Description

Topic under construction.

ISite.getContainer

Syntax
public IContainer getContainer();
Description

Topic under construction.

ISite.getDesignMode

Syntax
public boolean getDesignMode();
Description

Topic under construction.

ISite.getDisposing

Syntax
public boolean getDisposing();
Description

Topic under construction.

ISite.getName

Syntax
public String getName();
Description

Topic under construction.

ISite.getService

Syntax
public Object getService( Class service );
Description

Topic under construction.

ISite.setName

Syntax
public void setName( String value );
Description

Topic under construction.


 IValueAccess Interface

IValueAccess Interface

This Package | All Packages

public interface IValueAccess

Topic under construction.

Methods
Name | Description
getService(Class serviceClass) | Topic under construction.
getValue() | Topic under construction.
setValue(Object value) | Topic under construction.

Methods

IValueAccess.getService

Syntax
public Object getService( Class serviceClass );
Description

Topic under construction.

IValueAccess.getValue

Syntax
public Object getValue();
Description

Topic under construction.

IValueAccess.setValue

Syntax
public void setValue( Object value );
Description

Topic under construction.


 IValueEditor Interface

IValueEditor Interface

This Package | All Packages

public interface IValueEditor

The IValueEditor interface represents the implementation of an editor for values of a given type. The primary use of value editors is to edit property values in a property inspector. A class provides a value editor by implementing a public static inner class named "Editor" which in turn implements the IValueEditor interface. This method of implementation allows the value editor to be separated from the class itself in situations where the value editor is not required (such as when the class is deployed). The following example shows a class called Color and its associated value editor:

  public class Color
  {
    // Members of class Color

    public static class Editor implements IValueEditor
    {
      // Implementations of IValueEditor methods
    }
  }

When a class implements a value editor, the value editor implementation is automatically inherited by subclasses that don't implement their own value editors.

To create an instance of a value editor, the component manager first looks for a constructor that takes a single argument of type java.lang.Class. If such a constructor exists, it is called with the actual Class object for which the value editor is being created. Otherwise, the component manager calls the parameterless constructor of the value editor class.

The ComponentManager provides the ability to register value editors for a particular type through the registerValueEditorClass() method. This is useful for value editors that aren't implemented as inner classes.

The core.ValueEditor class provides a default implementation of the IValueEditor interface. Value editors may choose to inherit from ValueEditor instead of implementing the entire IValueEditor interface.

Fields
Name | Description
STYLE_DROPDOWNARROW | Bit mask for getStyle() method.
STYLE_EDITVALUE | Bit mask for getStyle() method.
STYLE_IMMEDIATE | Bit mask for getStyle() method.
STYLE_NOARRAYEXPANSION | Topic under construction.
STYLE_NOVALUEFROMTEXT | Bit mask for getStyle() method.
STYLE_PAINTVALUE | Bit mask for getStyle() method.
STYLE_PROPERTIES | Bit mask for getStyle() method.
STYLE_SHOWFIELDS | Bit mask for getStyle() method.
STYLE_VALUES | Bit mask for getStyle() method.

Methods
Name | Description
editValue(IValueAccess valueAccess) | Topic under construction.
getConstantName(Object value) | Returns the fully qualified name of a constant that represents the given value, or returns null if there is no constant for the value.
getStyle() | Returns the style flags for the value editor.
getSubProperties(Object value) | Returns the subproperties to be displayed under the object.
getTextFromValue(Object value) | Converts the given value to a text string.
getValueFromText(String text) | Converts the given text string to a value.
getValues() | Returns a list of possible values for the value editor's type.
paintValue(Object value, Graphics g, Rectangle rect) | Paints a representation of the given value in the given Rectangle of the given Graphics.

Fields

IValueEditor.STYLE_DROPDOWNARROW

Syntax
public static final int STYLE_DROPDOWNARROW;
Description
Bit mask for getStyle() method. Indicates that if STYLE_EDITVALUE is returned, a drop-down arrow should be shown instead of an ellipsis button.

IValueEditor.STYLE_EDITVALUE

Syntax
public static final int STYLE_EDITVALUE;
Description
Bit mask for getStyle() method. Indicates that the value editor implements the editValue() method. This style typically causes a property editor to display an ellipsis button for properties of the value editor's type.

IValueEditor.STYLE_IMMEDIATE

Syntax
public static final int STYLE_IMMEDIATE;
Description
Bit mask for getStyle() method. Indicates that values of this type are suitable for updating even when the new value is incomplete. This style typically causes a property editor to update the underlying property after each change made in the editor (for example, as each character is typed in an edit box).

IValueEditor.STYLE_NOARRAYEXPANSION

Syntax
public static final int STYLE_NOARRAYEXPANSION;
Description
Topic under construction.

IValueEditor.STYLE_NOVALUEFROMTEXT

Syntax
public static final int STYLE_NOVALUEFROMTEXT;
Description
Bit mask for getStyle() method. Indicates that the value editor does not implement the getValueFromText() method. This style typically causes a property editor to disallow typing in the edit box for properties of the value editor's type.

IValueEditor.STYLE_PAINTVALUE

Syntax
public static final int STYLE_PAINTVALUE;
Description
Bit mask for getStyle() method. Indicates that the value editor implements the paintValue() method. This style typically causes a property editor to paint a representation of properties of the value editor's type.

IValueEditor.STYLE_PROPERTIES

Syntax
public static final int STYLE_PROPERTIES;
Description
Bit mask for getStyle() method. Indicates that values of this type can have their constructor args browseable as properties.

IValueEditor.STYLE_SHOWFIELDS

Syntax
public static final int STYLE_SHOWFIELDS;
Description
Bit mask for getStyle() method. Indicates that a browser should show the fields of the component being edited.

IValueEditor.STYLE_VALUES

Syntax
public static final int STYLE_VALUES;
Description
Bit mask for getStyle() method. Indicates that the value editor implements the getValues() method. This style typically causes a property editor to display a drop-down list for properties of the value editor's type.

Methods

IValueEditor.editValue

Syntax
public void editValue( IValueAccess valueAccess );
Description

Topic under construction.

IValueEditor.getConstantName

Syntax
public String getConstantName( Object value );
Description

Returns the fully qualified name of a constant that represents the given value, or returns null if there is no constant for the value. The returned value must consist of a fully qualified class name followed by a period followed by the identifier of a public static final field of the given class, for example, "wfc.ui.Color.BLACK". This method is typically used by a design-time environment that generates source code to initialize a component's properties.

IValueEditor.getStyle

Syntax
public int getStyle();
Description

Returns the style flags for the value editor. The returned value must be a combination of the STYLE_XXX bit masks defined in this interface.

IValueEditor.getSubProperties

Syntax
public SubProperty[] getSubProperties( Object value );
Description

Returns the subproperties to be displayed under the object.

IValueEditor.getTextFromValue

Syntax
public String getTextFromValue( Object value );
Description

Converts the given value to a text string. The return value may be null if the value cannot be converted to a text string.

IValueEditor.getValueFromText

Syntax
public Object getValueFromText( String text );
Description

Converts the given text string to a value. This method is not called if the value editor specifies the STYLE_NOVALUEFROMTEXT style.

IValueEditor.getValues

Syntax
public Object[] getValues();
Description

Returns a list of possible values for the value editor's type. To display these values in a drop-down list, a property editor typically calls getTextFromValue() for each of the values in the list.

IValueEditor.paintValue

Syntax
public void paintValue( Object value, Graphics g, Rectangle rect );
Description

Paints a representation of the given value in the given Rectangle of the given Graphics. This method is called only if the value editor specifies the STYLE_PAINTVALUE style.


 Package wfc.html

Package wfc.html

The wfc.html package provides access to the Dynamic HTML object model from Java classes. This includes both client and server applications.


 About wfc.html

About wfc.html

The wfc.html package provides access to the Dynamic HTML object model from Java classes. This includes both client and server applications.

Classes

Class DhAlignEnum
Defines alignment constants.
Class DhAppletFactory
Creates an Applet object and adds it to the document.
Class DhBaseContainer
Represents the base class for all container elements.
Class DhBorderEnum
Defines constant definitions for border styles.
Class DhBorderInfo
Provides structured information about an element's border styles.
Class DhBreak
Represents an HTML line break (<BR>) element.
Class DhBrowser
Enables access to Internet Explorer browser functionality.
Class DhBulletedList
Represents the ordered and unordered list items in HTML.
Class DhButton
Implements a push button class.
Class DhButtonBase
Represents the base class for all buttons.
Class DhCantAddElementException
Signals that a request for a named element failed, because an element with that name does not exist.
Class DhCantModifyElementException
Signals that an attempt has been made to modify a read-only element, such as one that has been sent from a server to a client.
Class DhCell
Creates a table cell.
Class DhCheckBox
Represents an HTML-intrinsic check box with a text label.
Class DhComboBox
Represents a drop-down combo box control.
Class DhCursorEnum
Defines constants for controlling an element's cursor style.
Class DhDataSource
Represents a generic wrapper class for data sources.
Class DhDialogInfo
Represents an information class for dialog boxes.
Class DhDocument
Represents an HTML document.
Class DhDragDrop
Topic under construction.
Class DhEdit
Represents all edit box functions in an HTML document.
Class DhElement
Represents the super class for all user interface (UI) elements in this package.
Class DhElementExistsInDocumentException
Signals that a given element has already been added to the document.
Class DhElementNotFoundException
Signals that a request for a named element failed, because an element with that name does not exist.
Class DhEnumeration
Represents a collection of elements in the HTML document.
Class DhEvent
Carries event information from source to sink.
Class DhEventHandler
Represents an event callback object.
Class DhFilter
Derives photographic filters and transition effects from this superclass.
Class DhHorizontalRule
Represents an HTML horizontal rule (<HR>) element, which creates a horizontal divider bar on the page.
Class DhHotSpot
Represents a hotspot in an image map.
Class DhHTMLGenerator
Represents a base class for HTML generation.
Class DhHyperlink
Creates a jump in the document to another place in the current document or to a different document.
Class DhImage
Displays a bitmap file in the document.
Class DhImageMap
Represents an image map.
Class DhInlineFrame
Represents an inline frame (<IFRAME>) element.
Class DhInsertEnum
Provides constants for inserting DhElement items into container items.
Class DhInvalidEnumValueException
Signals that an attempt has been made to access a value within an enumeration that doesn't have a constant for that value.
Class DhJumpPoint
Represents an jump point within a document (that is, a <A NAME=...> reference).
Class DhListBox
Represents a list box control.
Class DhListTypeEnum
Provides constants and support for list types in a DhList control.
Class DhMarginEnum
Provides constant definitions for margin style manipulation.
Class DhMarginWidthInfo
Provides information about an element's current margin settings.
Class DhModule
Represents the class from which you should derive to use the wfc.html package.
Class DhNotSupportedException
Signals that a request for a named element failed, because an element with that name does not exist.
Class DhObjectDataSource
Provides encapsulation of data source objects in <OBJECT> tags.
Class DhObjectFactory
Creates an object and adds it to the document.
Class DhODBCTable
Represents an HTML table that can be populated with data from any ODBC data source.
Class DhPaddingEnum
Provides constant definitions for padding style manipulation.
Class DhPaddingWidthInfo
Provides information about an element's padding width settings.
Class DhPanel
Represents a container for elements that uses tradition graphical user interface two-dimensional positioning for layout.
Class DhPropertyBag
Retrieves values in the <PARAM> attributes of the module's HTML tags.
Class DhRadioButton
Represents the radio button HTML-intrinsic control with a text label.
Class DhRawHTML
Allows output of arbitrary raw HTML to the document.
Class DhRemoteDataSource
Encapsulates the Microsoft Remote Data Service (formerly ADC) control, which allows access to database information across an HTTP connection.
Class DhResetButton
Represents a reset button for an HTML form.
Class DhRow
Creates a table row.
Class DhSection
Represents an element container that uses traditional HTML one-dimensional flow layout.
Class DhStyle
Topic under construction.
Class DhStyleBase
Provides the superclass for classes that support styles, such as DhStyle objects and DhElement.
Class DhSubmitButton
Represents a submit button for an HTML form.
Class DhTable
Creates a table element that can be populated with rows and columns.
Class DhTabularDataSource
Encapsulates the Microsoft Tabular Data Control (TDC).
Class DhText
Represents static text in an HTML document.
Class DhTriState
Topic under construction.
Class DhTriStateImage
Topic under construction.
Class DhTriStateLink
Topic under construction.
Class DhUnexpectedStateException
Signals that a request for a named element failed, because an element with that name does not exist.
Class DhUnitEnum
Provides constants for various unit types in DHTML.
Class DhUnknownHTMLException
Signals that a request for a named element failed, because an element with that name does not exist.
Class DhWindow
Represents an HTML window object.
Class DhWindowInfo
Sets the features for a new browser window.
Class LinkTargetEnum
Provides constants for setting the document's target window.

Interfaces

Interface DhColors
Defines the HTML color constants.
Interface DhIFilterableObject
Represents an interface for objects with filters.
Interface IUploadNotify
Retrieves an element for the output stream.


 DhAlignEnum Class

DhAlignEnum Class

This Package | All Packages

Enum
  |
  +--DhAlignEnum
public class DhAlignEnum
extends wfc.core.Enum
implements DhStringIDs

Defines alignment constants.

Also see wfc.html.DhRadioButton, wfc.html.DhCheckBox

Fields
Name | Description
ABSBOTTOM | Topic under construction.
ABSMIDDLE | Topic under construction.
BASELINE | Topic under construction.
BOTTOM | Topic under construction.
CENTER | Topic under construction.
JUSTIFY | Topic under construction.
LEFT | Topic under construction.
RIGHT | Topic under construction.
SUBSCRIPT | Topic under construction.
SUPERSCRIPT | Topic under construction.
TEXT_LEFT | Specifies a left-aligned label.
TEXT_RIGHT | Specifies a right-aligned label.
TEXTTOP | Topic under construction.
TOP | Topic under construction.

Fields

DhAlignEnum.ABSBOTTOM

Syntax
public static final int ABSBOTTOM;
Description
Topic under construction.

DhAlignEnum.ABSMIDDLE

Syntax
public static final int ABSMIDDLE;
Description
Topic under construction.

DhAlignEnum.BASELINE

Syntax
public static final int BASELINE;
Description
Topic under construction.

DhAlignEnum.BOTTOM

Syntax
public static final int BOTTOM;
Description
Topic under construction.

DhAlignEnum.CENTER

Syntax
public static final int CENTER;
Description
Topic under construction.

DhAlignEnum.JUSTIFY

Syntax
public static final int JUSTIFY;
Description
Topic under construction.

DhAlignEnum.LEFT

Syntax
public static final int LEFT;
Description
Topic under construction.

DhAlignEnum.RIGHT

Syntax
public static final int RIGHT;
Description
Topic under construction.

DhAlignEnum.SUBSCRIPT

Syntax
public static final int SUBSCRIPT;
Description
Topic under construction.

DhAlignEnum.SUPERSCRIPT

Syntax
public static final int SUPERSCRIPT;
Description
Topic under construction.

DhAlignEnum.TEXT_LEFT

Syntax
public static final int TEXT_LEFT;
Description
Specifies a left-aligned label. The text is on the left; the button is on the right.

For example: <LABEL FOR=cbox2>This is a Left Aligned Label<INPUT ID=cbox2 TYPE="CHECKBOX" VALUE=2 CHECKED></LABEL>

DhAlignEnum.TEXT_RIGHT

Syntax
public static final int TEXT_RIGHT;
Description
Specifies a right-aligned label. The button is on the left; the text is on the right.

For example: <LABEL FOR=cbox><INPUT ID=cbox TYPE="CHECKBOX" VALUE=1 CHECKED>This is a Right Aligned Label</LABEL>

DhAlignEnum.TEXTTOP

Syntax
public static final int TEXTTOP;
Description
Topic under construction.

DhAlignEnum.TOP

Syntax
public static final int TOP;
Description
Topic under construction.


 DhAppletFactory Class

DhAppletFactory Class

This Package | All Packages

DhObjectFactory
  |
  +--DhAppletFactory
public class DhAppletFactory
extends DhObjectFactory

Creates an Applet object and adds it to the document. To use this, construct a DhAppletFactory object given the the URL or the class identifier (CLASSID) of an existing applet.

Constructors
Name | Description
DhAppletFactory() | Creates a DhAppletFactory object.
DhAppletFactory(String className) | Creates a DhAppletFactory object.
DhAppletFactory(String className, String codeBase) | Creates a DhAppletFactory object.
DhAppletFactory(String className, String codeBase, AppletContext context) | Creates a DhAppletFactory object.

Methods
Name | Description
getAppletPeer() | Retrieves the Applet object representing the applet instantiation.
setAppletContext( AppletContext appcontext) | Sets the applet context for the applet.

Constructors

DhAppletFactory.DhAppletFactory

Syntax 1
public DhAppletFactory();
Description

Creates a DhAppletFactory object.

Syntax 2
public DhAppletFactory( String className );
Parameters
className
The class to be loaded.
Description

Creates a DhAppletFactory object.

Syntax 3
public DhAppletFactory( String className, String codeBase );
Parameters
className
The name of the class to be loaded.
codeBase
The code base of the class to be loaded.
Description

Creates a DhAppletFactory object.

Syntax 4
public DhAppletFactory( String className, String codeBase, AppletContext context );
Parameters
className
The name of the class to be loaded.
codeBase
The code base of the class to be loaded.
context
The java.applet.AppletContext interface. The methods in this interface can be used by an applet to obtain information about its environment.
Description

Creates a DhAppletFactory object.

Methods

DhAppletFactory.getAppletPeer

Syntax
public synchronized Applet getAppletPeer();
Description

Retrieves the Applet object representing the applet instantiation. Returns the java.applet.Applet object.

DhAppletFactory.setAppletContext

Syntax
public synchronized void setAppletContext( AppletContext appcontext );
Parameters
appcontext
The java.applet.AppletContext interface. The methods in this interface can be used by an applet to obtain information about its environment.
Description

Sets the applet context for the applet.


 DhBaseContainer Class

DhBaseContainer Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
public abstract class DhBaseContainer
extends DhElement

Represents the base class for all container elements. This class should be derived from but never instantiated itself.

Methods
Name | Description
ensureElemsComplete() | Ensures that the m_elems collection is fully populated from peers.
getAllElements() | Recursively returns all child elements and their children.
getElementCount() | Topic under construction.
getElements() | Returns the child elements of this element.
getMatchingChildElements( String strQuery, boolean fRecursive ) | Retrieves an enumeration of the child elements that conform to the contraints of strQuery.
setDocument( DhDocument document ) | Topic under construction.
setHTMLGenerator( DhHTMLGenerator htmlGen ) | Topic under construction.

Methods

DhBaseContainer.ensureElemsComplete

Syntax
protected void ensureElemsComplete();
Description

Ensures that the m_elems collection is fully populated from peers. If the DhSection was created using findElement then we may have deferred creating DhElement derived instances for all the section's contents (that is, we may have only the ones explicitly added if any).

This method fully populates the m_elems array (but just one level down, not recursively).

DhBaseContainer.getAllElements

Syntax
public DhElement[] getAllElements();
Return Value

Returns An array of all child elements

Description

Recursively returns all child elements and their children.

DhBaseContainer.getElementCount

Syntax
public int getElementCount();
Description

Topic under construction.

DhBaseContainer.getElements

Syntax
public DhElement[] getElements();
Return Value

Returns An array of direct child elements.

Description

Returns the child elements of this element.

DhBaseContainer.getMatchingChildElements

Syntax
public IEnumerator getMatchingChildElements( String strQuery, boolean fRecursive );
Parameters
strQuery
A query string of the following format:

<predicate>=<query>

where

<predicate> ::= (style | attr | tag : <name>)|tag (=|<>) (* |'<value>')

<query> ::= {(} <predicate> { ( AND | OR ) <query> ) }

Queries are not case sensitive. A value of '*' indicates all elements where a non-null value of the specific type is present.

fRecursive
Set to true to recursively query child elements and their children, and false to query only direct children.
Return Value

Returns the enumeration of elements which conform to the query

Description

Retrieves an enumeration of the child elements that conform to the contraints of strQuery. The folowing are examples of queries:

  • "tag='div'"
  • "ATTR:width='10' OR TAG='SPAN'"
  • "(tag='input' and attr:type='button') or (STYLE:background-color='red' and STYLE:color='black')"

Exceptions

DhQueryParseException When the query is not properly formed.

DhBaseContainer.setDocument

Syntax
public void setDocument( DhDocument document );
Description

Topic under construction.

DhBaseContainer.setHTMLGenerator

Syntax
public synchronized void setHTMLGenerator( DhHTMLGenerator htmlGen );
Description

Topic under construction.


 DhBorderEnum Class

DhBorderEnum Class

This Package | All Packages

Enum
  |
  +--DhBorderEnum
public class DhBorderEnum
extends wfc.cor.Enum

Defines constant definitions for border styles.

Note that border attribute constants (those beginning with BORDER_ATTR_) cannot be combined.

Fields
Name | Description
BORDER_ATTR_COLOR | Specifies the border color attribute.
BORDER_ATTR_STYLE | Specifies the border style attribute.
BORDER_ATTR_WIDTH | Specifies the border width attribute.
BORDER_SIDE_ALL | Specifies the combination of all border side items.
BORDER_SIDE_BOTTOM | Specifies the bottom border.
BORDER_SIDE_LEFT | Specifies the left border.
BORDER_SIDE_RIGHT | Specifies the right border.
BORDER_SIDE_TOP | Specifies the top border.

Fields

DhBorderEnum.BORDER_ATTR_COLOR

Syntax
public static final int BORDER_ATTR_COLOR;
Description
Specifies the border color attribute.

DhBorderEnum.BORDER_ATTR_STYLE

Syntax
public static final int BORDER_ATTR_STYLE;
Description
Specifies the border style attribute.

DhBorderEnum.BORDER_ATTR_WIDTH

Syntax
public static final int BORDER_ATTR_WIDTH;
Description
Specifies the border width attribute.

DhBorderEnum.BORDER_SIDE_ALL

Syntax
public static final int BORDER_SIDE_ALL;
Description
Specifies the combination of all border side items.

This is equivalent to (BORDER_SIDE_TOP | BORDER_SIDE_RIGHT | BORDER_SIDE_BOTTOM | BORDER_SIDE_LEFT)

DhBorderEnum.BORDER_SIDE_BOTTOM

Syntax
public static final int BORDER_SIDE_BOTTOM;
Description
Specifies the bottom border.

DhBorderEnum.BORDER_SIDE_LEFT

Syntax
public static final int BORDER_SIDE_LEFT;
Description
Specifies the left border.

DhBorderEnum.BORDER_SIDE_RIGHT

Syntax
public static final int BORDER_SIDE_RIGHT;
Description
Specifies the right border.

DhBorderEnum.BORDER_SIDE_TOP

Syntax
public static final int BORDER_SIDE_TOP;
Description
Specifies the top border.


 DhBorderInfo Class

DhBorderInfo Class

This Package | All Packages

public class DhBorderInfo

Provides structured information about an element's border styles.

Fields
Name | Description
bottomColor | The string representation of the bottom border color, either in word form (for example, "white") or hexidecimal form (for example, "#FF00FF").
bottomColorInt | The numerical representation of this item's bottom border color.
bottomStyle | The current bottom border style in string form.
bottomWidth | The current bottom border width in string form.
bottomWidthInt | The integer value of the width of the bottom border.
bottomWidthUnit | The unit label of the width of the bottom border.
leftColor | The string representation of the left border color, either in word form (for example, "white") or hexidecimal form (for example, "#FF00FF").
leftColorInt | The numerical representation of this item's left border color.
leftStyle | The current left border style in string form.
leftWidth | The current left border width in string form.
leftWidthInt | The integer value of the width of the left border.
leftWidthUnit | The unit label of the width of the left border.
rightColor | The string representation of the right border color, either in the word form (for example, "white") or hexidecimal form (for example, "#FF00FF").
rightColorInt | The numerical representation of this item's right border color.
rightStyle | The current right border style in string form.
rightWidth | The current right border width in string form.
rightWidthInt | The integer value of the width of the right border.
rightWidthUnit | The unit label of the width of the right border.
topColor | The string representation of the top border color, either in the word form (for example, "white") or hexidecimal form (for example, "#FF00FF").
topColorInt | The numerical representation of this item's top border color.
topStyle | The current top border style in string form.
topWidth | The current top border width in string form.
topWidthInt | The integer value of the width of the top border.
topWidthUnit | The unit label of the width of the top border.

Constructors
Name | Description
DhBorderInfo() | Constructs a DhBorderInfo object.
DhBorderInfo( DhBorderInfo biInit ) | Constructs a DhBorderInfo object.

Methods
Name | Description
cloneThis() | Retrieves an identical copy of this DhBorderInfo object.
copy( DhBorderInfo biOther ) | Copies another DhBorderInfo object's internal data to this one.

Fields

DhBorderInfo.bottomColor

Syntax
public String bottomColor;
Description
The string representation of the bottom border color, either in word form (for example, "white") or hexidecimal form (for example, "#FF00FF"). If non-null, this value supercedes bottomColorInt.

DhBorderInfo.bottomColorInt

Syntax
public int bottomColorInt;
Description
The numerical representation of this item's bottom border color. This value may be superceded by bottomColor if its value is different and non-null.

DhBorderInfo.bottomStyle

Syntax
public String bottomStyle;
Description
The current bottom border style in string form.

DhBorderInfo.bottomWidth

Syntax
public String bottomWidth;
Description
The current bottom border width in string form.

DhBorderInfo.bottomWidthInt

Syntax
public int bottomWidthInt;
Description
The integer value of the width of the bottom border. This label is valid only if width is in value/unit form (such as 20px), and bottomWidthUnit does not equal UNIT_NULL.

DhBorderInfo.bottomWidthUnit

Syntax
public int bottomWidthUnit;
Description
The unit label of the width of the bottom border. This label is valid only if width is in value/unit form (such as 20px), and value is not UNIT_NULL.

See DhUnitEnum for unit label constants.

DhBorderInfo.leftColor

Syntax
public String leftColor;
Description
The string representation of the left border color, either in word form (for example, "white") or hexidecimal form (for example, "#FF00FF"). If non-null, this value supercedes leftColorInt.

DhBorderInfo.leftColorInt

Syntax
public int leftColorInt;
Description
The numerical representation of this item's left border color. This value may be superceded by leftColor if its value is different and non-null.

DhBorderInfo.leftStyle

Syntax
public String leftStyle;
Description
The current left border style in string form.

DhBorderInfo.leftWidth

Syntax
public String leftWidth;
Description
The current left border width in string form.

DhBorderInfo.leftWidthInt

Syntax
public int leftWidthInt;
Description
The integer value of the width of the left border. This label is valid only if width is in value/unit form (such as 20px), and leftWidthUnit does not equal UNIT_NULL.

DhBorderInfo.leftWidthUnit

Syntax
public int leftWidthUnit;
Description
The unit label of the width of the left border. This label is valid only if width is in value/unit form (such as 20px), and value is not UNIT_NULL.

See DhUnitEnum for unit label constants.

DhBorderInfo.rightColor

Syntax
public String rightColor;
Description
The string representation of the right border color, either in the word form (for example, "white") or hexidecimal form (for example, "#FF00FF"). If non-null, this value supercedes rightColorInt.

DhBorderInfo.rightColorInt

Syntax
public int rightColorInt;
Description
The numerical representation of this item's right border color. This value may be superceded by rightColor if its value is different and non-null.

DhBorderInfo.rightStyle

Syntax
public String rightStyle;
Description
The current right border style in string form.

DhBorderInfo.rightWidth

Syntax
public String rightWidth;
Description
The current right border width in string form.

DhBorderInfo.rightWidthInt

Syntax
public int rightWidthInt;
Description
The integer value of the width of the right border. This label is valid only if width is in value/unit form (such as 20px), and rightWidthUnit does not equal UNIT_NULL.

DhBorderInfo.rightWidthUnit

Syntax
public int rightWidthUnit;
Description
The unit label of the width of the right border. This label is valid only if width is in value/unit form (such as 20px), and value is not UNIT_NULL.

See DhUnitEnum for unit label constants.

DhBorderInfo.topColor

Syntax
public String topColor;
Description
The string representation of the top border color, either in the word form (for example, "white") or hexidecimal form (for example, "#FF00FF"). If non-null, this value supercedes topColorInt.

DhBorderInfo.topColorInt

Syntax
public int topColorInt;
Description
The numerical representation of this item's top border color. This value may be superceded by topColor if its value is different and non-null.

DhBorderInfo.topStyle

Syntax
public String topStyle;
Description
The current top border style in string form.

DhBorderInfo.topWidth

Syntax
public String topWidth;
Description
The current top border width in string form.

DhBorderInfo.topWidthInt

Syntax
public int topWidthInt;
Description
The integer value of the width of the top border. This label is valid only if the width is in value/unit form (such as 20px), and topWidthUnit does not equal UNIT_NULL.

DhBorderInfo.topWidthUnit

Syntax
public int topWidthUnit;
Description
The unit label of the width of the top border. This label is valid only if width is in value/unit form (such as 20px), and value is not UNIT_NULL.

See DhUnitEnum for unit label constants.

Constructors

DhBorderInfo.DhBorderInfo

Syntax 1
public DhBorderInfo();
Description

Constructs a DhBorderInfo object.

Syntax 2
public DhBorderInfo( DhBorderInfo biInit );
Parameters
biInit
Topic under construction.
Description

Constructs a DhBorderInfo object.

Methods

DhBorderInfo.cloneThis

Syntax
public DhBorderInfo cloneThis();
Return Value

Returns a new DhBorderInfo object.

Description

Retrieves an identical copy of this DhBorderInfo object.

DhBorderInfo.copy

Syntax
public void copy( DhBorderInfo biOther );
Parameters
biOther
The DhBorderInfo class to copy.
Description

Copies another DhBorderInfo object's internal data to this one.


 DhBreak Class

DhBreak Class

This Package | All Packages

DhElement
  |
  +--DhBreak
public class DhBreak
extends DhElement

Represents an HTML line break (<BR>) element.

Fields
Name | Description
CLEAR_ALL | Inserts vertical space so that the next text displayed is past all floating images.
CLEAR_LEFT | Inserts vertical space so that the next text displayed is past left-aligned floating images.
CLEAR_NONE | Inserts a standard line break (default).
CLEAR_RIGHT | Inserts vertical space so that the next text displayed is past right-aligned floating images.

Constructors
Name | Description
DhBreak() | Constructs a DhBreak object.
DhBreak( int clearFlag ) | Constructs a DhBreak object.

Methods
Name | Description
getClearFlag() | Retrieves the current clear flag.
setClearFlag(int clearFlag) | Sets the current clear flag.

Fields

DhBreak.CLEAR_ALL

Syntax
public static final int CLEAR_ALL;
Description
Inserts vertical space so that the next text displayed is past all floating images.

DhBreak.CLEAR_LEFT

Syntax
public static final int CLEAR_LEFT;
Description
Inserts vertical space so that the next text displayed is past left-aligned floating images.

DhBreak.CLEAR_NONE

Syntax
public static final int CLEAR_NONE;
Description
Inserts a standard line break (default).

DhBreak.CLEAR_RIGHT

Syntax
public static final int CLEAR_RIGHT;
Description
Inserts vertical space so that the next text displayed is past right-aligned floating images.

Constructors

DhBreak.DhBreak

Syntax 1
public DhBreak();
Description

Constructs a DhBreak object.

Syntax 2
public DhBreak( int clearFlag );
Parameters
clearFlag
The clear type flag.
Description

Constructs a DhBreak object. This is a one-step constructor specifying the clear type.

See Also
CLEAR_NONE, CLEAR_LEFT, CLEAR_RIGHT, CLEAR_ALL

Methods

DhBreak.getClearFlag

Syntax
public int getClearFlag();
Return Value

Returns the current flag type.

Description

Retrieves the current clear flag.

See Also
CLEAR_NONE, CLEAR_LEFT, CLEAR_RIGHT, CLEAR_ALL

DhBreak.setClearFlag

Syntax
public void setClearFlag( int clearFlag );
Parameters
clearFlag
The new flag type.
Description

Sets the current clear flag.

See Also
CLEAR_NONE, CLEAR_LEFT, CLEAR_RIGHT, CLEAR_ALL


 DhBrowser Class

DhBrowser Class

This Package | All Packages

public class DhBrowser

Enables access to Internet Explorer browser functionality.

Methods
Name | Description
getAppCodeName() | Retrieves the browser's code name.
getAppMinorVersion() | Retrieves the application minor version string.
getAppName() | Retrieves the name of the browser.
getAppVersion() | Retrieves the version of the browser.
getBrowserLanguage() | Retrieves the browser language setting.
getCpuClass() | Retrieves the CPU class string.
getOnLine() | Determines if the browser is connected online.
getPeer() | Retrieves the underlying peer object for this class.
getPlatform() | Retrieves the platform setting.
getSystemLanguage() | Retrieves the system language setting.
getUserAgent() | Retrieves the HTTP user-agent header string.
getUserLanguage() | Retrieves the user language setting.

Methods

DhBrowser.getAppCodeName

Syntax
public String getAppCodeName();
Return Value

Returns the code name of the browser.

Description

Retrieves the browser's code name.

DhBrowser.getAppMinorVersion

Syntax
public String getAppMinorVersion();
Return Value

Returns the minor version of the browser (for example, 0 for Internet Explorer 4.0).

Description

Retrieves the application minor version string.

DhBrowser.getAppName

Syntax
public String getAppName();
Return Value

Returns the name of the browser.

Description

Retrieves the name of the browser.

DhBrowser.getAppVersion

Syntax
public String getAppVersion();
Description

Retrieves the version of the browser.

DhBrowser.getBrowserLanguage

Syntax
public String getBrowserLanguage();
Return Value

Returns a string containing the browser language.

Description

Retrieves the browser language setting.

DhBrowser.getCpuClass

Syntax
public String getCpuClass();
Return Value

Returns a string, such as "x86", "Alpha", or "Other".

Description

Retrieves the CPU class string.

DhBrowser.getOnLine

Syntax
public boolean getOnLine();
Return Value

Returns true if browser is online; otherwise, returns false.

Description

Determines if the browser is connected online.

DhBrowser.getPeer

Syntax
public IUnknown getPeer();
Return Value

Returns the peer object which underlies the DhBrowser object.

Description

Retrieves the underlying peer object for this class. This object implements the IOmNavigator interface.

Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhBrowser.getPlatform

Syntax
public String getPlatform();
Description

Retrieves the platform setting.

DhBrowser.getSystemLanguage

Syntax
public String getSystemLanguage();
Return Value

Returns a string containing the system language.

Description

Retrieves the system language setting.

DhBrowser.getUserAgent

Syntax
public String getUserAgent();
Description

Retrieves the HTTP user-agent header string.

DhBrowser.getUserLanguage

Syntax
public String getUserLanguage();
Return Value

Returns a string containing the user language.

Description

Retrieves the user language setting.


 DhBulletedList Class

DhBulletedList Class

This Package | All Packages

DhSection
  |
  +--DhBulletedList
public class DhBulletedList
extends DhSection
implements DhStringIDs

Represents the ordered and unordered list items in HTML. This is a simple container class into which items can be added, each getting its own bullet or number, as appropriate.

Constructors
Name | Description
DhBulletedList() | Creates a list.
DhBulletedList( int listType ) | Creates a list.

Methods
Name | Description
getElementCount() | Returns the current number of elements in the list.
getListType() | Retrieves the current list type.
insert( DhElement newElement, int index ) | Inserts an element into the list at the specified index.
item( int index ) | Retrieves the element at the specified index.
remove( DhElement e ) | Removes the specified element from the list.
remove( int index ) | Removes the element at the specified index from the list.
removeAll() | Removes all the elements from the list.
setListType( int newType ) | Sets the current list type.

Constructors

DhBulletedList.DhBulletedList

Syntax 1
public DhBulletedList();
Description

Creates a list. This default constructor creates a bulleted list (ListTypeEnum.BULLETED).

See Also
wfc.html.ListTypeEnum.BULLETED

Syntax 2
public DhBulletedList( int listType );
Parameters
listType
The type of list, which can be one of the constants provided in ListTypeEnum.
Description

Creates a list.

Exceptions

IllegalArgumentException thrown if listType is not one of class constants.

Methods

DhBulletedList.getElementCount

Syntax
public int getElementCount();
Return Value

Returns the number of direct children (nonrecursive count).

Description

Returns the current number of elements in the list. Only top-level (direct children of the DhList) elements are counted.

DhBulletedList.getListType

Syntax
public int getListType();
Return Value

Returns one of the constants provided in ListTypeEnum.

Description

Retrieves the current list type.

DhBulletedList.insert

Syntax
public void insert( DhElement newElement, int index );
Parameters
newElement
The new element to insert.
index
The zero-based index where the element is to be placed.
Description

Inserts an element into the list at the specified index. If the index is less than 0 or greater than the number of elements in the list, the element is added to the end of the list.

DhBulletedList.item

Syntax
public DhElement item( int index );
Parameters
index
The index of the element to retrieve.
Description

Retrieves the element at the specified index.

Exceptions

RuntimeException thrown if index is not in the list.

DhBulletedList.remove

Syntax 1
public int remove( DhElement e );
Return Value

Returns the index of the element that was removed.

Description

Removes the specified element from the list.

Syntax 2
public int remove( int index );
Return Value

Returns the index of the element that was removed.

Description

Removes the element at the specified index from the list.

DhBulletedList.removeAll

Syntax
public void removeAll();
Description

Removes all the elements from the list.

DhBulletedList.setListType

Syntax
public void setListType( int newType );
Parameters
newType
The desired list type, which can be one of the constants provided in ListTypeEnum.
Description

Sets the current list type.


 DhButton Class

DhButton Class

This Package | All Packages

DhButtonBase
  |
  +--DhButton
public class DhButton
extends DhButtonBase

Implements a push button class. This can be used inside or outside of HTTP forms.

Constructors
Name | Description
DhButton() | Creates a button.
DhButton( String strText ) | Creates a button.

Methods
Name | Description
getEnabled() | Retrieves the enabled state of the button.
getText() | Retrieves the label from the button.
setEnabled(boolean f) | Sets the button's enabled state.
setText( String strText ) | Sets the button's text label.

Constructors

DhButton.DhButton

Syntax 1
public DhButton();
Description

Creates a button. This default constructor creates a button with a default text label of "button".

Syntax 2
public DhButton( String strText );
Parameters
strText
The new button's label.
Description

Creates a button.

Methods

DhButton.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns s true if enabled or false if disabled.

Description

Retrieves the enabled state of the button.

DhButton.getText

Syntax
public String getText();
Return Value

Returns the current label string.

Description

Retrieves the label from the button.

DhButton.setEnabled

Syntax
public void setEnabled( boolean f );
Parameters
f
Set to true if enabled; false if disabled.
Description

Sets the button's enabled state.

DhButton.setText

Syntax
public void setText( String strText );
Parameters
strText
The new label.
Description

Sets the button's text label.


 DhButtonBase Class

DhButtonBase Class

This Package | All Packages

DhElement
  |
  +--DhButtonBase
public abstract class DhButtonBase
extends DhElement

Represents the base class for all buttons.

Methods
Name | Description
createEvents() | Topic under construction.
getName( ) | Retrieves the button's name.
getText( ) | Retrieves the button label.
hasDefaultText() | Topic under construction.
setFocus() | Sets the input focus to this control.
setName( String n ) | Sets the buttons's name.
setText( String t ) | Sets the button label.

Methods

DhButtonBase.createEvents

Syntax
protected DhEvents createEvents();
Description

Topic under construction.

DhButtonBase.getName

Syntax
public String getName( );
Description

Retrieves the button's name.

DhButtonBase.getText

Syntax
public String getText( );
Description

Retrieves the button label.

DhButtonBase.hasDefaultText

Syntax
public boolean hasDefaultText();
Description

Topic under construction.

DhButtonBase.setFocus

Syntax
public void setFocus();
Description

Sets the input focus to this control.

DhButtonBase.setName

Syntax
public void setName( String n );
Parameters
n
The new button name.
Description

Sets the buttons's name.

DhButtonBase.setText

Syntax
public void setText( String t );
Parameters
t
The new button label.
Description

Sets the button label.


 DhCantAddElementException Class

DhCantAddElementException Class

This Package | All Packages

RuntimeException
  |
  +--DhCantAddElementException
public class DhCantAddElementException
extends RuntimeException

Signals that a request for a named element failed, because an element with that name does not exist.

Constructors
Name | Description
DhCantAddElementException() | Constructs a ElementNotFoundException with no detail message.
DhCantAddElementException(String s) | Constructs a ElementNotFoundException with a detail message.

Constructors

DhCantAddElementException.DhCantAddElementException

Syntax 1
public DhCantAddElementException();
Description

Constructs a ElementNotFoundException with no detail message.

Syntax 2
public DhCantAddElementException( String s );
Description

Constructs a ElementNotFoundException with a detail message.


 DhCantModifyElementException Class

DhCantModifyElementException Class

This Package | All Packages

RuntimeException
  |
  +--DhCantModifyElementException
public class DhCantModifyElementException
extends RuntimeException

Signals that an attempt has been made to modify a read-only element, such as one that has been sent from a server to a client.

Constructors
Name | Description
DhCantModifyElementException() | Topic under construction.
DhCantModifyElementException( String detail ) | Topic under construction.

Constructors

DhCantModifyElementException.DhCantModifyElementException

Syntax 1
public DhCantModifyElementException();
Description

Topic under construction.

Syntax 2
public DhCantModifyElementException( String detail );
Description

Topic under construction.


 DhCell Class

DhCell Class

This Package | All Packages

DhSection
  |
  +--DhCell
public class DhCell
extends DhSection

Creates a table cell. You can add any number of elements in any kind of layout to a cell using the add method.

Constructors
Name | Description
DhCell() | Creates an empty cell.
DhCell( String text ) | Creates a cell with the specified text contents.

Methods
Name | Description
add(DhElement e) | Adds this cell to the table.
getColSpan() | Returns the number of columns this cell spans.
getDataField() | Returns the data field bound to this cell.
getRowSpan() | Returns the number of rows this cell spans.
getTagNameID() | Topic under construction.
getText() | Retrieves the text of the cell.
getValue() | Retrieves the numeric value displayed in the cell.
setColSpan(int span) | Sets the number of columns this cell spans.
setRowSpan(int span) | Determines how many rows this cell spans.
setText( String text ) | Sets the text of the cell.
setValue( int i ) | Sets a numeric value for the cell.

Constructors

DhCell.DhCell

Syntax 1
public DhCell();
Description

Creates an empty cell.

Syntax 2
public DhCell( String text );
Parameters
text
The text contents of the cell.
Description

Creates a cell with the specified text contents.

Methods

DhCell.add

Syntax
public synchronized void add( DhElement e );
Description

Adds this cell to the table.

DhCell.getColSpan

Syntax
public int getColSpan();
Return Value

Returns the number of columns this cell spans.

Description

Returns the number of columns this cell spans. This number is over and above what the default table layout engine determines.

DhCell.getDataField

Syntax
public synchronized String getDataField();
Return Value

Returns the column name bound to this cell, or a null string if no column name is bound.

Description

Returns the data field bound to this cell.

DhCell.getRowSpan

Syntax
public int getRowSpan();
Return Value

Returns Number of rows this cell spans.

Description

Returns the number of rows this cell spans. This number is over and above what the default table layout engine determines.

DhCell.getTagNameID

Syntax
protected int getTagNameID();
Description

Topic under construction.

DhCell.getText

Syntax
public synchronized String getText();
Return Value

Returns The cell text.

Description

Retrieves the text of the cell.

See Also
setText

DhCell.getValue

Syntax
public int getValue();
Return Value

Returns an integer value.

Description

Retrieves the numeric value displayed in the cell.

See Also
setValue, setText

DhCell.setColSpan

Syntax
public void setColSpan( int span );
Parameters
span
The number of columns this cell should span.
Description

Sets the number of columns this cell spans. This number is over and above what the default table layout engine determines.

DhCell.setRowSpan

Syntax
public void setRowSpan( int span );
Parameters
span
Number of rows this cell should span.
Description

Determines how many rows this cell spans. This number is over and above what the default table layout engine determines.

DhCell.setText

Syntax
public synchronized void setText( String text );
Parameters
text
String to display to user.
Description

Sets the text of the cell. Setting this value overwrites any previous call to setText or setValue.

DhCell.setValue

Syntax
public void setValue( int i );
Parameters
i
The int value to display in the cell.
Description

Sets a numeric value for the cell. Setting this value overwrites any previous call to setText or setValue.


 DhCheckBox Class

DhCheckBox Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhCheckBox
public class DhCheckBox
extends DhBaseContainer

Represents an HTML-intrinsic check box with a text label.

Constructors
Name | Description
DhCheckBox() | Creates a check box.
DhCheckBox( String strText, boolean fChecked ) | Creates a check box.

Methods
Name | Description
getChecked() | Retrieves the checked state of the check box.
getEnabled() | Retrieves the enabled state of the check box.
getSubmitName( ) | Retrieves the current name attribute for this check box.
getSubmitValue( ) | Retrieves the submit value for this check box.
getText( ) | Retrieves the current text label for the check box.
getTextAlignment() | Retrieves the current alignment.
setChecked( boolean fChecked ) | Sets the checked state of the check box.
setEnabled( boolean f) | Sets the enabled state of the check box.
setFocus() | Sets the input focus to this control
setSubmitName( String strName ) | Sets the name for this check box.
setSubmitValue( String strValue ) | Sets the submit value for this check box.
setText( String strText ) | Sets the text label for the check box.
setTextAlignment( int newAlignment ) | Sets the current alignment.

Constructors

DhCheckBox.DhCheckBox

Syntax 1
public DhCheckBox();
Description

Creates a check box. By default, this check box has neither a label nor a check mark.

Syntax 2
public DhCheckBox( String strText, boolean fChecked );
Parameters
strText
The text label.
fChecked
The initial checked state of the check box.
Description

Creates a check box. By default, this check box has a right-aligned label.

Methods

DhCheckBox.getChecked

Syntax
public boolean getChecked();
Return Value

Returns true if the box is checked; returns false if not checked.

Description

Retrieves the checked state of the check box.

DhCheckBox.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns true if the box is enabled; returns false if it is not.

Description

Retrieves the enabled state of the check box.

DhCheckBox.getSubmitName

Syntax
public String getSubmitName( );
Return Value

Returns the name attribute. This attribute is used only for HTTP form submission; otherwise, it is not required.

Description

Retrieves the current name attribute for this check box.

DhCheckBox.getSubmitValue

Syntax
public String getSubmitValue( );
Return Value

Returns the current submit value.

Description

Retrieves the submit value for this check box.

See Also
setSubmitValue

DhCheckBox.getText

Syntax
public String getText( );
Return Value

Returns the current text label.

Description

Retrieves the current text label for the check box.

DhCheckBox.getTextAlignment

Syntax
public synchronized int getTextAlignment();
Return Value

Returns the current alignment, which can be either TEXT_RIGHT or TEXT_LEFT.

Description

Retrieves the current alignment.

DhCheckBox.setChecked

Syntax
public void setChecked( boolean fChecked );
Parameters
fChecked
Set to true for a selected box; set to false for a cleared box.
Description

Sets the checked state of the check box.

DhCheckBox.setEnabled

Syntax
public void setEnabled( boolean f );
Parameters
f
Set to true to enable the check box; set to false disabled it.
Description

Sets the enabled state of the check box.

DhCheckBox.setFocus

Syntax
public void setFocus();
Description

Sets the input focus to this control

DhCheckBox.setSubmitName

Syntax
public void setSubmitName( String strName );
Parameters
strName
The name attribute. This name should be unique on the form.
Description

Sets the name for this check box. This name is used during HTTP form submission.

DhCheckBox.setSubmitValue

Syntax
public void setSubmitValue( String strValue );
Parameters
strName
The new submit value.
Description

Sets the submit value for this check box.

DhCheckBox.setText

Syntax
public void setText( String strText );
Parameters
strText
The label to display for the check box.
Description

Sets the text label for the check box. The check box can be selected or cleared by clicking this label.

DhCheckBox.setTextAlignment

Syntax
public synchronized void setTextAlignment( int newAlignment );
Parameters
newAlignment
The new alignment, which can be either TEXT_LEFT or TEXT_RIGHT.
Description

Sets the current alignment.


 DhComboBox Class

DhComboBox Class

This Package | All Packages

DhSelectBox
  |
  +--DhComboBox
public class DhComboBox
extends DhSelectBox

Represents a drop-down combo box control.

Constructors
Name | Description
DhComboBox( ) | Creates an empty DhComboBox object.

Constructors

DhComboBox.DhComboBox

Syntax
public DhComboBox( );
Description

Creates an empty DhComboBox object.


 DhCursorEnum Class

DhCursorEnum Class

This Package | All Packages

Enum
  |
  +--DhCursorEnum
public class DhCursorEnum
extends wfc.cor.Enum
implements DhStringIDs

Defines constants for controlling an element's cursor style. For more information on setting cursor styles, see DhStyleBase.setCursor().

Fields
Name | Description
AUTO | Browser determines the cursor to display based on the current context.
CROSSHAIR | A simple cross-hair cursor.
DEFAULT | A platform-dependent default cursor (usually an arrow).
E_RESIZE | An arrow cursor indicating that an edge is to be moved in an eastern direction.
HAND | A hand pointer cursor.
HELP | An arrow cursor with a question mark, indicating Help.
MOVE | A cursor with crossed arrows indicating something is to be moved.
N_RESIZE | An arrow cursor indicating that an edge is to be moved in a northern direction.
NE_RESIZE | An arrow cursor indicating that an edge is to be moved in a northeastern direction.
NW_RESIZE | An arrow cursor indicating that an edge is to be moved in a northwestern direction.
S_RESIZE | An arrow cursor indicating that an edge is to be moved in a southern direction.
SE_RESIZE | An arrow cursor indicating that an edge is to be moved in a southeastern direction.
SW_RESIZE | An arrow cursor indicating that an edge is to be moved in a southwestern direction.
TEXT | An editable text cursor (usually an I-bar).
W_RESIZE | An arrow cursor indicating that an edge is to be moved in a western direction.
WAIT | An hourglass or watch indicating that the program is busy and the user should wait.

Fields

DhCursorEnum.AUTO

Syntax
public static final int AUTO;
Description
Browser determines the cursor to display based on the current context.

DhCursorEnum.CROSSHAIR

Syntax
public static final int CROSSHAIR;
Description
A simple cross-hair cursor.

DhCursorEnum.DEFAULT

Syntax
public static final int DEFAULT;
Description
A platform-dependent default cursor (usually an arrow).

DhCursorEnum.E_RESIZE

Syntax
public static final int E_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in an eastern direction.

DhCursorEnum.HAND

Syntax
public static final int HAND;
Description
A hand pointer cursor.

DhCursorEnum.HELP

Syntax
public static final int HELP;
Description
An arrow cursor with a question mark, indicating Help.

DhCursorEnum.MOVE

Syntax
public static final int MOVE;
Description
A cursor with crossed arrows indicating something is to be moved.

DhCursorEnum.N_RESIZE

Syntax
public static final int N_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a northern direction.

DhCursorEnum.NE_RESIZE

Syntax
public static final int NE_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a northeastern direction.

DhCursorEnum.NW_RESIZE

Syntax
public static final int NW_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a northwestern direction.

DhCursorEnum.S_RESIZE

Syntax
public static final int S_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a southern direction.

DhCursorEnum.SE_RESIZE

Syntax
public static final int SE_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a southeastern direction.

DhCursorEnum.SW_RESIZE

Syntax
public static final int SW_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a southwestern direction.

DhCursorEnum.TEXT

Syntax
public static final int TEXT;
Description
An editable text cursor (usually an I-bar).

DhCursorEnum.W_RESIZE

Syntax
public static final int W_RESIZE;
Description
An arrow cursor indicating that an edge is to be moved in a western direction.

DhCursorEnum.WAIT

Syntax
public static final int WAIT;
Description
An hourglass or watch indicating that the program is busy and the user should wait.


 DhDataSource Class

DhDataSource Class

This Package | All Packages

public class DhDataSource

Represents a generic wrapper class for data sources. It allows access to any object that is a data source, regardless of the tag type. This class also encapsulates access to the Data Source object ADO recordset functions.

Constructors
Name | Description
DhDataSource( DhElement e ) | Creates a DhDataSource object.

Methods
Name | Description
addNew() | Creates a new record for the recordset.
addOnDataAvailable( DhEventHandler h ) | Adds an event handler for the DataAvailable event.
addOnDataSetChanged( DhEventHandler h ) | Adds an event handler for the DataSetChanged event.
addOnDataSetComplete( DhEventHandler h ) | Adds an event handler for the DataSetComplete event.
cancelUpdate() | Cancels the current update operation, and restores recordset to its prior state.
delete() | Deletes the current record from the recordset.
getAbsolutePosition( ) | Retrieves the ordinal position of the current record in the recordset.
getBOF() | Determines if the current record is before the first record.
getDataFieldIndex( String strFieldName ) | Returns the ordinal column number of the column specified.
getDataFieldName( int nField ) | Returns the string name of the recordset field at the specified ordinal position.
getEditMode() | Retrieves the current edit mode.
getEOF() | Determines if the current record is after the last record.
getFieldUpdatable( int nField ) | Determines if the specified field is writeable.
getFieldUpdatable( String strField ) | Determines if the specified field is writeable.
getID() | Retrieves the identifier for the element associated with this data source.
getRecordCount() | Returns the number of records in the recordset.
getRecordsetPeer() | Returns the ADO recordset object represented by the data source object.
move( int nRecords ) | Moves the recordset a specified number of records.
moveFirst() | Moves to the first record in the recordset.
moveLast() | Moves to the last record in the recordset.
moveNext() | Moves to the next record in the recordset.
movePrevious() | Moves to the previous record in the recordset.
refresh() | Refreshes the recordset by reissuing the query that created it.
setAbsolutePosition( int nPos ) | Sets the internal recordset to an ordinal record position.
setDataSourceFromElement( DhElement e ) | Sets the element this DhDataSource represents.
update() | Commits an in-progress edit operation.

Constructors

DhDataSource.DhDataSource

Syntax
protected DhDataSource( DhElement e );
Parameters
e
The data source element to be contained.
Description

Creates a DhDataSource object. This constructor wraps an existing element that is a data source.

Methods

DhDataSource.addNew

Syntax
public synchronized boolean addNew();
Return Value

Returns true if successful; otherwise, returns false.

Description

Creates a new record for the recordset. The record will not be added until update() is called.

See Also
update

DhDataSource.addOnDataAvailable

Syntax
public synchronized void addOnDataAvailable( DhEventHandler h );
Parameters
h
The event handler.
Description

Adds an event handler for the DataAvailable event.

DhDataSource.addOnDataSetChanged

Syntax
public synchronized void addOnDataSetChanged( DhEventHandler h );
Parameters
h
The event handler.
Description

Adds an event handler for the DataSetChanged event.

DhDataSource.addOnDataSetComplete

Syntax
public synchronized void addOnDataSetComplete( DhEventHandler h );
Parameters
h
The event handler.
Description

Adds an event handler for the DataSetComplete event.

DhDataSource.cancelUpdate

Syntax
public synchronized boolean cancelUpdate();
Return Value

Returns true if successful; otherwise, returns false.

Description

Cancels the current update operation, and restores recordset to its prior state.

See Also
update

DhDataSource.delete

Syntax
public synchronized boolean delete();
Return Value

Returns true successful; otherwise, returns false.

Description

Deletes the current record from the recordset.

See Also
update

DhDataSource.getAbsolutePosition

Syntax
public synchronized int getAbsolutePosition( );
Return Value

Returns the zero-based position of the record, or returns -1 if the ordinal position cannot be determined.

Description

Retrieves the ordinal position of the current record in the recordset.

DhDataSource.getBOF

Syntax
public synchronized boolean getBOF();
Return Value

Returns true if at the first record; otherwise, returns false.

Description

Determines if the current record is before the first record.

DhDataSource.getDataFieldIndex

Syntax
public synchronized int getDataFieldIndex( String strFieldName );
Parameters
strFieldName
The name of the column to retrieve position.
Return Value

Returns the zero-based ordinal position of column in recordset.

Description

Returns the ordinal column number of the column specified.

DhDataSource.getDataFieldName

Syntax
public synchronized String getDataFieldName( int nField );
Parameters
nField
The zero-based position of the field to retrieve name of.
Return Value

Returns the name of the field, or returns a null string if it is unavailable.

Description

Returns the string name of the recordset field at the specified ordinal position.

DhDataSource.getEditMode

Syntax
public synchronized int getEditMode();
Return Value

Returns the current edit mode, which can be one of the following:

  • 0 - no edit in progress.
  • 1 - update edit in progress.
  • 2 - addition of new record in progress.
  • 3 - deletion of record in progress.
Description

Retrieves the current edit mode.

DhDataSource.getEOF

Syntax
public synchronized boolean getEOF();
Return Value

Returns true if at the last record; otherwise, returns false.

Description

Determines if the current record is after the last record.

DhDataSource.getFieldUpdatable

Syntax 1
public synchronized boolean getFieldUpdatable( int nField );
Parameters
nField
The ordinal position of the field to check permissions.
Return Value

Returns true if a write operation is allowed, returns false if not.

Description

Determines if the specified field is writeable.

Syntax 2
public synchronized boolean getFieldUpdatable( String strField );
Parameters
nField
The string name of the field to check permissions.
Return Value

Returns true if a write operation is allowed, returns false if not.

Description

Determines if the specified field is writeable.

DhDataSource.getID

Syntax
public String getID();
Return Value

Returns the identifier of the associated element.

Description

Retrieves the identifier for the element associated with this data source.

DhDataSource.getRecordCount

Syntax
public synchronized int getRecordCount();
Return Value

Returns 0 or greater if successful; otherwise, returns -1.

Description

Returns the number of records in the recordset. This number is often an estimate, and relies on the underlying recordset.

DhDataSource.getRecordsetPeer

Syntax
public synchronized Recordset getRecordsetPeer();
Return Value

Returns an ADO recordset object, or returns null if that interface cannot be obtained.

Description

Returns the ADO recordset object represented by the data source object. Not all data source objects expose a recordset object (for example, the Tabular Data Control does not).

DhDataSource.move

Syntax
public synchronized boolean move( int nRecords );
Parameters
nRecords
Number of records to move forward or backwards if negative If greater than zero, the current record position moves forward (toward the end of the recordset). If less than zero, the current record position moves backward (toward the beginning of the recordset).
Return Value

Returns true successful; otherwise, returns false.

Description

Moves the recordset a specified number of records.

DhDataSource.moveFirst

Syntax
public synchronized boolean moveFirst();
Return Value

Returns true if successful; otherwise, returns false.

Description

Moves to the first record in the recordset.

DhDataSource.moveLast

Syntax
public synchronized boolean moveLast();
Return Value

Returns true successful; otherwise, returns false.

Description

Moves to the last record in the recordset.

DhDataSource.moveNext

Syntax
public synchronized boolean moveNext();
Return Value

Returns true if successful; otherwise, returns false.

Description

Moves to the next record in the recordset.

DhDataSource.movePrevious

Syntax
public synchronized boolean movePrevious();
Return Value

Returns true if successful; otherwise, returns false.

Description

Moves to the previous record in the recordset.

DhDataSource.refresh

Syntax
public synchronized boolean refresh();
Return Value

Returns true successful; otherwise, returns false.

Description

Refreshes the recordset by reissuing the query that created it.

DhDataSource.setAbsolutePosition

Syntax
public synchronized boolean setAbsolutePosition( int nPos );
Parameters
nPos
The ordinal (zero-based) position of the record to move to.
Return Value

Returns true if successful; otherwise, returns false.

Description

Sets the internal recordset to an ordinal record position.

DhDataSource.setDataSourceFromElement

Syntax
public synchronized void setDataSourceFromElement( DhElement e );
Parameters
e
The data source object element to encapsulate. Recordset operations will be available only if e is a DhObjectFactory object or a class derived from DhObjectFactory.
Description

Sets the element this DhDataSource represents.

DhDataSource.update

Syntax
public synchronized boolean update();
Return Value

Returns true if the update was successful; otherwise, returns false.

Description

Commits an in-progress edit operation.

See Also
addNew


 DhDialogInfo Class

DhDialogInfo Class

This Package | All Packages

DhStyleBase
  |
  +--DhDialogInfo
public class DhDialogInfo
extends DhStyleBase

Represents an information class for dialog boxes.

Fields
Name | Description
showCentered | Displays the dialog box centered on the desktop.
showHelpButton | Adds or removes a Help button on the dialog box's title bar.
showMaximizeButton | Adds or removes a Maximize button on the dialog box's title bar.
showMinimizeButton | Adds or removes a Minimize button on the dialog box's title bar.

Constructors
Name | Description
DhDialogInfo() | Creates a DhDialogInfo object.

Methods
Name | Description
toString() | Retrieves a string representation of this object.

Fields

DhDialogInfo.showCentered

Syntax
public boolean showCentered;
Description
Displays the dialog box centered on the desktop. This is used by DhWindow.showModalDialog().

DhDialogInfo.showHelpButton

Syntax
public boolean showHelpButton;
Description
Adds or removes a Help button on the dialog box's title bar. This is used by DhWindow.showModalDialog().

DhDialogInfo.showMaximizeButton

Syntax
public boolean showMaximizeButton;
Description
Adds or removes a Maximize button on the dialog box's title bar. This is used by DhWindow.showModalDialog().

DhDialogInfo.showMinimizeButton

Syntax
public boolean showMinimizeButton;
Description
Adds or removes a Minimize button on the dialog box's title bar. This is used by DhWindow.showModalDialog().

Constructors

DhDialogInfo.DhDialogInfo

Syntax
public DhDialogInfo();
Description

Creates a DhDialogInfo object.

Methods

DhDialogInfo.toString

Syntax
public String toString();
Description

Retrieves a string representation of this object.


 DhDocument Class

DhDocument Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhDocument
public class DhDocument
extends DhBaseContainer
implements DhIFilterableObject

Represents an HTML document. You can use it to bind to an existing HTML page and traverse the elements on that page. Alternatively, you can create new elements and add them to the page through this class.

Objects in this class cannot be created directly; instead, you acquire a reference to it through a DhModule class.

Also see wfc.html.DhStyle, wfc.html.DhText, wfc.html.DhElement, wfc.html.DhSection, DhPane

Constructors
Name | Description
DhDocument( DhModule module, IHTMLDocument2 document, IHTMLWindow2 window ) | Creates a document object.
DhDocument() | Creates a document object.

Methods
Name | Description
add(DhElement element) | Adds an element into this container.
add(DhElement element, int insertFlag ) | Adds an element into this container.
add( DhElement element, DhElement relativeTo, int insertFlag ) | Adds an element into this container.
add( DhStyle newStyle ) Explicitly adds a DhStyle style object to this document.

Note that this is done automatically for you whenever you call the setStyle method on any element.

addFilter(DhFilter filter) | Topic under construction.
addFilter(DhFilter filter, boolean bApply) | Adds a filter to this element.
addFilter(DhFilter filter, boolean bApply, boolean bFlush) | Adds a filter to this element.
addText( String text ) | Appends a text string to the current document.
addTransition(DhFilter trans) | Adds a transition effect to this element.
applyFilters() | Applies filters that were previously deferred.
enumerate( int type ) | Returns an enumerator that represents the collection of elements.
findElement( String id ) | Searches for an element in the document.
findFilter(Class filterClass) | Retrieves the current filter with the specified filter class.
findStyle(String style) | Retrieves a DHStyle object with the named style for this document.
getAllElements() | Recursively retrieves all child elements and their children.
getDomain() | Returns the host name of the server the page is from.
getElement( IHTMLElement peer ) | Returns the corresponding derivation of DhElement given the underlying HTML element peer.
getElements() | Retrieves the child elements of this element.
getFixed() | Determines whether the default placement of elements uses fixed x-y coordinate positioning or traditional HTML text flow layout positioning.
getHTML() | Returns the representative HTML of this document (also known as the page).
getLastModified() Retrieves the last modified date of the current document in the form
MM/DD/YY HH:MM:SS

Return Value:

Returns the document's last modified date, or returns a null string if it is unavailable.

getLocation() | Retrieves the current location of the document.
getMatchingChildElements( String strQuery, boolean fRecursive ) | Retrieves the matching child elements according to the parameters in strQuery.
getModule() | Returns the DhModule associated with this document.
getPeer() | Return the underlying HTML peer element for this class.
getProtocol() | Retrieves the long name of the protocol.
getReferrer() | Retrieves the referring document.
getSize() | Retrieves the current size of the document.
getStyles() | Retrieves all styles in this document.
getTitle() | Retrieves the title of the document.
getWindow() | Retrieves the window object of this document.
getWindowPeer() | Retrieves the window peer of this document.
importHTML(String html) | Topic under construction.
importHTMLFromFile(String file) throws IOException | Imports the HTML code from the specified file.
MessageBox( String s ) | Displays a modal user message box.
moveElement( DhElement element, int newOrder ) | Moves an element to a new numeric order in the layout flow.
newLine() | Appends a new line to the current document.
recreateElement( String html ) | Deserializes HTML text generated by generateHTML.
recreateElement( String html, boolean fHonorIDs ) | Deserializes HTML text generated by generateHTML.
remove(DhElement element) | Removes an element from this container.
removeAll() | Removes all child elements from this container.
removeAllFilters() | Automatically removes all filters from this element immediately.
removeAllFilters(boolean bApply) | Removes all filters from this element.
removeFilter(DhFilter filter) | Removes the specified filter from this element.
removeFilter(DhFilter filter, boolean bApply) | Removes the specified filter from this element.
replaceFilter(DhFilter filter1, DhFilter filter2) | Replaces filters currently applied to the document.
replaceFilter(DhFilter filter1, DhFilter filter2, boolean bApply) | Replaces filters currently applied to the document.
setDomain( String strDomain ) | Sets the host domain for the page.
setFixed( boolean isFixed ) | Determines whether the default placement of elements uses fixed x-y coordinate positioning or traditional HTML text flow layout positioning.
setFixed() | Sets the default placement of elements to fixed x-y coordinate positioning in contrast to traditional HTML text flow layout.
setGenerateTags( boolean fGenerate ) | Determines whether HEAD and TITLE tags are generated by the generateHTML() method.
setTitle( String newTitle ) | Sets the title of the document.

Constructors

DhDocument.DhDocument

Syntax 1
public DhDocument( DhModule module, IHTMLDocument2 document, IHTMLWindow2 window );
Description

Creates a document object.

Syntax 2
public DhDocument();
Description

Creates a document object. This is a blank document with no object model binding.

Methods

DhDocument.add

Syntax 1
public void add( DhElement element );
Parameters
element
The DhElement to add to the end of the flow of this container.
Description

Adds an element into this container. This method adds the element following all other elements.

Syntax 2
public void add( DhElement element, int insertFlag );
Parameters
element
The DhElement to add to this container.
insertFlag
One of the applicable insert constants from DhInsertEnum. The valid values for insertFlag are:
  • INSERT_END
  • INSERT_BEGINNING
Description

Adds an element into this container. This method adds the element either at the beginning or at the end of this container depending on the insertFlag parameter.

Syntax 3
public void add( DhElement element, DhElement relativeTo, int insertFlag );
Parameters
element
The element to be added.
relativeTo
An element to which the insertFlags parameter relates (this can be null depending on the value of insertFlags).
insertFlags
One of the INSERT_ constants in DhInsertEnum.
Description

Adds an element into this container. This method adds the specified element either at the end or at the beginning of the document, or before or after another element.

For details of this method and other available add methods, see DhSection.add.

Syntax 4
public synchronized void add( DhStyle newStyle );
Parameters
newStyle
The DhStyle object to add to this document.
Description

Explicitly adds a DhStyle style object to this document.

Note that this is done automatically for you whenever you call the setStyle method on any element.

DhDocument.addFilter

Syntax 1
public void addFilter( DhFilter filter );
Description

Topic under construction.

Syntax 2
public void addFilter( DhFilter filter, boolean bApply );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay the application.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

Syntax 3
public void addFilter( DhFilter filter, boolean bApply, boolean bFlush );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay applying the filter.
bFlush
Set to true to flush the previously applied filters; set to false to combine filter with those already present.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. You can also specify whether you want to flush filters that were previously applied to this element or whether you want this filter to be combined with those already present.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

DhDocument.addText

Syntax
public void addText( String text );
Parameters
text
The text string.
Description

Appends a text string to the current document.

DhDocument.addTransition

Syntax
public void addTransition( DhFilter trans );
Parameters
trans
The transition effect you will run.
Description

Adds a transition effect to this element. You must call this method before you can run the effect. Note that this functionality is provided for extension only (see the sample classes). This package does provide transition effects.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of transition effect already exists on this element.

See Also
replaceFilter

DhDocument.applyFilters

Syntax
public void applyFilters();
Description

Applies filters that were previously deferred. Use this method if you called addFilter(DhFilter,boolean) with false as the second parameter. This function applies every filter that was added to this element.

See Also
addFilter(DhFilter,boolean), addFilter

DhDocument.enumerate

Syntax
public DhEnumeration enumerate( int type );
Parameters
type
One of the types enumerated by the DhEnumeration class.
Return Value

Returns a DhEnumeration enumerator that represents the collection of elements of the types defined by the type parameter. This can be one of the following:

  • ELEMENTS, which include all elements (tags including the HEAD and BODY).
  • IMAGES, which include only the images (such as IMG tags).
  • HLINKS, which include only the links (such as A tags).

Description

Returns an enumerator that represents the collection of elements.

DhDocument.findElement

Syntax
public DhElement findElement( String id );
Parameters
id
The HTML ID attribute of the element to search for. For example,
ID="Caption1"

this argument would be: "Caption1".

Return Value

Returns the DhElement representing the element in the document. This element can then be cast to the actual element type (for example, DhText).

Description

Searches for an element in the document. This method can be used to find any element in the document by the HTML ID attribute.

DhDocument.findFilter

Syntax
public DhFilter findFilter( Class filterClass );
Parameters
filterClass
The class of the filter you are looking for, for example, wfc.html.DhDropShadowFilter.
Return Value

Returns the DhFilter object (if found) that is of type filterClass.

Description

Retrieves the current filter with the specified filter class.

DhDocument.findStyle

Syntax
public DhStyle findStyle( String style );
Parameters
style
The string name of the style you are looking for (for example, ".myClass").
Return Value

Returns the style object that corresponds to the style parameter, or returns null if no such style exists in this document.

Description

Retrieves a DHStyle object with the named style for this document.

Note This method is not used in the normal course of programming this package.

DhDocument.getAllElements

Syntax
public DhElement[] getAllElements();
Return Value

Returns an array of all child elements.

Description

Recursively retrieves all child elements and their children.

Overrides

getAllElements() in DhBaseContainer.

DhDocument.getDomain

Syntax
public String getDomain();
Return Value

Returns the current host server domain, or returns a null string if it is unavailable.

Description

Returns the host name of the server the page is from.

DhDocument.getElement

Syntax
public synchronized DhElement getElement( IHTMLElement peer );
Parameters
peer
The underlying HTML element peer. This peer may have been acquired using DhElement.getPeer.
Return Value

Returns the specific derivation that corresponds to the peer parameter.

Description

Returns the corresponding derivation of DhElement given the underlying HTML element peer.

Note Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhDocument.getElements

Syntax
public DhElement[] getElements();
Return Value

Returns an array of direct child elements.

Description

Retrieves the child elements of this element.

Overrides

getElements() in DhBaseContainer.

DhDocument.getFixed

Syntax
public synchronized boolean getFixed();
Return Value

Returns true if this document uses fixed positioning; otherwise, returns false, which is the default.

Description

Determines whether the default placement of elements uses fixed x-y coordinate positioning or traditional HTML text flow layout positioning. Rather than use this property, it is much more useful to create DhSections and/or DhPanels to control the placement of elements.

DhDocument.getHTML

Syntax
public synchronized String getHTML();
Return Value

Returns the generated or bound HTML text.

Description

Returns the representative HTML of this document (also known as the page).

DhDocument.getLastModified

Syntax
public String getLastModified();
Return Value

Returns the document's last modified date, or returns a null string if it is unavailable.

Description

Retrieves the last modified date of the current document in the form

MM/DD/YY HH:MM:SS

DhDocument.getLocation

Syntax
public Point getLocation();
Return Value

Returns a Point object holding the document's location.

Description

Retrieves the current location of the document.

DhDocument.getMatchingChildElements

Syntax
public IEnumerator getMatchingChildElements( String strQuery, boolean fRecursive );
Parameters
strQuery
The query criteria string.
fRecursive
Set to true to apply to all children; set to false to apply to only direct children.
Return Value

Returns an enumeration of matching elements, or returns null if there are none.

Description

Retrieves the matching child elements according to the parameters in strQuery.

Some query examples are as follows:

  • "tag='div'"
  • "ATTR:width='10' OR TAG='SPAN'"
  • "(tag='input' and attr:type='button') or (STYLE:background-color='red' and STYLE:color='black')"

Overrides

getMatchingChildElements(String,boolean) in DhBaseContainer.

DhDocument.getModule

Syntax
public DhModule getModule();
Return Value

Returns the DhModule associated with this document.

Description

Returns the DhModule associated with this document. DhDocument cannot be created directly; instead, you acquire a reference to it through a DhModule object.

DhDocument.getPeer

Syntax
public IUnknown getPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Return the underlying HTML peer element for this class. This method may return null if the document is not bound to this class. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (such as wfc.html.om.IHTMLDocument2). This method always returns null if the code is running in a Web server environment.

Note Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhDocument.getProtocol

Syntax
public String getProtocol();
Return Value

Returns the name of the protocol.

Description

Retrieves the long name of the protocol.

Examples:

"Hypertext Transfer Protocol"

"File Protocol"

See Also
getDocumentUrl

DhDocument.getReferrer

Syntax
public String getReferrer();
Return Value

Returns the URL of the referring document, or returns a null string if it is unavailable.

Description

Retrieves the referring document. This is the document that contains the hyperlink to the current document.

DhDocument.getSize

Syntax
public Point getSize();
Return Value

Returns a Point object holding the document's size.

Description

Retrieves the current size of the document.

DhDocument.getStyles

Syntax
public DhStyle[] getStyles();
Return Value

Returns an array of DhStyle objects found on this document.

Description

Retrieves all styles in this document. Style objects can be applied to any element using the setStyle method.

DhDocument.getTitle

Syntax
public String getTitle();
Return Value

Returns the title of document.

Description

Retrieves the title of the document. For a browser, the title appears in the caption of the browser window.

DhDocument.getWindow

Syntax
final public DhWindow getWindow();
Return Value

Returns the window object of the document.

Description

Retrieves the window object of this document.

DhDocument.getWindowPeer

Syntax
protected IHTMLWindow2 getWindowPeer();
Return Value

Returns the WindowPeer object related to this the document.

Description

Retrieves the window peer of this document.

DhDocument.importHTML

Syntax
public void importHTML( String html );
Description

Topic under construction.

DhDocument.importHTMLFromFile

Syntax
public void importHTMLFromFile( String file ) throws IOException;
Parameters
file
The file to import from.
Description

Imports the HTML code from the specified file.

Exceptions

IOException thrown if file cannot be read or opened.

DhDocument.MessageBox

Syntax
final public void MessageBox( String s );
Parameters
s
The message string to display.
Description

Displays a modal user message box.

DhDocument.moveElement

Syntax
public void moveElement( DhElement element, int newOrder );
Parameters
element
The element to move.
newOrder
The new numeric order in the flow of this container.
Description

Moves an element to a new numeric order in the layout flow.

DhDocument.newLine

Syntax
public void newLine();
Description

Appends a new line to the current document. All elements added after this call will be on a new line.

DhDocument.recreateElement

Syntax 1
public DhElement recreateElement( String html );
Parameters
html
The text that was generated by calling generateHTML on a given DhElement.
Return Value

Returns the corresponding tree of derivations of DhElements that originally created the text in the html parameter.

Description

Deserializes HTML text generated by generateHTML. The default case of calling this method ignores the ID attributes of the HTML and overrides those attributes with IDs that are unique to this document. To control this behavior, see recreateElement(String,boolean).

Syntax 2
public DhElement recreateElement( String html, boolean fHonorIDs );
Parameters
html
The text that was generated by calling generateHTML() on a given DhElement.
fHonorIDs
Set to true to prevent destruction of ID attributes.
Return Value

Returns the corresponding tree of derivations of DhElements that originally created the text in the html parameter.

Description

Deserializes HTML text generated by generateHTML. Passing true to fHonorIDs tells this method not to overwrite the ID attributes of the HTML tags in the html parameter. This is a very advanced usage of this method. If ID attributes conflict with elements already on the page, the resulting behavior is undefined in the rest of the package.

See Also
recreateElement

DhDocument.remove

Syntax
public int remove( DhElement element );
Parameters
element
The element to remove from this container.
Description

Removes an element from this container. If the element was visible prior to this call, it will not be visible after the call.

DhDocument.removeAll

Syntax
public void removeAll();
Description

Removes all child elements from this container. If the elements were visible prior to this call, they will not be visible after the call.

DhDocument.removeAllFilters

Syntax 1
public void removeAllFilters();
Description

Automatically removes all filters from this element immediately.

Syntax 2
public void removeAllFilters( boolean bApply );
Description

Removes all filters from this element. You can clear all filters on this element or delay removal.

DhDocument.removeFilter

Syntax 1
public void removeFilter( DhFilter filter );
Parameters
filter
The filter to remove.
Description

Removes the specified filter from this element. This method automatically reapplies filters that may be left after this method is called.

See Also
findFilter.

Syntax 2
public void removeFilter( DhFilter filter, boolean bApply );
Parameters
filter
A reference to the filter to remove.
bApply
Set to true to reapply other filters left on this element; set to false to delay reapplying the filters.
Description

Removes the specified filter from this element. You can reapply other filters that may be left after this method is called, or you can delay if you are removing more than one filter.

See Also
findFilter.

DhDocument.replaceFilter

Syntax 1
public void replaceFilter( DhFilter filter1, DhFilter filter2 );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
Description

Replaces filters currently applied to the document. This method provides an easy way to swap filters. It automatically applies all the changes immediately.

Syntax 2
public void replaceFilter( DhFilter filter1, DhFilter filter2, boolean bApply );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
bApply
Set to true to apply visual changes now; set to false to delay making changes.
Description

Replaces filters currently applied to the document. This method provides an easy way to swap filters. You can specify whether to apply all the changes immediately or to delay making changes until later.

See Also
applyFilters

DhDocument.setDomain

Syntax
public void setDomain( String strDomain );
Parameters
strDomain
The domain to set.
Description

Sets the host domain for the page. Pages on different frames can have their domains set to the same host to allow communication between frames.

DhDocument.setFixed

Syntax 1
public synchronized void setFixed( boolean isFixed );
Parameters
isFixed
Set to true to enable x-y coordinate placement by default; set to false to use traditional HTML text flow layout.
Description

Determines whether the default placement of elements uses fixed x-y coordinate positioning or traditional HTML text flow layout positioning. Rather than use this method, it is much more useful to create DhSection objects and/or DhPanel objects to control the placement of elements.

See Also
isFixed

Syntax 2
public void setFixed();
Description

Sets the default placement of elements to fixed x-y coordinate positioning in contrast to traditional HTML text flow layout. Rather than use this method, it is much more useful to create DhSections and/or DhPanels to control the placement of elements.

See Also
isFixed

DhDocument.setGenerateTags

Syntax
public void setGenerateTags( boolean fGenerate );
Parameters
fGenerate
Set to true to generate <HEAD> and <TITLE> tags in a call to generateHTML(); otherwise, set to false.
Description

Determines whether HEAD and TITLE tags are generated by the generateHTML() method.

DhDocument.setTitle

Syntax
public void setTitle( String newTitle );
Parameters
newTitle
The text that goes into the caption of the host.
Description

Sets the title of the document. For a browser, the title appears in the caption of the browser window.


 DhDragDrop Class

DhDragDrop Class

This Package | All Packages

public class DhDragDrop

Topic under construction.

Constructors
Name | Description
DhDragDrop( DhElement element ) | Topic under construction.
DhDragDrop( DhElement element, boolean fEnableNow ) | Topic under construction.

Methods
Name | Description
addOnBeginDrag(DhEventHandler h) | Topic under construction.
addOnEndDrag(DhEventHandler h) | Topic under construction.
enable( boolean fOn ) | Topic under construction.
removeOnBeginDrag(DhEventHandler h) | Topic under construction.
removeOnEndDrag(DhEventHandler h) | Topic under construction.

Constructors

DhDragDrop.DhDragDrop

Syntax 1
public DhDragDrop( DhElement element );
Description

Topic under construction.

Syntax 2
public DhDragDrop( DhElement element, boolean fEnableNow );
Description

Topic under construction.

Methods

DhDragDrop.addOnBeginDrag

Syntax
final public void addOnBeginDrag( DhEventHandler h );
Description

Topic under construction.

DhDragDrop.addOnEndDrag

Syntax
final public void addOnEndDrag( DhEventHandler h );
Description

Topic under construction.

DhDragDrop.enable

Syntax
public synchronized void enable( boolean fOn );
Description

Topic under construction.

DhDragDrop.removeOnBeginDrag

Syntax
final public void removeOnBeginDrag( DhEventHandler h );
Description

Topic under construction.

DhDragDrop.removeOnEndDrag

Syntax
final public void removeOnEndDrag( DhEventHandler h );
Description

Topic under construction.


 DhEdit Class

DhEdit Class

This Package | All Packages

DhText
  |
  +--DhEdit
public class DhEdit
extends DhText

Represents all edit box functions in an HTML document. Edit boxes can be multiline, single line, or single line password styles. Password edit boxes behave like single line edit boxes, except their contents are masked by the asterisk (*) character.

Constructors
Name | Description
DhEdit() | Creates an edit box.
DhEdit( String strText ) | Creates an edit box.
DhEdit( String strText, boolean multiline ) | Creates an edit box.

Methods
Name | Description
addOnChange ( DhEventHandler h ) | Sets the handler for the onchange event.
addOnSelect ( DhEventHandler h ) | Sets the handler for the onselect event.
getCols() | Retrieves the width, in characters, of the edit box.
getEnabled() | Retrieves the enabled state of the edit box.
getMaxLength() | Retrieves the current maximum input length for the edit.
getMultiline() | Indicates if the edit control allows editing on more than one line or not.
getPassword() | Indicates whether the edit control is being used for password input and must conceal its value.
getReadOnly() | Retrieves the current read-only mode.
getRows() | Retrieves the current number of rows for a multiline edit box.
getSubmitName( ) | Retrieves the name of the edit box, which is used for HTTP form submissions.
getText( ) | Retrieves the current text for the edit.
getWordWrap() | Retrieves the current wrapping mode.
removeOnChange ( DhEventHandler h ) | Removes the handler for the onchange event.
removeOnSelect ( DhEventHandler h ) | Removes the handler for the onselect event.
setCols(int cols) | Sets the number of columns (characters) for the edit box width.
setEnabled( boolean f) | Sets the enabled state of the edit box.
setFocus() | Sets the input focus to this edit box
setMaxLength( int nMaxLength ) | Sets the current maximum input length of the edit control in characters.
setMultiline(boolean multiline) | Indicates if the edit control allows editing on more than one line or not.
setPassword(boolean value) | Specifies whether the edit control is being used for password input and must conceal its value.
setReadOnly( boolean fReadOnly ) | Sets the read-only mode for the edit control.
setRows(int rows) | Sets the number of rows in a multiline edit box.
setSubmitName( String strName ) | Sets the name of the edit box.
setText( String strText ) | Sets the current text display of the edit box.
setWordWrap(boolean wrap) | Sets the wrapping mode for a multiline edit box.

Constructors

DhEdit.DhEdit

Syntax 1
public DhEdit();
Description

Creates an edit box. This constructor creates a blank, single line DhEdit edit box.

Syntax 2
public DhEdit( String strText );
Parameters
strText
The initial text contents of DhEdit.
Description

Creates an edit box. This constructor creates a single line DhEdit edit box.

Syntax 3
public DhEdit( String strText, boolean multiline );
Parameters
strText
The initial text contents of DhEdit.
multiline
Set to true if the edit box has multiple lines, or false if it does not.
Description

Creates an edit box. This constructor creates a DhEdit edit box.

Methods

DhEdit.addOnChange

Syntax
final public void addOnChange ( DhEventHandler h );
Parameters
h
The event handler for this edit box event.
Description

Sets the handler for the onchange event. This event occurs when the user modifies the contents of the edit box, then presses the enter key or moves the focus to a different window or control.

DhEdit.addOnSelect

Syntax
final public void addOnSelect ( DhEventHandler h );
Parameters
h
The event handler for this edit box event.
Description

Sets the handler for the onselect event. This event occurs when the user sets or modifies the selected region of the text box.

DhEdit.getCols

Syntax
public synchronized int getCols();
Return Value

Returns the width in characters.

Description

Retrieves the width, in characters, of the edit box.

DhEdit.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns true if the box is enabled; returns false if it is not.

Description

Retrieves the enabled state of the edit box.

DhEdit.getMaxLength

Syntax
public int getMaxLength();
Return Value

Returns the maximum input length, in characters.

Description

Retrieves the current maximum input length for the edit. If this value is unset, it may be up to Integer.MAX_VALUE.

DhEdit.getMultiline

Syntax
public boolean getMultiline();
Return Value

Returns true if editing of more than one line is allowed; otherwise, returns false.

Description

Indicates if the edit control allows editing on more than one line or not. By default, only one line of editing is permitted and ENTER characters are ignored.

DhEdit.getPassword

Syntax
public boolean getPassword();
Description

Indicates whether the edit control is being used for password input and must conceal its value.

DhEdit.getReadOnly

Syntax
public boolean getReadOnly();
Return Value

Returns true if control is read-only; otherwise, returns false.

Description

Retrieves the current read-only mode.

DhEdit.getRows

Syntax
public synchronized int getRows();
Return Value

Returns number of rows.

Description

Retrieves the current number of rows for a multiline edit box. Always returns 1 if style is not multiline.

DhEdit.getSubmitName

Syntax
public String getSubmitName( );
Return Value

Returns the name of the edit box.

Description

Retrieves the name of the edit box, which is used for HTTP form submissions.

See Also
setSubmitName

DhEdit.getText

Syntax
public synchronized String getText( );
Return Value

Returns the currently displayed string in the edit.

Description

Retrieves the current text for the edit. For ES_PASSWORD style edit boxes, this is the actual string, not the mask.

DhEdit.getWordWrap

Syntax
public boolean getWordWrap();
Return Value

Returns true if wrapping is active, otherwise false.

Description

Retrieves the current wrapping mode.

DhEdit.removeOnChange

Syntax
final public void removeOnChange ( DhEventHandler h );
Parameters
h
The event handler for this edit box event.
Description

Removes the handler for the onchange event. This event occurs when the user modifies the contents of the edit box, then presses the enter key or moves the focus to a different window or control.

DhEdit.removeOnSelect

Syntax
final public void removeOnSelect ( DhEventHandler h );
Parameters
h
The event handler for this edit box event.
Description

Removes the handler for the onselect event. This event occurs when the user sets or modifies the selected region of the text box.

DhEdit.setCols

Syntax
public synchronized void setCols( int cols );
Parameters
cols
The width of the edit box in characters. This number must be greater than zero.
Description

Sets the number of columns (characters) for the edit box width.

DhEdit.setEnabled

Syntax
public void setEnabled( boolean f );
Parameters
f
Set to true to enable the edit box; set to false disabled it.
Description

Sets the enabled state of the edit box.

DhEdit.setFocus

Syntax
public void setFocus();
Description

Sets the input focus to this edit box

DhEdit.setMaxLength

Syntax
public void setMaxLength( int nMaxLength );
Parameters
nMaxLength
Maximum input length, in characters.
Description

Sets the current maximum input length of the edit control in characters. This value is independent of the current column width, and only applies to password or single line edut boxes. Strings set from code can exceed this length; only user input is restricted.

DhEdit.setMultiline

Syntax
public void setMultiline( boolean multiline );
Parameters
value
Set to true if editing of more than one line is allowed; otherwise, set to false.
Description

Indicates if the edit control allows editing on more than one line or not. By default, only one line of editing is permitted and ENTER characters are ignored.

DhEdit.setPassword

Syntax
public void setPassword( boolean value );
Parameters
value
Set to true if the control is used to enter passwords; otherwise, set to false.
Description

Specifies whether the edit control is being used for password input and must conceal its value. Password controls must be single line, so if this is set to true, then the Multiline property becomes false.

DhEdit.setReadOnly

Syntax
public void setReadOnly( boolean fReadOnly );
Parameters
fReadOnly
Set to true for read-only or false for read-write.
Description

Sets the read-only mode for the edit control.

DhEdit.setRows

Syntax
public void setRows( int rows );
Parameters
rows
the number of rows
Description

Sets the number of rows in a multiline edit box.

Exceptions

IllegalArgumentException Thrown if rows is less than or equal to 0

IllegalArgumentException Thrown if rows is greater than 1 and style is not multiline.

DhEdit.setSubmitName

Syntax
public void setSubmitName( String strName );
Parameters
strName
The name to assign the control. This should be unique on the form.
Description

Sets the name of the edit box. Useful when submitting edit box content through an HTML form.

DhEdit.setText

Syntax
public synchronized void setText( String strText );
Parameters
strText
the text to display.
Description

Sets the current text display of the edit box.

DhEdit.setWordWrap

Syntax
public void setWordWrap( boolean wrap );
Parameters
wrap
true for wrapping, false for no wrapping.
Description

Sets the wrapping mode for a multiline edit box.


 DhElement Class

DhElement Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
public class DhElement
extends DhStyleBase

Represents the super class for all user interface (UI) elements in this package. An instance of this class should be thought of as the Java representation of a given UI element in an HTML document. DhElement objects are never created directly. Instead, you instantiate a derivation of this class and then add the instance to the document (or a container destined for, or already on, the document). Alternatively, you can call the DhDocument.findElement method to locate and bind to an existing element, then cast the return value to the proper derivation.

Also see DhStyle, DhText, DhDocument, DhSection, and DhPanel.

Fields
Name | Description
OK_TO_CACHE_ATTRIBUTES | Setting this flag to false (default is true) forces all HTML tag attributes to be drawn from the client peer instead of a cached value.
OK_TO_EMIT_CODECLASS | Setting this flag to false (default is true) stops the default behavior of emitting the __CODECLASS attribute used exclusively by this package.

Methods
Name | Description
addOnClick ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnDoubleClick ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnKeyDown ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnKeyPress ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnKeyUp ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnMouseDown( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnMouseEnter( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnMouseLeave ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnMouseMove( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnMouseUp ( DhEventHandler h ) Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

addOnSetParent(DhEventHandler h) | Sets up the callback that is invoked when the parent is set on this element.
cloneSettings( DhElement eSrc ) | Topic under construction.
dataSource() | Retrieves the data source for this element.
generateHTML() | Retrieves a string that contains the representative HTML text for this element and all its child elements.
getAlign( ) | Returns the alignment of the element.
getDataField() | Retrieves the data field this element is to display.
getDataSource() | Returns the current data source as a DhDataSource object.
getDocument() | Retrieves the document object associated with this element.
getElementCount() | Topic under construction.
getElements() | Topic under construction.
getEvents() | Retrieves the event event for this element.
getHTMLGenerator() | Retrieves the current HTML generator for this element.
getID() | Returns the ID attribute of the HTML element underlying this class.
getLocation() | Topic under construction.
getModule() | Retrieves the module object associated with element.
getParent() | Retrieves the parent element which contains this element.
getPeer() | Retrieves the underlying HTML peer element for this class.
getSize() | Topic under construction.
getStyle() | Retrieves the DhStyle style object associated with this element.
getTagName() | Retrieves the string that contains the tag name that corresponds to this element given its current state (for example, "SPAN").
getTagNameID() | Returns the DhStringIDs string identifier that will be generated when the generateHTML method is called.
getToolTip() | Retrieves the string that represents the tooltip that appears when the user's mouse pointer is hovering over this element.
hasPeer() | Return the underlying HTML peer element for this class.
onStateChange( int stateChange ) | Implements a callback method for the stateChange event.
removeAttribute(String strAttr) removeOnClick
final public void removeOnClick ( DhEventHandler h );

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnClick ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnDoubleClick ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnKeyDown ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnKeyPress ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnKeyUp ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnMouseDown( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnMouseEnter( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnMouseLeave ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnMouseMove( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnMouseUp ( DhEventHandler h ) Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

removeOnSetParent(DhEventHandler h) | Sets the alignment of the element.
setAlign( int nAlign )
setAttribute(String strAttr, String value)
setAttribute(String strAttr, String value)
setAttributeInt(String strAttr, int value) | Sets the data field for this object to display.
setDataField( String strDataField ) | Sets the data source for this element.
setDataSource( DhDataSource ds ) | Sets the data source for this element.
setDataSource( DhElement dsParent ) | Sets the document that is associated with this element.
setDocument( DhDocument document ) | Sets the height of the element using one of the DhUnit constants to express the units of measurement.
setHeightUnit( int h, int unit ) | Sets the HTML generator to use for this element.
setHTMLGenerator( DhHTMLGenerator htmlGen ) | Sets the size of the element.
setSize(int w, int h) | Set the style object associated with this element.
setStyle(DhStyle style) | Sets the tooltip that appears when the user's mouse pointer is hovering over this element.
setToolTip(String string) | Sets the width of the element using one of the DhUnit constants to express the units of measurement.
setWidthUnit( int w, int unit )

Fields

DhElement.OK_TO_CACHE_ATTRIBUTES

Syntax
public static boolean OK_TO_CACHE_ATTRIBUTES;
Description
Setting this flag to false (default is true) forces all HTML tag attributes to be drawn from the client peer instead of a cached value.

DhElement.OK_TO_EMIT_CODECLASS

Syntax
public static boolean OK_TO_EMIT_CODECLASS;
Description
Setting this flag to false (default is true) stops the default behavior of emitting the __CODECLASS attribute used exclusively by this package.

Methods

DhElement.addOnClick

Syntax
final public void addOnClick ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnDoubleClick

Syntax
final public void addOnDoubleClick ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnKeyDown

Syntax
final public void addOnKeyDown ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnKeyPress

Syntax
final public void addOnKeyPress ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnKeyUp

Syntax
final public void addOnKeyUp ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnMouseDown

Syntax
final public void addOnMouseDown( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnMouseEnter

Syntax
final public void addOnMouseEnter( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnMouseLeave

Syntax
final public void addOnMouseLeave ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnMouseMove

Syntax
final public void addOnMouseMove( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnMouseUp

Syntax
final public void addOnMouseUp ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.addOnSetParent

Syntax
protected void addOnSetParent( DhEventHandler h );
Parameters
onSetParent
The DhEventHandler callback method to invoke when the parent is set on this element.
Description

Sets up the callback that is invoked when the parent is set on this element.

DhElement.cloneSettings

Syntax
public synchronized void cloneSettings( DhElement eSrc );
Description

Topic under construction.

DhElement.dataSource

Syntax
protected DhDataSource dataSource();
Return Value

Returns s null for DhElement.

Description

Retrieves the data source for this element.

See Also
wfc.html.DhObjectDataSource, DhAppletDataSource

DhElement.generateHTML

Syntax
public String generateHTML();
Return Value

Returns the HTML string that represents this element and all its children.

Description

Retrieves a string that contains the representative HTML text for this element and all its child elements.

DhElement.getAlign

Syntax
public int getAlign( );
Return Value

Returns the desired alignment, or returns -1 if alignment is uninitialized.

Description

Returns the alignment of the element. Specified as one of the DhAlignEnum constants.

DhElement.getDataField

Syntax
public String getDataField();
Return Value

Returns the current field name.

Description

Retrieves the data field this element is to display.

DhElement.getDataSource

Syntax
public DhDataSource getDataSource();
Return Value

Returns the associated DhDataSourceObject, or returns null if there is not one attached.

Description

Returns the current data source as a DhDataSource object. If there is no attached data source or another error occurs, null is returned.

DhElement.getDocument

Syntax
public synchronized DhDocument getDocument();
Return Value

Returns the DhDocument that this element has associated with it.

Description

Retrieves the document object associated with this element.

DhElement.getElementCount

Syntax
public int getElementCount();
Description

Topic under construction.

DhElement.getElements

Syntax
public DhElement[] getElements();
Description

Topic under construction.

DhElement.getEvents

Syntax
public synchronized DhEvents getEvents();
Return Value

Returns the event event for this element.

Description

Retrieves the event event for this element. Despite the fact that this method is public in this class, most derivations hide it.

DhElement.getHTMLGenerator

Syntax
public DhHTMLGenerator getHTMLGenerator();
Description

Retrieves the current HTML generator for this element.

See Also
setHTMLGenerator

DhElement.getID

Syntax
public synchronized String getID();
Return Value

Returns the string used for the ID attribute of the element.

Description

Returns the ID attribute of the HTML element underlying this class. This ID is one persisted with the generateHTML method.

Note Calling this method is not typically part of the usage of this package. The package automatically generates an ID for all DhElements even if this method isn't directly called.

DhElement.getLocation

Syntax
public Point getLocation();
Description

Topic under construction.

DhElement.getModule

Syntax
public DhModule getModule();
Return Value

Returns the DhModule that this element has associated with it.

Description

Retrieves the module object associated with element.

DhElement.getParent

Syntax
public synchronized DhElement getParent();
Return Value

Returns the parent element that this element has associated with it.

Description

Retrieves the parent element which contains this element.

See Also
wfc.html.DhDocument.add, wfc.html.DhPanel.add, wfc.html.DhSection.add

DhElement.getPeer

Syntax
public IUnknown getPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Retrieves the underlying HTML peer element for this class. This method may return null if the element or its parent was never added to a document. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLElement). This method always returns null if the code is running in a Web server environment.

Note that calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhElement.getSize

Syntax
public Point getSize();
Description

Topic under construction.

DhElement.getStyle

Syntax
public synchronized DhStyle getStyle();
Return Value

Returns the DhStyle style object associated with this element.

Description

Retrieves the DhStyle style object associated with this element.

See Also
wfc.html.DhStyle, setStyle

DhElement.getTagName

Syntax
public synchronized String getTagName();
Description

Retrieves the string that contains the tag name that corresponds to this element given its current state (for example, "SPAN").

Note that this value can change during the life of the instance. In many cases, it depends on specific attribute settings known only to the derivation of this class.

This method is not very useful except in special cases.

DhElement.getTagNameID

Syntax
protected int getTagNameID();
Return Value

Returns s (int) the DhStringIDs string identifier for the tag name of this element. (The base class returns -1, an invalid ID.)

Description

Returns the DhStringIDs string identifier that will be generated when the generateHTML method is called.

DhElement.getToolTip

Syntax
public String getToolTip();
Return Value

Returns the tooltip string.

Description

Retrieves the string that represents the tooltip that appears when the user's mouse pointer is hovering over this element.

See Also
setToolTip

DhElement.hasPeer

Syntax
public synchronized IUnknown hasPeer();
Return Value

Returns the element peer underlying the HTML peer for this class, assuming it is available.

Description

Return the underlying HTML peer element for this class. This method may return null even if the element or its parent was added to a document, but there hasn't been occasion to bind to its peer. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLElement). This method always returns null if the code is running in a Web server environment.

Calling getPeer() retrieve the peer element even if the element hasn't had a chance to bind to the document yet.

Note that calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhElement.onStateChange

Syntax
protected synchronized void onStateChange( int stateChange );
Parameters
stateChange
Topic under construction.
Description

Implements a callback method for the stateChange event. Derivations of this class that keep peers cached around must override this method and destroy that reference.

DhElement.removeAttribute

Syntax
public void removeAttribute( String strAttr );
Description

DhElement.removeOnClick

Syntax
final public void removeOnClick ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnDoubleClick

Syntax
final public void removeOnDoubleClick ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnKeyDown

Syntax
final public void removeOnKeyDown ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnKeyPress

Syntax
final public void removeOnKeyPress ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnKeyUp

Syntax
final public void removeOnKeyUp ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnMouseDown

Syntax
final public void removeOnMouseDown( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnMouseEnter

Syntax
final public void removeOnMouseEnter( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnMouseLeave

Syntax
final public void removeOnMouseLeave ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnMouseMove

Syntax
final public void removeOnMouseMove( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnMouseUp

Syntax
final public void removeOnMouseUp ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.removeOnSetParent

Syntax
protected void removeOnSetParent( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback.

Note that not all elements support all events exposed in DhElement.

DhElement.setAlign

Syntax
public void setAlign( int nAlign );
Parameters
nAlign
The desired alignment.
Description

Sets the alignment of the element. Specified as one of the DhAlignEnum constants.

DhElement.setAttribute

Syntax 1
public void setAttribute( String strAttr, String value );
Description

Syntax 2
public void setAttribute( String strAttr, String value );
Description

DhElement.setAttributeInt

Syntax
public void setAttributeInt( String strAttr, int value );
Description

DhElement.setDataField

Syntax
public void setDataField( String strDataField );
Parameters
strDataField
The name of a field in the available data set.
Description

Sets the data field for this object to display. This value must match the name of a returned column in the database queried by the current data source.

See Also
setDataSource

DhElement.setDataSource

Syntax 1
public void setDataSource( DhDataSource ds );
Parameters
A
DhDataSource
Description

Sets the data source for this element.

Syntax 2
public void setDataSource( DhElement dsParent );
Parameters
A
DhDataSource
Description

Sets the data source for this element.

DhElement.setDocument

Syntax
public synchronized void setDocument( DhDocument document );
Parameters
document
The DhDocument associated with this element.
Description

Sets the document that is associated with this element.

Care should be used when setting this value. Unexpected results in behavior can occur if done outside the confines of this package.

DhElement.setHeightUnit

Syntax
public synchronized void setHeightUnit( int h, int unit );
Parameters
h
The height value.
unit
One of DhUnit constants to express the units of measurement.
Description

Sets the height of the element using one of the DhUnit constants to express the units of measurement.

See Also
wfc.html.DhStyleBase.getBounds

DhElement.setHTMLGenerator

Syntax
public synchronized void setHTMLGenerator( DhHTMLGenerator htmlGen );
Description

Sets the HTML generator to use for this element. This allows you to override the library's default method of generating HTML syntax to represent an element.

See Also
getHTMLGenerator

DhElement.setSize

Syntax
public synchronized void setSize( int w, int h );
Parameters
width
The new width of the element.
height
The new height of the element.
Description

Sets the size of the element.

See Also
setWidthUnit, setHeightUnit

DhElement.setStyle

Syntax
public synchronized void setStyle( DhStyle style );
Parameters
style
The style object associated with this element.
Description

Set the style object associated with this element.

DhElement.setToolTip

Syntax
public void setToolTip( String string );
Parameters
string
The string to use for the tooltip.
Description

Sets the tooltip that appears when the user's mouse pointer is hovering over this element.

DhElement.setWidthUnit

Syntax
public synchronized void setWidthUnit( int w, int unit );
Parameters
w
The width values.
unit
One of DhUnitEnum constants to express the units of measurement.
Description

Sets the width of the element using one of the DhUnit constants to express the units of measurement.

See Also
wfc.html.DhStyleBase.getBounds


 DhElementExistsInDocumentException Class

DhElementExistsInDocumentException Class

This Package | All Packages

RuntimeException
  |
  +--DhElementExistsInDocumentException
public class DhElementExistsInDocumentException
extends RuntimeException

Signals that a given element has already been added to the document. Elements can only be added once.

Constructors
Name | Description
DhElementExistsInDocumentException() | Constructs an ElementNotFoundException with no detail message.
DhElementExistsInDocumentException(String s) | Constructs an ElementNotFoundException with a detail message.

Constructors

DhElementExistsInDocumentException.DhElementExistsInDocumentException

Syntax 1
public DhElementExistsInDocumentException();
Description

Constructs an ElementNotFoundException with no detail message.

Syntax 2
public DhElementExistsInDocumentException( String s );
Description

Constructs an ElementNotFoundException with a detail message.


 DhElementNotFoundException Class

DhElementNotFoundException Class

This Package | All Packages

RuntimeException
  |
  +--DhElementNotFoundException
public class DhElementNotFoundException
extends RuntimeException

Signals that a request for a named element failed, because an element with that name does not exist.

Constructors
Name | Description
DhElementNotFoundException() | Constructs a ElementNotFoundException with no detail message.
DhElementNotFoundException(String s) | Constructs a ElementNotFoundException with a detail message.

Constructors

DhElementNotFoundException.DhElementNotFoundException

Syntax 1
public DhElementNotFoundException();
Description

Constructs a ElementNotFoundException with no detail message.

Syntax 2
public DhElementNotFoundException( String s );
Description

Constructs a ElementNotFoundException with a detail message.


 DhEnumeration Class

DhEnumeration Class

This Package | All Packages

public class DhEnumeration
implements IEnumerator

Represents a collection of elements in the HTML document. You can either create a DhEnumeration object class directly (using new()) or call DhDocument.enumerate to get the collection.

Note As of this Beta release, there are only three types of collections: ELEMENTS, IMAGES, and HLINKS.

Many HTML tags do not map one-to-one to Java classes in this package. When enumerating through the return of next(), always check the result with an instanceof() call.

Fields
Name | Description
ELEMENTS | Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all elements on the page.
HLINKS | Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all link (A) elements on the page.
IMAGES | Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all Image (IMG) elements on the page.

Constructors
Name | Description
DhEnumeration( DhDocument document, int enumType ) | Creates a DhEnumeration object.

Methods
Name | Description
hasMoreItems() | Tests if this enumeration contains more elements.
next() | Returns the next element of this enumeration.
nextItem() | Returns the next element of this enumeration.
reset() | Resets the enumerator to the beginning.

Fields

DhEnumeration.ELEMENTS

Syntax
public static final int ELEMENTS;
Description
Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all elements on the page.

DhEnumeration.HLINKS

Syntax
public static final int HLINKS;
Description
Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all link (A) elements on the page.

DhEnumeration.IMAGES

Syntax
public static final int IMAGES;
Description
Used by either DhDocument.enumerate or the DhEnumeration constructor to indicate a collection of all Image (IMG) elements on the page.

Constructors

DhEnumeration.DhEnumeration

Syntax
public DhEnumeration( DhDocument document, int enumType );
Parameters
document
A reference to a DhDocument.
enumType
One of the legal types of collections (ELEMENTS, IMAGES, or HLINKS).
Description

Creates a DhEnumeration object. You can use this constructor or call DhDocument.enumerate to get the collection.

Methods

DhEnumeration.hasMoreItems

Syntax
public synchronized boolean hasMoreItems();
Return Value

Returns true if this enumeration contains more elements; otherwise, returns false.

Description

Tests if this enumeration contains more elements.

DhEnumeration.next

Syntax
public synchronized DhElement next();
Return Value

Returns the next element of this enumeration, or returns null if one does not exist.

Description

Returns the next element of this enumeration. This override of IEnumerator.next() returns a DhElement object so there is no need to cast the result to a DhElement object. The result can be further cast (for example, to DhImage) depending on the type of enumeration this is.

Many HTML tags do not map one-to-one into Java classes in this package. When enumerating through the return of next(), always check the result with an instanceof() call.

DhEnumeration.nextItem

Syntax
public Object nextItem();
Return Value

Returns the next element of this enumeration.

Description

Returns the next element of this enumeration.

Exceptions

NoSuchElementException thrown if no more elements exist.

See Also
next

DhEnumeration.reset

Syntax
public void reset();
Description

Resets the enumerator to the beginning.


 DhEvent Class

DhEvent Class

This Package | All Packages

public class DhEvent

Carries event information from source to sink. This object is the only parameter on any HTML event callback. The information relayed in this class is rich and deep. Probably the best way to understand all the different information conveyed here is to experiment.

Start with the following code example:

   import wfc.html.*;
   import wfc.html.event.*;

   public class DumpEvent extends DhModule
   {
       DhDocument  document;
       DhText		text;

       public void documentLoad(Object sender, DhEvent e)
       {
           document = getDocument();
           text = new DhText();
           document.add(text,DhDocument.INSERT_BEGINNING);
           document.addOnMouseMove( new DhEventHandler(this,"onMouseMove") );
       }

       public void onMouseMove( Object sender, DhEvent event )
       {
           text.setText( event.toString() );
       }
   }

Compile that code and put the result onto your CLASSPATH. Now put the following portion of HTML code onto any page:

<object classid="java:DumpEvent"></object>

Now point Internet Explorer (4.0 or later) at that page. As you move the mouse around the page and over elements, hold down various keys (ALT, CTRL, and so on). You will see the results of all the different types of keyboard and mouse position information available to you.

You should also note the effects of the event bubbling. This is an effect caused by the fact that all event sources in HTML trigger the same events all the way up their containment hierarchy. (This is also known as bubbling, broadcasting, or multicasting.) Because the mouse move events are sinked at the document (the top of the containment hierarchy), we see all mouse move events of all elements on the screen.

Fields
Name | Description
EVT_LEFTBUTTON | Indicates that the left mouse button has been pressed.
EVT_MIDDLEBUTTON | Indicates that the middle mouse button has been pressed.
EVT_NOBUTTON | Indicates that no mouse button has been pressed.
EVT_RIGHTBUTTON | Indicates that the right mouse button has been pressed.

Methods
Name | Description
cancelBubble() | All event sources in HTML trigger the same events all the way up their containment hierarchy Calling this method tells the HTML document to stop event bubbling.
getChar() | Tests for the presence of any key and returns that keypress.
getClientPoint() | Retrieves the current position of the mouse relative to the parent client area.
getDocument() | Retrieves the document object on which this event was triggered.
getMouseButton() | Tests for mouse button events.
getOffsetPoint() | Retrieves the current position of the mouse relative to the element's client area.
getPeer() | Retrieves the underlying HTML peer element for this class.
getPoint() | Retrieves the current position of the mouse relative to the document client.
getReturnValue() | Determines if return data has been set.
getScreenPoint() | Retrieves the current position of the mouse relative to the desktop.
getSource() | Retrieves the original source of the event.
isAltKey() | Tests for the ALT key.
isCtrlKey() | Tests for the CTRL key.
isShiftKey() | Tests for the SHIFT key.
setChar( int c ) | Topic under construction.
setReturnValue(boolean b) | Sets return data.
setReturnValue(String s) | Sets return data.
setReturnValue(int i) | Sets return data.
setReturnValue( Variant v) | Sets return data.
toString() | Converts this event object to a string.

Fields

DhEvent.EVT_LEFTBUTTON

Syntax
public static final int EVT_LEFTBUTTON;
Description
Indicates that the left mouse button has been pressed.

DhEvent.EVT_MIDDLEBUTTON

Syntax
public static final int EVT_MIDDLEBUTTON;
Description
Indicates that the middle mouse button has been pressed.

DhEvent.EVT_NOBUTTON

Syntax
public static final int EVT_NOBUTTON;
Description
Indicates that no mouse button has been pressed.

DhEvent.EVT_RIGHTBUTTON

Syntax
public static final int EVT_RIGHTBUTTON;
Description
Indicates that the right mouse button has been pressed.

Methods

DhEvent.cancelBubble

Syntax
final public synchronized void cancelBubble();
Description

All event sources in HTML trigger the same events all the way up their containment hierarchy Calling this method tells the HTML document to stop event bubbling.

DhEvent.getChar

Syntax
final public synchronized int getChar();
Return Value

Returns the key code of the currently pressed key (or 0 if no key is pressed).

Description

Tests for the presence of any key and returns that keypress.

DhEvent.getClientPoint

Syntax
final public synchronized Point getClientPoint();
Return Value

Returns the current position of the mouse relative to the parent client area.

Description

Retrieves the current position of the mouse relative to the parent client area.

See Also
toString

DhEvent.getDocument

Syntax
final public synchronized DhDocument getDocument();
Return Value

Returns the document object this event came from.

Description

Retrieves the document object on which this event was triggered.

DhEvent.getMouseButton

Syntax
final public synchronized int getMouseButton();
Return Value

Returns one of the mouse buttons constants (EVT_NOBUTTON, EVT_LEFTBUTTON, EVT_RIGHTBUTTON, or EVT_MIDDLEBUTTON).

Description

Tests for mouse button events.

DhEvent.getOffsetPoint

Syntax
final public synchronized Point getOffsetPoint();
Return Value

Returns the current position of the mouse.

Description

Retrieves the current position of the mouse relative to the element's client area.

See Also
toString

DhEvent.getPeer

Syntax
final public IUnknown getPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Retrieves the underlying HTML peer element for this class. This method may return null if the event is not bound to the document. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLEventObj). This method always returns null if the code is running in a Web server environment.

Note Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhEvent.getPoint

Syntax
final public synchronized Point getPoint();
Return Value

Returns the current position of the mouse.

Description

Retrieves the current position of the mouse relative to the document client.

See Also
toString

DhEvent.getReturnValue

Syntax
final public synchronized Variant getReturnValue();
Description

Determines if return data has been set. Certain kinds of events require a response value. Use this method to see if another handler has set the return data to the event source.

DhEvent.getScreenPoint

Syntax
final public synchronized Point getScreenPoint();
Return Value

Returns the current position of the mouse.

Description

Retrieves the current position of the mouse relative to the desktop.

See Also
toString

DhEvent.getSource

Syntax
final public synchronized DhElement getSource();
Return Value

Returns the element that first triggered this event.

Description

Retrieves the original source of the event. This may be the object you actually hooked the event on, or it may one of its children (because all events bubble up the containment hierarchy automatically).

DhEvent.isAltKey

Syntax
final public synchronized boolean isAltKey();
Return Value

Returns true if the ALT key is pressed.

Description

Tests for the ALT key.

DhEvent.isCtrlKey

Syntax
final public synchronized boolean isCtrlKey();
Return Value

Returns true if the CTRL key is pressed.

Description

Tests for the CTRL key.

DhEvent.isShiftKey

Syntax
final public synchronized boolean isShiftKey();
Return Value

Returns true if the SHIFT key is pressed.

Description

Tests for the SHIFT key.

DhEvent.setChar

Syntax
final public synchronized void setChar( int c );
Description

Topic under construction.

DhEvent.setReturnValue

Syntax 1
final public void setReturnValue( boolean b );
Parameters
b
The boolean value to return.
Description

Sets return data. Certain kinds of events require a response value. Use this method to return data to the event source.

Syntax 2
final public void setReturnValue( String s );
Parameters
s
The string value to return.
Description

Sets return data. Certain kinds of events require a response value. Use this method to return data to the event source.

Syntax 3
final public void setReturnValue( int i );
Parameters
i
The integer value to return.
Description

Sets return data. Certain kinds of events require a response value. Use this method to return data to the event source.

Syntax 4
final public synchronized void setReturnValue( Variant v );
Parameters
v
The variant value to return.
Description

Sets return data. Certain kinds of events require a response value. Use this method to return data to the event source.

DhEvent.toString

Syntax
public synchronized String toString();
Description

Converts this event object to a string. Use this when performing diagnostics on your code.


 DhEventHandler Class

DhEventHandler Class

This Package | All Packages

public multicast delegate void DhEventHandler(Object sender, DhEvent event);

Represents an event callback object. You create this when you need to sink an event off an HTML element. The following example code calls DhElement.addOnClick when a button is clicked:

     public void documentLoad(Object sender, DhEvent e)
     {
        DhButton b1 = new DhButton();

        b1.setText("Say hello");

        b1.addOnClick( new DhEventHandler( this.myHandler) );

        getDocument().add(b1);

      }

      public void myHandler( Object sender, DhEvent e )
      {
          // event handler code...
      }

The method signature that you use as your sink must have a void return type and two arguments, of type Object and DhEvent. The Object parameter is the object sending the event; in the example above, it would be the DhButton. The DhEvent parameter is an object which can be queried for further information about the event.


 DhFilter Class

DhFilter Class

This Package | All Packages

public class DhFilter
implements DhStringIDs

Derives photographic filters and transition effects from this superclass. They can be applied to certain kinds of objects (for example, DhImage, DhPanel, DhSection and DhStyle). Although this package does not provide filters directly, there are many samples that demonstrate how to derive and apply filters and transitions of various types.


 DhHorizontalRule Class

DhHorizontalRule Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhHorizontalRule
public class DhHorizontalRule
extends DhElement

Represents an HTML horizontal rule (<HR>) element, which creates a horizontal divider bar on the page.

Constructors
Name | Description
DhHorizontalRule() | Creates a DhHorizontalRule object (a horizonal rule element).

Constructors

DhHorizontalRule.DhHorizontalRule

Syntax
public DhHorizontalRule();
Description

Creates a DhHorizontalRule object (a horizonal rule element).


 DhHotSpot Class

DhHotSpot Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhHotSpot
public class DhHotSpot
extends DhElement

Represents a hotspot in an image map. A hotspot is an area within the map that a user can click to jump to a URL. DhHotSpot objects are to be added to DhImageMap objects.

Fields
Name | Description
SHAPE_CIRCLE | The hotspot is of circular shape.
SHAPE_POLYGON | The hotspot is of polygon shape.
SHAPE_RECTANGLE | The hotspot is of rectangluar shape.

Constructors
Name | Description
DhHotSpot() | Creates a rectangle of 0 height and 0 width.
DhHotSpot( int nShape, String strCoords, String strUrl ) | One-step constructor.
DhHotSpot( int nShape, String strCoords, DhHyperlink hl ) | One-step constructor.
DhHotSpot( Rectangle r ) | Topic under construction.
DhHotSpot( Polygon p ) | Topic under construction.

Methods
Name | Description
getAltText() | Retreives the current alternate text string that is displayed if the browser cannot display the image.
getCoords() | Retreives the current coordinate string.
getCoordsIntArray() | Retrieves a integer array representing the current coordinate string.
getShape() | Returns the current shape constant.
getTargetWindow() | Retrieves the target window for this hotspot.
getURL() | Retrieves the URL to navigate to if the user selects this DhHotSpot.
setAltText( String strAltText ) | Sets the alternate text for the hotspot if the browser cannot display the image.
setCoords( int[] nCoordArray ) | Sets the coordiante string for this DhHotSpot using an array of integers.
setCoords( String strCoords ) | Sets the current coordinate string.
setCoords( Polygon p ) | Topic under construction.
setFromHyperlink( DhHyperlink hl ) | Sets the URL and target window of this DhHotSpot equal to those set in the DhHyperlink specified.
setShape( int nShape ) | Sets the shape of this DhHotSpot.
setTargetWindow( String strTargetWnd ) | Sets the target window for this hotspot.
setURL( String strUrl ) | Sets the URL for this DhHotSpot to navigate to.

Fields

DhHotSpot.SHAPE_CIRCLE

Syntax
public static final int SHAPE_CIRCLE;
Description
The hotspot is of circular shape. Coordinates are specified as "center x, center y, radius"

Example: "12, 19, 7"

DhHotSpot.SHAPE_POLYGON

Syntax
public static final int SHAPE_POLYGON;
Description
The hotspot is of polygon shape. Coordinates are specified as three or more coordinate pairs.

Example: "10,10,15,15,5,15" creates a triangle

DhHotSpot.SHAPE_RECTANGLE

Syntax
public static final int SHAPE_RECTANGLE;
Description
The hotspot is of rectangluar shape. Coordinates are specified as "top, left, width, height"

Example: "5,5,10,20"

Constructors

DhHotSpot.DhHotSpot

Syntax 1
public DhHotSpot();
Description

Creates a rectangle of 0 height and 0 width. This is the default.

Syntax 2
public DhHotSpot( int nShape, String strCoords, String strUrl );
Parameters
nShape
The shape of the hotspot.
strCoords
A coordinate string appropriate to the shape.
strUrl
The URL to navigate to when the hotpot is clicked.
Description

One-step constructor.

See Also
SHAPE_RECTANGLE, SHAPE_POLYGON, SHAPE_CIRCLE

Syntax 3
public DhHotSpot( int nShape, String strCoords, DhHyperlink hl );
Parameters
nShape
The shape of the hotspot.
strCoords
A coordinate string appropriate to the shape.
hl
A DhHyperlink from which to extract a URL and target window.
Description

One-step constructor.

See Also
SHAPE_RECTANGLE, SHAPE_POLYGON, SHAPE_CIRCLE

Syntax 4
public DhHotSpot( Rectangle r );
Description

Topic under construction.

Syntax 5
public DhHotSpot( Polygon p );
Description

Topic under construction.

Methods

DhHotSpot.getAltText

Syntax
public String getAltText();
Description

Retreives the current alternate text string that is displayed if the browser cannot display the image.

DhHotSpot.getCoords

Syntax
public String getCoords();
Return Value

Returns the string of the current coordinates.

Description

Retreives the current coordinate string.

DhHotSpot.getCoordsIntArray

Syntax
public int[] getCoordsIntArray();
Return Value

Returns an array of integers.

Description

Retrieves a integer array representing the current coordinate string.

DhHotSpot.getShape

Syntax
public int getShape();
Return Value

Returns The shape.

Description

Returns the current shape constant.

See Also
SHAPE_RECTANGLE, SHAPE_POLYGON, SHAPE_CIRCLE

DhHotSpot.getTargetWindow

Syntax
public String getTargetWindow();
Return Value

Returns the target window name.

Description

Retrieves the target window for this hotspot.

DhHotSpot.getURL

Syntax
public String getURL();
Return Value

Returns the current URL.

Description

Retrieves the URL to navigate to if the user selects this DhHotSpot.

DhHotSpot.setAltText

Syntax
public void setAltText( String strAltText );
Parameters
strAltText
The new alt text string.
Description

Sets the alternate text for the hotspot if the browser cannot display the image.

DhHotSpot.setCoords

Syntax 1
public void setCoords( int[] nCoordArray );
Parameters
nCoordArray
The array of coordinates.
Description

Sets the coordiante string for this DhHotSpot using an array of integers.

Exceptions

RuntimeException thrown if the coordinates do not match the current shape type.

Syntax 2
public void setCoords( String strCoords );
Parameters
strCoords
A string of coordinates appropriate for this shape type.
Description

Sets the current coordinate string.

Exceptions

RuntimeException thrown if the coordinates do not match the current shape type.

Syntax 3
public void setCoords( Polygon p );
Description

Topic under construction.

DhHotSpot.setFromHyperlink

Syntax
public void setFromHyperlink( DhHyperlink hl );
Parameters
hl
The DhHyperlink with the settings to copy.
Description

Sets the URL and target window of this DhHotSpot equal to those set in the DhHyperlink specified.

DhHotSpot.setShape

Syntax
public void setShape( int nShape );
Parameters
nShape
The new shape constant.
Description

Sets the shape of this DhHotSpot.

See Also
SHAPE_RECTANGLE, SHAPE_POLYGON, SHAPE_CIRCLE

DhHotSpot.setTargetWindow

Syntax
public void setTargetWindow( String strTargetWnd );
Parameters
strTargetWnd
The name of the new target window.
Description

Sets the target window for this hotspot.

DhHotSpot.setURL

Syntax
public void setURL( String strUrl );
Description

Sets the URL for this DhHotSpot to navigate to.


 DhHTMLGenerator Class

DhHTMLGenerator Class

This Package | All Packages

public class DhHTMLGenerator

Represents a base class for HTML generation. Override this class to create alternate HTML generations from the package. Call DhElement.setHTMLGenerator with an instance of your override to enable. On each tag, style, and attribute, the appropriate function is called, and you can manipulate the element in any way you choose.

Fields
Name | Description
UNKNOWN_KEY | This value is returned by getNameKey if the name is not registered.

Methods
Name | Description
addAttrString( String strAttr, String strValue ) | Adds an attribute inside the current tag's less than (<) and greater than (>) brackets.
addEnclosingTag( String strTag, String strAttrs, boolean fClose ) | Adds an enclosing tag around the current tag.
addInnerTag( String strTag, String strAttrs, boolean fClose ) | Adds an inner tag inside the current tag, but encloses its contents.
addStyleString( String strStyle, String strValue ) | Adds an attribute inside the current tag's "STYLE=" attribute.
generateHTML( DhElement e ) | Generates browser-targeted HTML for the specified DhElement.
getAttributeValue( String strAttrName ) | Retrieves the value of a specified attribute.
getContent() | Retrieves the current content string.
getNameKey( String strName ) | Returns the integer key associated with the given name.
getStyleValue( String strStyleName ) | Retrieves the value of a specified style.
getSupportsCSS() | Retrieves target's ability to support cascading style sheets.
getSupportsOM() | Retrieves the target's ability to support the Document Object Model.
getTagName() | Retreives the tag name for the current generation.
onAttrGenerate( String strName, String strValue ) | Called for each attribute[,value] pair.
onAttrGenerate( int key, String strName, String strValue ) | Topic under construction.
onStyleGenerate( int key, String strName, String strValue ) | Called for each style-attribute[,value] pair.
onStyleGenerate( String strName, String strValue ) | Topic under construction.
onTagGenerate( int key, String strTagName ) | Called with the default name for the current tag.
onTagGenerate( String strTagName ) | Topic under construction.
registerName( String strName, int key ) | Use this function to associate an integer value with a style or attribute name or tag.
setContent( String strNewContent ) | Replaces the current content, destroying any existing content.
setFormatItems( char cAttrAssign, char cAttrSeparator, char cAttrQuote, char cStyleAssign, char cStyleSeparator, char cStyleQuote ) | Sets the delimeter items.
setSupportsCSS( boolean supportsCSS ) | Specifies whether the target browser supports style sheets.
setSupportsOM( boolean supportsOM ) | Specifies whether the target browser supports an object model.
setTagName( String strNewName ) | Replaces the current tag name with the new value.

Fields

DhHTMLGenerator.UNKNOWN_KEY

Syntax
public static final int UNKNOWN_KEY;
Description
This value is returned by getNameKey if the name is not registered.

Methods

DhHTMLGenerator.addAttrString

Syntax
protected final synchronized void addAttrString( String strAttr, String strValue );
Parameters
strAttr
The name of the attribute to add.
strValue
The string value of the new attribute.
Description

Adds an attribute inside the current tag's less than (<) and greater than (>) brackets.

DhHTMLGenerator.addEnclosingTag

Syntax
protected synchronized final void addEnclosingTag( String strTag, String strAttrs, boolean fClose );
Parameters
strTag
The new enclosing tag name.
strAttrs
The new enclosing tag's attribute string or strings.
fClose
Set to true to additionally add the closing tag for this tag.
Description

Adds an enclosing tag around the current tag. This tag also encloses any existing enclosing tags.

DhHTMLGenerator.addInnerTag

Syntax
protected synchronized final void addInnerTag( String strTag, String strAttrs, boolean fClose );
Parameters
strTag
The new inner tag name.
strAttrs
The new inner tag's attribute string(s).
fClose
true
Description

Adds an inner tag inside the current tag, but encloses its contents. This tag appears between the contents and any existing inner tags.

DhHTMLGenerator.addStyleString

Syntax
protected final synchronized void addStyleString( String strStyle, String strValue );
Parameters
strAttr
The name of the style to add.
strValue
The String value of the new style.
Description

Adds an attribute inside the current tag's "STYLE=" attribute. These styles are emitted only if supportsCSS is true.

See Also
getSupportsCSS, setSupportsCSS

DhHTMLGenerator.generateHTML

Syntax
public synchronized StringBuffer generateHTML( DhElement e );
Parameters
e
The DhElement to generate code for based on this DhHTMLGenerator.
Return Value

Returns a StringBuffer with the generated HTML.

Description

Generates browser-targeted HTML for the specified DhElement.

DhHTMLGenerator.getAttributeValue

Syntax
protected final String getAttributeValue( String strAttrName );
Parameters
strAttrName
The name of the attribute.
Return Value

Returns s the value of the attribute, or returns null if it is not present.

Description

Retrieves the value of a specified attribute.

DhHTMLGenerator.getContent

Syntax
protected final String getContent();
Return Value

Returns the current content string.

Description

Retrieves the current content string.

DhHTMLGenerator.getNameKey

Syntax
protected int getNameKey( String strName );
Parameters
strName
The name of the tag, attribute, or style to retrieve a key for.
Return Value

Returns the key for the name, or returns UNKNOWN_KEY if it is not present.

Description

Returns the integer key associated with the given name. This function is not case sensitive.

See Also
registerName, UNKNOWN_KEY

DhHTMLGenerator.getStyleValue

Syntax
protected final String getStyleValue( String strStyleName );
Parameters
strStyleName
The name of the style.
Return Value

Returns s the value of the style, or returns null if it is not present.

Description

Retrieves the value of a specified style.

DhHTMLGenerator.getSupportsCSS

Syntax
public final boolean getSupportsCSS();
Return Value

Returns true if cascading style sheets are supported.

Description

Retrieves target's ability to support cascading style sheets.

DhHTMLGenerator.getSupportsOM

Syntax
public final boolean getSupportsOM();
Return Value

Returns true if the Document Object Model is supported (currently Microsoft Internet Explorer version 4.0 or later only)

Description

Retrieves the target's ability to support the Document Object Model.

DhHTMLGenerator.getTagName

Syntax
protected final String getTagName();
Return Value

Returns the current tag name string.

Description

Retreives the tag name for the current generation.

DhHTMLGenerator.onAttrGenerate

Syntax 1
public boolean onAttrGenerate( String strName, String strValue );
Parameters
strName
The default name of the attribute.
strValue
The default value for the attribute.
Return Value

Returns true to generate the default tag, or returns false to skip it.

Description

Called for each attribute[,value] pair. You can perform any desired additions or manipulations for the specified attribute. The following is an example of moving WIDTH attribute into style text:

if ( strName.equalsIgnoreCase( "WIDTH" ) ){
  addStyleString( "width", strValue );
  return false;
}

See Also
addEnclosingTag, addInnerTag, addStyleString, addAttrString

Syntax 2
public boolean onAttrGenerate( int key, String strName, String strValue );
Description

Topic under construction.

DhHTMLGenerator.onStyleGenerate

Syntax 1
public boolean onStyleGenerate( int key, String strName, String strValue );
Parameters
key
The key for this style, if registered; otherwise, -1.
strName
The default name of the attribute.
strValue
The default value for the attribute.
Return Value

Returns true to generate the default tag, or returns false to skip it.

Description

Called for each style-attribute[,value] pair. You can perform any desired additions or manipulations for the specified style.

The following is an example of non-CSS-compatible code for font color:

if ( strName.equalsIgnoreCase( "color" ) ){
  addEnclosingTag( "FONT", "COLOR=" + strValue );
  return false;
}

See Also
addEnclosingTag, addInnerTag, addStyleString, addAttrString

Syntax 2
public boolean onStyleGenerate( String strName, String strValue );
Description

Topic under construction.

DhHTMLGenerator.onTagGenerate

Syntax 1
public boolean onTagGenerate( int key, String strTagName );
Parameters
key
The key for this tag, if registered; otherwise, -1.
strTagName
The default name for the current tag.
Return Value

Returns true to use the default tag.

Description

Called with the default name for the current tag. You can perform any desired operations within your override.

The following is an example of replacing <STRONG> with <BOLD>

if ( strTagName.equalsIgnoreCase( "STRONG" ) ){
  setTagName( "BOLD" );
  return false;
}

See Also
setTagName, getTagName

Syntax 2
public boolean onTagGenerate( String strTagName );
Description

Topic under construction.

DhHTMLGenerator.registerName

Syntax
protected boolean registerName( String strName, int key );
Parameters
strName
The tag, attribute name, or style name.
key
The key you want to associate with that value. It cannot be -1.
Return Value

Returns true if the name was successfully registered, or returns false if -1 is used or the key is already assigned to another name.

Description

Use this function to associate an integer value with a style or attribute name or tag. If registered, you will receive this value with the name in calls to onTagGenerate, onAttrGenerate, and onStyleGenerate. Registering a key allows you to avoid string comparison in your handler functions.

Note: key cannot be -1;

Example:

public class MyHTMLGenerator{
        public final static TAG_BR = 0;
     public final static TAG_DIV = 1;

        public MyHTMLGenerator(){
            registerName( "BR", TAG_BR );
            registerName( "DIV", TAG_DIV );
        }

        // ...
        public boolean onTagGenerate( int key, String strTagName ){
            switch ( key ){
                case TAG_BR:
                case TAG_DIV:
                    setTagName( "P" );
                    return false;
                break;
            }
            return true;
        }

}

DhHTMLGenerator.setContent

Syntax
protected final synchronized void setContent( String strNewContent );
Parameters
strNewContent
The new content string.
Description

Replaces the current content, destroying any existing content.

DhHTMLGenerator.setFormatItems

Syntax
public final synchronized void setFormatItems( char cAttrAssign, char cAttrSeparator, char cAttrQuote, char cStyleAssign, char cStyleSeparator, char cStyleQuote );
Parameters
cAttrAssign
Assignment character for attributes (default is '=').
cAttrSeparator
Separator character between attributes (default is ' ').
cAttrQuote
Delimiter to place around attribute values (default is '"').
cStyleAssign
Assignment character for styles (default is ':').
cStyleSeparator
Separator character between styles (default is ';').
cStyleQuote
Delimiter to place around style values (default is "'").
Description

Sets the delimeter items.

DhHTMLGenerator.setSupportsCSS

Syntax
public synchronized final void setSupportsCSS( boolean supportsCSS );
Parameters
supportsCSS
true
Description

Specifies whether the target browser supports style sheets. The default is false.

DhHTMLGenerator.setSupportsOM

Syntax
public synchronized final void setSupportsOM( boolean supportsOM );
Parameters
supportsOM
true
Description

Specifies whether the target browser supports an object model. The default is false.

DhHTMLGenerator.setTagName

Syntax
protected final synchronized void setTagName( String strNewName );
Parameters
strNewName
The replacement tag name, which can be null.
Description

Replaces the current tag name with the new value.


 DhHyperlink Class

DhHyperlink Class

This Package | All Packages

DhSection
  |
  +--DhHyperlink
public class DhHyperlink
extends DhSection

Creates a jump in the document to another place in the current document or to a different document.

Constructors
Name | Description
DhHyperlink() | Creates default hyperlink object.
DhHyperlink(String url, String text) | Creates a "classic" hyperlink that navigates the user to the document the url parameter points to.

Methods
Name | Description
getEnabled() | Retrieves the enabled state of the hyperlink.
getJumpPoint() | Returns the local target of the jump.
getStockTargetWindow() | Returns the window id where the browser will put the document.
getTargetWindow() | Retrieves the name of the window where the browser will put the document.
getText() | Retrieves the hyperlink text.
getURL() | Retrieves the target URL for the hyperlink.
setEnabled( boolean f) | Sets the enabled state of the hyperlink.
setJumpPoint( DhElement target ) | Sets the destination of this hyperlink to be some element on this page.
setStockTargetWindow( int targetID ) | Tells the browser which window to put the document into.
setTargetWindow(String winName) | Tells the browser which window to put the document into.
setText( String text ) | Sets the text the user sees in the hyperlink.
setURL(String url) | Sets the pointer to the document.

Constructors

DhHyperlink.DhHyperlink

Syntax 1
public DhHyperlink();
Description

Creates default hyperlink object.

See Also
setURL, setJumpPoint, setText

Syntax 2
public DhHyperlink( String url, String text );
Parameters
url
The document to link to.
text
The text that the user sees as the hyperlink.
Description

Creates a "classic" hyperlink that navigates the user to the document the url parameter points to.

Methods

DhHyperlink.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns true if the hyperlink is enabled; otherwise, returns false .

Description

Retrieves the enabled state of the hyperlink.

DhHyperlink.getJumpPoint

Syntax
public synchronized DhElement getJumpPoint();
Description

Returns the local target of the jump.

See Also
setJumpPoint

DhHyperlink.getStockTargetWindow

Syntax
public int getStockTargetWindow();
Return Value

Returns one of the stock window IDs in LinkTargetEnum.

Description

Returns the window id where the browser will put the document.

See Also
getTargetWindow

DhHyperlink.getTargetWindow

Syntax
public String getTargetWindow();
Parameters
winName
The name of a window in a frameset.
Description

Retrieves the name of the window where the browser will put the document.

See Also
setStockTargetWindow

DhHyperlink.getText

Syntax
public synchronized String getText();
Return Value

Returns the text the user sees in the hyperlink.

Description

Retrieves the hyperlink text.

DhHyperlink.getURL

Syntax
public String getURL();
Return Value

Returns the current URL where users would be sent if they clicked the hyperlink.

Description

Retrieves the target URL for the hyperlink.

DhHyperlink.setEnabled

Syntax
public void setEnabled( boolean f );
Parameters
f
Set to true to enable the hyperlink; set to false disabled it.
Description

Sets the enabled state of the hyperlink.

DhHyperlink.setJumpPoint

Syntax
public synchronized void setJumpPoint( DhElement target );
Parameters
target
The element you want users to jump to when they click this hyperlink.
Description

Sets the destination of this hyperlink to be some element on this page.

DhHyperlink.setStockTargetWindow

Syntax
public void setStockTargetWindow( int targetID );
Parameters
targetID
One of the stock window IDs in LinkTargetEnum.
Description

Tells the browser which window to put the document into.

See Also
setTargetWindow

DhHyperlink.setTargetWindow

Syntax
public void setTargetWindow( String winName );
Parameters
winName
The name of a window in a frameset.
Description

Tells the browser which window to put the document into.

See Also
setStockTargetWindow

DhHyperlink.setText

Syntax
public synchronized void setText( String text );
Parameters
text
The string displayed to the user.
Description

Sets the text the user sees in the hyperlink.

DhHyperlink.setURL

Syntax
public void setURL( String url );
Parameters
url
Sets the pointer to the document.
Description

Sets the pointer to the document.


 DhImage Class

DhImage Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhImage
public class DhImage
extends DhElement
implements DhIFilterableObject

Displays a bitmap file in the document. To create a dhImage object on your page, construct an object using the URL of the image (which can be relative to the HTML document).

Constructors
Name | Description
DhImage(String url) | Creates a DhImage obect.

Methods
Name | Description
addFilter(DhFilter filter) | Adds a filter to this element and applies it immediately.
addFilter(DhFilter filter, boolean bApply) | Adds a filter to this element.
addFilter(DhFilter filter, boolean bApply, boolean bFlush) | Adds a filter to this element.
addOnReadyStateChange ( DhEventHandler h ) | Topic under construction.
addTransition(DhFilter trans) | Adds a transition effect to this element.
applyFilters() | Applies filters that were previously deferred.
findFilter(Class filterClass) | Retrieves the current filter with the specified filter class.
getImageMap() | Retrieves the DhImageMap object associated with this image.
getImageMapName() | Retrieves the name of the image map associated with this image.
getLoadComplete() | Determines if the image has been fully loaded.
getReadyState() | Returns the current state of the image object.
getURL() | Retrieves the current URL that refers to the location of the bitmap file.
removeAllFilters() | Removes all filters from this element.
removeAllFilters(boolean bApply) | Removes all filters from this element.
removeFilter(DhFilter filter) | Removes the specified filter from this element.
removeFilter(DhFilter filter, boolean bApply) | Removes the given filter from this element.
removeOnReadyStateChange ( DhEventHandler h ) | Topic under construction.
replaceFilter(DhFilter filter1, DhFilter filter2) | Replaces a filter with another filter.
replaceFilter(DhFilter filter1, DhFilter filter2, boolean bApply) | Replaces a filter with a specified filter.
setImageMap( DhImageMap im ) | Sets the DhImageMap to associate with this image.
setImageMapName( String strName ) | Sets the name of the image map to associate with this image.
setURL(String url) | Sets the URL of the bitmap file.

Constructors

DhImage.DhImage

Syntax
public DhImage( String url );
Parameters
url
The URL that refers to the bitmap file to display. The URL can be relative to the HTML document.
Description

Creates a DhImage obect.

Methods

DhImage.addFilter

Syntax 1
public void addFilter( DhFilter filter );
Parameters
filter
The DhFilter object to apply.
Description

Adds a filter to this element and applies it immediately. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
replaceFilter

Syntax 2
public void addFilter( DhFilter filter, boolean bApply );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter immediately; set to false to delay applying the filter.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

Syntax 3
public void addFilter( DhFilter filter, boolean bApply, boolean bFlush );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter immediately; set to false to delay applying the filter.
bFlush
Set to true to flush the previously applied filters; set to combine filter with those already present.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. You can also specify whether to flush filters that were previously applied to this element or to combine this filter with those already present.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

DhImage.addOnReadyStateChange

Syntax
final public void addOnReadyStateChange ( DhEventHandler h );
Description

Topic under construction.

DhImage.addTransition

Syntax
public void addTransition( DhFilter trans );
Parameters
trans
The transition effect you will run.
Description

Adds a transition effect to this element. You must call this method before you can run the effect. Note that this functionality is provided for extension only (see the sample classes). This package does provide transition effects.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of transition effect already exists on this element.

See Also
replaceFilter

DhImage.applyFilters

Syntax
public void applyFilters();
Description

Applies filters that were previously deferred. Use this method if you called addFilter(DhFilter,boolean) with false for the second parameter. This function applies every filter that was added to this element.

See Also
addFilter(DhFilter,boolean), addFilter

DhImage.findFilter

Syntax
public DhFilter findFilter( Class filterClass );
Parameters
filterClass
The class of the filter you are looking for.
Return Value

Returns the DhFilter object (if found) that is of type filterClass.

Description

Retrieves the current filter with the specified filter class.

DhImage.getImageMap

Syntax
public DhImageMap getImageMap();
Return Value

Returns a DhImageMap object, or returns null if none is set.

Description

Retrieves the DhImageMap object associated with this image.

DhImage.getImageMapName

Syntax
public String getImageMapName();
Return Value

Returns the name of the image map, or returns a null string if none is set.

Description

Retrieves the name of the image map associated with this image.

DhImage.getLoadComplete

Syntax
public boolean getLoadComplete();
Return Value

Returns true if loading of the image is complete; otherwise, returns false. .

Description

Determines if the image has been fully loaded.

See Also
addReadyStateChange, getReadyState

DhImage.getReadyState

Syntax
public String getReadyState();
Return Value

Returns the current state.

Description

Returns the current state of the image object.

Possible values include:

  • uninitialized The object is not initialized with data.
  • loading The object is currently loading its data.
  • interactive The object can be interacted with even though it is not fully loaded.
  • complete The image is completely loaded

DhImage.getURL

Syntax
public String getURL();
Return Value

Returns the URL that refers to the bitmap file to display.

Description

Retrieves the current URL that refers to the location of the bitmap file.

DhImage.removeAllFilters

Syntax 1
public void removeAllFilters();
Description

Removes all filters from this element. This method automatically clears all filters on this element.

Syntax 2
public void removeAllFilters( boolean bApply );
Description

Removes all filters from this element. You can clear all filters on this element or delay removal.

DhImage.removeFilter

Syntax 1
public void removeFilter( DhFilter filter );
Parameters
filter
The filter to remove.
Description

Removes the specified filter from this element. This method automatically reapplies filters that may be left after this method is called.

See Also
findFilter.

Syntax 2
public void removeFilter( DhFilter filter, boolean bApply );
Parameters
filter
The filter to remove.
bApply
Set to true to reapply other filters left on this element; set to false to delay applying the filters.
Description

Removes the given filter from this element. You can reapply filters that may be left after this method is called, or you can delay application if you are removing more than one filter.

See Also
findFilter.

DhImage.removeOnReadyStateChange

Syntax
final public void removeOnReadyStateChange ( DhEventHandler h );
Description

Topic under construction.

DhImage.replaceFilter

Syntax 1
public void replaceFilter( DhFilter filter1, DhFilter filter2 );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1.
Description

Replaces a filter with another filter. This method provides an easy way to swap filters. This method applies all changes due to this swap immediately.

Syntax 2
public void replaceFilter( DhFilter filter1, DhFilter filter2, boolean bApply );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
bApply
Set to true to apply the filter immediately; set to false to delay applying the filter. If you set this parameter to false, you can call applyFilters when you want to apply the filters.
Description

Replaces a filter with a specified filter. This method provides an easy way to swap filters. You can specify whether to apply all the changes due to this swap immediately or to delay application until later.

See Also
applyFilters

DhImage.setImageMap

Syntax
public void setImageMap( DhImageMap im );
Parameters
im
The DhImageMap.
Description

Sets the DhImageMap to associate with this image.

DhImage.setImageMapName

Syntax
public void setImageMapName( String strName );
Parameters
strName
The name of the image map to associate with the image.
Description

Sets the name of the image map to associate with this image.

DhImage.setURL

Syntax
public void setURL( String url );
Parameters
url
The URL that refers to the bitmap file to display. The URL can be relative to the HTML document.
Description

Sets the URL of the bitmap file.


 DhImageMap Class

DhImageMap Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhImageMap
public class DhImageMap
extends DhBaseContainer

Represents an image map. An image map contains several DhHotSpot items that describe the areas in the image that the user can click to navigate.

Constructors
Name | Description
DhImageMap() | Creates a DhImageMap object.
DhImageMap( String strName ) | Creates a DhImageMap object.

Methods
Name | Description
addHotSpot( DhHotSpot hs ) | Adds a DhHotSpot object to this image map.
addHotSpot( int nShape, String strCoords, String strUrl ) | Adds a DhHotSpot object to this image map.
addHotSpot( int nShape, String strCoords, DhHyperlink hlUrl ) | Adds a DhHotSpot object to this image map.
getHotSpots() | Retrieves an array of the DhHotSpot objects contained in this image map.
getName() | Retrieves the name for this image map.
removeHotSpot( DhHotSpot hs ) | Removes the specified DhHotSpot from the image map.
setName( String strName ) | Sets the name for this image map.

Constructors

DhImageMap.DhImageMap

Syntax 1
public DhImageMap();
Description

Creates a DhImageMap object. The name of the image map is generated automatically.

Syntax 2
public DhImageMap( String strName );
Parameters
strName
The name of the image map.
Description

Creates a DhImageMap object. This constructor creates a map with a specified name.

Methods

DhImageMap.addHotSpot

Syntax 1
public void addHotSpot( DhHotSpot hs );
Parameters
hs
The DhHotSpot to add.
Description

Adds a DhHotSpot object to this image map.

Syntax 2
public void addHotSpot( int nShape, String strCoords, String strUrl );
Parameters
nShape
The shape of the hot spot. Can be any one of DhHotSpot.SHAPE_RECTANGLE, DhHotSpot.SHAPE_POLYGON, or DhHotSpot.SHAPE_CIRCLE.
strCoords
The coordinate string for this hotspot. For details, see DhHotSpot.
strUrl
The URL to navigate to if the hot spot is selected.
Description

Adds a DhHotSpot object to this image map.

Syntax 3
public void addHotSpot( int nShape, String strCoords, DhHyperlink hlUrl );
Parameters
nShape
The shape of the hot spot. Can be any one of DhHotSpot.SHAPE_RECTANGLE, DhHotSpot.SHAPE_POLYGON, or DhHotSpot.SHAPE_CIRCLE.
strCoords
The coordinate string for this hotspot. For details, see DhHotSpot.
hlUrl
The URL to navigate to if the hot spot is selected.
Description

Adds a DhHotSpot object to this image map.

DhImageMap.getHotSpots

Syntax
public synchronized DhHotSpot[] getHotSpots();
Return Value

Returns the DhHotSpot array.

Description

Retrieves an array of the DhHotSpot objects contained in this image map.

DhImageMap.getName

Syntax
public String getName();
Return Value

Returns the image map name.

Description

Retrieves the name for this image map.

DhImageMap.removeHotSpot

Syntax
public synchronized void removeHotSpot( DhHotSpot hs );
Parameters
hs
The DhHotSpot to remove.
Description

Removes the specified DhHotSpot from the image map.

DhImageMap.setName

Syntax
public void setName( String strName );
Parameters
strName
The name of the image map.
Description

Sets the name for this image map.


 DhInlineFrame Class

DhInlineFrame Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhInlineFrame
public class DhInlineFrame
extends DhElement

Represents an inline frame (<IFRAME>) element.

Constructors
Name | Description
DhInlineFrame() | Creates an empty frame.
DhInlineFrame(String url) | Creates an frame using the HTML from the specified URL as its source.

Methods
Name | Description
getFrameDocument() | Retrieves the document in this frame.
getURL() | Retrieves the URL that defines the location of the contents of this frame.
setURL(String url) | Sets the URL that defines the location of the contents of this frame.

Constructors

DhInlineFrame.DhInlineFrame

Syntax 1
public DhInlineFrame();
Description

Creates an empty frame.

Syntax 2
public DhInlineFrame( String url );
Parameters
url
The source of the frame.
Description

Creates an frame using the HTML from the specified URL as its source.

Methods

DhInlineFrame.getFrameDocument

Syntax
public DhDocument getFrameDocument();
Return Value

Returns a DhDocument object representing the contents of this frame.

Description

Retrieves the document in this frame.

DhInlineFrame.getURL

Syntax
public String getURL();
Return Value

Returns the location of the URL for this frame.

Description

Retrieves the URL that defines the location of the contents of this frame.

DhInlineFrame.setURL

Syntax
public void setURL( String url );
Parameters
url
The location URL of the frame.
Description

Sets the URL that defines the location of the contents of this frame.


 DhInsertEnum Class

DhInsertEnum Class

This Package | All Packages

Enum
  |
  +--DhInsertEnum
public class DhInsertEnum
extends wfc.cor.Enum

Provides constants for inserting DhElement items into container items.

Fields
Name | Description
INSERT_AFTER | Inserts the item after the specified item in the list.
INSERT_BEFORE | Inserts the item before the specific item in the list.
INSERT_BEGINNING | Inserts the item at the beginning of the current list.
INSERT_END | Inserts the item at the end of the current list.

Fields

DhInsertEnum.INSERT_AFTER

Syntax
public static final int INSERT_AFTER;
Description
Inserts the item after the specified item in the list.

DhInsertEnum.INSERT_BEFORE

Syntax
public static final int INSERT_BEFORE;
Description
Inserts the item before the specific item in the list.

DhInsertEnum.INSERT_BEGINNING

Syntax
public static final int INSERT_BEGINNING;
Description
Inserts the item at the beginning of the current list.

DhInsertEnum.INSERT_END

Syntax
public static final int INSERT_END;
Description
Inserts the item at the end of the current list.


 DhInvalidEnumValueException Class

DhInvalidEnumValueException Class

This Package | All Packages

RuntimeException
  |
  +--DhInvalidEnumValueException
public class DhInvalidEnumValueException
extends RuntimeException

Signals that an attempt has been made to access a value within an enumeration that doesn't have a constant for that value.

Constructors
Name | Description
DhInvalidEnumValueException() | Topic under construction.
DhInvalidEnumValueException( String detail ) | Topic under construction.

Constructors

DhInvalidEnumValueException.DhInvalidEnumValueException

Syntax 1
public DhInvalidEnumValueException();
Description

Topic under construction.

Syntax 2
public DhInvalidEnumValueException( String detail );
Description

Topic under construction.


 DhJumpPoint Class

DhJumpPoint Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhJumpPoint
public class DhJumpPoint
extends DhElement

Represents an jump point within a document (that is, a <A NAME=...> reference).

Constructors
Name | Description
DhJumpPoint() | Creates a DhJumpPoint object.
DhJumpPoint(String name) | Creates a DhJumpPoint object.

Methods
Name | Description
getName() | Retrieves the current jump point name.
setName(String n) | Sets the jump point name.

Constructors

DhJumpPoint.DhJumpPoint

Syntax 1
public DhJumpPoint();
Description

Creates a DhJumpPoint object.

Syntax 2
public DhJumpPoint( String name );
Parameters
name
The name of the jump point.
Description

Creates a DhJumpPoint object. This is a one-step constructor that initializes the name of the jump point.

Methods

DhJumpPoint.getName

Syntax
public String getName();
Return Value

Returns the name, or returns a null string if one does not exist.

Description

Retrieves the current jump point name.

DhJumpPoint.setName

Syntax
public void setName( String n );
Parameters
n
The new jump point name.
Description

Sets the jump point name.


 DhListBox Class

DhListBox Class

This Package | All Packages

DhSelectBox
  |
  +--DhListBox
public class DhListBox
extends DhSelectBox

Represents a list box control. This class manages adding, removing, and selecting items, as well as scrolling. The list box control can be used within a form (see DhSection) to transmit data.

Constructors
Name | Description
DhListBox( ) | Creates a DhListBox control.
DhListBox( int nRows, int selectionStyle) | Creates a DhListBox object.

Methods
Name | Description
getAlignment() | Retrieves the current alignment value of the list box.
getSelectionStyle() | Returns the current selection style of the list box.
getVisibleRows( ) | Retrieves the number of currently visible rows.
setAlignment( int nAlignment ) | Sets the alignment of the list box relative to the text around it.
setSelectionStyle(int value) | Determines how many items at a time can be selected in the list box.
setVisibleRows( int nRows ) | Sets the number of visible rows in the list box.

Constructors

DhListBox.DhListBox

Syntax 1
public DhListBox( );
Description

Creates a DhListBox control. This default constructor creates a list box control with two visible rows, which allows only single selections.

Syntax 2
public DhListBox( int nRows, int selectionStyle );
Parameters
nRows
The initial number of visible rows. This must be greater than 1.
selectionStyle
A value determining whether the user can select multiple rows. This can be any value in com.ms.wfc.cor.SelectionStyle.
Description

Creates a DhListBox object.

Methods

DhListBox.getAlignment

Syntax
public int getAlignment();
Description

Retrieves the current alignment value of the list box. Returns one of the alignment constant values in DhAlignEnum.

See Also
wfc.html.DhAlignEnum

DhListBox.getSelectionStyle

Syntax
public int getSelectionStyle();
Return Value

Returns the selection style. Possible values are:

  • SelectionStyle.NONE, which indicates that items can be selected in the list.
  • SelectionStyle.MULTI_EXTENDED, which indicates that more than one item at a time can be selected and keyboard characters such as SHIFT and CTRL can be used to assist in the selection.

Description

Returns the current selection style of the list box.

See Also
wfc.cor.SelectionStyle

DhListBox.getVisibleRows

Syntax
public int getVisibleRows( );
Return Value

Returns the number of rows.

Description

Retrieves the number of currently visible rows.

DhListBox.setAlignment

Syntax
public void setAlignment( int nAlignment );
Parameters
nAlignment
The new alignment, which can be one of the alignment constant values in DhAlignEnum.
Description

Sets the alignment of the list box relative to the text around it.

See Also
wfc.html.DhAlignEnum

DhListBox.setSelectionStyle

Syntax
public void setSelectionStyle( int value );
Parameters
value
The new selection style. Possible values are:
  • SelectionStyle.NONE, which indicates that items can be selected in the list.
  • SelectionStyle.MULTI_EXTENDED, which indicates that more than one item at a time can be selected and keyboard characters such as SHIFT and CTRL can be used to assist in the selection.

Note that The SelectionStyle.ONE and SelectionStyle.MULTI_SIMPLE are not valid for DhListBox.

Description

Determines how many items at a time can be selected in the list box.

DhListBox.setVisibleRows

Syntax
public void setVisibleRows( int nRows );
Parameters
nRows
Number of rows. This must be greater than 1.
Description

Sets the number of visible rows in the list box.

Exceptions

IllegalArgumentException thrown if nRow is less than 2.


 DhListTypeEnum Class

DhListTypeEnum Class

This Package | All Packages

Enum
  |
  +--DhListTypeEnum
public class DhListTypeEnum
extends Enum

Provides constants and support for list types in a DhList control.

Fields
Name | Description
BULLETED | Represents a list in which each item has a small bullet.
DIR | Represents a list in which each item has a large bullet.
LARGE_LETTER | Represents a list in which each item has an assigned uppercase letter.
LARGE_ROMAN | Represents a list in which each item has an assigned uppercase roman numeral
MENU | Represents a list in which each item has a large bullet.
NUMBERED | Represents a list in which each item has an assigned number.
SMALL_LETTER | Represents a list in which each item has an assigned lowercase letter.
SMALL_ROMAN | Represents a list in which each item has an assigned lowercase roman numeral.

Methods
Name | Description
ensureValid(int n ) | Topic under construction.
valid(int n) | Topic under construction.

Fields

DhListTypeEnum.BULLETED

Syntax
public final static int BULLETED;
Description
Represents a list in which each item has a small bullet.

DhListTypeEnum.DIR

Syntax
public final static int DIR;
Description
Represents a list in which each item has a large bullet.

DhListTypeEnum.LARGE_LETTER

Syntax
public final static int LARGE_LETTER;
Description
Represents a list in which each item has an assigned uppercase letter.

DhListTypeEnum.LARGE_ROMAN

Syntax
public final static int LARGE_ROMAN;
Description
Represents a list in which each item has an assigned uppercase roman numeral

DhListTypeEnum.MENU

Syntax
public final static int MENU;
Description
Represents a list in which each item has a large bullet. This is similar to MENU.

DhListTypeEnum.NUMBERED

Syntax
public final static int NUMBERED;
Description
Represents a list in which each item has an assigned number.

DhListTypeEnum.SMALL_LETTER

Syntax
public final static int SMALL_LETTER;
Description
Represents a list in which each item has an assigned lowercase letter.

DhListTypeEnum.SMALL_ROMAN

Syntax
public final static int SMALL_ROMAN;
Description
Represents a list in which each item has an assigned lowercase roman numeral.

Methods

DhListTypeEnum.ensureValid

Syntax
public static void ensureValid( int n );
Description

Topic under construction.

DhListTypeEnum.valid

Syntax
public static boolean valid( int n );
Description

Topic under construction.


 DhMarginEnum Class

DhMarginEnum Class

This Package | All Packages

Enum
  |
  +--DhMarginEnum
public class DhMarginEnum
extends wfc.cor.Enum

Provides constant definitions for margin style manipulation.

Fields
Name | Description
MARGIN_SIDE_ALL | Specifies combination of all MARGIN_SIDE_ items. This is equivalent to (MARGIN_SIDE_TOP | MARGIN_SIDE_RIGHT | MARGIN_SIDE_BOTTOM | MARGIN_SIDE_LEFT)
MARGIN_SIDE_BOTTOM | Specifies a bottom margin.
MARGIN_SIDE_LEFT | Specifies a left margin.
MARGIN_SIDE_RIGHT | Specifies a right margin.
MARGIN_SIDE_TOP | Specifies a top margin.

Fields

DhMarginEnum.MARGIN_SIDE_ALL

Syntax
public static final int MARGIN_SIDE_ALL;
Description
Specifies combination of all MARGIN_SIDE_ items.
This is equivalent to (MARGIN_SIDE_TOP | MARGIN_SIDE_RIGHT | MARGIN_SIDE_BOTTOM | MARGIN_SIDE_LEFT)

DhMarginEnum.MARGIN_SIDE_BOTTOM

Syntax
public static final int MARGIN_SIDE_BOTTOM;
Description
Specifies a bottom margin.

DhMarginEnum.MARGIN_SIDE_LEFT

Syntax
public static final int MARGIN_SIDE_LEFT;
Description
Specifies a left margin.

DhMarginEnum.MARGIN_SIDE_RIGHT

Syntax
public static final int MARGIN_SIDE_RIGHT;
Description
Specifies a right margin.

DhMarginEnum.MARGIN_SIDE_TOP

Syntax
public static final int MARGIN_SIDE_TOP;
Description
Specifies a top margin.


 DhMarginWidthInfo Class

DhMarginWidthInfo Class

This Package | All Packages

public class DhMarginWidthInfo

Provides information about an element's current margin settings.

Fields
Name | Description
bottomUnit | Specifies the bottom margin width unit.
bottomWidth | Specifies the bottom margin width.
leftUnit | Specifies the left margin width unit.
leftWidth | Specifies the left margin width.
rightUnit | Specifies the right margin width unit.
rightWidth | Specifies the right margin width.
topUnit | Specifies the top margin width unit.
topWidth | Specifies the top margin width.

Constructors
Name | Description
DhMarginWidthInfo() | Constructs a DhMarginWidthInfo object.
DhMarginWidthInfo( DhMarginWidthInfo mwi ) | Constructs a DhMarginWidthInfo object.

Fields

DhMarginWidthInfo.bottomUnit

Syntax
public int bottomUnit;
Description
Specifies the bottom margin width unit.

DhMarginWidthInfo.bottomWidth

Syntax
public int bottomWidth;
Description
Specifies the bottom margin width.

DhMarginWidthInfo.leftUnit

Syntax
public int leftUnit;
Description
Specifies the left margin width unit.

DhMarginWidthInfo.leftWidth

Syntax
public int leftWidth;
Description
Specifies the left margin width.

DhMarginWidthInfo.rightUnit

Syntax
public int rightUnit;
Description
Specifies the right margin width unit.

DhMarginWidthInfo.rightWidth

Syntax
public int rightWidth;
Description
Specifies the right margin width.

DhMarginWidthInfo.topUnit

Syntax
public int topUnit;
Description
Specifies the top margin width unit.

DhMarginWidthInfo.topWidth

Syntax
public int topWidth;
Description
Specifies the top margin width.

Constructors

DhMarginWidthInfo.DhMarginWidthInfo

Syntax 1
public DhMarginWidthInfo();
Description

Constructs a DhMarginWidthInfo object.

Syntax 2
public DhMarginWidthInfo( DhMarginWidthInfo mwi );
Parameters
mwi
The object used to initialize current settings.
Description

Constructs a DhMarginWidthInfo object. This constructor initializes values from an existing DhMarginWidthInfo object.


 DhModule Class

DhModule Class

This Package | All Packages

public class DhModule
implements IObjectWithSite, IPersistPropertyBag, DhStringIDs, ISiteable, IPersistHistory

Represents the class from which you should derive to use the wfc.html package. You then author your derivation into your HTML file as an object tag. You never create a DhModule; it is created automatically when you put it on the HTML page as an OBJECT tag.

Methods
Name | Description
addOnGotFocus ( DhEventHandler h ) | Sets the DhEventHandler event handler method callback that is triggered when the document is ready to unload.
addOnLoad ( DhEventHandler h ) | Sets the DhEventHandler event handler method callback that is triggered when the document has finished loading.
addOnLostFocus ( DhEventHandler h ) | Sets the DhEventHandler event handler method callback that is triggered when the document has finished loading.
addOnUnload ( DhEventHandler h ) | Sets the DhEventHandler event handler method callback that is triggered when the document is ready to unload.
createEvents() | Topic under construction.
documentLoad(Object sender, DhEvent event) | Called by the module host to inform this module that it should start its execution.
documentUnload(Object sender, DhEvent event) | Called by the module host to inform this module to cease its execution.
GetClassID(com.ms.com._Guid pClassID) | Implements IPersist.GetClassID().
getCurrentModule() | Topic under construction.
getDocument() | Retrieves the current DhDocument object associated with this module.
getPeer() | Retrieves the underlying HTML peer element for this class.
GetPositionCookie() | Implements IPersistHistory.GetPositionCookie().
getRequest() | Topic under construction.
getResponse() | Topic under construction.
getServerMode() | Retrieves the current site for this DhModule.
getSite() | Implements ISite.getSite().
GetSite( _Guid g ) | Implements IObjectWithSite.GetSite()
InitNew() | Implements IPersistPropertyBag.InitNew.
Load(IPropertyBag pPropBag, IUnknown pErrorLog) | Implements IPersistPropertyBag.Load().
LoadHistory( com.ms.com.IStream pStream, IUnknown bindCtx) | Implements IPersistHistory.LoadHistory().
LoadParameters( DhPropertyBag pb ) | This is the first and last time this module has a chance to look at the parameters that were authored into the PARAM tags of the hosting HTML document.
removeOnGotFocus ( DhEventHandler h ) | Removes the DhEventHandler event handler method callback that is triggered when the document is ready to unload.
removeOnLoad ( DhEventHandler h ) | Removes the DhEventHandler event handler method callback that is triggered when the document has finished loading.
removeOnLostFocus ( DhEventHandler h ) | Removes the DhEventHandler event handler method callback that is triggered when the document has finished loading.
removeOnUnload ( DhEventHandler h ) | Removes the DhEventHandler event handler method callback that is triggered when the document is ready to unload.
Save(IPropertyBag pPropBag, int fClearDirty, int fSaveAllProperties) | Implements IPersistPropertyBag.Save().
SaveHistory( com.ms.com.IStream pStream) | Implements IPersistHistory.SaveHistory().
SetPositionCookie(int dwPositioncookie) | Implements IPersistHistory.SetPositionCookie().
setSite(ISite site) | Implements ISite.setSite().
SetSite(IUnknown punk) | Implements IObjectWithSite.SetSite()
setupSite(IOleClientSite ocs, boolean isMainThread) | Topic under construction.
write( String strHTML ) | Writes the specified HTML string to the current site.
write( DhElement element ) | Writes the specified DhElement to the current site.
write( IDataStream inputStream, IUploadNotify iNotify, String flagToken ) | Writes the specified data stream to the document stream.
write( IDataStream inputStream, IUploadNotify iNotify ) | Writes the specified data stream to the document stream.

Methods

DhModule.addOnGotFocus

Syntax
public void addOnGotFocus ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback that is triggered when the document is ready to unload.

DhModule.addOnLoad

Syntax
public void addOnLoad ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback that is triggered when the document has finished loading.

DhModule.addOnLostFocus

Syntax
public void addOnLostFocus ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback that is triggered when the document has finished loading.

DhModule.addOnUnload

Syntax
public void addOnUnload ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Sets the DhEventHandler event handler method callback that is triggered when the document is ready to unload.

DhModule.createEvents

Syntax
protected DhEvents createEvents();
Description

Topic under construction.

DhModule.documentLoad

Syntax
protected synchronized void documentLoad( Object sender, DhEvent event );
Parameters
sender
The object sending this event.
event
The event object.
Description

Called by the module host to inform this module that it should start its execution. It is the first time that is it "safe" to call any object in the main document.

A subclass of DhModule should override this method if it has any operation that it wants to perform each time the module is loaded.

The implementation of this method provided by the DhModule class does nothing.

DhModule.documentUnload

Syntax
protected synchronized void documentUnload( Object sender, DhEvent event );
Parameters
sender
The object sending this event.
event
The event object.
Description

Called by the module host to inform this module to cease its execution. It is the last time that is it "safe" to call any object in the main document.

A subclass of DhModule should override this method if it has any operation that it wants to perform each time the module is unloaded.

The implementation of this method provided by the DhModule class does nothing.

DhModule.GetClassID

Syntax
final public void GetClassID( com.ms.com._Guid pClassID );
Description

Implements IPersist.GetClassID().

DhModule.getCurrentModule

Syntax
static public synchronized DhModule getCurrentModule();
Description

Topic under construction.

DhModule.getDocument

Syntax
public synchronized DhDocument getDocument();
Return Value

Returns the current DhDocument, or returns null if the page has not finished loading.

Description

Retrieves the current DhDocument object associated with this module.

DhModule.getPeer

Syntax
public IUnknown getPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Retrieves the underlying HTML peer element for this class. This method may return null if the document is not bound to this class. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLWindow2). This method will always return null if the code is running in a Web server environment.

Note that calling this method represents an advanced usage scenario. Typically, you would never use this method.

DhModule.GetPositionCookie

Syntax
final public int GetPositionCookie();
Description

Implements IPersistHistory.GetPositionCookie().

DhModule.getRequest

Syntax
public IRequest getRequest();
Description

Topic under construction.

DhModule.getResponse

Syntax
public IResponse getResponse();
Description

Topic under construction.

DhModule.getServerMode

Syntax
public boolean getServerMode();
Return Value

Returns true if DhModule is sited on a web server, or returns false if it is sited on a client or other container.

Description

Retrieves the current site for this DhModule.

DhModule.getSite

Syntax
final public synchronized ISite getSite();
Description

Implements ISite.getSite().

DhModule.GetSite

Syntax
final synchronized public IUnknown GetSite( _Guid g );
Description

Implements IObjectWithSite.GetSite()

DhModule.InitNew

Syntax
final public void InitNew();
Description

Implements IPersistPropertyBag.InitNew.

DhModule.Load

Syntax
final public void Load( IPropertyBag pPropBag, IUnknown pErrorLog );
Description

Implements IPersistPropertyBag.Load().

DhModule.LoadHistory

Syntax
final synchronized public void LoadHistory( com.ms.com.IStream pStream, IUnknown bindCtx );
Description

Implements IPersistHistory.LoadHistory().

DhModule.LoadParameters

Syntax
public void LoadParameters( DhPropertyBag pb );
Parameters
pb
The collection of PARAM tags.
Description

This is the first and last time this module has a chance to look at the parameters that were authored into the PARAM tags of the hosting HTML document.

DhModule.removeOnGotFocus

Syntax
public void removeOnGotFocus ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback that is triggered when the document is ready to unload.

DhModule.removeOnLoad

Syntax
public void removeOnLoad ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback that is triggered when the document has finished loading.

DhModule.removeOnLostFocus

Syntax
public void removeOnLostFocus ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback that is triggered when the document has finished loading.

DhModule.removeOnUnload

Syntax
public void removeOnUnload ( DhEventHandler h );
Parameters
h
The event handler callback method.
Description

Removes the DhEventHandler event handler method callback that is triggered when the document is ready to unload.

DhModule.Save

Syntax
final public void Save( IPropertyBag pPropBag, int fClearDirty, int fSaveAllProperties );
Description

Implements IPersistPropertyBag.Save().

DhModule.SaveHistory

Syntax
final synchronized public void SaveHistory( com.ms.com.IStream pStream );
Description

Implements IPersistHistory.SaveHistory().

DhModule.SetPositionCookie

Syntax
final public void SetPositionCookie( int dwPositioncookie );
Description

Implements IPersistHistory.SetPositionCookie().

DhModule.setSite

Syntax
final public void setSite( ISite site );
Description

Implements ISite.setSite().

Note This method is obsolete.

DhModule.SetSite

Syntax
final public void SetSite( IUnknown punk );
Description

Implements IObjectWithSite.SetSite()

DhModule.setupSite

Syntax
protected void setupSite( IOleClientSite ocs, boolean isMainThread );
Description

Topic under construction.

DhModule.write

Syntax 1
public void write( String strHTML );
Parameters
strHTML
The HTML string to write.
Description

Writes the specified HTML string to the current site. If running in server mode, the string is written to the output stream; otherwise, it is added to the end of the current document body.

Syntax 2
public void write( DhElement element );
Parameters
element
The element to write.
Description

Writes the specified DhElement to the current site. If running in server mode, the element's HTML code is generated and sent to the output stream. Otherwise, the element is added to the end of the current document body.

Syntax 3
public void write( IDataStream inputStream, IUploadNotify iNotify, String flagToken );
Parameters
inputStream
An IDataStream input stream.
iNotify
The user supplied IUploadNotify inteface.
flagToken
The token attribute to flag items for notification.
Description

Writes the specified data stream to the document stream. Elements with the flagToken attribute are passed to the user-supplied IUploadNotify interface.

Syntax 4
public void write( IDataStream inputStream, IUploadNotify iNotify );
Parameters
inputStream
An IDataStream input stream.
iNotify
The user-supplied IUploadNotify interface.
Description

Writes the specified data stream to the document stream. Elements with the "__NOTIFY" attribute are passed to the user-supplied IUploadNotify interface.


 DhNotSupportedException Class

DhNotSupportedException Class

This Package | All Packages

RuntimeException
  |
  +--DhNotSupportedException
public class DhNotSupportedException
extends RuntimeException

Signals that a request for a named element failed, because an element with that name does not exist.

Constructors
Name | Description
DhNotSupportedException() | Constructs a ElementNotFoundException with no detail message.
DhNotSupportedException(String s) | Constructs a ElementNotFoundException with a detail message.

Constructors

DhNotSupportedException.DhNotSupportedException

Syntax 1
public DhNotSupportedException();
Description

Constructs a ElementNotFoundException with no detail message.

Syntax 2
public DhNotSupportedException( String s );
Description

Constructs a ElementNotFoundException with a detail message.


 DhObjectDataSource Class

DhObjectDataSource Class

This Package | All Packages

DhObjectFactory
  |
  +--DhObjectDataSource
public class DhObjectDataSource
extends DhObjectFactory

Provides encapsulation of data source objects in <OBJECT> tags.

Constructors
Name | Description
DhObjectDataSource() | Constructs a DhObjectDataSource object.
DhObjectDataSource( _Guid iid ) | Constructs a DhObjectDataSource object.

Methods
Name | Description
dataSource() | Retrieves the DhDataSource member for this object.

Constructors

DhObjectDataSource.DhObjectDataSource

Syntax 1
public DhObjectDataSource();
Description

Constructs a DhObjectDataSource object.

Syntax 2
public DhObjectDataSource( _Guid iid );
Parameters
iid
A _Guid object initialized with the GUID class identifer for this data source object.
Description

Constructs a DhObjectDataSource object. This is a one-step construction with _Guid for object instantiation.

Methods

DhObjectDataSource.dataSource

Syntax
public DhDataSource dataSource();
Return Value

Returns the data source member.

Description

Retrieves the DhDataSource member for this object.


 DhObjectFactory Class

DhObjectFactory Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhObjectFactory
public class DhObjectFactory
extends DhBaseContainer

Creates an object and adds it to the document. To use this, create this class specifying the object's class identifier (CLASSID).

Constructors
Name | Description
DhObjectFactory() | Constructs a DhObjectFactory object.
DhObjectFactory(String classid) | One-step construction.

Methods
Name | Description
add(DhElement h) | Adds an element as the child of the object tag.
addOnAfterUpdate(DhEventHandler h) | Topic under construction.
addOnBeforeUpdate(DhEventHandler h) | Topic under construction.
addOnDataAvailable(DhEventHandler h) | Topic under construction.
addOnDataSetChanged(DhEventHandler h) | Topic under construction.
addOnDataSetComplete(DhEventHandler h) | Topic under construction.
addOnError(DhEventHandler h) | Topic under construction.
addOnErrorUpdate(DhEventHandler h) | Topic under construction.
addOnReadyStateChange(DhEventHandler h) | Topic under construction.
addOnRowEnter(DhEventHandler h) | Topic under construction.
addOnRowExit(DhEventHandler h) | Topic under construction.
addParam(String param, String value) | Adds a new parameter.
getClassid() | Retrieves the object's current CLASSID.
getClsid() | Retrieves the object's current CLASSID.
getCodeBase() | Retrieves the object's current CODEBASE.
getCodeClassName() | Retrieves the object's current className.
getContent(StringBuffer sb) | Retrieves a string representing the HTML of the contents.
getDispatchPeer() | Retrieves the IDispatch interface implemented by the OBJECT currently instantiated.
getObjectPeer() | Retrieves the object representing the OBJECT instanstiated.
getProgid() | Retrieves the object's current PROGID.
getValue(String param) | Retrieves the value of the parameter.
removeOnAfterUpdate(DhEventHandler h) | Topic under construction.
removeOnBeforeUpdate(DhEventHandler h) | Topic under construction.
removeOnDataAvailable(DhEventHandler h) | Topic under construction.
removeOnDataSetChanged(DhEventHandler h) | Topic under construction.
removeOnDataSetComplete(DhEventHandler h) | Topic under construction.
removeOnError(DhEventHandler h) | Topic under construction.
removeOnErrorUpdate(DhEventHandler h) | Topic under construction.
removeOnReadyStateChange(DhEventHandler h) | Topic under construction.
removeOnRowEnter(DhEventHandler h) | Topic under construction.
removeOnRowExit(DhEventHandler h) | Topic under construction.
removeParam(String param) | Removes a parameter from the list.
setClassid(String classid) | Sets the object's current CLASSID.
setClsid(_Guid guid) | Sets the object's CLASSID.
setCodeBase(String url) | Sets the object's CODEBASE.
setCodeClassName(String className) | Sets the object's class name.
setProgid(String progid) | Sets the object's PROGID.

Constructors

DhObjectFactory.DhObjectFactory

Syntax 1
public DhObjectFactory();
Description

Constructs a DhObjectFactory object.

Syntax 2
public DhObjectFactory( String classid );
Parameters
classid
The class identifier (CLASSID) of an existing object.
Description

One-step construction.

Methods

DhObjectFactory.add

Syntax
protected synchronized void add( DhElement h );
Parameters
h
The DhElement to be added.
Description

Adds an element as the child of the object tag.

DhObjectFactory.addOnAfterUpdate

Syntax
public final void addOnAfterUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnBeforeUpdate

Syntax
public final void addOnBeforeUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnDataAvailable

Syntax
public final void addOnDataAvailable( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnDataSetChanged

Syntax
public final void addOnDataSetChanged( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnDataSetComplete

Syntax
public final void addOnDataSetComplete( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnError

Syntax
public final void addOnError( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnErrorUpdate

Syntax
public final void addOnErrorUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnReadyStateChange

Syntax
public final void addOnReadyStateChange( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnRowEnter

Syntax
public final void addOnRowEnter( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addOnRowExit

Syntax
public final void addOnRowExit( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.addParam

Syntax
public synchronized void addParam( String param, String value );
Parameters
param
The name of the parameter.
value
The value of the parameter.
Description

Adds a new parameter.

DhObjectFactory.getClassid

Syntax
public String getClassid();
Return Value

Returns the object's class identifier.

Description

Retrieves the object's current CLASSID.

DhObjectFactory.getClsid

Syntax
public _Guid getClsid();
Return Value

Returns the object's class identifier.

Description

Retrieves the object's current CLASSID.

DhObjectFactory.getCodeBase

Syntax
public String getCodeBase();
Return Value

Returns the object's code base.

Description

Retrieves the object's current CODEBASE.

DhObjectFactory.getCodeClassName

Syntax
public String getCodeClassName();
Return Value

Returns the object's className.

Description

Retrieves the object's current className.

DhObjectFactory.getContent

Syntax
protected synchronized StringBuffer getContent( StringBuffer sb );
Parameters
sb
Topic under construction.
Return Value

Returns the StringBuffer representing the HTML of the contents.

Description

Retrieves a string representing the HTML of the contents.

DhObjectFactory.getDispatchPeer

Syntax
public Object getDispatchPeer();
Return Value

Returns the object representing the IDispatch interface of the OBJECT.

Description

Retrieves the IDispatch interface implemented by the OBJECT currently instantiated. This object can be used along with the com.ms.com.Dispatch class to invoke methods exposed through the controls' IDispatch.

DhObjectFactory.getObjectPeer

Syntax
public Object getObjectPeer();
Return Value

Returns the object representing the OBJECT instanstiated.

Description

Retrieves the object representing the OBJECT instanstiated.

DhObjectFactory.getProgid

Syntax
public String getProgid();
Return Value

Returns the object's PROGID.

Description

Retrieves the object's current PROGID.

DhObjectFactory.getValue

Syntax
public synchronized String getValue( String param );
Parameters
param
The name of the parameter.
Description

Retrieves the value of the parameter.

DhObjectFactory.removeOnAfterUpdate

Syntax
public final void removeOnAfterUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnBeforeUpdate

Syntax
public final void removeOnBeforeUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnDataAvailable

Syntax
public final void removeOnDataAvailable( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnDataSetChanged

Syntax
public final void removeOnDataSetChanged( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnDataSetComplete

Syntax
public final void removeOnDataSetComplete( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnError

Syntax
public final void removeOnError( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnErrorUpdate

Syntax
public final void removeOnErrorUpdate( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnReadyStateChange

Syntax
public final void removeOnReadyStateChange( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnRowEnter

Syntax
public final void removeOnRowEnter( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeOnRowExit

Syntax
public final void removeOnRowExit( DhEventHandler h );
Description

Topic under construction.

DhObjectFactory.removeParam

Syntax
public synchronized void removeParam( String param );
Parameters
param
The name of the parameter to remove.
Description

Removes a parameter from the list.

DhObjectFactory.setClassid

Syntax
public void setClassid( String classid );
Parameters
classid
The object's class identifier.
Description

Sets the object's current CLASSID.

DhObjectFactory.setClsid

Syntax
public void setClsid( _Guid guid );
Parameters
guid
The GUID representing the object.
Description

Sets the object's CLASSID.

DhObjectFactory.setCodeBase

Syntax
public void setCodeBase( String url );
Parameters
url
The object's code base.
Description

Sets the object's CODEBASE.

DhObjectFactory.setCodeClassName

Syntax
public void setCodeClassName( String className );
Parameters
className
The new object's class name.
Description

Sets the object's class name.

DhObjectFactory.setProgid

Syntax
public void setProgid( String progid );
Parameters
progid
The PROGID representing the object.
Description

Sets the object's PROGID.


 DhODBCTable Class

DhODBCTable Class

This Package | All Packages

DhTable
  |
  +--DhODBCTable
public class DhODBCTable
extends DhTable

Represents an HTML table that can be populated with data from any ODBC data source. This table works on the server or on the client.

Constructors
Name | Description
DhODBCTable() | Creates a DhODBCTable object.
DhODBCTable( String strConnection, String strSQL, dhRow repeaterRow ) | Creates a DhODBCTable object.

Methods
Name | Description
close() | Closes the record set and the connection to the data source.
execute( String strCommand ) | Runs the specified command string query on the database indicated by the connection string.
execute( String strCommand, int options ) | Runs the specified command string query on the database indicated by the connection string.
getAutoHeader( ) | Retrieves the current header generation mode.
getConnectionString() | Retrieves the connection string and query string that will be used to create the table.
getRangeEnd() | Retrieves the end of the current record range.
getRangeStart() | Retrieves the beginning of the current record range.
getSQL() | Retrieves the query string that will be used to create the table.
onColumnData( String strColName, String strColData, Object srcField ) | Retrieves column values for fields in the underlying data table.
open() | Connects to the data source and creates a new recordset.
setAutoHeader( boolean fAuto ) | Enables or disables automatic generation of column headings.
setConnectionString( String strConnection ) | Sets the connection string and query string that will be used to create the table.
setPageSize( int nPageSize ) | Sets the number of records to be displayed per page.
setRecordRange( int nStartRecord, int nEndRecord ) | Sets the range of records that will be displayed in the table.
setSQL( String strSQL, DhRow repeaterRow ) | Sets the query string that will be used to create the table.
showNextPage() | Displays the next page of data in the table.
showPreviousPage() | Displays the previous page of data in the table.

Constructors

DhODBCTable.DhODBCTable

Syntax 1
public DhODBCTable();
Description

Creates a DhODBCTable object. This is the default constructor.

Syntax 2
public DhODBCTable( String strConnection, String strSQL, dhRow repeaterRow );
Parameters
strConnection
The connection string in the form. "DSN=data source name;DATABASE=database;UID=user id;PWD=password"
strSQL
The SQL query to run.
repeaterRow
A row containing the data fields and format that you want repeated for each record.
Description

Creates a DhODBCTable object. This constructor inititalizes the connection string and query string that will be used to create the table.

Methods

DhODBCTable.close

Syntax
public void close();
Description

Closes the record set and the connection to the data source.

See Also
open

DhODBCTable.execute

Syntax 1
public boolean execute( String strCommand );
Parameters
strCommand
The command string.
Return Value

Returns true if the command was successful; otherwise, returns false.

Description

Runs the specified command string query on the database indicated by the connection string.

See Also
setConnectionString

Syntax 2
public boolean execute( String strCommand, int options );
Parameters
strCommand
The command string.
options
The context of strCommand, which can be one of the following:
  • 1 - strCommand is a textual command.
  • 2 - strCommand is a table name.
  • 4 - strCommand is a call to a stored procedure.
  • 8 - strCommand is of an unknown type (default).

.

Return Value

Returns true if the command was successful; otherwise, returns false.

Description

Runs the specified command string query on the database indicated by the connection string.

See Also
setConnectionString

DhODBCTable.getAutoHeader

Syntax
public boolean getAutoHeader( );
Return Value

Returns true if a header row will be created; otherwise, returns false.

Description

Retrieves the current header generation mode.

See Also
setAutoHeader

DhODBCTable.getConnectionString

Syntax
public String getConnectionString();
Return Value

Returns the connection string.

Description

Retrieves the connection string and query string that will be used to create the table.

See Also
setConnectionString

DhODBCTable.getRangeEnd

Syntax
public int getRangeEnd();
Return Value

Returns the end of the record range. The default is -1, indicating records will be displayed until the end of the recordset.

Description

Retrieves the end of the current record range.

See Also
setRecordRange

DhODBCTable.getRangeStart

Syntax
public int getRangeStart();
Return Value

Returns the beginning of the record range. The default is 0.

Description

Retrieves the beginning of the current record range.

See Also
setRecordRange

DhODBCTable.getSQL

Syntax
public String getSQL();
Return Value

Returns the SQL query string to retrieve the data.

Description

Retrieves the query string that will be used to create the table.

DhODBCTable.onColumnData

Syntax
public String onColumnData( String strColName, String strColData, Object srcField );
Parameters
strColName
The column name.
strColData
The default string representation of the column data.
srcField
A reference to the underlying com.ms.ado.Field object.
Return Value

Returns the desired field string value.

Description

Retrieves column values for fields in the underlying data table. This method will be called by the framework on each field value. Returns the string representation you want to be displayed for that field, or strColData to use the default. You can override this method to provide special handling of column values.

DhODBCTable.open

Syntax
public boolean open();
Return Value

Returns true if the recordset was created successfully; otherwise, returns false.

Description

Connects to the data source and creates a new recordset.

DhODBCTable.setAutoHeader

Syntax
public void setAutoHeader( boolean fAuto );
Parameters
fAuto
Set to true to generate header rows; set to false to disable automatic generation.
Description

Enables or disables automatic generation of column headings. If enabled, a heading row with the column names is automatically added to the table when it is generated.

DhODBCTable.setConnectionString

Syntax
public void setConnectionString( String strConnection );
Parameters
strConnection
The connection string in the form "DSN=data source name;DATABASE=database;UID=user id;PWD=password".
Description

Sets the connection string and query string that will be used to create the table.

DhODBCTable.setPageSize

Syntax
public void setPageSize( int nPageSize );
Parameters
nPageSize
The number of records to display per page.
Description

Sets the number of records to be displayed per page.

See Also
showNextPage, showPreviousPage

DhODBCTable.setRecordRange

Syntax
public void setRecordRange( int nStartRecord, int nEndRecord );
Parameters
nStartRecord
The first record to display.
nEndRecord
The last record to display.
Description

Sets the range of records that will be displayed in the table. These numbers reflect absolute, zero-based record positions.

DhODBCTable.setSQL

Syntax
public void setSQL( String strSQL, DhRow repeaterRow );
Parameters
strQuery
The SQL query string to retrieve the data.
repeaterRow
A row containing the data fields and format that you want repeated for each record.
Description

Sets the query string that will be used to create the table. If the requested query is different from the current query and a connection is open, the new query is run immediately.

DhODBCTable.showNextPage

Syntax
public void showNextPage();
Description

Displays the next page of data in the table. This method updates the record range start and end properties.

See Also
setPageSize, setRecordRange

DhODBCTable.showPreviousPage

Syntax
public void showPreviousPage();
Description

Displays the previous page of data in the table. This method updates the record range start and end properties.

See Also
setPageSize, setRecordRange


 DhPaddingEnum Class

DhPaddingEnum Class

This Package | All Packages

Enum
  |
  +--DhPaddingEnum
public class DhPaddingEnum
extends wfc.cor.Enum

Provides constant definitions for padding style manipulation.

Fields
Name | Description
PADDING_SIDE_ALL | Specifies a combination of all PADDING_SIDE_ items. This is equivalent to (PADDING_SIDE_TOP | PADDING_SIDE_RIGHT | PADDING_SIDE_BOTTOM | PADDING_SIDE_LEFT)
PADDING_SIDE_BOTTOM | Specifies bottom padding.
PADDING_SIDE_LEFT | Specifies left padding.
PADDING_SIDE_RIGHT | Specifies right padding.
PADDING_SIDE_TOP | Specifies top padding.

Fields

DhPaddingEnum.PADDING_SIDE_ALL

Syntax
public static final int PADDING_SIDE_ALL;
Description
Specifies a combination of all PADDING_SIDE_ items.
This is equivalent to (PADDING_SIDE_TOP | PADDING_SIDE_RIGHT | PADDING_SIDE_BOTTOM | PADDING_SIDE_LEFT)

DhPaddingEnum.PADDING_SIDE_BOTTOM

Syntax
public static final int PADDING_SIDE_BOTTOM;
Description
Specifies bottom padding.

DhPaddingEnum.PADDING_SIDE_LEFT

Syntax
public static final int PADDING_SIDE_LEFT;
Description
Specifies left padding.

DhPaddingEnum.PADDING_SIDE_RIGHT

Syntax
public static final int PADDING_SIDE_RIGHT;
Description
Specifies right padding.

DhPaddingEnum.PADDING_SIDE_TOP

Syntax
public static final int PADDING_SIDE_TOP;
Description
Specifies top padding.


 DhPaddingWidthInfo Class

DhPaddingWidthInfo Class

This Package | All Packages

public class DhPaddingWidthInfo

Provides information about an element's padding width settings.

Fields
Name | Description
bottomUnit | Specifies the bottom padding width unit.
bottomWidth | Specifies the bottom padding width.
leftUnit | Specifies the left padding width unit.
leftWidth | Specifies the left padding width.
rightUnit | Specifies the right padding width unit.
rightWidth | Specifies the right padding width.
topUnit | Specifies the top padding width unit.
topWidth | Specifies the top padding width.

Constructors
Name | Description
DhPaddingWidthInfo() | Constructs a DhPaddingWidthInfo object.
DhPaddingWidthInfo( DhPaddingWidthInfo mwi ) | Constructs a DhPaddingWidthInfo object.

Fields

DhPaddingWidthInfo.bottomUnit

Syntax
public int bottomUnit;
Description
Specifies the bottom padding width unit.

DhPaddingWidthInfo.bottomWidth

Syntax
public int bottomWidth;
Description
Specifies the bottom padding width.

DhPaddingWidthInfo.leftUnit

Syntax
public int leftUnit;
Description
Specifies the left padding width unit.

DhPaddingWidthInfo.leftWidth

Syntax
public int leftWidth;
Description
Specifies the left padding width.

DhPaddingWidthInfo.rightUnit

Syntax
public int rightUnit;
Description
Specifies the right padding width unit.

DhPaddingWidthInfo.rightWidth

Syntax
public int rightWidth;
Description
Specifies the right padding width.

DhPaddingWidthInfo.topUnit

Syntax
public int topUnit;
Description
Specifies the top padding width unit.

DhPaddingWidthInfo.topWidth

Syntax
public int topWidth;
Description
Specifies the top padding width.

Constructors

DhPaddingWidthInfo.DhPaddingWidthInfo

Syntax 1
public DhPaddingWidthInfo();
Description

Constructs a DhPaddingWidthInfo object.

Syntax 2
public DhPaddingWidthInfo( DhPaddingWidthInfo mwi );
Description

Constructs a DhPaddingWidthInfo object. This constructor initializes values from an existing DhPaddingWidthInfo object.


 DhPanel Class

DhPanel Class

This Package | All Packages

DhSection
  |
  +--DhPanel
public class DhPanel
extends DhSection

Represents a container for elements that uses tradition graphical user interface two-dimensional positioning for layout. Elements that are added into this kind of container are positioned in x-y coordinates as opposed to HTML one-dimentional flow layout. Elements can (and do) sit on top of each other in a z-order (or layered) manner. For a version of this container that is not based on x-y positioning, see DhSection.

Constructors
Name | Description
DhPanel() | Creates the DhPanel container.
DhPanel( Point size ) | Creates the DhPanel container.
DhPanel( int width, int height ) | Creates the DhPanel container.
DhPanel( Rectangle bounds ) | Creates the DhPanel container.

Methods
Name | Description
add(DhElement element, DhElement relativeTo, int insertFlag) | Adds an element into this container in a specific place in the z-order.
getAllElements() | Recursively returns all child elements and their children.
getElements() | Retrieves the child elements of this element.

Constructors

DhPanel.DhPanel

Syntax 1
public DhPanel();
Description

Creates the DhPanel container.

Syntax 2
public DhPanel( Point size );
Parameters
size
The initial size of the container.
Description

Creates the DhPanel container. This constructor creates a panel container of a specified size based on a Point object.

Syntax 3
public DhPanel( int width, int height );
Parameters
width
The initial width of the container.
height
The initial height of the container.
Description

Creates the DhPanel container. This constructor creates a panel container of a specified size based on height and width.

Syntax 4
public DhPanel( Rectangle bounds );
Parameters
bounds
The initial location and size of the container.
Description

Creates the DhPanel container. This constructor creates a panel container of a specified size and location.

Methods

DhPanel.add

Syntax
public synchronized void add( DhElement element, DhElement relativeTo, int insertFlag );
Parameters
element
The DhElement to add to this container.
relativeTo
The DhElement referred to when using the INSERT_BEFORE or INSERT_AFTER constants for the insertFlag parameter.
insertFlag
One of the valid and applicable DhInsertEnum insert constants. The valid values for insertFlag are:
  • INSERT_END, element will be on top of all other elements in this panel. The relativeTo paramater must be null.
  • INSERT_BEGINNING, element will be behind all other elements in this panel. The relativeTo paramater must be null.
  • INSERT_BEFORE, element will be behind the relativeTo parameter. The relativeTo paramater must not be null.
  • INSERT_AFTER, element will be on top of the relativeTo parameter. The relativeTo paramater must not be null.
Description

Adds an element into this container in a specific place in the z-order. The order depends on the insertFlag parameter.

You can also call add and then move setZIndex.

Elements are added with a default size and position. Therefore, you should always call element.setBounds to perform a visual cleanup.

DhPanel.getAllElements

Syntax
public DhElement[] getAllElements();
Return Value

Returns an array of all child elements.

Description

Recursively returns all child elements and their children.

DhPanel.getElements

Syntax
public DhElement[] getElements();
Return Value

Returns an array of direct child elements.

Description

Retrieves the child elements of this element.


 DhPropertyBag Class

DhPropertyBag Class

This Package | All Packages

public class DhPropertyBag

Retrieves values in the <PARAM> attributes of the module's HTML tags. You never actually create this class; instead, an instance of this class is passed along to DhModule.LoadParameters.

Methods
Name | Description
getInt(String name) | Retrieves the NAME parameter of a PARAM tag given the VALUE parameter.
getString(String name) | Retrieves the VALUE parameter of a PARAM tag given the NAME parameter.

Methods

DhPropertyBag.getInt

Syntax
public int getInt( String name );
Parameters
name
The NAME parameter of the PARAM tag.
Return Value

Returns the corresponding numeric VALUE part of the same PARAM tag.

Description

Retrieves the NAME parameter of a PARAM tag given the VALUE parameter. For example, for the construct <PARAM NAME=fee VALUE=33>, this method retrieves the 33 when getInt("fee") is called.

DhPropertyBag.getString

Syntax
public String getString( String name );
Parameters
name
The NAME parameter of the PARAM tag.
Return Value

Returns the corresponding VALUE part of the same PARAM tag.

Description

Retrieves the VALUE parameter of a PARAM tag given the NAME parameter. For example, for the construct <PARAM NAME=foo VALUE=bar>, this method retrieves the "bar" when getString("foo") is called.


 DhRadioButton Class

DhRadioButton Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhRadioButton
public class DhRadioButton
extends DhBaseContainer

Represents the radio button HTML-intrinsic control with a text label. Radio button groups allow for mutually exclusive choices from a list of options.

Constructors
Name | Description
DhRadioButton() | Creates a DhRadioButton object.
DhRadioButton( String strText, boolean fChecked ) | Creates a DhRadioButton object.

Methods
Name | Description
addEventHandler( DhEventID id, DhEventHandler handler ) | Topic under construction.
getEnabled() | Retrieves the enabled state of the button.
getName( ) | Retrieves the name of the button.
getSubmitName( ) | Retrieves the submit name for this DhRadioButton.
getSubmitValue( ) | Retrieves the submit value for this DhRadioButton.
getText( ) | Retrieves the current text label for the radio button.
getTextAlignment() | Retrieves the current alignment.
setChecked( boolean fValue ) | Sets the selected state of the radio button.
setEnabled( boolean f) | Sets the enabled state of the button.
setFocus() | Sets the input focus to this control.
setName( String n ) | Sets the name of the button.
setSubmitName( String strName ) | Sets the group name/submit name for this radio button.
setSubmitValue( String strValue ) | Sets the submit value for this radio button.
setText( String strText ) | Sets the text label of the button.
setTextAlignment( int newAlignment ) | Sets the current alignment.
setValue() | Retrieves the current selected state of the DhRadioButton.

Constructors

DhRadioButton.DhRadioButton

Syntax 1
public DhRadioButton();
Description

Creates a DhRadioButton object. The default constructor creates a blank DhRadioButton with no check or text label. You set the values to initialize them.

Syntax 2
public DhRadioButton( String strText, boolean fChecked );
Parameters
strText
The label text to display with the button.
fChecked
The initial selected state of the button.
Description

Creates a DhRadioButton object. This constructor creates a radio button with right-aligned text (DhAlignEnum.TEXT_RIGHT).

Methods

DhRadioButton.addEventHandler

Syntax
public void addEventHandler( DhEventID id, DhEventHandler handler );
Description

Topic under construction.

DhRadioButton.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns true if the button is enabled; returns false if it is not.

Description

Retrieves the enabled state of the button.

DhRadioButton.getName

Syntax
public String getName( );
Return Value

Returns the button name.

Description

Retrieves the name of the button.

DhRadioButton.getSubmitName

Syntax
public String getSubmitName( );
Return Value

Returns the group name.

Description

Retrieves the submit name for this DhRadioButton. The submit name designates which groups of radio buttons are connected. Only one DhRadioButton in a group can be selected at a time.

See Also
setSubmitName

DhRadioButton.getSubmitValue

Syntax
public String getSubmitValue( );
Return Value

Returns the group name.

Description

Retrieves the submit value for this DhRadioButton.

See Also
setSubmitValue

DhRadioButton.getText

Syntax
public String getText( );
Return Value

Returns the text label.

Description

Retrieves the current text label for the radio button.

DhRadioButton.getTextAlignment

Syntax
public synchronized int getTextAlignment();
Return Value

Returns the current alignment.

Description

Retrieves the current alignment. Can be right-aligned (DhAlignEnum.TEXT_RIGHT) or left-aligned (DhAlignEnum.TEXT_LEFT).

DhRadioButton.setChecked

Syntax
public void setChecked( boolean fValue );
Parameters
fValue
Set to true to select the radio button; set to false to clear it.
Description

Sets the selected state of the radio button. If this button is bound and is a member of a group, setting its value can affect other DhRadioButton items in the group.

See Also
setSubmitName, getSubmitName

DhRadioButton.setEnabled

Syntax
public void setEnabled( boolean f );
Parameters
f
Set to true to enable the button; set to false disabled it.
Description

Sets the enabled state of the button.

DhRadioButton.setFocus

Syntax
public void setFocus();
Description

Sets the input focus to this control.

DhRadioButton.setName

Syntax
public void setName( String n );
Description

Sets the name of the button.

DhRadioButton.setSubmitName

Syntax
public void setSubmitName( String strName );
Parameters
strName
The group name. Group names must be unique in each document.
Description

Sets the group name/submit name for this radio button. DhRadioButtons within the same group are mutally exclusive, that is, only one can be selected at a given time. Additionally, group names are used for HTTP form submission.

DhRadioButton.setSubmitValue

Syntax
public void setSubmitValue( String strValue );
Parameters
strName
The group name. Group names must be unique in each document.
Description

Sets the submit value for this radio button. DhRadioButtons within the same group are mutally exclusive, that is, only one can be selected at a given time. The selected item's value is transmitted in the HTTP submit string as [SubmitName]=[SubmitValue]

DhRadioButton.setText

Syntax
public void setText( String strText );
Parameters
strText
The text label of the button.
Description

Sets the text label of the button.

DhRadioButton.setTextAlignment

Syntax
public synchronized void setTextAlignment( int newAlignment );
Parameters
newAlignment
This can be DhAlignEnum.TEXT_LEFT or DhAlignEnum.TEXT_RIGHT.
Description

Sets the current alignment.

DhRadioButton.setValue

Syntax
public boolean setValue();
Return Value

Returns true if the button is selected; otherwise, returns false.

Description

Retrieves the current selected state of the DhRadioButton.


 DhRawHTML Class

DhRawHTML Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhRawHTML
public class DhRawHTML
extends DhElement

Allows output of arbitrary raw HTML to the document.

Constructors
Name | Description
DhRawHTML() | Constructs a DhRawHTML object.
DhRawHTML( String html ) | Constructs a DhRawHTML object.

Methods
Name | Description
getHTML() | Retrieves the current HTML string.
setHTML( String html ) | Sets the HTML string to output to the document.

Constructors

DhRawHTML.DhRawHTML

Syntax 1
public DhRawHTML();
Description

Constructs a DhRawHTML object.

Syntax 2
public DhRawHTML( String html );
Parameters
html
The initial HTML string.
Description

Constructs a DhRawHTML object. This is a one-step construction that takes an HTML string.

See Also
setHTML

Methods

DhRawHTML.getHTML

Syntax
public synchronized String getHTML();
Return Value

Returns the HTML string, or null if one is not set.

Description

Retrieves the current HTML string.

DhRawHTML.setHTML

Syntax
public synchronized void setHTML( String html );
Parameters
html
The string to output.
Description

Sets the HTML string to output to the document.


 DhRemoteDataSource Class

DhRemoteDataSource Class

This Package | All Packages

DhObjectFactory
  |
  +--DhObjectDataSource
    |
    +--DhRemoteDataSource
public class DhRemoteDataSource
extends DhObjectDataSource

Encapsulates the Microsoft Remote Data Service (formerly ADC) control, which allows access to database information across an HTTP connection.

Constructors
Name | Description
DhRemoteDataSource() | Creates a DhRemoteDataSource object.
DhRemoteDataSource( String strConnection, String strServer, String strSQL ) | Creates a DhRemoteDataSource object.

Methods
Name | Description
cancel() | Cancels the current data-retrieval operation.
getConnectionString( ) | Retrieves the current connection string (for example, "DSN=AdvWorks;") for this data source object.
getServer( ) | Retrieves the currently set server name for this data source object.
getSortDirection( ) | Retrieves the current sort direction.
getSortField( ) | Retrieves the name of the currently sorted column.
getSQL() | Retrieves the currently set SQL query string.
refresh() | Refreshes the data source with new settings, such as a connection string or a SQL query.
setConnectionString( String strConn ) | Sets the connection string (for example, "DSN=AdvWorks;") for this data source object.
setServer( String strServer ) | Sets the HTTP server to query for database information.
setSortDirection( boolean fAscending ) | Sets the sort direction.
setSortField( String strSortField ) | Sets the field for sorting data.
setSQL( String strSQL ) | Sets the SQL query for this object and refreshes, if necessary.
submitChanges() | Gathers and submits any data changes made to bound controls.

Constructors

DhRemoteDataSource.DhRemoteDataSource

Syntax 1
public DhRemoteDataSource();
Description

Creates a DhRemoteDataSource object.

Syntax 2
public DhRemoteDataSource( String strConnection, String strServer, String strSQL );
Parameters
strConnection
The connection string (for example, "DSN=AdvWorks" ).
strServer
The server running the database (for example, http://dbserver).
strSQL
The SQL query to generate results (for example, "SELECT * FROM Products").
Description

Creates a DhRemoteDataSource object. This is a one-step construction with the connection string, server, and SQL query for the connection.

Methods

DhRemoteDataSource.cancel

Syntax
public void cancel();
Description

Cancels the current data-retrieval operation.

DhRemoteDataSource.getConnectionString

Syntax
public String getConnectionString( );
Return Value

Returns the current connection string.

Description

Retrieves the current connection string (for example, "DSN=AdvWorks;") for this data source object.

See Also
setConnectionString

DhRemoteDataSource.getServer

Syntax
public String getServer( );
Return Value

Returns the name of the current server.

Description

Retrieves the currently set server name for this data source object.

See Also
setServer

DhRemoteDataSource.getSortDirection

Syntax
public boolean getSortDirection( );
Return Value

Returns true if the sort direction is ascending, or returns false if it is descending.

Description

Retrieves the current sort direction.

See Also
setSortField

DhRemoteDataSource.getSortField

Syntax
public String getSortField( );
Return Value

Returns the currently sorted column name.

Description

Retrieves the name of the currently sorted column.

DhRemoteDataSource.getSQL

Syntax
public String getSQL();
Return Value

Returns the query String.

Description

Retrieves the currently set SQL query string.

DhRemoteDataSource.refresh

Syntax
public void refresh();
Description

Refreshes the data source with new settings, such as a connection string or a SQL query.

DhRemoteDataSource.setConnectionString

Syntax
public void setConnectionString( String strConn );
Parameters
strConn
The new connection string.
Description

Sets the connection string (for example, "DSN=AdvWorks;") for this data source object.

See Also
getConnectionString

DhRemoteDataSource.setServer

Syntax
public void setServer( String strServer );
Parameters
strServer
The server name (for example, "http://dbserver").
Description

Sets the HTTP server to query for database information.

DhRemoteDataSource.setSortDirection

Syntax
public void setSortDirection( boolean fAscending );
Parameters
fAscending
Set to true if the sort direction is ascending; set to false if it is descending.
Description

Sets the sort direction.

See Also
setSortField

DhRemoteDataSource.setSortField

Syntax
public void setSortField( String strSortField );
Parameters
strSortField
The name of the field to sort.
Description

Sets the field for sorting data.

DhRemoteDataSource.setSQL

Syntax
public void setSQL( String strSQL );
Parameters
strSQL
The desired SQL string.
Description

Sets the SQL query for this object and refreshes, if necessary.

DhRemoteDataSource.submitChanges

Syntax
public void submitChanges();
Description

Gathers and submits any data changes made to bound controls.


 DhResetButton Class

DhResetButton Class

This Package | All Packages

DhElement
  |
  +--DhButtonBase
    |
    +--DhResetButton
public class DhResetButton
extends DhButtonBase

Represents a reset button for an HTML form. This button resets the state of all controls on the form to their initial values.

Adding a DhResetButton to a DhSection object causes the DhSection to represent an HTML form element.

Also see wfc.html.DhSection

Constructors
Name | Description
DhResetButton() | Creates a DhResetButton object.
DhResetButton( String caption ) | Creates a DhResetButton object.

Methods
Name | Description
getText() | Retrieves the button's current text caption.
setText( String strCaption ) | Sets the button caption.

Constructors

DhResetButton.DhResetButton

Syntax 1
public DhResetButton();
Description

Creates a DhResetButton object. This default constructor creates a reset button with the caption "Reset".

Syntax 2
public DhResetButton( String caption );
Parameters
caption
The caption for the new reset button.
Description

Creates a DhResetButton object. This constructor creates a reset button with a specified caption.

Methods

DhResetButton.getText

Syntax
public String getText();
Return Value

Returns the button caption.

Description

Retrieves the button's current text caption.

Overrides

getText() in DhButtonBase.

DhResetButton.setText

Syntax
public void setText( String strCaption );
Parameters
strCaption
The new caption string.
Description

Sets the button caption.

Overrides

setText(String) in DhButtonBase.


 DhRow Class

DhRow Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhRow
public class DhRow
extends DhBaseContainer

Creates a table row.

Constructors
Name | Description
DhRow() | Creates a DhRow object.

Methods
Name | Description
add(DhCell cell) | Adds a cell to end of this row.
getCell( int nCol ) | Topic under construction.
getColumnCount() | Topic under construction.
getDataField( ) | Topic under construction.
getRecordNumber() | Topic under construction.
setDataField( String strDataField ) | Topic under construction.

Constructors

DhRow.DhRow

Syntax
public DhRow();
Description

Creates a DhRow object. This constructor creates an empty row.

Methods

DhRow.add

Syntax
public void add( DhCell cell );
Parameters
cell
The cell to add to this row.
Description

Adds a cell to end of this row.

DhRow.getCell

Syntax
public DhCell getCell( int nCol );
Description

Topic under construction.

DhRow.getColumnCount

Syntax
public int getColumnCount();
Description

Topic under construction.

DhRow.getDataField

Syntax
public String getDataField( );
Description

Topic under construction.

DhRow.getRecordNumber

Syntax
public int getRecordNumber();
Description

Topic under construction.

DhRow.setDataField

Syntax
public void setDataField( String strDataField );
Description

Topic under construction.


 DhSection Class

DhSection Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhSection
public class DhSection
extends DhBaseContainer
implements DhIFilterableObject

Represents an element container that uses traditional HTML one-dimensional flow layout. Elements that are added into this kind of container cannot be positioned in x-y coordinates but rather "flow" around each other. For a version of this container that is based on x-y positioning, see DhPanel.

Constructors
Name | Description
DhSection() | Creates a DhSection section container.

Methods
Name | Description
add(DhElement element) | Adds an element into this container, following all other elements.
add(DhElement element, int insertFlag ) | Adds an element either at the beginning or at the end of this container, depending on the DhInsertEnum value in the insertFlag parameter.
add(DhElement element, DhElement relativeTo, int insertFlag) | Adds an element either at the beginning or end of this container, or before or after another element, depending on the insertFlag parameter.
addFilter(DhFilter filter) | Adds a filter to this element and applies it immediately.
addFilter(DhFilter filter, boolean bApply) | Adds a filter to this element.
addFilter(DhFilter filter, boolean bApply, boolean bFlush) | Adds a filter to this element.
addOnFormReset( DhEventHandler h ) | Topic under construction.
addOnHTTPSubmit( DhEventHandler h ) | Topic under construction.
addText( String text ) | Appends a text string to the current section.
addTransition(DhFilter trans) | Adds a transition effect to this element.
applyFilters() | Applies filters that were previously deferred.
findElement(String id) | Topic under construction.
findFilter(Class filterClass) | Retrieves the current filter with the specified filter class.
getAsForm( ) | Retrieves the current FORM/DIV state.
getMatchingChildElements( String strQuery, boolean fRecursive ) | Topic under construction.
moveElement( DhElement element, int newOrder ) | Moves an element to a new numeric order in the flow.
newLine() | Appends a new line to the current section.
remove(DhElement element) | Removes an element from this container.
removeAll() | Removes all child elements from this container.
removeAllFilters() | Removes all filters from this element automatically.
removeAllFilters(boolean bApply) | Removes all filters from this element.
removeFilter(DhFilter filter) | Removes the specified filter from this element.
removeFilter(DhFilter filter, boolean bApply) | Removes the specified filter from this element.
removeOnFormReset( DhEventHandler h ) | Topic under construction.
removeOnHTTPSubmit( DhEventHandler h ) | Topic under construction.
replaceFilter(DhFilter filter1, DhFilter filter2) | Provides an easy way to swap filters.
replaceFilter(DhFilter filter1, DhFilter filter2, boolean bApply) | Replaces filters currently applied to the document.
setAsForm( boolean fAsForm ) | Forces this DhSection to produce an HTML FORM or DIV section.
setHTMLGenerator( DhHTMLGenerator htmlGen ) | Topic under construction.

Constructors

DhSection.DhSection

Syntax
public DhSection();
Description

Creates a DhSection section container.

Methods

DhSection.add

Syntax 1
public void add( DhElement element );
Parameters
element
The DhElement to add to the end of the flow of this container.
Description

Adds an element into this container, following all other elements.

Syntax 2
public void add( DhElement element, int insertFlag );
Parameters
element
The DhElement to add to this container.
insertFlag
One of the valid and applicable DhInsertEnum insert constants. The valid values are:
  • INSERT_END
  • INSERT_BEGINNING
Description

Adds an element either at the beginning or at the end of this container, depending on the DhInsertEnum value in the insertFlag parameter.

Syntax 3
public void add( DhElement element, DhElement relativeTo, int insertFlag );
Parameters
element
The DhElement object to add to this container.
relativeTo
The DhElement object referred to when using the INSERT_BEFORE or INSERT_AFTER constants for the insertFlag parameter.
insertFlag
One of the valid and applicable DhInsertEnum insert constants. The valid values for insertFlag are:
  • INSERT_END inserts into the end of the flow or into this container. The relativeTo parameter must be null.
  • INSERT_BEGINNING inserts into the beginning of the flow or this container. The relativeTo parameter must be null.
  • INSERT_BEFORE inserts before the element referred to by the relativeTo parameter. The relativeTo parameter must not be null.
  • INSERT_AFTER insert after the element referred to by the relativeTo parameter. The relativeTo parameter must not be null.
Description

Adds an element either at the beginning or end of this container, or before or after another element, depending on the insertFlag parameter.

DhSection.addFilter

Syntax 1
public void addFilter( DhFilter filter );
Parameters
filter
The DhFilter object to apply.
Description

Adds a filter to this element and applies it immediately. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException Thrown if this type of filter already exists on this element.

Syntax 2
public void addFilter( DhFilter filter, boolean bApply );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay applying the filter.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

Syntax 3
public void addFilter( DhFilter filter, boolean bApply, boolean bFlush );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay applying the filter.
bFlush
Set to true to flush the previously applied filters; set to false to combine filter with those already present.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. You can also specify whether to flush filters that were previously applied to this element or combine this filter with those already present.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

DhSection.addOnFormReset

Syntax
public void addOnFormReset( DhEventHandler h );
Description

Topic under construction.

DhSection.addOnHTTPSubmit

Syntax
public void addOnHTTPSubmit( DhEventHandler h );
Description

Topic under construction.

DhSection.addText

Syntax
public void addText( String text );
Parameters
text
The text string.
Description

Appends a text string to the current section.

DhSection.addTransition

Syntax
public void addTransition( DhFilter trans );
Parameters
trans
The transition effect you will run.
Description

Adds a transition effect to this element. You must call this method before you can run the effect. Note that this functionality is provided for extension only (see the sample classes). This package does provide transition effects.

Exceptions

wfc.html.DhCantAddElementException Thrown if this type of transition effect already exists on this element.

See Also
replaceFilter

DhSection.applyFilters

Syntax
public void applyFilters();
Description

Applies filters that were previously deferred. Use this method if you called addFilter(DhFilter,boolean) with false for the second paramater. This function applies every filter that was added to this element.

See Also
addFilter(DhFilter,boolean), addFilter

DhSection.findElement

Syntax
public DhElement findElement( String id );
Description

Topic under construction.

DhSection.findFilter

Syntax
public DhFilter findFilter( Class filterClass );
Parameters
filterClass
The class of the filter you are looking for, for example, wfc.html.DhDropShadowFilter.
Return Value

Returns the DhFilter (if found) that is of type filterClass.

Description

Retrieves the current filter with the specified filter class.

DhSection.getAsForm

Syntax
public synchronized boolean getAsForm( );
Return Value

Returns true if set to FORM, or returns false if set to DIV.

Description

Retrieves the current FORM/DIV state. The FORM state can be set by using setAsForm or adding a DhSubmitButton into the DhSection.

See Also
setAsForm

DhSection.getMatchingChildElements

Syntax
public IEnumerator getMatchingChildElements( String strQuery, boolean fRecursive );
Description

Topic under construction.

Overrides

getMatchingChildElements(String,boolean) in DhBaseContainer.

DhSection.moveElement

Syntax
public void moveElement( DhElement element, int newOrder );
Parameters
element
The DhElement to move.
newOrder
The new numeric order in the flow of this container.
Description

Moves an element to a new numeric order in the flow.

DhSection.newLine

Syntax
public void newLine();
Description

Appends a new line to the current section. All elements added after this call will be on a new line.

DhSection.remove

Syntax
public int remove( DhElement element );
Parameters
element
The DhElement to remove from this container.
Return Value

Returns topic under construction.

Description

Removes an element from this container. If the element was visible prior to this call, it will not be visible after the call.

DhSection.removeAll

Syntax
public void removeAll();
Description

Removes all child elements from this container. These elements would no longer be visible if they were added prior to this call.

DhSection.removeAllFilters

Syntax 1
public void removeAllFilters();
Description

Removes all filters from this element automatically.

Syntax 2
public void removeAllFilters( boolean bApply );
Description

Removes all filters from this element. You can clear all filters on this element or delay removal.

DhSection.removeFilter

Syntax 1
public void removeFilter( DhFilter filter );
Parameters
filter
A reference to the filter to remove.
Description

Removes the specified filter from this element. This method automatically reapplies filters that may be left after this method is called.

See Also
findFilter.

Syntax 2
public void removeFilter( DhFilter filter, boolean bApply );
Parameters
filter
A reference to the filter to remove.
bApply
Set to true to reapply other filters left on this element; set to false to delay reapplying the filters.
Description

Removes the specified filter from this element. You can reapply filters that may be left after this method is called, or you can delay reapplying filters if you are removing more than one filter.

See Also
findFilter.

DhSection.removeOnFormReset

Syntax
public void removeOnFormReset( DhEventHandler h );
Description

Topic under construction.

DhSection.removeOnHTTPSubmit

Syntax
public void removeOnHTTPSubmit( DhEventHandler h );
Description

Topic under construction.

DhSection.replaceFilter

Syntax 1
public void replaceFilter( DhFilter filter1, DhFilter filter2 );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1.
Description

Provides an easy way to swap filters. It automatically applies all the changes immediately.

Syntax 2
public void replaceFilter( DhFilter filter1, DhFilter filter2, boolean bApply );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
bApply
Set to true to apply visual changes now; set to false to delay making changes.
Description

Replaces filters currently applied to the document. This method provides an easy way to swap filters. You can specify whether to apply all the changes immediately or to delay making changes until later.

See Also
applyFilters

DhSection.setAsForm

Syntax
public synchronized void setAsForm( boolean fAsForm );
Parameters
fAsForm
Set to true to set as FORM; set to false to set as DIV.
Description

Forces this DhSection to produce an HTML FORM or DIV section.

DhSection.setHTMLGenerator

Syntax
public synchronized void setHTMLGenerator( DhHTMLGenerator htmlGen );
Description

Topic under construction.

Overrides

setHTMLGenerator(DhHTMLGenerator) in DhBaseContainer.


 DhStyle Class

DhStyle Class

This Package | All Packages

DhStyleBase
  |
  +--DhStyle
public class DhStyle
extends DhStyleBase
implements DhIFilterableObject

Topic under construction.

Constructors
Name | Description
DhStyle(String name) | Creates a DhStyle object.
DhStyle() | Creates a DhStyle object.

Methods
Name | Description
addFilter(DhFilter filter) | Topic under construction.
addFilter(DhFilter filter, boolean bApply) | Adds a filter to this element.
addFilter(DhFilter filter, boolean bApply, boolean bFlush) | Adds a filter to this element.
addTransition(DhFilter trans) | Adds a transition effect to this element.
applyFilters() | Applies a delayed filter.
findFilter(Class filterClass) | Retrieves the current filter with the specified filter class.
getName() | Retrieves the underlying name for this style object as seen by the HTML object.
removeAllFilters() | Removes all filters from this element.
removeAllFilters(boolean bApply) | Removes all filters from this element.
removeFilter(DhFilter filter) | Removes the specified filter from this element.
removeFilter(DhFilter filter, boolean bApply) | Removes the specified filter from this element.
replaceFilter(DhFilter filter1, DhFilter filter2) | Replaces a specified filter with another filter.
replaceFilter(DhFilter filter1, DhFilter filter2, boolean bApply) | Replaces a specified filter with another filter.
setName(String name) | Sets the underlying name for the style object as seen by the HTML object.

Constructors

DhStyle.DhStyle

Syntax 1
public DhStyle( String name );
Parameters
name
Name of style to use for underlying HTML generation.
Description

Creates a DhStyle object. This constructor allows you to name your style and control the underlying HTML code that is generated by this object. Note, however, that this is completely handled for you in the default (empty) constructor.

See Also
DhStyle()

Syntax 2
public DhStyle();
Description

Creates a DhStyle object. Use this constructor to create the default style object.

Methods

DhStyle.addFilter

Syntax 1
public void addFilter( DhFilter filter );
Description

Topic under construction.

Syntax 2
public void addFilter( DhFilter filter, boolean bApply );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay the application of the filter.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException t6hrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

Syntax 3
public void addFilter( DhFilter filter, boolean bApply, boolean bFlush );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter directly; set to false to delay the application of the filter.
bFlush
Set to true to flush the previously applied filters; set to false to combine filter with those already present.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. You can also specify whether to flush filters that were previously applied to this element or combine this filter with those already present.

Exceptions

wfc.html.DhCantAddElementException Thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

DhStyle.addTransition

Syntax
public void addTransition( DhFilter trans );
Parameters
trans
The transition effect you will run.
Description

Adds a transition effect to this element. You must call this method before you can run the effect. Note that this functionality is provided for extension only (see the sample classes). This package does provide transition effects.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of transition effect already exists on this element.

See Also
replaceFilter

DhStyle.applyFilters

Syntax
public void applyFilters();
Description

Applies a delayed filter. Use this method if you called addFilter(DhFilter,boolean) with false for the second parameter. This function applies every filter that was added to this element.

See Also
addFilter

DhStyle.findFilter

Syntax
public DhFilter findFilter( Class filterClass );
Parameters
filterClass
The class of the filter you are looking for, for example, wfc.html.DhDropShadowFilter.
Return Value

Returns the DhFilter (if found) that is of type filterClass.

Description

Retrieves the current filter with the specified filter class.

DhStyle.getName

Syntax
public synchronized String getName();
Return Value

Returns the string name of the style rule.

Description

Retrieves the underlying name for this style object as seen by the HTML object. This is an advanced feature and is not part of normal usage scenarios.

DhStyle.removeAllFilters

Syntax 1
public void removeAllFilters();
Description

Removes all filters from this element. This method automatically clears all filters on this element.

Syntax 2
public void removeAllFilters( boolean bApply );
Description

Removes all filters from this element. You can remove all filters immediately or delay removal.

DhStyle.removeFilter

Syntax 1
public void removeFilter( DhFilter filter );
Parameters
filter
A reference to the filter to remove.
Description

Removes the specified filter from this element. This method automatically reapplies filters that may be left after this method is called.

See Also
findFilter.

Syntax 2
public void removeFilter( DhFilter filter, boolean bApply );
Parameters
filter
A reference to the filter to remove.
bApply
Set to true to reapply other filters left on this element; set to false to delay the application of the filter.
Description

Removes the specified filter from this element. You can reapply filters that may be left after this method is called, or you can delay application if you are removing more than one filter.

See Also
findFilter.

DhStyle.replaceFilter

Syntax 1
public void replaceFilter( DhFilter filter1, DhFilter filter2 );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
Description

Replaces a specified filter with another filter. This method gives you a direct means of swapping filters. All changes that occur due to this swap are automatically applied immediately.

Syntax 2
public void replaceFilter( DhFilter filter1, DhFilter filter2, boolean bApply );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1
bApply
Set to true to apply visual changes immediately; set to false to delay making changes.
Description

Replaces a specified filter with another filter. This method gives you a direct means of swapping filters. You can specify whether to apply all the changes due to this swap immediately or to delay making changes until later.

See Also
applyFilters

DhStyle.setName

Syntax
public synchronized void setName( String name );
Parameters
name
The string name of the style rule.
Description

Sets the underlying name for the style object as seen by the HTML object. This is an advanced feature and is not part of normal usage scenarios.


 DhStyleBase Class

DhStyleBase Class

This Package | All Packages

Component
  |
  +--DhStyleBase
public class DhStyleBase
extends cor.Component
implements DhStringIDs

Provides the superclass for classes that support styles, such as DhStyle objects and DhElement. Classes that extend DhStyleBase have certain typographic and other visual properties, such as colors, fonts, and so on.

Also see DhStyle, DhElement

Fields
Name | Description
BOLD | Used by the style attribute of the setFont method.
ITALIC | Used by the style attribute of the setFont method.
OK_TO_CACHE_STYLES | Setting this flag to false (default is true) forces all CSS styles to be drawn from the client peer instead of a cached value.
STRIKEOUT | Used by the style attribute of the setFont method.
UNDERLINE | Used by the style attribute of the setFont method.

Constructors
Name | Description
DhStyleBase() | Topic under construction.
DhStyleBase(int unit) | Topic under construction.

Methods
Name | Description
ensurePaddings() | Topic under construction.
getBackColor() | Retrieves the background color property.
getBackgroundColor() | Retrieves the background color property.
getBackgroundColorString() | Retrieves the background color property as a string.
getBorderInfo() | Retrieves the DhBorderInfo class with informatioon about the current border state.
getBounds() | Retrieves the position and size of the element.
getClipRect() | Retrieves the current clipping rectangle.
getClipString() | Retrieves the current clip setting string.
getColor() | Retrieves the text foreground color property.
getCursor() | Retrieves the cursor style for this element.
getCursorString() | Retrieves the cursor style for this element.
getFont() | Topic under construction.
getFontName() | Retrieves the font name for this element.
getFontSize() | Retrieves the size of the font for this element.
getFontStyle() | Topic under construction.
getForeColor() | Retrieves the foreground color property.
getHeightUnit() | Retrieves the height unit.
getLeftUnit() | Retrieves the left position unit.
getLocation() | Retrieves the position (or location) of the element.
getMarginWidthInfo() | Retrieves a DhMarginWidthInfo class describing the current margin settings for this element.
getPaddingWidthInfo() | Retrieves a DhPaddingWidthInfo class describing the current padding width settings for this element.
getPositionInfo() | Topic under construction.
getSize() | Retrieves the size of the element.
getStyleInt(String strStyleKey) | Retrieves the style number.
getStyleString(String strStyleKey) | Retrieves the style.
getStyleText() | Retrieves the underlying CSS text string.
getTextAlignment( ) | Retrieves the current text alignment setting.
getTextVerticalAlign( ) | Retrieves the current text alignment setting.
getTopUnit() | Retrieves the top position unit.
getVisible() | Retrieves the visibility state of this element.
getWidthUnit() | Retrieves the width unit.
getZIndex() | Retrieves the z-index (layering) ordering of this element with respect to its container.
hasDefaultBackColor() | Determines if the background color is set to the default.
hasDefaultFont() | Topic under construction.
hasDefaultForeColor() | Determines if the background color is the default (black).
hasDefaultLocation() | Topic under construction.
hasDefaultPositionInfo() | Topic under construction.
hasDefaultSize() | Topic under construction.
hasDefaultZIndex() | Topic under construction.
setBackColor(Color color) | Sets the background color of the element.
setBackgroundColor(int color) | Sets the background color of the element.
setBackgroundColor(String color) | Sets the background color of the element.
setBorderColor( int nBordermask, String strColor ) | Sets the border color to the specified value.
setBorderColor( String strColor ) | Sets all border colors to the specified value.
setBorderColor( int nBorderMask, int nColor ) | Sets the border color to the specified value defined in DhColors.
setBorderColor( int nColor ) | Sets all border colors to the specified value defined in DhColor.
setBorderInfo( DhBorderInfo biNew ) | Updates the border styles for this element.
setBorderStyle( int nBorderMask, String strStyle ) | Sets the border style to a specified value.
setBorderStyle( String strStyle ) | Sets all border styles to a specified value.
setBorderStyle( int nBorderMask, int nBorderKey ) | Sets the style to a specified value constant.
setBorderStyle( int nBorderKey ) | Sets the style to a specified value constant.
setBorderWidth( int nBorderMask, String strWidth ) | Sets the border width to the value specified.
setBorderWidth( int nBorderMask, int nWidth, int nUnitKey ) | Sets the border width to the value and unit specified.
setBorderWidth( int nWidth, int nUnitKey ) | Sets all border widths to the value and unit specified.
setBorderWidth( String strWidth ) | Sets the border width to the value specified.
setBorderWidth( int nBorderWidthKey ) | Sets the border width to the value specified.
setBounds(int x, int y, int width, int height) | Sets the position and size of the element.
setBounds(Rectangle rect) | Sets the position and size of the element.
setClip( Rectangle r ) | Sets the clipping rectangle.
setClip( String strClip ) | Sets the clipping rectangle string in the form: rect( top, right, bottom, left ) where top, left, bottom or right can be "auto" or a length measurement.
setColor(int color) | Sets the text color (and other foreground objects).
setColor(String color) | Sets the color for foreground objects, such as text.
setCursor( int nCursor ) | Sets the cursor style for this element.
setCursor( String strCursor ) | Sets the cursor style for this element.
setFont(String name, int size, int style) | Sets the font value for this element.
setFont(String name, int size) | Sets the font value for this element.
setFont(Font font) | Topic under construction.
setForeColor(Color color) | Sets the color of foreground objects, such as text.
setHeightUnit( int h, int unit ) | Sets the height of the element.
setLeftUnit( int v, int unit ) | Sets the left position of the element.
setLocation(int x, int y) | Sets the position of the element.
setLocation( Point pt ) | Sets the position of the element.
setMarginWidth( int nWidth, int nUnit ) | Sets the width of all the margins to the specified value.
setMarginWidth( int nMarginMask, int nWidth, int nUnit ) | Sets the width of the margins to the specified value.
setMarginWidthInfo( DhMarginWidthInfo mwi ) | Sets the margins widths according to those in a DhMarginWidthInfo class.
setPaddingWidth( int nWidth, int nUnit ) | Sets the width of all paddings to the specified value.
setPaddingWidth( int nPaddingMask, int nWidth, int nUnit ) | Sets the width of the padding to the specified value.
setPaddingWidthInfo( DhPaddingWidthInfo mwi ) | Sets the padding widths according to those in a DhPaddingWidthInfo class.
setPositionInfo(PositionInfo posi) | Topic under construction.
setSize(int w, int h) | Sets the size of the element.
setSize(Point pt) | Sets the size of the element.
setStyle(String strStyleKey, String value) | Sets the style.
setStyleInt(String strStyleKey, int value) | Sets the style.
setTextAlignment( int nAlignment ) | Sets the text alignment style.
setTextVerticalAlign( int nVerticalAlign ) | Sets the text vertical alignment style.
setTopUnit( int t, int unit ) | Sets the top position of the element.
setVisible( boolean visible ) | Sets the visiblility of the element.
setWidthUnit( int w, int unit ) | Sets the width of the element.
setZIndex( int i ) | Sets the z-index (layering) order of this element relative to the other elements in its container.

Fields

DhStyleBase.BOLD

Syntax
public static final int BOLD;
Description
Used by the style attribute of the setFont method.

DhStyleBase.ITALIC

Syntax
public static final int ITALIC;
Description
Used by the style attribute of the setFont method.

DhStyleBase.OK_TO_CACHE_STYLES

Syntax
public static boolean OK_TO_CACHE_STYLES;
Description
Setting this flag to false (default is true) forces all CSS styles to be drawn from the client peer instead of a cached value. This flag will probably be removed by release.

DhStyleBase.STRIKEOUT

Syntax
public static final int STRIKEOUT;
Description
Used by the style attribute of the setFont method.

DhStyleBase.UNDERLINE

Syntax
public static final int UNDERLINE;
Description
Used by the style attribute of the setFont method.

Constructors

DhStyleBase.DhStyleBase

Syntax 1
public DhStyleBase();
Description

Topic under construction.

Syntax 2
public DhStyleBase( int unit );
Description

Topic under construction.

Methods

DhStyleBase.ensurePaddings

Syntax
public synchronized void ensurePaddings();
Description

Topic under construction.

DhStyleBase.getBackColor

Syntax
public Color getBackColor();
Return Value

Returns one of the DhColors constants.

Description

Retrieves the background color property.

DhStyleBase.getBackgroundColor

Syntax
public int getBackgroundColor();
Return Value

Returns one of the DhColors constants.

Description

Retrieves the background color property.

DhStyleBase.getBackgroundColorString

Syntax
public String getBackgroundColorString();
Return Value

Returns a string representing the current background color.

Description

Retrieves the background color property as a string.

DhStyleBase.getBorderInfo

Syntax
public DhBorderInfo getBorderInfo();
Return Value

Returns the border information class.

Description

Retrieves the DhBorderInfo class with informatioon about the current border state.

DhStyleBase.getBounds

Syntax
final public Rectangle getBounds();
Return Value

Returns the location of the element as a Rectangle object.

Description

Retrieves the position and size of the element.

See Also
getWidthUnit, getHeightUnit, getTopUnit, getLeftUnit

DhStyleBase.getClipRect

Syntax
public Rectangle getClipRect();
Return Value

Returns a Rectangle object with the current clipping rectangle values. If the values are undefined or "auto", -1 is returned.

Description

Retrieves the current clipping rectangle.

DhStyleBase.getClipString

Syntax
public String getClipString();
Return Value

Returns the clip string.

Description

Retrieves the current clip setting string.

See Also
setClip

DhStyleBase.getColor

Syntax
public int getColor();
Return Value

Returns one of the DhColors constants.

Description

Retrieves the text foreground color property.

DhStyleBase.getCursor

Syntax
public int getCursor();
Return Value

Returns the current cursor type.

Description

Retrieves the cursor style for this element. For predefined values, see DhCursorEnum.

DhStyleBase.getCursorString

Syntax
public String getCursorString();
Return Value

Returns the current cursor type.

Description

Retrieves the cursor style for this element. For details, see the CSS cursor reference in the CSS Attributes reference of the Internet Client SDK (http://www.microsoft.com/msdn/sdk/inetsdk/help/dhtml/references/css/cursor.htm).

DhStyleBase.getFont

Syntax
public Font getFont();
Description

Topic under construction.

DhStyleBase.getFontName

Syntax
public String getFontName();
Return Value

Returns the name of the font family (for example, "arial").

Description

Retrieves the font name for this element.

DhStyleBase.getFontSize

Syntax
public int getFontSize();
Return Value

Returns the size of the font for this element.

Description

Retrieves the size of the font for this element.

DhStyleBase.getFontStyle

Syntax
public int getFontStyle();
Description

Topic under construction.

DhStyleBase.getForeColor

Syntax
public Color getForeColor();
Return Value

Returns one of the DhColors constants.

Description

Retrieves the foreground color property.

DhStyleBase.getHeightUnit

Syntax
final public int getHeightUnit();
Return Value

Returns one of DhUnitEnum constants to express the units of measurement.

Description

Retrieves the height unit.

See Also
getBounds

DhStyleBase.getLeftUnit

Syntax
final public int getLeftUnit();
Return Value

Returns one of DhUnitEnum constants to express the units of measurement.

Description

Retrieves the left position unit.

See Also
getBounds

DhStyleBase.getLocation

Syntax
public Point getLocation();
Return Value

Returns the location of the element.

Description

Retrieves the position (or location) of the element.

See Also
getTopUnit, getLeftUnit

DhStyleBase.getMarginWidthInfo

Syntax
public DhMarginWidthInfo getMarginWidthInfo();
Return Value

Returns a DhMarginWidthInfo class.

Description

Retrieves a DhMarginWidthInfo class describing the current margin settings for this element.

DhStyleBase.getPaddingWidthInfo

Syntax
public DhPaddingWidthInfo getPaddingWidthInfo();
Return Value

Returns a DhPaddingWidthInfo class.

Description

Retrieves a DhPaddingWidthInfo class describing the current padding width settings for this element.

DhStyleBase.getPositionInfo

Syntax
public PositionInfo getPositionInfo();
Description

Topic under construction.

DhStyleBase.getSize

Syntax
public Point getSize();
Return Value

Returns the size of the element as a Point object.

Description

Retrieves the size of the element.

See Also
getWidthUnit, getHeightUnit

DhStyleBase.getStyleInt

Syntax
public int getStyleInt( String strStyleKey );
Parameters
strStyleKey
The name of the style to get.
Description

Retrieves the style number. Calling this method directly is not part of the normal usage of this package. You should use more specific style methods (for example, DhStyleBase.getFontName).

DhStyleBase.getStyleString

Syntax
public String getStyleString( String strStyleKey );
Parameters
strStyleKey
The name of the style to get.
Return Value

Returns the style string.

Description

Retrieves the style. Calling this method directly is not part of the normal usage of this package. You should use more specific style methods (for example, DhStyleBase.getFontName).

DhStyleBase.getStyleText

Syntax
public String getStyleText();
Return Value

Returns the underlying CSS text string for this object.

Description

Retrieves the underlying CSS text string. (This is a very advanced feature of the library and is not part of normal usage scenarios.)

DhStyleBase.getTextAlignment

Syntax
public int getTextAlignment( );
Return Value

Returns the current alignment as LEFT (default), RIGHT, CENTER, or JUSTIFY from DhAlignEnum.

Description

Retrieves the current text alignment setting.

See Also
setTextAlignment

DhStyleBase.getTextVerticalAlign

Syntax
public int getTextVerticalAlign( );
Return Value

Returns the current alignment. This can be one of the following values found in DhAlignEnum:

  • BASELINE (default)
  • SUBSCRIPT
  • SUPERSCRIPT

Description

Retrieves the current text alignment setting.

See Also
setTextVerticalAlign

DhStyleBase.getTopUnit

Syntax
final public int getTopUnit();
Return Value

Returns one of DhUnitEnum constants to express the units of measurement.

Description

Retrieves the top position unit.

See Also
getBounds

DhStyleBase.getVisible

Syntax
public boolean getVisible();
Return Value

Returns true if element is visible; otherwise, returns false.

Description

Retrieves the visibility state of this element.

DhStyleBase.getWidthUnit

Syntax
final public int getWidthUnit();
Return Value

Returns one of DhUnitEnum constants to express the units of measurement.

Description

Retrieves the width unit.

See Also
getBounds

DhStyleBase.getZIndex

Syntax
public int getZIndex();
Return Value

Returns the z-index value set by setZIndex.

Description

Retrieves the z-index (layering) ordering of this element with respect to its container.

See Also
setZIndex

DhStyleBase.hasDefaultBackColor

Syntax
public boolean hasDefaultBackColor();
Return Value

Returns true if the background color is the default (white); otherwise, returns false.

Description

Determines if the background color is set to the default.

DhStyleBase.hasDefaultFont

Syntax
public boolean hasDefaultFont();
Description

Topic under construction.

DhStyleBase.hasDefaultForeColor

Syntax
public boolean hasDefaultForeColor();
Return Value

Returns true if successful; otherwise, returns false.

Description

Determines if the background color is the default (black).

DhStyleBase.hasDefaultLocation

Syntax
public boolean hasDefaultLocation();
Description

Topic under construction.

DhStyleBase.hasDefaultPositionInfo

Syntax
public boolean hasDefaultPositionInfo();
Description

Topic under construction.

DhStyleBase.hasDefaultSize

Syntax
public boolean hasDefaultSize();
Description

Topic under construction.

DhStyleBase.hasDefaultZIndex

Syntax
public boolean hasDefaultZIndex();
Description

Topic under construction.

DhStyleBase.setBackColor

Syntax
public void setBackColor( Color color );
Parameters
color
One of the DhColors constants.
Description

Sets the background color of the element. If never set, the background color used is that of the container.

DhStyleBase.setBackgroundColor

Syntax 1
public void setBackgroundColor( int color );
Parameters
color
One of the DhColors constants.
Description

Sets the background color of the element. If never set, the background color used is that of the container.

Syntax 2
public void setBackgroundColor( String color );
Parameters
color
One of the CSS-approved string constants, such as red or saddle brown.
Description

Sets the background color of the element. If never set, the background color used is that of the container.

DhStyleBase.setBorderColor

Syntax 1
public void setBorderColor( int nBordermask, String strColor );
Parameters
nBorderMask
The border sides you want to set. Can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
strColor
The color string.
Description

Sets the border color to the specified value. It can be a hexadecimal color (for example, "#F0F0FF") or a defined color word (for example, "white", "black", "blue", and so on.)

Syntax 2
public void setBorderColor( String strColor );
Parameters
strColor
The color string.
Description

Sets all border colors to the specified value. The color can be a hexadecimal color (for example, "#F0F0FF") or a defined color word (for example, "white", "black", "blue", and so on.)

Syntax 3
public void setBorderColor( int nBorderMask, int nColor );
Parameters
nBorderMask
The border sides you want to set. Can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
nColor
One of the DhColors constants.
Description

Sets the border color to the specified value defined in DhColors.

Syntax 4
public void setBorderColor( int nColor );
Parameters
nColor
One of the DhColors constants.
Description

Sets all border colors to the specified value defined in DhColor.

DhStyleBase.setBorderInfo

Syntax
public void setBorderInfo( DhBorderInfo biNew );
Parameters
biNew
The class containing the new state of the borders. String values are used over integer settings in the structure.
Description

Updates the border styles for this element.

DhStyleBase.setBorderStyle

Syntax 1
public void setBorderStyle( int nBorderMask, String strStyle );
Parameters
nBorderMask
The border sides you want to set. This can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
strStyle
The style string. This can be one of the following strings:
  • "solid"
  • "dotted"
  • "dashed"
  • "groove"
  • "inset"
  • "outset"
  • "double"
  • "ridge"
  • "none"
Description

Sets the border style to a specified value.

Syntax 2
public void setBorderStyle( String strStyle );
Parameters
strStyle
The style string. This can be one of the following strings:
  • "solid"
  • "dotted"
  • "dashed"
  • "groove"
  • "inset"
  • "outset"
  • "double"
  • "ridge"
  • "none"
Description

Sets all border styles to a specified value.

Syntax 3
public void setBorderStyle( int nBorderMask, int nBorderKey );
Parameters
nBorderMask
The border sides you want to set. This can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
nBorderKey
One of the DhBorderEnum constants.
Description

Sets the style to a specified value constant.

Syntax 4
public void setBorderStyle( int nBorderKey );
Parameters
nBorderKey
One of the DhBorderEnum constants.
Description

Sets the style to a specified value constant.

DhStyleBase.setBorderWidth

Syntax 1
public void setBorderWidth( int nBorderMask, String strWidth );
Parameters
nBorderMask
The border sides you want to set. This can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
strWidth
String describing width in format described above.
Description

Sets the border width to the value specified. Border width is in the following form:

<border-width> ::= thick | medium | thin | none | <width-value>
<width-value>  ::= <integer><unit>
<unit>		 ::= px | pc | pt | em | in | mm | cm | ex

Syntax 2
public void setBorderWidth( int nBorderMask, int nWidth, int nUnitKey );
Parameters
nBorderMask
The border sides you want to set. This can be any combination of DhBorderEnum.BORDER_SIDE_ALL, DhBorderEnum.BORDER_SIDE_LEFT, DhBorderEnum.BORDER_SIDE_RIGHT, DhBorderEnum.BORDER_SIDE_TOP, DhBorderEnum.BORDER_SIDE_BOTTOM.
nWidth
The numerical width of the border.
nUnitKey
The unit key to assign to the width. See DhUnitEnum for values.
Description

Sets the border width to the value and unit specified.

Syntax 3
public void setBorderWidth( int nWidth, int nUnitKey );
Parameters
nWidth
The numerical width of the borders.
nUnitKey
The unit key to assign to the width. See DhUnitEnum for values.
Description

Sets all border widths to the value and unit specified.

Syntax 4
public void setBorderWidth( String strWidth );
Parameters
strWidth
The border width.
Description

Sets the border width to the value specified.

Syntax 5
public void setBorderWidth( int nBorderWidthKey );
Parameters
strWidth
A string describing the width, such as a key from DhStringIDs.
Description

Sets the border width to the value specified.

DhStyleBase.setBounds

Syntax 1
final public void setBounds( int x, int y, int width, int height );
Parameters
x
The left coordinate of the position.
y
The top coordinate of the position.
width
The new width of the element.
height
The new height of the element.
Description

Sets the position and size of the element.

See Also
setWidthUnit, setHeightUnit, setTopUnit, setLeftUnit, setSize, setLocation

Syntax 2
final public void setBounds( Rectangle rect );
Parameters
rect
The position and dimensions of the element.
Description

Sets the position and size of the element.

See Also
setWidthUnit, setHeightUnit, setTopUnit, setLeftUnit

DhStyleBase.setClip

Syntax 1
public void setClip( Rectangle r );
Parameters
r
The clipping rectangle.
Description

Sets the clipping rectangle. Regions outside the clipping rectangle will not be drawn.

Syntax 2
public void setClip( String strClip );
Parameters
strClip
The clip string.
Description

Sets the clipping rectangle string in the form:

rect( top, right, bottom, left )

where top, left, bottom or right can be "auto" or a length measurement.

DhStyleBase.setColor

Syntax 1
public void setColor( int color );
Parameters
color
One of the DhColors constants.
Description

Sets the text color (and other foreground objects).

Syntax 2
public void setColor( String color );
Parameters
color
One of the CSS-approved string constants, such as red or saddle brown.
Description

Sets the color for foreground objects, such as text.

DhStyleBase.setCursor

Syntax 1
public void setCursor( int nCursor );
Parameters
nCursor
The cursor type.
Description

Sets the cursor style for this element. For predefined values, see DhCursorEnum.

Syntax 2
public void setCursor( String strCursor );
Parameters
strCursor
The desired cursor.
Description

Sets the cursor style for this element. For details, see the CSS cursor reference in the CSS Attributes reference of the Internet Client SDK (http://www.microsoft.com/msdn/sdk/inetsdk/help/dhtml/references/css/cursor.htm).

DhStyleBase.setFont

Syntax 1
public void setFont( String name, int size, int style );
Parameters
name
The name of the font family (for example, "arial", "comic sans ms", and so on.)
size
The size of the font (in points).
style
A set of flags (BOLD, ITALIC, UNDERLINE, STRIKEOUT) that can be bitwise OR'd together to form the style of font. The number 0 is also valid and implies none of these attributes.
Description

Sets the font value for this element.

Syntax 2
public void setFont( String name, int size );
Parameters
name
The name of the font family (for example, "arial", "comic sans ms", and so on.)
size
The size of the font (in points).
Description

Sets the font value for this element.

Syntax 3
public void setFont( Font font );
Description

Topic under construction.

DhStyleBase.setForeColor

Syntax
public void setForeColor( Color color );
Parameters
color
One of the DhColors constants.
Description

Sets the color of foreground objects, such as text.

DhStyleBase.setHeightUnit

Syntax
public void setHeightUnit( int h, int unit );
Parameters
h
The height value.
unit
One of DhUnitEnum constants to express the units of measurement.
Description

Sets the height of the element.

See Also
setBounds

DhStyleBase.setLeftUnit

Syntax
final public void setLeftUnit( int v, int unit );
Parameters
v
The left position value.
unit
One of DhUnitEnum constants to express the units of measurement.
Description

Sets the left position of the element.

See Also
setBounds

DhStyleBase.setLocation

Syntax 1
public void setLocation( int x, int y );
Parameters
x
The left coordinate of the position.
y
The top coordinate of the position.
Description

Sets the position of the element.

See Also
setTopUnit, setLeftUnit

Syntax 2
public void setLocation( Point pt );
Parameters
pt
The new location of the element.
Description

Sets the position of the element.

See Also
setTopUnit, setLeftUnit

DhStyleBase.setMarginWidth

Syntax 1
public void setMarginWidth( int nWidth, int nUnit );
Parameters
nWidth
The width of the margins.
nUnit
The unit of the margins widths. See DhUnitEnum) for details.
Description

Sets the width of all the margins to the specified value.

Syntax 2
public void setMarginWidth( int nMarginMask, int nWidth, int nUnit );
Parameters
nMarginMask
A combination of the margins you want apply. See DhMarginEnum.
nWidth
The width of the margins.
nUnit
The unit of the margin widths. See DhUnitEnum) for details.
Description

Sets the width of the margins to the specified value.

DhStyleBase.setMarginWidthInfo

Syntax
public void setMarginWidthInfo( DhMarginWidthInfo mwi );
Parameters
mni
The margin width settings.
Description

Sets the margins widths according to those in a DhMarginWidthInfo class.

DhStyleBase.setPaddingWidth

Syntax 1
public void setPaddingWidth( int nWidth, int nUnit );
Parameters
nWidth
The padding widths.
nUnit
The unit of the padding widths. See DhUnitEnum for details.
Description

Sets the width of all paddings to the specified value.

Syntax 2
public void setPaddingWidth( int nPaddingMask, int nWidth, int nUnit );
Parameters
nPaddingMask
A combination of the paddings you want to apply. See DhEnumConstants for details.
nWidth
The padding widths.
nUnit
The unit of the padding widths. See DhUnitEnum for details.
Description

Sets the width of the padding to the specified value.

DhStyleBase.setPaddingWidthInfo

Syntax
public void setPaddingWidthInfo( DhPaddingWidthInfo mwi );
Parameters
mwi
The new padding width settings.
Description

Sets the padding widths according to those in a DhPaddingWidthInfo class.

DhStyleBase.setPositionInfo

Syntax
public void setPositionInfo( PositionInfo posi );
Description

Topic under construction.

DhStyleBase.setSize

Syntax 1
public void setSize( int w, int h );
Parameters
width
The new width of the element.
height
The new height of the element.
Description

Sets the size of the element.

See Also
setWidthUnit, setHeightUnit

Syntax 2
public void setSize( Point pt );
Parameters
pt
The new width and height of the element.
Description

Sets the size of the element.

Exceptions

IllegalArgumentException thrown if either width or height is less than 0.

See Also
setWidthUnit, setHeightUnit

DhStyleBase.setStyle

Syntax
public void setStyle( String strStyleKey, String value );
Parameters
strStyleKey
The name of the style to set.
value
A string value.
Description

Sets the style.

Calling this method directly is not part of the normal usage of this package. You should use the more specific style methods (for example, DhStyleBase.setFont).

DhStyleBase.setStyleInt

Syntax
public void setStyleInt( String strStyleKey, int value );
Parameters
strStyleKey
The name of the style to set.
value
An integer value.
Description

Sets the style.

Calling this method directly is not part of the normal usage of this package. You should use the more specific style methods (for example, DhStyleBase.setFont).

DhStyleBase.setTextAlignment

Syntax
public void setTextAlignment( int nAlignment );
Parameters
nAlignment
The new alignment setting. This can be one of values found in DhAlignEnum:
  • LEFT (default)
  • RIGHT
  • CENTER
  • JUSTIFY
Description

Sets the text alignment style.

Exceptions

IllegalArgumentException Thrown if nAlignment is not one of the above values.

DhStyleBase.setTextVerticalAlign

Syntax
public void setTextVerticalAlign( int nVerticalAlign );
Parameters
nVerticalAlign
The new alignment setting. This can be one of values found in DhAlignEnum:
  • BASELINE (default)
  • SUBSCRIPT
  • SUPERSCRIPT
Description

Sets the text vertical alignment style.

Exceptions

IllegalArgumentException Thrown if nAlignment is not one of the above values.

DhStyleBase.setTopUnit

Syntax
final public void setTopUnit( int t, int unit );
Parameters
t
The top position value.
unit
One of DhUnitEnum constants to express the units of measurement.
Description

Sets the top position of the element.

See Also
setBounds

DhStyleBase.setVisible

Syntax
public void setVisible( boolean visible );
Parameters
visible
Set to true to allow element to be rendered; otherwise, set to false.
Description

Sets the visiblility of the element.

DhStyleBase.setWidthUnit

Syntax
public void setWidthUnit( int w, int unit );
Parameters
w
The width value.
unit
One of DhUnitEnum constants to express the units of measurement.
Description

Sets the width of the element.

See Also
getBounds

DhStyleBase.setZIndex

Syntax
public void setZIndex( int i );
Parameters
i
The z-index value of this element
Description

Sets the z-index (layering) order of this element relative to the other elements in its container. The lower the number, the further back this element is displayed. The element with the highest number z-index in any given container is displayed over all other elements.


 DhSubmitButton Class

DhSubmitButton Class

This Package | All Packages

DhElement
  |
  +--DhButtonBase
    |
    +--DhSubmitButton
public class DhSubmitButton
extends DhButtonBase

Represents a submit button for an HTML form. The submit button invokes the URL specified in the form's ACTION attribute (For more information, see DhSection.setHTTPSubmitUrl().) Adding a DhSubmitButton to a DhSection object causes the DhSection to represent an HTML form element

Also see wfc.html.DhSection

Fields
Name | Description
METHOD_GET | Topic under construction.
METHOD_POST | Topic under construction.

Constructors
Name | Description
DhSubmitButton() | Creates a DhSubmitButton object.
DhSubmitButton( String strCaption ) | Creates a DhSubmitButton object.

Methods
Name | Description
getSubmitMethod() | Topic under construction.
getSubmitUrl( ) | Retrieves the current URL that will be called if the form's Submit button is clicked.
getText() | Retrieves the button's current text caption.
setSubmitMethod( int newMethod ) | Topic under construction.
setSubmitUrl( String strActionUrl ) | Sets the URL to be called when the form's Submit button is clicked.
setText( String strCaption ) | Sets the button caption.

Fields

DhSubmitButton.METHOD_GET

Syntax
public static final int METHOD_GET;
Description
Topic under construction.

DhSubmitButton.METHOD_POST

Syntax
public static final int METHOD_POST;
Description
Topic under construction.

Constructors

DhSubmitButton.DhSubmitButton

Syntax 1
public DhSubmitButton();
Description

Creates a DhSubmitButton object. This default constructor creates a DhSubmitButton with Submit as its caption.

Syntax 2
public DhSubmitButton( String strCaption );
Parameters
strCaption
The initial caption for the new button.
Description

Creates a DhSubmitButton object. This constructor creates a DhSubmitButton with the specified caption.

Methods

DhSubmitButton.getSubmitMethod

Syntax
public int getSubmitMethod();
Description

Topic under construction.

DhSubmitButton.getSubmitUrl

Syntax
public String getSubmitUrl( );
Return Value

Returns the URL to be called.

Description

Retrieves the current URL that will be called if the form's Submit button is clicked.

See Also
setHTTPSubmitUrl

DhSubmitButton.getText

Syntax
public String getText();
Return Value

Returns the button caption.

Description

Retrieves the button's current text caption.

Overrides

getText() in DhButtonBase.

DhSubmitButton.setSubmitMethod

Syntax
public void setSubmitMethod( int newMethod );
Description

Topic under construction.

DhSubmitButton.setSubmitUrl

Syntax
public void setSubmitUrl( String strActionUrl );
Parameters
strActionUrl
The URL to be called on submit.
Description

Sets the URL to be called when the form's Submit button is clicked. Parameters from form fields are concatenated onto this URL.

DhSubmitButton.setText

Syntax
public void setText( String strCaption );
Parameters
strCaption
The new caption string.
Description

Sets the button caption.

Overrides

setText(String) in DhButtonBase.


 DhTable Class

DhTable Class

This Package | All Packages

DhElement
  |
  +--DhBaseContainer
    |
    +--DhTable
public class DhTable
extends DhBaseContainer

Creates a table element that can be populated with rows and columns.

Constructors
Name | Description
DhTable() | Creates a DhTable object.

Methods
Name | Description
add(DhRow row, DhRow relativeTo, int insertFlag) | Adds a row to this table either at the top or the bottom, or before or after another the row depending on the DhInsertEnum insertFlag parameter.
add(DhRow row, int insertFlag) | Adds a row to this table either at the top or bottom depending on the DhInsertEnum insertFlag parameter.
add(DhRow row) | Adds a row at the bottom of this table.
getBorder() | Retrieves the default (non-CSS) border thickness of the table Return Value: Returns the thickness of the border.
getCell( int nRow, int nCol ) | Retrieves the cell at the given location.
getFooterRow() | Retrieves the footer row if there is one.
getHeaderRow( ) | Retrieves the header row if there is one.
getPageSize() | Retrieves the current data page size, in rows, to display in a data-bound operation.
getRepeaterClone() | Retrieves data row cloning for databound tables.
getRow( int nRow ) | Retrieves the specified row.
getRowCount() | Retrieves the number of rows in the table, including header and footer rows.
getTagNameID() | Topic under construction.
removeAll() | Topic under construction.
removeBodyRows() | Topic under construction.
setBorder( int width ) | Sets the default (non-CSS) border width for this table.
setDataSource( DhDataSource ds ) | Note This method is obsolete.
setDataSource( DhDataSource ds, DhRow repeaterRow ) | Sets the data source and repeater row template for this table.
setDataSource( DhElement ds ) | Note This method is obsolete.
setDataSource( DhElement ds, DhRow repeaterRow ) | Sets the data source and repeater row template for this table.
setFooterRow( DhRow r ) | Sets the footer row to the DhRow specified.
setHeaderRow( DhRow r ) | Sets the header row to the DhRow specified.
setHTMLGenerator( DhHTMLGenerator htmlGen ) | Topic under construction.
setPageSize( int nPageSize ) | Sets the display page size for this table when bound to data.
setRepeaterClone( boolean value ) | Sets data row cloning for data-bound tables.
showNextPage() | Displays the next page of data in the table.
showPreviousPage() | Displays the previous page of data in the table.

Constructors

DhTable.DhTable

Syntax
public DhTable();
Description

Creates a DhTable object. This default constructor creates an empty table element.

Methods

DhTable.add

Syntax 1
public void add( DhRow row, DhRow relativeTo, int insertFlag );
Parameters
row
The row to add to this table.
relativeTo
The row referred to when using the INSERT_BEFORE or INSERT_AFTER constants for the insertFlag parameter.
insertFlag
One of the valid and applicable insert constants. The valid values for insertFlag are:
  • INSERT_END inserts the row at the bottom of this table. The relativeTo parameter must be null.
  • INSERT_BEGINNING inserts the row at the top of this table. The relativeTo parameter must be null.
  • INSERT_BEFORE inserts the row before the row referred to by the relativeTo parameter. The relativeTo parameter must not be null.
  • INSERT_AFTER inserts the row after the row referred to by the relativeTo parameter. The relativeTo parameter must not be null.
Description

Adds a row to this table either at the top or the bottom, or before or after another the row depending on the DhInsertEnum insertFlag parameter.

Syntax 2
public void add( DhRow row, int insertFlag );
Parameters
row
The DhRow row to add to this table.
insertFlag
One of the valid and applicable insert constants. The valid values for insertFlag are:
  • INSERT_END inserts the row at the bottom of this table. The relativeTo parameter must be null.
  • INSERT_BEGINNING inserts the row at the top of this table. The relativeTo parameter must be null.
Description

Adds a row to this table either at the top or bottom depending on the DhInsertEnum insertFlag parameter.

Syntax 3
public void add( DhRow row );
Parameters
row
The DhRow row to add to this table.
Description

Adds a row at the bottom of this table.

DhTable.getBorder

Syntax
public int getBorder();
Return Value

Returns the thickness of the border.

Description

Retrieves the default (non-CSS) border thickness of the table

DhTable.getCell

Syntax
public DhCell getCell( int nRow, int nCol );
Parameters
nRow
The zero-based row number.
nCol
The zero-based column number.
Return Value

Returns the cell at the requested position.

Description

Retrieves the cell at the given location.

Exceptions

wfc.html.DhElementNotFoundException thrown if there is no cell at the specified location.

DhTable.getFooterRow

Syntax
public synchronized DhRow getFooterRow();
Return Value

Returns the footer DhRow, or returns null if no footer DhRow exists.

Description

Retrieves the footer row if there is one.

DhTable.getHeaderRow

Syntax
public synchronized DhRow getHeaderRow( );
Return Value

Returns the header DhRow, or returns null if no header DhRow exists.

Description

Retrieves the header row if there is one.

DhTable.getPageSize

Syntax
public int getPageSize();
Description

Retrieves the current data page size, in rows, to display in a data-bound operation.

DhTable.getRepeaterClone

Syntax
public boolean getRepeaterClone();
Return Value

Returns true if cloning is enabled; otherwise, false.

Description

Retrieves data row cloning for databound tables. If true, generated data rows will be converted into DhElement derived items that you can interact with. This process considerably slows down table generation, so activate it only if you need to interact with, or sink events from, the elements in a databound table.

See Also
setRepeaterClone

DhTable.getRow

Syntax
public synchronized DhRow getRow( int nRow );
Parameters
nRow
The row to retrieve.
Return Value

Returns the row at position nRow.

Description

Retrieves the specified row. If a header row exists, 0 is specified for the header row; otherwise, it specifies the first row in the table body.

Exceptions

wfc.html.DhElementNotFoundException thrown if the row is not in the table.

DhTable.getRowCount

Syntax
public synchronized int getRowCount();
Return Value

Returns the total number of rows.

Description

Retrieves the number of rows in the table, including header and footer rows.

DhTable.getTagNameID

Syntax
protected int getTagNameID();
Description

Topic under construction.

DhTable.removeAll

Syntax
public void removeAll();
Description

Topic under construction.

DhTable.removeBodyRows

Syntax
public void removeBodyRows();
Description

Topic under construction.

DhTable.setBorder

Syntax
public void setBorder( int width );
Parameters
width
The thickness of the border.
Description

Sets the default (non-CSS) border width for this table.

DhTable.setDataSource

Syntax 1
public synchronized void setDataSource( DhDataSource ds );
Description

Note This method is obsolete.

Syntax 2
public synchronized void setDataSource( DhDataSource ds, DhRow repeaterRow );
Parameters
ds
The data source.
repeaterRow
The row template to use.
Description

Sets the data source and repeater row template for this table. The row template contains cells with items that have data field attributes set on them. This row and all its styles are copied for each record in the database. To access the generated rows, call setRepeaterClone( true ). By default, this is set to false because cloning is time and processor intensive.

Syntax 3
public synchronized void setDataSource( DhElement ds );
Description

Note This method is obsolete.

Syntax 4
public synchronized void setDataSource( DhElement ds, DhRow repeaterRow );
Parameters
ds
The data source.
repeaterRow
The row template to use.
Description

Sets the data source and repeater row template for this table. The row template contains cells with items that have data field attributes set on them. This row and all its styles are copied for each record in the database. To access the generated rows, call setRepeaterClone( true ). By default, this is set to false because cloning is time and processor intensive.

DhTable.setFooterRow

Syntax
public synchronized void setFooterRow( DhRow r );
Parameters
r
The new footer row. Set to null to clear the existing footer row.
Description

Sets the footer row to the DhRow specified.

DhTable.setHeaderRow

Syntax
public synchronized void setHeaderRow( DhRow r );
Parameters
r
The new header row. Set to null to clear the existing header row.
Description

Sets the header row to the DhRow specified.

DhTable.setHTMLGenerator

Syntax
public synchronized void setHTMLGenerator( DhHTMLGenerator htmlGen );
Description

Topic under construction.

Overrides

setHTMLGenerator(DhHTMLGenerator) in DhBaseContainer.

DhTable.setPageSize

Syntax
public void setPageSize( int nPageSize );
Parameters
nPageSize
Number of rows to display per page.
Description

Sets the display page size for this table when bound to data.

DhTable.setRepeaterClone

Syntax
public void setRepeaterClone( boolean value );
Parameters
value
Set to true to enable cloning; otherwise, set to false.
Description

Sets data row cloning for data-bound tables. If true, generated data rows will be converted into DhElement-derived items that you can interact with. This process considerably slows down table generation, so activate it only if you need to interact with, or sink events from, the elements in a databound table.

See Also
getRepeaterClone

DhTable.showNextPage

Syntax
public void showNextPage();
Description

Displays the next page of data in the table.

See Also
setPageSize

DhTable.showPreviousPage

Syntax
public void showPreviousPage();
Description

Displays the previous page of data in the table.

See Also
setPageSize


 DhTabularDataSource Class

DhTabularDataSource Class

This Package | All Packages

DhObjectFactory
  |
  +--DhObjectDataSource
    |
    +--DhTabularDataSource
public class DhTabularDataSource
extends DhObjectDataSource

Encapsulates the Microsoft Tabular Data Control (TDC). This control allows access to data that is stored in a delimited text file. For more information, see your Internet SDK documentation.

Constructors
Name | Description
DhTabularDataSource() | Constructs a DhTabularDataSource object.
DhTabularDataSource( String strUrl ) | Constructs a DhTabularDataSource object.

Methods
Name | Description
getCaseSensitive() | Retrieves the current case-sensitivity setting for sorting.
getDataUrl( ) | Retrieves the current URL setting for retrieving a data file.
getEscapeChar() | Retrieves the current escape character.
getFieldDelim() | Retrieves the current field delimiter character or characters.
getFilter() | Retrieves the current data filter string.
getRowDelim() | Retrieves the current row delimiter character or characters.
getSortColumns( ) | Retrieves the current column sort setting string.
getTextQualifier() | Retrieves the current text qualifier character.
getUseHeader() | Retrieves the current header-row setting.
reset() | Queries the data again based on the new control settings.
setCaseSensitive( boolean fCaseSensitive ) | Sets case sensitivity in sorting.
setDataUrl( String strUrl ) | Sets the URL for retrieving the file data in a standard format, such as http:, file:, ftp:, and so on.
setEscapeChar( char c ) | Specifies the character used to escape special characters.
setFieldDelim( String fd ) | Sets the field delimiter character or characters.
setFilter( String strFilter ) | Sets the filter for the data display, and then queries for the data again.
setRowDelim( String rd ) | Sets the row delimiter character(s).
setSortColumns( String strSort ) | Sets the column or columns to be sorted in ascending or descending order.
setTextQualifier( char c ) | Specifies a single character used to surround fields that can include special characters such as new lines, tabs, or commas.
setUseHeader( boolean fUseHeader ) | Specifies whether the first row of the data contains header information.

Constructors

DhTabularDataSource.DhTabularDataSource

Syntax 1
public DhTabularDataSource();
Description

Constructs a DhTabularDataSource object.

Syntax 2
public DhTabularDataSource( String strUrl );
Parameters
strUrl
Specifies the initial dataUrl to reference.
Description

Constructs a DhTabularDataSource object.

See Also
setDataUrl

Methods

DhTabularDataSource.getCaseSensitive

Syntax
public boolean getCaseSensitive();
Return Value

Returns true to sort by case; otherwise, returns false.

Description

Retrieves the current case-sensitivity setting for sorting.

DhTabularDataSource.getDataUrl

Syntax
public String getDataUrl( );
Return Value

Returns the dataURL of the file.

Description

Retrieves the current URL setting for retrieving a data file.

See Also
setDataUrl

DhTabularDataSource.getEscapeChar

Syntax
public char getEscapeChar();
Return Value

Returns the escape character.

Description

Retrieves the current escape character. The default is none.

DhTabularDataSource.getFieldDelim

Syntax
public String getFieldDelim();
Return Value

Returns the field delimiter character sequence.

Description

Retrieves the current field delimiter character or characters.

DhTabularDataSource.getFilter

Syntax
public String getFilter();
Return Value

Returns the data filter.

Description

Retrieves the current data filter string.

See Also
setDataFilter

DhTabularDataSource.getRowDelim

Syntax
public String getRowDelim();
Return Value

Returns the row delimiter character sequence.

Description

Retrieves the current row delimiter character or characters.

DhTabularDataSource.getSortColumns

Syntax
public String getSortColumns( );
Return Value

Returns the current sort string.

Description

Retrieves the current column sort setting string.

See Also
setSortColumns

DhTabularDataSource.getTextQualifier

Syntax
public char getTextQualifier();
Return Value

Returns the current text qualifier character.

Description

Retrieves the current text qualifier character. The default is the double quotation mark (").

DhTabularDataSource.getUseHeader

Syntax
public boolean getUseHeader();
Return Value

Returns true if first the line of data contains header information, or returns false if it does not.

Description

Retrieves the current header-row setting.

See Also
setUseHeader()

DhTabularDataSource.reset

Syntax
public void reset();
Description

Queries the data again based on the new control settings.

DhTabularDataSource.setCaseSensitive

Syntax
public void setCaseSensitive( boolean fCaseSensitive );
Parameters
fCaseSensitive
Set to true to sort with case sensitivity; set to false to ignore case.
Description

Sets case sensitivity in sorting.

DhTabularDataSource.setDataUrl

Syntax
public void setDataUrl( String strUrl );
Parameters
strUrl
The URL of the data file.
Description

Sets the URL for retrieving the file data in a standard format, such as http:, file:, ftp:, and so on.

Note: This URL must be in the same security zone as the document that loaded the control.

DhTabularDataSource.setEscapeChar

Syntax
public void setEscapeChar( char c );
Parameters
c
The escape character.
Description

Specifies the character used to escape special characters. The default is none.

DhTabularDataSource.setFieldDelim

Syntax
public void setFieldDelim( String fd );
Parameters
fd
The new field delimiter character or sequence.
Description

Sets the field delimiter character or characters. The default is a comma (,).

DhTabularDataSource.setFilter

Syntax
public void setFilter( String strFilter );
Parameters
strFilter
The new data filter; for example, "PhoneNum <> '9*'" or "(Quantity > 10 & color = 'lime') | Quantity < 5".
Description

Sets the filter for the data display, and then queries for the data again.

DhTabularDataSource.setRowDelim

Syntax
public void setRowDelim( String rd );
Parameters
rd
The new row delimiter character or sequence.
Description

Sets the row delimiter character(s). The default is the newline character.

DhTabularDataSource.setSortColumns

Syntax
public void setSortColumns( String strSort );
Parameters
strSort
The sort description string.
Description

Sets the column or columns to be sorted in ascending or descending order. The following example sorts the "ProductName" column ascending, followed by the "Price" column descending:

ProductName; -Price

DhTabularDataSource.setTextQualifier

Syntax
public void setTextQualifier( char c );
Parameters
c
The text qualifier character.
Description

Specifies a single character used to surround fields that can include special characters such as new lines, tabs, or commas. These characters can also be active as field or row delimiters. The default value is the double quotation mark (").

DhTabularDataSource.setUseHeader

Syntax
public void setUseHeader( boolean fUseHeader );
Parameters
fUseHeader
Set to true if first row contains header information; set to false if it does not.
Description

Specifies whether the first row of the data contains header information.


 DhText Class

DhText Class

This Package | All Packages

DhStyleBase
  |
  +--DhElement
    |
    +--DhText
public class DhText
extends DhElement

Represents static text in an HTML document. This element is displayed in one of two modes: freely formatted (the default) or honor white space. The latter means that all white space (including carriage returns) is maintained.

Constructors
Name | Description
DhText() | Creates a DhText object.
DhText( String text ) | Creates a DhText object.

Methods
Name | Description
getRespectSpace() | Determines if this element currently honors white space.
getText() | Retrieves the text this element currently displays when rendered.
hasDefaultText() | Determines if there is text in the object.
setRespectSpace(boolean f) | Sets the text format either to honor white space or to be freely formatted.
setText( String s ) | Sets (or resets) the text to display in this element.

Constructors

DhText.DhText

Syntax 1
public DhText();
Description

Creates a DhText object.

Syntax 2
public DhText( String text );
Parameters
text
The text to display.
Description

Creates a DhText object. For one-step construction, the text parameter is what is displayed in this element.

Methods

DhText.getRespectSpace

Syntax
public synchronized boolean getRespectSpace();
Return Value

Returns true if white space is honored; otherwise, returns false.

Description

Determines if this element currently honors white space.

See Also
setRespectSpace(boolean)

DhText.getText

Syntax
public synchronized String getText();
Return Value

Returns the text this element displays.

Description

Retrieves the text this element currently displays when rendered.

DhText.hasDefaultText

Syntax
public boolean hasDefaultText();
Return Value

Returns true if there is no text; otherwise, returns false.

Description

Determines if there is text in the object.

DhText.setRespectSpace

Syntax
public synchronized void setRespectSpace( boolean f );
Parameters
f
Set to true to honor white space; set to false (the default) to cause the text to be freely formatted.
Description

Sets the text format either to honor white space or to be freely formatted.

DhText.setText

Syntax
public synchronized void setText( String s );
Parameters
s
The text to display.
Description

Sets (or resets) the text to display in this element.


 DhTriState Class

DhTriState Class

This Package | All Packages

public class DhTriState

Topic under construction.

Constructors
Name | Description
DhTriState( DhElement element ) | Topic under construction.
DhTriState ( DhElement element, DhSetStringCallback callback, String normalString, String mouseEnterString, String mouseDownString ) | Topic under construction.
DhTriState( DhElement element, DhSetIntCallback callback, int normalInt, int mouseEnterInt, int mouseDownInt ) | Topic under construction.

Methods
Name | Description
enable( boolean fOn ) | Topic under construction.

Constructors

DhTriState.DhTriState

Syntax 1
public DhTriState( DhElement element );
Description

Topic under construction.

Syntax 2
public DhTriState ( DhElement element, DhSetStringCallback callback, String normalString, String mouseEnterString, String mouseDownString );
Description

Topic under construction.

Syntax 3
public DhTriState( DhElement element, DhSetIntCallback callback, int normalInt, int mouseEnterInt, int mouseDownInt );
Description

Topic under construction.

Methods

DhTriState.enable

Syntax
public synchronized void enable( boolean fOn );
Description

Topic under construction.


 DhTriStateImage Class

DhTriStateImage Class

This Package | All Packages

DhTriState
  |
  +--DhTriStateImage
public class DhTriStateImage
extends DhTriState

Topic under construction.

Constructors
Name | Description
DhTriStateImage ( DhImage image, String normalURL, String mouseOverURL, String mouseDownURL ) | Topic under construction.

Constructors

DhTriStateImage.DhTriStateImage

Syntax
public DhTriStateImage ( DhImage image, String normalURL, String mouseOverURL, String mouseDownURL );
Description

Topic under construction.


 DhTriStateLink Class

DhTriStateLink Class

This Package | All Packages

DhTriState
  |
  +--DhTriStateLink
public class DhTriStateLink
extends DhTriState

Topic under construction.

Constructors
Name | Description
DhTriStateLink ( DhHyperlink link, int normalColor, int mouseOverColor, int mouseDownColor ) | Topic under construction.

Constructors

DhTriStateLink.DhTriStateLink

Syntax
public DhTriStateLink ( DhHyperlink link, int normalColor, int mouseOverColor, int mouseDownColor );
Description

Topic under construction.


 DhUnexpectedStateException Class

DhUnexpectedStateException Class

This Package | All Packages

RuntimeException
  |
  +--DhUnexpectedStateException
public class DhUnexpectedStateException
extends RuntimeException

Signals that a request for a named element failed, because an element with that name does not exist.

Constructors
Name | Description
DhUnexpectedStateException() | Constructs a ElementNotFoundException with no detail message.
DhUnexpectedStateException(String s) | Constructs a ElementNotFoundException with a detail message.

Constructors

DhUnexpectedStateException.DhUnexpectedStateException

Syntax 1
public DhUnexpectedStateException();
Description

Constructs a ElementNotFoundException with no detail message.

Syntax 2
public DhUnexpectedStateException( String s );
Description

Constructs a ElementNotFoundException with a detail message.


 DhUnitEnum Class

DhUnitEnum Class

This Package | All Packages

Enum
  |
  +--DhUnitEnum
public class DhUnitEnum
extends cor.Enum
implements DhStringIDs

Provides constants for various unit types in DHTML.

Fields
Name | Description
UNIT_AUTO | Represents the auto type.
UNIT_CM | Represents the centimeter (cm) type.
UNIT_COLOR | Represents the color type.
UNIT_EM | Represents the relative height of the element's font (em).
UNIT_EX | Represents an x height (ex).
UNIT_INCH | Represents an inches (in) type.
UNIT_MM | Represents a millimeter (mm) type.
UNIT_NULL | Represents an unspecified or absent type.
UNIT_PC | Represents a pica (pc) type.
UNIT_PERCENT | Represents the percentage (%) type.
UNIT_PIXEL | Represents a pixel (px) type.
UNIT_POINT | Represents a point (pt) type.

Fields

DhUnitEnum.UNIT_AUTO

Syntax
public static final int UNIT_AUTO;
Description
Represents the auto type.

DhUnitEnum.UNIT_CM

Syntax
public static final int UNIT_CM;
Description
Represents the centimeter (cm) type.

DhUnitEnum.UNIT_COLOR

Syntax
public static final int UNIT_COLOR;
Description
Represents the color type.

DhUnitEnum.UNIT_EM

Syntax
public static final int UNIT_EM;
Description
Represents the relative height of the element's font (em).

DhUnitEnum.UNIT_EX

Syntax
public static final int UNIT_EX;
Description
Represents an x height (ex). This is approximately the height of the letter 'x' in the current element font.

DhUnitEnum.UNIT_INCH

Syntax
public static final int UNIT_INCH;
Description
Represents an inches (in) type.

DhUnitEnum.UNIT_MM

Syntax
public static final int UNIT_MM;
Description
Represents a millimeter (mm) type.

DhUnitEnum.UNIT_NULL

Syntax
public static final int UNIT_NULL;
Description
Represents an unspecified or absent type.

DhUnitEnum.UNIT_PC

Syntax
public static final int UNIT_PC;
Description
Represents a pica (pc) type.

DhUnitEnum.UNIT_PERCENT

Syntax
public static final int UNIT_PERCENT;
Description
Represents the percentage (%) type.

DhUnitEnum.UNIT_PIXEL

Syntax
public static final int UNIT_PIXEL;
Description
Represents a pixel (px) type.

DhUnitEnum.UNIT_POINT

Syntax
public static final int UNIT_POINT;
Description
Represents a point (pt) type.


 DhUnknownHTMLException Class

DhUnknownHTMLException Class

This Package | All Packages

RuntimeException
  |
  +--DhUnknownHTMLException
public class DhUnknownHTMLException
extends RuntimeException

Signals that a request for a named element failed, because an element with that name does not exist.

Constructors
Name | Description
DhUnknownHTMLException() | Constructs a ElementNotFoundException with no detail message.
DhUnknownHTMLException(String s) | Constructs a ElementNotFoundException with a detail message.

Constructors

DhUnknownHTMLException.DhUnknownHTMLException

Syntax 1
public DhUnknownHTMLException();
Description

Constructs a ElementNotFoundException with no detail message.

Syntax 2
public DhUnknownHTMLException( String s );
Description

Constructs a ElementNotFoundException with a detail message.


 DhWindow Class

DhWindow Class

This Package | All Packages

public class DhWindow

Represents an HTML window object.

Constructors
Name | Description
DhWindow() | Creates a DhWindow object.
DhWindow(IHTMLWindow2 window, IHTMLDocument2 docPeer, DhDocument document) | Creates a DhWindow object.

Methods
Name | Description
close() | Closes the window, and resets its document and window peers to null.
findWindow( IHTMLWindow2 windowPeer) | Loops through all the known windows and tries to locate the one with the specified windowPeer.
getBrowser() | Retrieves the representation of the browser object.
getClosed() | Determines if the window is closed.
getDialogArguments() | Retrieves the arguments passed to a modal dialog window.
getDocument() | Retrieves the document contained in this window.
getEventPeer() | Retrieves a peer that handles events for this window.
getFrame(String name) | Retrieves the first frame that has the specified name.
getFrames() | Retrieves an array of DhWindow objects, one for each frame enclosed in this window.
getHashString() | Retrieves a hash string passed to the document.
getHistoryLength() | Retrieves the number of entries in the window's history.
getName() | Retrieves a string representing the name of the window.
getParent() | Retrieves the parent of this window.
getPeer() | Retrieves the underlying HTML peer element for this class.
getReturnValue() | Retrieves the return value from a modal dialog window.
getSearchString() | Retrieves a search string passed to the document.
getUrl() | Retrieves a string representing the URL of the window's document.
getWindowPeer() | Retrieves the underlying HTML peer element for this class.
goBackInHistory(int delta, DhEventHandler h) | Loads the previous URL in the history list.
goForwardInHistory(int delta, DhEventHandler h) | Loads the next URL in the history list.
goRelativeInHistory(int delta, DhEventHandler h) | Loads the previous URL in the history list.
MessageBox( String s ) | Displays a modal user message box.
navigate(String url, DhEventHandler h) | Opens a new URL in this window with the specified name and properties and returns a DhWindow handle to the newly opened window.
open(String url, String name, DhWindowInfo wi, boolean fReplace) | Opens a new URL in this window with the given name and properties and returns a DhWindow handle to the newly opened window.
setFocus(boolean focus) | Sets or removes the focus of the current window.
setName(String name) | Sets the name of the current window.
setReturnValue(Variant retValue) | Retrieves the return value from a modal dialog window.
setStatus(String s ) | Displays a string in the status bar of the window host (typically the browser).
showModalDialog(String dialogUrl, Variant dialogArgs, DhDialogInfo di) | Opens an HTML dialog window using the URL as the source of the contents and dialoginfo to define the appearance of the dialog window.

Constructors

DhWindow.DhWindow

Syntax 1
public DhWindow();
Description

Creates a DhWindow object.

Syntax 2
public DhWindow( IHTMLWindow2 window, IHTMLDocument2 docPeer, DhDocument document );
Parameters
window
The peer for this window.
document
The document associated with this window.
Description

Creates a DhWindow object.

Methods

DhWindow.close

Syntax
public synchronized void close();
Description

Closes the window, and resets its document and window peers to null.

DhWindow.findWindow

Syntax
protected synchronized DhWindow findWindow( IHTMLWindow2 windowPeer );
Parameters
windowPeer
The windowPeer to be searched on.
Return Value

Returns the DhWindow object corresponding to the specified windowPeer.

Description

Loops through all the known windows and tries to locate the one with the specified windowPeer.

DhWindow.getBrowser

Syntax
final public DhBrowser getBrowser();
Return Value

Returns an object representing the browser.

Description

Retrieves the representation of the browser object.

DhWindow.getClosed

Syntax
final public synchronized boolean getClosed();
Return Value

Returns true if the window is closed; otherwise, returns false.

Description

Determines if the window is closed.

DhWindow.getDialogArguments

Syntax
final public Variant getDialogArguments();
Return Value

Returns arguments passed to this dialog window through showModalDialog().

Description

Retrieves the arguments passed to a modal dialog window.

DhWindow.getDocument

Syntax
public synchronized DhDocument getDocument();
Return Value

Returns the document associated with this window.

Description

Retrieves the document contained in this window. The result can be null if the document is not accessible (for example, because of security restrictions).

DhWindow.getEventPeer

Syntax
final public IUnknown getEventPeer();
Return Value

Returns an IUnknown object containing a reference to the peer that handles events for this window.

Description

Retrieves a peer that handles events for this window.

DhWindow.getFrame

Syntax
public DhWindow getFrame( String name );
Parameters
name
The name of the frame to locate.
Return Value

Returns the window defining the enclosed frame having the specified name.

Description

Retrieves the first frame that has the specified name. This name has to be unique. Otherwise, it returns null.

DhWindow.getFrames

Syntax
public DhWindow[] getFrames();
Return Value

Returns the array of windows defining the enclosed frames.

Description

Retrieves an array of DhWindow objects, one for each frame enclosed in this window.

DhWindow.getHashString

Syntax
final public String getHashString();
Return Value

Returns hash segment of the window's URL.

Description

Retrieves a hash string passed to the document. This is usually the string after the hash mark (#).

DhWindow.getHistoryLength

Syntax
final public int getHistoryLength();
Return Value

Returns the history length.

Description

Retrieves the number of entries in the window's history.

DhWindow.getName

Syntax
final public String getName();
Return Value

Returns the name of the window.

Description

Retrieves a string representing the name of the window.

DhWindow.getParent

Syntax
public DhWindow getParent();
Return Value

Returns the parent window of this window.

Description

Retrieves the parent of this window.

DhWindow.getPeer

Syntax
final public synchronized IUnknown getPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Retrieves the underlying HTML peer element for this class. This method returns null if the document is not bound to this class. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLWindow2). This method always returns null if the code is running in a Web server environment.

Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhWindow.getReturnValue

Syntax
final public Variant getReturnValue();
Return Value

Returns arguments passed to this dialog window through showModalDialog().

Description

Retrieves the return value from a modal dialog window.

DhWindow.getSearchString

Syntax
final public String getSearchString();
Return Value

Returns the search segment of URL of the window.

Description

Retrieves a search string passed to the document. This is usually the string after the question mark (?).

DhWindow.getUrl

Syntax
final public String getUrl();
Return Value

Returns the location URL of the window.

Description

Retrieves a string representing the URL of the window's document.

DhWindow.getWindowPeer

Syntax
protected synchronized IHTMLWindow2 getWindowPeer();
Return Value

Returns the element peer underlying the HTML peer for this class.

Description

Retrieves the underlying HTML peer element for this class. This method returns null if the document is not bound to this class. Java code that is running in a trusted environment can freely cast the resulting reference to a specific element peer type (for example, wfc.html.om.IHTMLWindow2). This method always returns null if the code is running in a Web server environment.

Calling this method represents a very advanced usage scenario. Typically, you would never use this method.

DhWindow.goBackInHistory

Syntax
final public void goBackInHistory( int delta, DhEventHandler h );
Parameters
delta
The number of pages to go back relative to the current page.
Description

Loads the previous URL in the history list.

DhWindow.goForwardInHistory

Syntax
final public void goForwardInHistory( int delta, DhEventHandler h );
Parameters
delta
The number of pages to go forward relative to the current page.
Description

Loads the next URL in the history list.

DhWindow.goRelativeInHistory

Syntax
final public void goRelativeInHistory( int delta, DhEventHandler h );
Parameters
delta
The number of pages to go back or forward relative to the current page.
Return Value

Returns a unique index representing this navigation.

Description

Loads the previous URL in the history list.

DhWindow.MessageBox

Syntax
final public void MessageBox( String s );
Parameters
s
The message to display.
Description

Displays a modal user message box.

DhWindow.navigate

Syntax
final public void navigate( String url, DhEventHandler h );
Parameters
url
A string defining the URL of the new location.
Description

Opens a new URL in this window with the specified name and properties and returns a DhWindow handle to the newly opened window.

DhWindow.open

Syntax
final public DhWindow open( String url, String name, DhWindowInfo wi, boolean fReplace );
Parameters
url
The string defining the URL of the new location.
name
The name of the window. This name cannot have spaces in it.
wi
A structure (DhWindowInfo class) defining the appearance and size of the new window.
fReplace
Set to true to replace the current contents.
Description

Opens a new URL in this window with the given name and properties and returns a DhWindow handle to the newly opened window.

DhWindow.setFocus

Syntax
final public void setFocus( boolean focus );
Parameters
focus
Set to true to set the focus; set to false to remove focus.
Description

Sets or removes the focus of the current window.

DhWindow.setName

Syntax
final public void setName( String name );
Parameters
name
The name of the window. This name cannot have punctuation in it.
Description

Sets the name of the current window.

DhWindow.setReturnValue

Syntax
final public void setReturnValue( Variant retValue );
Return Value

Returns arguments passed to this dialog through showModalDialog().

Description

Retrieves the return value from a modal dialog window.

DhWindow.setStatus

Syntax
final public void setStatus( String s );
Parameters
s
The string to display in the status bar.
Description

Displays a string in the status bar of the window host (typically the browser).

DhWindow.showModalDialog

Syntax
final public Variant showModalDialog( String dialogUrl, Variant dialogArgs, DhDialogInfo di );
Parameters
dialogUrl
A string defining the URL of the dialog window contents.
dialogArgs
Arguments to the document defining the contents.
di
A structure which defines the appearance of the dialog window.
Return Value

Returns a com.ms.com.Variant object that packages the returned values or values of the dialog window.

Description

Opens an HTML dialog window using the URL as the source of the contents and dialoginfo to define the appearance of the dialog window. It retrieves a Variant object that packages the return value or values of the dialog window.


 DhWindowInfo Class

DhWindowInfo Class

This Package | All Packages

public class DhWindowInfo

Sets the features for a new browser window. For more information, see DhWindow.open.

Fields
Name | Description
isResizable | Informs the browser to open a new window and make it resizable using resize handles.
showChannelMode | Informs the browser to open a new window in theatre mode and show the channel band.
showDirectoryButtons | Informs the browser to open a new window and add directory buttons.
showFullScreen | Informs the browser to open a new window using the full screen as size.
showLocation | Informs the browser to open a new window and display the input field for entering URLs directly into the browser.
showMenubar | Informs the browser to open a new window with the menu bar showing.
showScrollbars | Informs the browser to open a new window with the scroll bars showing.
showStatusbar | Informs the browser to open a new window with the status bar showing.
showToolbar | Informs the browser to open a new window with toolbars showing.
size | Informs the browser to open a new window using the rectangle as the size.

Constructors
Name | Description
DhWindowInfo() | Topic under construction.
DhWindowInfo(Rectangle size) | Topic under construction.

Methods
Name | Description
addFeature(String name, String value) | Adds a new custom feature.
getValue(String name) | Retrieves the value of the custom feature.
removeFeature(String name) | Removes a custom feature.
toString() | Topic under construction.

Fields

DhWindowInfo.isResizable

Syntax
public boolean isResizable;
Description
Informs the browser to open a new window and make it resizable using resize handles. This is used by DhWindow.open().

DhWindowInfo.showChannelMode

Syntax
public boolean showChannelMode;
Description
Informs the browser to open a new window in theatre mode and show the channel band. This is used by DhWindow.open().

DhWindowInfo.showDirectoryButtons

Syntax
public boolean showDirectoryButtons;
Description
Informs the browser to open a new window and add directory buttons. This is used by DhWindow.open().

DhWindowInfo.showFullScreen

Syntax
public boolean showFullScreen;
Description
Informs the browser to open a new window using the full screen as size. This is used by DhWindow.open().

DhWindowInfo.showLocation

Syntax
public boolean showLocation;
Description
Informs the browser to open a new window and display the input field for entering URLs directly into the browser. This is used by DhWindow.open().

DhWindowInfo.showMenubar

Syntax
public boolean showMenubar;
Description
Informs the browser to open a new window with the menu bar showing. This is used by DhWindow.open().

DhWindowInfo.showScrollbars

Syntax
public boolean showScrollbars;
Description
Informs the browser to open a new window with the scroll bars showing. This is used by DhWindow.open().

DhWindowInfo.showStatusbar

Syntax
public boolean showStatusbar;
Description
Informs the browser to open a new window with the status bar showing. This is used by DhWindow.open().

DhWindowInfo.showToolbar

Syntax
public boolean showToolbar;
Description
Informs the browser to open a new window with toolbars showing. This is used by DhWindow.open().

DhWindowInfo.size

Syntax
public Rectangle size;
Description
Informs the browser to open a new window using the rectangle as the size. This is used by DhWindow.open().

Constructors

DhWindowInfo.DhWindowInfo

Syntax 1
public DhWindowInfo();
Description

Topic under construction.

Syntax 2
public DhWindowInfo( Rectangle size );
Description

Topic under construction.

Methods

DhWindowInfo.addFeature

Syntax
public void addFeature( String name, String value );
Parameters
name
The name of the custom feature.
value
The value of the custom feature.
Description

Adds a new custom feature.

DhWindowInfo.getValue

Syntax
public String getValue( String name );
Parameters
name
The name of the custom feature.
Description

Retrieves the value of the custom feature.

DhWindowInfo.removeFeature

Syntax
public void removeFeature( String name );
Parameters
name
The name of the custom feature.
Description

Removes a custom feature.

DhWindowInfo.toString

Syntax
public String toString();
Description

Topic under construction.


 LinkTargetEnum Class

LinkTargetEnum Class

This Package | All Packages

Enum
  |
  +--LinkTargetEnum
public class LinkTargetEnum
extends Enum

Provides constants for setting the document's target window. These constants are used by setStockTargetWindow and getStockTargetWindow.

Fields
Name | Description
NEW_WINDOW | Instructs the browser to put the document into a new top-level browser window.
PARENT_DOC | Instructs the browser to put the document into the window that is the parent of the current window.
THIS_FRAME | Instructs the browser to put the document into the current frame of the frameset.
TOP_FRAME | Instructs the browser to put the document into the top-most window, replacing the current frameset.

Fields

LinkTargetEnum.NEW_WINDOW

Syntax
public static final int NEW_WINDOW;
Description
Instructs the browser to put the document into a new top-level browser window.

LinkTargetEnum.PARENT_DOC

Syntax
public static final int PARENT_DOC;
Description
Instructs the browser to put the document into the window that is the parent of the current window.

LinkTargetEnum.THIS_FRAME

Syntax
public static final int THIS_FRAME;
Description
Instructs the browser to put the document into the current frame of the frameset.

LinkTargetEnum.TOP_FRAME

Syntax
public static final int TOP_FRAME;
Description
Instructs the browser to put the document into the top-most window, replacing the current frameset.


 DhColors Interface

DhColors Interface

This Package | All Packages

public interface DhColors

Defines the HTML color constants.

Fields
Name | Description
ALICEBLUE | The color alice blue.
ANTIQUEWHITE | The color antique white.
AQUA | The color aqua.
AQUAMARINE | The color aquamarine.
AZURE | The color azure.
BEIGE | The color beige.
BISQUE | The color bisque.
BLACK | The color black.
BLANCHEDALMOND | The color blanched almond.
BLUE | The color blue.
BLUEVIOLET | The color violet blue.
BROWN | The color brown.
BURLYWOOD | The color burlywood.
CADETBLUE | The color cadet blue.
CHARTREUSE | The color chartreuse.
CHOCOLATE | The color chocolate brown.
CORAL | The color coral.
CORNFLOWERBLUE | The color cornflower blue.
CORNSILK | The color cornsilk.
CRIMSON | The color crimson.
CYAN | The color cyan.
DARKBLUE | The color dark blue.
DARKCYAN | The color dark cyan.
DARKGOLDENROD | The color dark goldenrod yellow.
DARKGRAY | The color dark gray.
DARKGREEN | The color dark green.
DARKKHAKI | The color dark khaki.
DARKMAGENTA | The color dark magenta.
DARKOLIVEGREEN | The color dark olive green.
DARKORANGE | The color dark orange.
DARKORCHID | The color dark orchid.
DARKRED | The color dark red.
DARKSALMON | The color dark salmon.
DARKSEAGREEN | The color dark sea green.
DARKSLATEBLUE | The color dark slate blue.
DARKSLATEGRAY | The color dark slate gray.
DARKTURQUOISE | The color dark turquoise.
DARKVIOLET | The color dark violet.
DEEPPINK | The color deep pink.
DEEPSKYBLUE | The color deep sky blue.
DIMGRAY | The color dim gray.
DODGERBLUE | The color Dodger blue.
FIREBRICK | The color firebrick.
FLORALWHITE | The color floral white.
FORESTGREEN | The color forest green.
FUCHSIA | The color fuchsia.
GAINSBORO | The color gainsboro.
GHOSTWHITE | The color ghost white.
GOLD | The color gold.
GOLDENROD | The color goldenrod (yellow).
GRAY | The color gray.
GREEN | The color green.
GREENYELLOW | The color green yellow.
HONEYDEW | The color honeydew.
HOTPINK | The color hot pink.
INDIANRED | The color Indian red.
INDIGO | The color indigo.
IVORY | The color ivory.
KHAKI | The color khaki.
LAVENDER | The color lavender.
LAVENDERBLUSH | The color lavender blush.
LAWNGREEN | The color lawn green.
LEMONCHIFFON | The color lemon chiffon.
LIGHTBLUE | The color light blue.
LIGHTCORAL | The color light coral.
LIGHTCYAN | The color light cyan.
LIGHTGOLDENRODYELLOW | The color light goldenrod yellow.
LIGHTGREEN | The color light green.
LIGHTGREY | The color light grey.
LIGHTPINK | The color light pink.
LIGHTSALMON | The color light salmon.
LIGHTSEAGREEN | The color light sea green.
LIGHTSKYBLUE | The color light sky blue.
LIGHTSLATEGRAY | The color slate gray.
LIGHTSTEELBLUE | The color steel blue.
LIGHTYELLOW | The color light yellow.
LIME | The color lime.
LIMEGREEN | The color lime green.
LINEN | The color linen.
MAGENTA | The color magenta.
MAROON | The color maroon.
MEDIUMAQUAMARINE | The color medium aquamarine.
MEDIUMBLUE | The color medium blue.
MEDIUMORCHID | The color medium orchid.
MEDIUMPURPLE | The color medium purple.
MEDIUMSEAGREEN | The color medium sea green.
MEDIUMSLATEBLUE | The color medium slate blue.
MEDIUMSPRINGGREEN | The color medium spring green.
MEDIUMTURQUOISE | The color medium turquoise.
MEDIUMVIOLETRED | The color medium violet red.
MIDNIGHTBLUE | The color midnight blue.
MINTCREAM | The color mint cream.
MISTYROSE | The color misty rose.
MOCCASIN | The color moccasin.
NAVAJOWHITE | The color navajo white.
NAVY | The color navy blue.
OLDLACE | The color old lace.
OLIVE | The color olive green.
OLIVEDRAB | The color drab olive green.
ORANGE | The color orange.
ORANGERED | The color orange red.
ORCHID | The color orchid.
PALEGOLDENROD | The color pale goldenrod yellow.
PALEGREEN | The color pale green.
PALETURQUOISE | The color pale turquoise.
PALEVIOLETRED | The color pale violet red.
PAPAYAWHIP | The color papayawhip.
PEACHPUFF | The color peachpuff.
PERU | The color Peru.
PINK | The color pink.
PLUM | The color plum.
POWDERBLUE | The color powder blue.
PURPLE | The color purple.
RED | The color red.
ROSYBROWN | The color rosy brown.
ROYALBLUE | The color royal blue.
SADDLEBROWN | The color saddle brown.
SALMON | The color salmon.
SANDYBROWN | The color sandy brown.
SEAGREEN | The color sea green.
SEASHELL | The color seashell.
SIENNA | The color sienna.
SILVER | The color silver.
SKYBLUE | The color sky blue.
SLATEBLUE | The color slate blue.
SLATEGRAY | The color slate gray.
SNOW | The color snow.
SPRINGGREEN | The color spring green.
STEELBLUE | The color steel blue.
TAN | The color tan.
TEAL | The color teal.
THISTLE | The color thistle.
TOMATO | The color tomato red.
TURQUOISE | The color turquoise.
VIOLET | The color violet.
WHEAT | The color wheat.
WHITE | The color white.
WHITESMOKE | The color white smoke.
YELLOW | The color yellow.
YELLOWGREEN | The color yellow green.

Fields

DhColors.ALICEBLUE

Syntax
public static final int ALICEBLUE;
Description
The color alice blue.

DhColors.ANTIQUEWHITE

Syntax
public static final int ANTIQUEWHITE;
Description
The color antique white.

DhColors.AQUA

Syntax
public static final int AQUA;
Description
The color aqua.

DhColors.AQUAMARINE

Syntax
public static final int AQUAMARINE;
Description
The color aquamarine.

DhColors.AZURE

Syntax
public static final int AZURE;
Description
The color azure.

DhColors.BEIGE

Syntax
public static final int BEIGE;
Description
The color beige.

DhColors.BISQUE

Syntax
public static final int BISQUE;
Description
The color bisque.

DhColors.BLACK

Syntax
public static final int BLACK;
Description
The color black.

DhColors.BLANCHEDALMOND

Syntax
public static final int BLANCHEDALMOND;
Description
The color blanched almond.

DhColors.BLUE

Syntax
public static final int BLUE;
Description
The color blue.

DhColors.BLUEVIOLET

Syntax
public static final int BLUEVIOLET;
Description
The color violet blue.

DhColors.BROWN

Syntax
public static final int BROWN;
Description
The color brown.

DhColors.BURLYWOOD

Syntax
public static final int BURLYWOOD;
Description
The color burlywood.

DhColors.CADETBLUE

Syntax
public static final int CADETBLUE;
Description
The color cadet blue.

DhColors.CHARTREUSE

Syntax
public static final int CHARTREUSE;
Description
The color chartreuse.

DhColors.CHOCOLATE

Syntax
public static final int CHOCOLATE;
Description
The color chocolate brown.

DhColors.CORAL

Syntax
public static final int CORAL;
Description
The color coral.

DhColors.CORNFLOWERBLUE

Syntax
public static final int CORNFLOWERBLUE;
Description
The color cornflower blue.

DhColors.CORNSILK

Syntax
public static final int CORNSILK;
Description
The color cornsilk.

DhColors.CRIMSON

Syntax
public static final int CRIMSON;
Description
The color crimson.

DhColors.CYAN

Syntax
public static final int CYAN;
Description
The color cyan.

DhColors.DARKBLUE

Syntax
public static final int DARKBLUE;
Description
The color dark blue.

DhColors.DARKCYAN

Syntax
public static final int DARKCYAN;
Description
The color dark cyan.

DhColors.DARKGOLDENROD

Syntax
public static final int DARKGOLDENROD;
Description
The color dark goldenrod yellow.

DhColors.DARKGRAY

Syntax
public static final int DARKGRAY;
Description
The color dark gray.

DhColors.DARKGREEN

Syntax
public static final int DARKGREEN;
Description
The color dark green.

DhColors.DARKKHAKI

Syntax
public static final int DARKKHAKI;
Description
The color dark khaki.

DhColors.DARKMAGENTA

Syntax
public static final int DARKMAGENTA;
Description
The color dark magenta.

DhColors.DARKOLIVEGREEN

Syntax
public static final int DARKOLIVEGREEN;
Description
The color dark olive green.

DhColors.DARKORANGE

Syntax
public static final int DARKORANGE;
Description
The color dark orange.

DhColors.DARKORCHID

Syntax
public static final int DARKORCHID;
Description
The color dark orchid.

DhColors.DARKRED

Syntax
public static final int DARKRED;
Description
The color dark red.

DhColors.DARKSALMON

Syntax
public static final int DARKSALMON;
Description
The color dark salmon.

DhColors.DARKSEAGREEN

Syntax
public static final int DARKSEAGREEN;
Description
The color dark sea green.

DhColors.DARKSLATEBLUE

Syntax
public static final int DARKSLATEBLUE;
Description
The color dark slate blue.

DhColors.DARKSLATEGRAY

Syntax
public static final int DARKSLATEGRAY;
Description
The color dark slate gray.

DhColors.DARKTURQUOISE

Syntax
public static final int DARKTURQUOISE;
Description
The color dark turquoise.

DhColors.DARKVIOLET

Syntax
public static final int DARKVIOLET;
Description
The color dark violet.

DhColors.DEEPPINK

Syntax
public static final int DEEPPINK;
Description
The color deep pink.

DhColors.DEEPSKYBLUE

Syntax
public static final int DEEPSKYBLUE;
Description
The color deep sky blue.

DhColors.DIMGRAY

Syntax
public static final int DIMGRAY;
Description
The color dim gray.

DhColors.DODGERBLUE

Syntax
public static final int DODGERBLUE;
Description
The color Dodger blue.

DhColors.FIREBRICK

Syntax
public static final int FIREBRICK;
Description
The color firebrick.

DhColors.FLORALWHITE

Syntax
public static final int FLORALWHITE;
Description
The color floral white.

DhColors.FORESTGREEN

Syntax
public static final int FORESTGREEN;
Description
The color forest green.

DhColors.FUCHSIA

Syntax
public static final int FUCHSIA;
Description
The color fuchsia.

DhColors.GAINSBORO

Syntax
public static final int GAINSBORO;
Description
The color gainsboro.

DhColors.GHOSTWHITE

Syntax
public static final int GHOSTWHITE;
Description
The color ghost white.

DhColors.GOLD

Syntax
public static final int GOLD;
Description
The color gold.

DhColors.GOLDENROD

Syntax
public static final int GOLDENROD;
Description
The color goldenrod (yellow).

DhColors.GRAY

Syntax
public static final int GRAY;
Description
The color gray.

DhColors.GREEN

Syntax
public static final int GREEN;
Description
The color green.

DhColors.GREENYELLOW

Syntax
public static final int GREENYELLOW;
Description
The color green yellow.

DhColors.HONEYDEW

Syntax
public static final int HONEYDEW;
Description
The color honeydew.

DhColors.HOTPINK

Syntax
public static final int HOTPINK;
Description
The color hot pink.

DhColors.INDIANRED

Syntax
public static final int INDIANRED;
Description
The color Indian red.

DhColors.INDIGO

Syntax
public static final int INDIGO;
Description
The color indigo.

DhColors.IVORY

Syntax
public static final int IVORY;
Description
The color ivory.

DhColors.KHAKI

Syntax
public static final int KHAKI;
Description
The color khaki.

DhColors.LAVENDER

Syntax
public static final int LAVENDER;
Description
The color lavender.

DhColors.LAVENDERBLUSH

Syntax
public static final int LAVENDERBLUSH;
Description
The color lavender blush.

DhColors.LAWNGREEN

Syntax
public static final int LAWNGREEN;
Description
The color lawn green.

DhColors.LEMONCHIFFON

Syntax
public static final int LEMONCHIFFON;
Description
The color lemon chiffon.

DhColors.LIGHTBLUE

Syntax
public static final int LIGHTBLUE;
Description
The color light blue.

DhColors.LIGHTCORAL

Syntax
public static final int LIGHTCORAL;
Description
The color light coral.

DhColors.LIGHTCYAN

Syntax
public static final int LIGHTCYAN;
Description
The color light cyan.

DhColors.LIGHTGOLDENRODYELLOW

Syntax
public static final int LIGHTGOLDENRODYELLOW;
Description
The color light goldenrod yellow.

DhColors.LIGHTGREEN

Syntax
public static final int LIGHTGREEN;
Description
The color light green.

DhColors.LIGHTGREY

Syntax
public static final int LIGHTGREY;
Description
The color light grey.

DhColors.LIGHTPINK

Syntax
public static final int LIGHTPINK;
Description
The color light pink.

DhColors.LIGHTSALMON

Syntax
public static final int LIGHTSALMON;
Description
The color light salmon.

DhColors.LIGHTSEAGREEN

Syntax
public static final int LIGHTSEAGREEN;
Description
The color light sea green.

DhColors.LIGHTSKYBLUE

Syntax
public static final int LIGHTSKYBLUE;
Description
The color light sky blue.

DhColors.LIGHTSLATEGRAY

Syntax
public static final int LIGHTSLATEGRAY;
Description
The color slate gray.

DhColors.LIGHTSTEELBLUE

Syntax
public static final int LIGHTSTEELBLUE;
Description
The color steel blue.

DhColors.LIGHTYELLOW

Syntax
public static final int LIGHTYELLOW;
Description
The color light yellow.

DhColors.LIME

Syntax
public static final int LIME;
Description
The color lime.

DhColors.LIMEGREEN

Syntax
public static final int LIMEGREEN;
Description
The color lime green.

DhColors.LINEN

Syntax
public static final int LINEN;
Description
The color linen.

DhColors.MAGENTA

Syntax
public static final int MAGENTA;
Description
The color magenta.

DhColors.MAROON

Syntax
public static final int MAROON;
Description
The color maroon.

DhColors.MEDIUMAQUAMARINE

Syntax
public static final int MEDIUMAQUAMARINE;
Description
The color medium aquamarine.

DhColors.MEDIUMBLUE

Syntax
public static final int MEDIUMBLUE;
Description
The color medium blue.

DhColors.MEDIUMORCHID

Syntax
public static final int MEDIUMORCHID;
Description
The color medium orchid.

DhColors.MEDIUMPURPLE

Syntax
public static final int MEDIUMPURPLE;
Description
The color medium purple.

DhColors.MEDIUMSEAGREEN

Syntax
public static final int MEDIUMSEAGREEN;
Description
The color medium sea green.

DhColors.MEDIUMSLATEBLUE

Syntax
public static final int MEDIUMSLATEBLUE;
Description
The color medium slate blue.

DhColors.MEDIUMSPRINGGREEN

Syntax
public static final int MEDIUMSPRINGGREEN;
Description
The color medium spring green.

DhColors.MEDIUMTURQUOISE

Syntax
public static final int MEDIUMTURQUOISE;
Description
The color medium turquoise.

DhColors.MEDIUMVIOLETRED

Syntax
public static final int MEDIUMVIOLETRED;
Description
The color medium violet red.

DhColors.MIDNIGHTBLUE

Syntax
public static final int MIDNIGHTBLUE;
Description
The color midnight blue.

DhColors.MINTCREAM

Syntax
public static final int MINTCREAM;
Description
The color mint cream.

DhColors.MISTYROSE

Syntax
public static final int MISTYROSE;
Description
The color misty rose.

DhColors.MOCCASIN

Syntax
public static final int MOCCASIN;
Description
The color moccasin.

DhColors.NAVAJOWHITE

Syntax
public static final int NAVAJOWHITE;
Description
The color navajo white.

DhColors.NAVY

Syntax
public static final int NAVY;
Description
The color navy blue.

DhColors.OLDLACE

Syntax
public static final int OLDLACE;
Description
The color old lace.

DhColors.OLIVE

Syntax
public static final int OLIVE;
Description
The color olive green.

DhColors.OLIVEDRAB

Syntax
public static final int OLIVEDRAB;
Description
The color drab olive green.

DhColors.ORANGE

Syntax
public static final int ORANGE;
Description
The color orange.

DhColors.ORANGERED

Syntax
public static final int ORANGERED;
Description
The color orange red.

DhColors.ORCHID

Syntax
public static final int ORCHID;
Description
The color orchid.

DhColors.PALEGOLDENROD

Syntax
public static final int PALEGOLDENROD;
Description
The color pale goldenrod yellow.

DhColors.PALEGREEN

Syntax
public static final int PALEGREEN;
Description
The color pale green.

DhColors.PALETURQUOISE

Syntax
public static final int PALETURQUOISE;
Description
The color pale turquoise.

DhColors.PALEVIOLETRED

Syntax
public static final int PALEVIOLETRED;
Description
The color pale violet red.

DhColors.PAPAYAWHIP

Syntax
public static final int PAPAYAWHIP;
Description
The color papayawhip.

DhColors.PEACHPUFF

Syntax
public static final int PEACHPUFF;
Description
The color peachpuff.

DhColors.PERU

Syntax
public static final int PERU;
Description
The color Peru.

DhColors.PINK

Syntax
public static final int PINK;
Description
The color pink.

DhColors.PLUM

Syntax
public static final int PLUM;
Description
The color plum.

DhColors.POWDERBLUE

Syntax
public static final int POWDERBLUE;
Description
The color powder blue.

DhColors.PURPLE

Syntax
public static final int PURPLE;
Description
The color purple.

DhColors.RED

Syntax
public static final int RED;
Description
The color red.

DhColors.ROSYBROWN

Syntax
public static final int ROSYBROWN;
Description
The color rosy brown.

DhColors.ROYALBLUE

Syntax
public static final int ROYALBLUE;
Description
The color royal blue.

DhColors.SADDLEBROWN

Syntax
public static final int SADDLEBROWN;
Description
The color saddle brown.

DhColors.SALMON

Syntax
public static final int SALMON;
Description
The color salmon.

DhColors.SANDYBROWN

Syntax
public static final int SANDYBROWN;
Description
The color sandy brown.

DhColors.SEAGREEN

Syntax
public static final int SEAGREEN;
Description
The color sea green.

DhColors.SEASHELL

Syntax
public static final int SEASHELL;
Description
The color seashell.

DhColors.SIENNA

Syntax
public static final int SIENNA;
Description
The color sienna.

DhColors.SILVER

Syntax
public static final int SILVER;
Description
The color silver.

DhColors.SKYBLUE

Syntax
public static final int SKYBLUE;
Description
The color sky blue.

DhColors.SLATEBLUE

Syntax
public static final int SLATEBLUE;
Description
The color slate blue.

DhColors.SLATEGRAY

Syntax
public static final int SLATEGRAY;
Description
The color slate gray.

DhColors.SNOW

Syntax
public static final int SNOW;
Description
The color snow.

DhColors.SPRINGGREEN

Syntax
public static final int SPRINGGREEN;
Description
The color spring green.

DhColors.STEELBLUE

Syntax
public static final int STEELBLUE;
Description
The color steel blue.

DhColors.TAN

Syntax
public static final int TAN;
Description
The color tan.

DhColors.TEAL

Syntax
public static final int TEAL;
Description
The color teal.

DhColors.THISTLE

Syntax
public static final int THISTLE;
Description
The color thistle.

DhColors.TOMATO

Syntax
public static final int TOMATO;
Description
The color tomato red.

DhColors.TURQUOISE

Syntax
public static final int TURQUOISE;
Description
The color turquoise.

DhColors.VIOLET

Syntax
public static final int VIOLET;
Description
The color violet.

DhColors.WHEAT

Syntax
public static final int WHEAT;
Description
The color wheat.

DhColors.WHITE

Syntax
public static final int WHITE;
Description
The color white.

DhColors.WHITESMOKE

Syntax
public static final int WHITESMOKE;
Description
The color white smoke.

DhColors.YELLOW

Syntax
public static final int YELLOW;
Description
The color yellow.

DhColors.YELLOWGREEN

Syntax
public static final int YELLOWGREEN;
Description
The color yellow green.


 DhIFilterableObject Interface

DhIFilterableObject Interface

This Package | All Packages

public interface DhIFilterableObject

Represents an interface for objects with filters. Objects that implement this interface can have filters applied to them. The following classes implement this interface:

  • DhDocument
  • DhImage
  • DhSection
  • DhStyle

Methods
Name | Description
addFilter(DhFilter filter) | Adds a filter to this element and applies it immediately.
addFilter(DhFilter filter, boolean bApply) | Adds a filter to this element.
addFilter(DhFilter filter, boolean bApply, boolean bFlush) | Adds a filter to this element.
addTransition(DhFilter trans) | Adds a transition effect to this element.
applyFilters() | Applies filters that were previously deferred.
findFilter(Class filterClass) | Retrieves the current filter with the specified filter class.
removeAllFilters() | Removes all filters from this element.
removeAllFilters(boolean bApply) | Removes all filters from this element.
removeFilter(DhFilter filter) | Removes the given filter from this element.
removeFilter(DhFilter filter, boolean bApply) | Removes the specified filter from this element.
replaceFilter(DhFilter filter1, DhFilter filter2) | This method provides an easy way to swap filters.
replaceFilter(DhFilter filter1, DhFilter filter2, boolean bApply) | This method provides an easy way to swap filters.

Methods

DhIFilterableObject.addFilter

Syntax 1
public void addFilter( DhFilter filter );
Parameters
filter
The DhFilter object to apply.
Description

Adds a filter to this element and applies it immediately. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
replaceFilter

Syntax 2
public void addFilter( DhFilter filter, boolean bApply );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter immediately; set to false to delay applying the filter.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. Filters added this way are combined with other filters that were previously added and not explicity flushed or removed.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

Syntax 3
public void addFilter( DhFilter filter, boolean bApply, boolean bFlush );
Parameters
filter
The DhFilter object to apply.
bApply
Set to true to apply the filter immediately; set to false to delay applying the filter.
bFlush
Set to true to flush the previously applied filters; set to false to combine filter with those already present.
Description

Adds a filter to this element. You can apply the filter immediately or delay application. Delaying application is useful if you are applying more than one filter to this element. You can also specify whether you want to flush filters that were previously applied to this element or whether you want this filter to be combined with those already present.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of filter already exists on this element.

See Also
applyFilters, replaceFilter

DhIFilterableObject.addTransition

Syntax
public void addTransition( DhFilter trans );
Parameters
trans
The transition effect you will run.
Description

Adds a transition effect to this element. You must call this method before you can run the effect. Note that this functionality is provided for the purpose of an extension (see the sample classes). This package does provide transition effects.

Exceptions

wfc.html.DhCantAddElementException thrown if this type of transition effect already exists on this element.

See Also
replaceFilter

DhIFilterableObject.applyFilters

Syntax
public void applyFilters();
Description

Applies filters that were previously deferred. Use this method if you called addFilter(DhFilter,boolean) with false for the second paramater. This function applies every filter that was added to this element.

See Also
addFilter(DhFilter,boolean), addFilter

DhIFilterableObject.findFilter

Syntax
public DhFilter findFilter( Class filterClass );
Parameters
filterClass
The class of the filter you are looking for, for example, wfc.html.DhDropShadowFilter.
Return Value

Returns the DhFilter (if found) that is of type filterClass.

Description

Retrieves the current filter with the specified filter class.

DhIFilterableObject.removeAllFilters

Syntax 1
public void removeAllFilters();
Description

Removes all filters from this element. This method automatically clears any sign of filters on this element.

Syntax 2
public void removeAllFilters( boolean bApply );
Description

Removes all filters from this element. You can clear all filters on this element or delay removal.

DhIFilterableObject.removeFilter

Syntax 1
public void removeFilter( DhFilter filter );
Parameters
filter
A reference to the filter to remove.
Description

Removes the given filter from this element. This method automatically reapplies other filters that may be left after this method is called.

See Also
findFilter.

Syntax 2
public void removeFilter( DhFilter filter, boolean bApply );
Parameters
filter
A reference to the filter to remove.
bApply
Set to true to reapply filters left on this element immediately; set to false to delay applying filters.
Description

Removes the specified filter from this element. You can reapply other filters that may be left after this method is called, or you can delay the process if you are removing more than one filter.

See Also
findFilter.

DhIFilterableObject.replaceFilter

Syntax 1
public void replaceFilter( DhFilter filter1, DhFilter filter2 );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1.
Description

This method provides an easy way to swap filters. It automatically applies all the changes immediately.

Syntax 2
public void replaceFilter( DhFilter filter1, DhFilter filter2, boolean bApply );
Parameters
filter1
The filter to be replaced.
filter2
The filter that is to replace filter1.
bApply
Set to true to apply visual changes immediately; set to false to delay making changes.
Description

This method provides an easy way to swap filters. You can specify whether to apply all the changes immediately or to delay making changes until later.

See Also
applyFilters


 IUploadNotify Interface

IUploadNotify Interface

This Package | All Packages

public interface IUploadNotify

Retrieves an element for the output stream. Implement this interface to supply to DhModule.write functions for writing items to the output stream.

Methods
Name | Description
getElement( DhElement e ) | Retrieves an element for the output stream.

Methods

IUploadNotify.getElement

Syntax
public DhElement getElement( DhElement e );
Return Value

Returns the element to send to the stream.

Description

Retrieves an element for the output stream. This method is called by the framework when a requested element is ready for output to the stream. Any manipulation or replacement can be performed on the element.


 Package wfc.ui

Package wfc.ui

The wfc.ui package provides the graphical user interface components of the Windows Foundation Classes. This includes both controls and graphics features.


 About wfc.ui

About wfc.ui

The wfc.ui package provides the graphical user interface components of the Windows Foundation Classes. This includes both controls and graphics features.

Classes

Class AcceleratorTable
Topic under construction.
Class Animation
Provides the animation common control.
Class AutoSizeEvent
Topic under construction.
Class AxControl
Hosts an ActiveX control.
Class Bitmap
Implements a Windows bitmap as a WFC object.
Class Border3DSide
This class defines the constants that you pass to the Graphics.drawBorder3D method to define a three-dimensional border's appearance.
Class Border3DStyle
Defines the constants that you pass to the Graphics.drawBorder3D method to define a 3D border's appearance.
Class BorderStyle
Enumeration class for window border styles.
Class Brush
This class encapsulates a Windows brush.
Class Button
Encapsulates a Windows button control.
Class ButtonState
Enumerator to be used with the drawButton* functions.
Class CaptionButton
Defines that constants that you can pass to the Graphics.drawCaptionButton method.
Class CharacterCasing
Enumeration class used to specify character casing (uppercased, lowercased, or unchanged).
Class Checkbox
Encapsulates a standard Windows check box control.
Class CheckedListBox
Provides an extension of the regular ListBox class that adds events and methods for checked list box functionality.
Class CheckState
Represents an enumeration used for various controls that can have checked or selected states (for example, a CheckBox or a CheckedListBox).
Class Color
Describes a color in an object.
Class ColumnHeader
Encapsulates the settings on a column in a ListView control.
Class ComboBox
Encapsulates a standard Windows combo box.
Class ComboBoxStyle
Defines the constants that you apply to a ComboBox control to determine its appearance.
Class Control
Defines the base functionality of a Win32 control.
Class ControlDock
Control Dock values.
Class CreateEvent
Topic under construction.
Class Cursor
Implements a Windows cursor as a WFC object.
Class DateTimeChangeEvent
The DateTimeChangeEvent is fired when the time changes in the DateTimePicker.
Class DateTimeFormatEvent
The DateTimeFormatEvent is fired when the DateTimePicker is formatting time to display to the user.
Class DateTimeFormatQueryEvent
The DateTimeFormatQueryEvent is fired when the DateTimePicker needs to determine the maximum size of text to be displayed.
Class DateTimePicker
Implements a date and time picker control.
Class DateTimeUserStringEvent
The DateTimeUserStringEvent is fired when the DateTimePicker needs to parse a user-entered string.
Class DateTimeWmKeyDownEvent
The DateTimeWmKeyDownEvent is fired when the user presses a key in a custom field.
Class DialogResult
Topic under construction.
Class DragEvent
The DragEvent is fired in response to drag-and-drop events in a control.
Class DrawItemEvent
Topic under construction.
Class DrawMode
Enumeration class used to specify the draw modes of a list box
Class Edit
Creates a standard Windows edit control.
Class FileDialog
Represents the abstract base class for the OpenFileDialog and SaveFileDialog classes.
Class Font
Encapsulates a Win32 font.
Class Form
Represents the basic top-level window.
Class FormBorderStyle
Enumeration class that represents the border styles of a form.
Class FormPaletteMode
Topic under construction.
Class FormStartPosition
Specifies form start position values.
Class FormWindowState
Topic under construction.
Class GiveFeedbackEvent
Topic under construction.
Class Graphics
Encapsulates a Win 32 device context (DC) and the drawing operations that are typically performed on a DC.
Class GroupBox
A GroupBox is a simple container that holds other controls and wraps a a frame around them.
Class HorizontalAlignment
Enumeration class that represents horizontal alignment values.
Class HScrollBar
Topic under construction.
Class Icon
Implements a Windows icon as a WFC object.
Class IconArrange
Topic under construction.
Class Image
Represents the base class for image classes such as Bitmap, Cursor, Metafile, and Icon.
Class ImageButton
Topic under construction.
Class ImageList
ImageList common control.
Class ImageListDrawMode
ImageList drawing modes.
Class InputLangChangeEvent
The InputLangChangeEvent is fired after the input language has changed.
Class InputLangChangeRequestEvent
The InputLangChangeRequestEvent is fired before the input language changes.
Class ItemCheckEvent
An event sent to a CheckedListBox when the state of one of the check boxes is about to change.
Class Key
Contains constants to use for processing keyboard input.
Class KeyEvent
Topic under construction.
Class Label
Implements a simple static label control.
Class ListBox
Encapsulates the Windows list box control.
Class ListItem
Manages items in a listview.
Class ListStyle
Topic under construction.
Class ListView
Topic under construction.
Class MainMenu
Topic under construction.
Class MDIClient
Topic under construction.
Class MDILayout
Topic under construction.
Class MeasureItemEvent
This event is sent by controls, such as the ListBox and ComboBox, that need users to tell them how large a given item is to be.
Class Menu
Topic under construction.
Class MenuGlyph
Enum to be used with the drawMenuGlyph function.
Class MenuItem
Topic under construction.
Class MenuMerge
Topic under construction.
Class MessageBox
Allows you to display a message box with various buttons and icons.
Class Metafile
Implements a Windows metafile as a WFC object.
Class MouseEvent
Topic under construction.
Class OpenFileDialog
Displays a Windows common dialog box that lets you select a file for opening.
Class Orientation
Topic under construction.
Class PaintEvent
Topic under construction.
Class Panel
Topic under construction.
Class Pen
This is a graphics pen.
Class PictureBox
Topic under construction.
Class Point
Represents a single (x,y) coordinate and various operations on such a coordinate.
Class ProgressBar
A progress bar control is a window that an application can use to indicate the progress of a lengthy operation.
Class QueryContinueDragEvent
The QueryContinueDragEvent is fired to determine if the drag operation should continue.
Class RadioButton
Encapsulates a radio button control.
Class RasterOp
The RasterOp class encapsulates a Win32 raster operation.
Class Rebar
Encapsulates a Rebar control.
Class RebarBand
This class encapsulates a RebarBand, a child control in a Rebar object.
Class Rectangle
The Rectangle class is similar to a Win32 RECT structure.
Class Region
Topic under construction.
Class ReSizeRestriction
Topic under construction.
Class RichEdit
The RichEdit class encapsulates a Win32 RichEdit control.
Class SaveFileDialog
Displays a Windows common dialog box that lets you save a file.
Class ScrollBar
Topic under construction.
Class ScrollBars
Topic under construction.
Class ScrollButton
Enum to be used with the drawScrollButton function.
Class ScrollEvent
Topic under construction.
Class SelectionStyle
Topic under construction.
Class SizeMode
An enumeration class used for tabs.
Class SortingEnum
Topic under construction.
Class Splitter
Topic under construction.
Class StaticImage
Topic under construction.
Class StatusBar
This class wraps the comctl32 status bar control.
Class StatusBarMode
The status bar style.
Class StatusBarPanel
Stores the panel information.
Class StatusBarPanelAutoSize
The autosize style of a panel on a status bar.
Class StatusBarPanelBorderStyle
The border style of a panel on a status bar.
Class StatusBarPanelClickEvent
Topic under construction.
Class StatusBarPanelStyle
The style of a panel on a status bar.
Class TabControl
This control inherits the functionality of a TabStrip but manages a list of tabs for pages to be stored.
Class TabDrawStyle
Enumeration class for tab drawing styles.
Class TabStrip
A control for creating tabbed dialogs or tabbed toolbar/taskbar type windows.
Class TabStyle
Enumeration class for tab styles.
Class TextFormat
Provides different ways for text to be formatted.
Class TickStyle
Enumeration class for tick styles.
Class ToolBar
This class wraps the comctl32 toolbar control.
Class ToolBarAppearance
The button appearance on a toolbar.
Class ToolBarBorderStyle
The border of a toolbar.
Class ToolBarButton
Represents a button on a toolbar.
Class ToolBarButtonClickEvent
Topic under construction.
Class ToolBarButtonStyle
The button style within a toolbar.
Class ToolBarStandardImages
The toolbar standard images.
Class ToolTip
Provides tooltips for other controls.
Class ToolTipRegion
A ToolTipRegion defines an area either by a rectangle or control that displays a tooltip when the mouse hovers over it.
Class TrackBar
Topic under construction.
Class TreeNode
Encapsulates a node in a TreeView control.
Class TreeView
Windows TreeView common control.
Class UpDown
Implements an UpDown common control.
Class ViewEnum
Topic under construction.
Class VScrollBar
Topic under construction.


 AcceleratorTable Class

AcceleratorTable Class

This Package | All Packages

public class AcceleratorTable

Topic under construction.

Constructors
Name | Description
AcceleratorTable() | Topic under construction.

Methods
Name | Description
add(int keyCode, EventHandler onKey) | Topic under construction.
dispose() | Topic under construction.
remove(int keyCode) | Topic under construction.
translateMessage(MSG msg) | Topic under construction.

Constructors

AcceleratorTable.AcceleratorTable

Syntax
public AcceleratorTable();
Description

Topic under construction.

Methods

AcceleratorTable.add

Syntax
public void add( int keyCode, EventHandler onKey );
Description

Topic under construction.

AcceleratorTable.dispose

Syntax
public void dispose();
Description

Topic under construction.

AcceleratorTable.remove

Syntax
public void remove( int keyCode );
Description

Topic under construction.

AcceleratorTable.translateMessage

Syntax
public boolean translateMessage( MSG msg );
Description

Topic under construction.


 Animation Class

Animation Class

This Package | All Packages

Control
  |
  +--Animation
public class Animation
extends Control

Provides the animation common control. This control plays an .avi animation file in its window. The methods play and stop control the playback of the video, and the FileName property (getFileName and setFileName) allow you to load in new files.

Constructors
Name | Description
Animation() | Topic under construction.

Methods
Name | Description
addOnStart(EventHandler value) | Adds an event handler for the OnStart event notification.
addOnStop(EventHandler value) | Adds an event handler for the OnStop event notification.
getAutoPlay() | Indicates whether the Animation control is configured to start playing as soon as a video clip is opened.
getCentered() | Indicates whether the animation will be in the top-left of the animation control's area or whether it will be centered as necessary.
getCreateParams() | Retrieves the parameters when the window was created.
getFileName() | Retrieves the file name of the animation to be played.
getTransparent() | Indicates whether Windows will draw the animation using a transparent background, or the background color specified in the animation clip.
getUseTimer() | Indicates whether a Win32 timer instead of a separate thread is used to manage playback of the animation.
onStart(Event e) | Fires the OnStart event.
onStop(Event e) | Fires the OnStop event.
play() | Plays the animation clip from beginning to end.
play(int repeat, int start, int end) | Plays the animation clip the specified number of times with the specified start and end frames.
recreateHandle() | Override this method to guarantee the file name is restored correctly after re-creation.
removeOnStart(EventHandler value) | Removes the specified event handler for the OnStart event.
removeOnStop(EventHandler value) | Removes the specified event handler for the OnStop event.
setAutoPlay(boolean value) | Indicates whether the animation control should start playing the animation as soon as a video clip is opened.
setCentered(boolean value) | Indicates whether the animation will be in the top-left of the animation control's area or centered as necessary.
setFileName(String value) | Sets the file name of the animation to be played.
setTransparent(boolean value) | Indicates whether Windows draws the animation using a transparent background rather than using the background color specified in the animation clip.
setUseTimer(boolean value) | Indicates whether a Win32 timer should be used instead of a separate thread to manage the playback of the animation.
stop() | Stops playing the animation.
wndProc(Message m) | The control's window procedure (WndProc).

Constructors

Animation.Animation

Syntax
public Animation();
Description

Topic under construction.

Methods

Animation.addOnStart

Syntax
public final void addOnStart( EventHandler value );
Parameters
value
The new event handler to install for this event.
Description

Adds an event handler for the OnStart event notification. This notification is sent out whenever an animation starts playing. Duplicate calls to addOnStart are not filtered out.

Animation.addOnStop

Syntax
public final void addOnStop( EventHandler value );
Parameters
value
The new event handler to install for this event.
Description

Adds an event handler for the OnStop event notification. This notification is sent out whenever an animation stops playing. Duplicate calls to addOnStop are not filtered out.

Animation.getAutoPlay

Syntax
public final boolean getAutoPlay();
Return Value

Returns true if the control is configured to start playing as soon as a clip is opened; otherwise, returns false. If getAutoPlay returns false, the Animation control does not start playing the animation clip until the play method is called.

Description

Indicates whether the Animation control is configured to start playing as soon as a video clip is opened.

Animation.getCentered

Syntax
public final boolean getCentered();
Return Value

Returns true if the animation will be centered as necessary; otherwise, returns false.

Description

Indicates whether the animation will be in the top-left of the animation control's area or whether it will be centered as necessary.

Animation.getCreateParams

Syntax
protected CreateParams getCreateParams();
Return Value

Returns an object with the information needed to create a window for this component.

Description

Retrieves the parameters when the window was created. This method is called when creating a window. Derived classes can override this method to add extra functionality, However you should first call super.getCreateParams() to make sure the control continues to work correctly.

Animation.getFileName

Syntax
public final String getFileName();
Return Value

Returns the file name of the animation to be played.

Description

Retrieves the file name of the animation to be played.

Animation.getTransparent

Syntax
public final boolean getTransparent();
Return Value

Returns true if the color specified in the Animation clip will not be used; otherwise, returns false.

Description

Indicates whether Windows will draw the animation using a transparent background, or the background color specified in the animation clip.

Animation.getUseTimer

Syntax
public final boolean getUseTimer();
Return Value

Returns true if a timer will be used; otherwise, returns false.

Description

Indicates whether a Win32 timer instead of a separate thread is used to manage playback of the animation.

Animation.onStart

Syntax
protected void onStart( Event e );
Parameters
e
The data in the event that is raised.
Description

Fires the OnStart event. Derived classes should just override this method instead of adding a listener for the event. When overriding this method, be sure to call super.onStart(e) to ensure that the original event is still raised.

Animation.onStop

Syntax
protected void onStop( Event e );
Parameters
e
The data in the event that is raised.
Description

Fires the OnStop event. Derived classes should just override this method instead of adding a listener for the event. When overriding this method, be sure to call super.onStart(e) to ensure that the original event is still raised.

Animation.play

Syntax 1
public final void play();
Description

Plays the animation clip from beginning to end.

Syntax 2
public final void play( int repeat, int start, int end );
Parameters
repeat
The number of times to play the animation clip.
start
The frame on which to start playing.
end
The frame on which to stop playing. A value of -1 indicates that the clip should be played until it ends.
Description

Plays the animation clip the specified number of times with the specified start and end frames.

Animation.recreateHandle

Syntax
public void recreateHandle();
Description

Override this method to guarantee the file name is restored correctly after re-creation.

Animation.removeOnStart

Syntax
public final void removeOnStart( EventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the specified event handler for the OnStart event. If there are duplicate entries, all are removed.

Animation.removeOnStop

Syntax
public final void removeOnStop( EventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the specified event handler for the OnStop event. If there are duplicate entries, all are removed.

Animation.setAutoPlay

Syntax
public final void setAutoPlay( boolean value );
Parameters
value
Set to true for the animation to automatically begin playing; set to false for the clip to begin playing when the play method is called.
Description

Indicates whether the animation control should start playing the animation as soon as a video clip is opened.

Animation.setCentered

Syntax
public final void setCentered( boolean value );
Parameters
value
The new value for this property. Set to true for the animation to be centered as necessary; set to false for it to be played in the top-left of the animation control area.
Description

Indicates whether the animation will be in the top-left of the animation control's area or centered as necessary.

Animation.setFileName

Syntax
public final void setFileName( String value );
Parameters
value
The name of the file to play. A null value clears the display.
Description

Sets the file name of the animation to be played.

Animation.setTransparent

Syntax
public final void setTransparent( boolean value );
Parameters
value
The new value for this property. Set to true for Windows to use a transparent background; set to false for the background color specified in the animation clip to be used.
Description

Indicates whether Windows draws the animation using a transparent background rather than using the background color specified in the animation clip.

Animation.setUseTimer

Syntax
public final void setUseTimer( boolean value );
Parameters
value
Set to true to use a timer; set to false to use a separate thread to manage animation playback.
Description

Indicates whether a Win32 timer should be used instead of a separate thread to manage the playback of the animation.

Animation.stop

Syntax
public final void stop();
Description

Stops playing the animation.

Animation.wndProc

Syntax
protected void wndProc( Message m );
Parameters
m
The Windows message sent to the control.
Description

The control's window procedure (WndProc). Derived classes can override this method to monitor messages but should be sure to call super.wndProc(m) to ensure correct functionality.


 AutoSizeEvent Class

AutoSizeEvent Class

This Package | All Packages

Event
  |
  +--AutoSizeEvent
public class AutoSizeEvent
extends Event

Topic under construction.

Fields
Name | Description
newRectangle | Topic under construction.

Constructors
Name | Description
AutoSizeEvent(Rectangle newRectangle) | Topic under construction.

Fields

AutoSizeEvent.newRectangle

Syntax
public final Rectangle newRectangle;
Description
Topic under construction.

Constructors

AutoSizeEvent.AutoSizeEvent

Syntax
public AutoSizeEvent( Rectangle newRectangle );
Description

Topic under construction.


 AxControl Class

AxControl Class

This Package | All Packages

Control
  |
  +--AxControl
public class AxControl
extends Control

Hosts an ActiveX control.

Constructors
Name | Description
AxControl(String tricsData) | Topic under construction.

Methods
Name | Description
AtlAxGetControl(int h) | Wraps the AtlAxGetControl function.
AtlAxGetHost(int h) | Wraps the AtlAxGetHost function.
AtlAxHostInit() | Wraps the AtlAxHostInit function.
getControl() | Topic under construction.

Constructors

AxControl.AxControl

Syntax
public AxControl( String tricsData );
Description

Topic under construction.

Methods

AxControl.AtlAxGetControl

Syntax
public static native IUnknown AtlAxGetControl( int h );
Parameters
h
Topic under construction.
Description

Wraps the AtlAxGetControl function.

AxControl.AtlAxGetHost

Syntax
public static native IUnknown AtlAxGetHost( int h );
Parameters
h
Topic under construction.
Description

Wraps the AtlAxGetHost function.

AxControl.AtlAxHostInit

Syntax
public static native void AtlAxHostInit();
Description

Wraps the AtlAxHostInit function.

AxControl.getControl

Syntax
public IUnknown getControl();
Description

Topic under construction.


 Bitmap Class

Bitmap Class

This Package | All Packages

Image
  |
  +--Bitmap
public class Bitmap
extends Image
implements IPersistable

Implements a Windows bitmap as a WFC object.

Constructors
Name | Description
Bitmap(int handle) | Topic under construction.
Bitmap(int handle, boolean fOwned) | Topic under construction.
Bitmap(int handle, int hpal, boolean fOwned) | Topic under construction.
Bitmap(int width, int height) | Topic under construction.
Bitmap(int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short lpvBits[]) | Topic under construction.
Bitmap(String fileName) | Topic under construction.
Bitmap(Class type, String resource) | Topic under construction.
Bitmap(IDataStream stream) | Topic under construction.
Bitmap(IStream stream) | Topic under construction.
Bitmap(IPicture picture) | Topic under construction.

Methods
Name | Description
clone() | Topic under construction.
cloneBitmap() | Topic under construction.
copyHandle(int h) | Retrieves a copy of the bitmap.
copyHandle() | Retrieves a copy of the bitmap.
drawStretchTo(Graphics g, int x, int y, int width, int height, int rop) | Draws this bitmap to the given DC and stretches it to the given width and height.
drawTo(Graphics g, int x, int y, int width, int height, int rop) | Draws this bitmap to the given DC.
finalize() | Topic under construction.
getDitheredBitmap(Color solid, Color dither) | Topic under construction.
getExtension() | Topic under construction.
getGraphics() | Retrieves a Graphics object that you can use to paint to this image.
getHandle() | Retrieves the handle to this bitmap.
getPalette() | Topic under construction.
getPICTDESC() | Topic under construction.
getSafeHandle(Bitmap i) | Topic under construction.
getSize() | Topic under construction.
getTransparentBitmap(boolean f3D) | Topic under construction.
getTransparentBitmap(Color color) | Topic under construction.
getTransparentColor() | Topic under construction.
toString() | Topic under construction.

Constructors

Bitmap.Bitmap

Syntax 1
public Bitmap( int handle );
Description

Topic under construction.

Syntax 2
public Bitmap( int handle, boolean fOwned );
Description

Topic under construction.

Syntax 3
public Bitmap( int handle, int hpal, boolean fOwned );
Description

Topic under construction.

Syntax 4
public Bitmap( int width, int height );
Description

Topic under construction.

Syntax 5
public Bitmap( int nWidth, int nHeight, int nPlanes, int nBitsPerPixel, short lpvBits[] );
Description

Topic under construction.

Syntax 6
public Bitmap( String fileName );
Description

Topic under construction.

Syntax 7
public Bitmap( Class type, String resource );
Description

Topic under construction.

Syntax 8
public Bitmap( IDataStream stream );
Description

Topic under construction.

Syntax 9
public Bitmap( IStream stream );
Description

Topic under construction.

Syntax 10
public Bitmap( IPicture picture );
Description

Topic under construction.

Methods

Bitmap.clone

Syntax
public Object clone();
Description

Topic under construction.

Bitmap.cloneBitmap

Syntax
public Bitmap cloneBitmap();
Description

Topic under construction.

Bitmap.copyHandle

Syntax 1
public static int copyHandle( int h );
Description

Retrieves a copy of the bitmap.

Syntax 2
public static int copyHandle();
Description

Retrieves a copy of the bitmap.

Bitmap.drawStretchTo

Syntax
protected void drawStretchTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
g
The HDC to draw to (supplied by Graphics).
x
The x-coordinate at which to start drawing.
y
The y-coordinate at which to start drawing.
width
The width to stretch the bitmap to.
height
The height to stretch the bitmap to.
rop
The ROP code.
Description

Draws this bitmap to the given DC and stretches it to the given width and height. This method is used by Graphics to draw any type of image.

Bitmap.drawTo

Syntax
protected void drawTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
g
The HDC to draw to (supplied by Graphics).
x
The x-coordinate at which to start drawing.
y
The y-coordinate at which to start drawing.
width
The width of the bitmap.
height
The height of the bitmap.
rop
The ROP code.
Description

Draws this bitmap to the given DC. This method is used by Graphics to draw any type of image.

Bitmap.finalize

Syntax
public void finalize();
Description

Topic under construction.

Bitmap.getDitheredBitmap

Syntax
public Bitmap getDitheredBitmap( Color solid, Color dither );
Description

Topic under construction.

Bitmap.getExtension

Syntax
public String getExtension();
Description

Topic under construction.

Bitmap.getGraphics

Syntax
public Graphics getGraphics();
Return Value

Returns a Graphics object.

Description

Retrieves a Graphics object that you can use to paint to this image. This method creates a Graphics object if none exists or returns the one that already exists.

Bitmap.getHandle

Syntax
public int getHandle();
Return Value

Returns the handle to this bitmap.

Description

Retrieves the handle to this bitmap.

Bitmap.getPalette

Syntax
public Palette getPalette();
Description

Topic under construction.

Bitmap.getPICTDESC

Syntax
public PICTDESC getPICTDESC();
Description

Topic under construction.

Bitmap.getSafeHandle

Syntax
public static final int getSafeHandle( Bitmap i );
Description

Topic under construction.

Bitmap.getSize

Syntax
public Point getSize();
Description

Topic under construction.

Bitmap.getTransparentBitmap

Syntax 1
public Bitmap getTransparentBitmap( boolean f3D );
Description

Topic under construction.

Syntax 2
public Bitmap getTransparentBitmap( Color color );
Description

Topic under construction.

Bitmap.getTransparentColor

Syntax
public Color getTransparentColor();
Description

Topic under construction.

Bitmap.toString

Syntax
public String toString();
Description

Topic under construction.


 Border3DSide Class

Border3DSide Class

This Package | All Packages

public final class Border3DSide

This class defines the constants that you pass to the Graphics.drawBorder3D method to define a three-dimensional border's appearance.

Also see wfc.ui.Graphics

Fields
Name | Description
ALL | Combines all available position constants (LEFT, TOP, RIGHT, BOTTOM, and MIDDLE).
BOTTOM | Draws the bottom side of a three-dimensional border.
LEFT | Draws the left side of a three-dimensional border.
MIDDLE | Fills in the middle part of the three-dimensional border.
RIGHT | Draws the right side of a three-dimensional border.
TOP | Draws the top side of a three-dimensional border.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the specified value is not supported by this class.
valid(int value) | Retrieves a boolean value that indicates whether the specified value is supported by this class.

Fields

Border3DSide.ALL

Syntax
public static final int ALL;
Description
Combines all available position constants (LEFT, TOP, RIGHT, BOTTOM, and MIDDLE).

Border3DSide.BOTTOM

Syntax
public static final int BOTTOM;
Description
Draws the bottom side of a three-dimensional border.

Border3DSide.LEFT

Syntax
public static final int LEFT;
Description
Draws the left side of a three-dimensional border.

Border3DSide.MIDDLE

Syntax
public static final int MIDDLE;
Description
Fills in the middle part of the three-dimensional border.

Border3DSide.RIGHT

Syntax
public static final int RIGHT;
Description
Draws the right side of a three-dimensional border.

Border3DSide.TOP

Syntax
public static final int TOP;
Description
Draws the top side of a three-dimensional border.

Methods

Border3DSide.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the specified value is not supported by this class.

Exceptions

InvalidEnumArgument

Border3DSide.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified value is supported by this class.


 Border3DStyle Class

Border3DStyle Class

This Package | All Packages

Enum
  |
  +--Border3DStyle
public final class Border3DStyle
extends Enum

Defines the constants that you pass to the Graphics.drawBorder3D method to define a 3D border's appearance.

Also see wfc.ui.Graphics

Fields
Name | Description
ADJUST | Specifies that the border should be drawn outside of the given rectangle, preserving the dimensions of the rectangle for drawing.
ALL | All viable flags in the bit mask.
BUMP | Consists of a raised outer edge and a sunken inner edge.
ETCHED | Consists of a sunken inner edge and a raised outer edge.
FLAT | Draws the border entirely flat with no three-dimensional effects.
RAISED | Consists of raised inner and outer edges.
RAISEDINNER | Consists of a raised inner edge and no outer edge.
RAISEDOUTER | Consists of a raised outer edge and no inner edge.
SUNKEN | Consists of sunken inner and outer edges.
SUNKENINNER | Consists of a sunken inner edge and no outer edge.
SUNKENOUTER | Consists of a sunken outer edge and no inner edge.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the specified value is not supported by this class.
valid(int value) | Returns true if the given value is allowable by this class; otherwise, returns false.

Fields

Border3DStyle.ADJUST

Syntax
public static final int ADJUST;
Description
Specifies that the border should be drawn outside of the given rectangle, preserving the dimensions of the rectangle for drawing.

Border3DStyle.ALL

Syntax
public static final int ALL;
Description
All viable flags in the bit mask.

Border3DStyle.BUMP

Syntax
public static final int BUMP;
Description
Consists of a raised outer edge and a sunken inner edge.

Border3DStyle.ETCHED

Syntax
public static final int ETCHED;
Description
Consists of a sunken inner edge and a raised outer edge.

Border3DStyle.FLAT

Syntax
public static final int FLAT;
Description
Draws the border entirely flat with no three-dimensional effects.

Border3DStyle.RAISED

Syntax
public static final int RAISED;
Description
Consists of raised inner and outer edges.

Border3DStyle.RAISEDINNER

Syntax
public static final int RAISEDINNER;
Description
Consists of a raised inner edge and no outer edge.

Border3DStyle.RAISEDOUTER

Syntax
public static final int RAISEDOUTER;
Description
Consists of a raised outer edge and no inner edge.

Border3DStyle.SUNKEN

Syntax
public static final int SUNKEN;
Description
Consists of sunken inner and outer edges.

Border3DStyle.SUNKENINNER

Syntax
public static final int SUNKENINNER;
Description
Consists of a sunken inner edge and no outer edge.

Border3DStyle.SUNKENOUTER

Syntax
public static final int SUNKENOUTER;
Description
Consists of a sunken outer edge and no inner edge.

Methods

Border3DStyle.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the specified value is not supported by this class.

Exceptions

InvalidEnumArgument thrown if value does not reference a valid Border3DStyle constant.

Border3DStyle.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Returns true if the given value is allowable by this class; otherwise, returns false.


 BorderStyle Class

BorderStyle Class

This Package | All Packages

Enum
  |
  +--BorderStyle
public class BorderStyle
extends Enum

Enumeration class for window border styles.

Fields
Name | Description
FIXED_SINGLE | The associated window will have a single-line border.
MAX | Topic under construction.
MIN | Topic under construction.
NONE | The associated window will not have a border.

Fields

BorderStyle.FIXED_SINGLE

Syntax
public static final int FIXED_SINGLE;
Description
The associated window will have a single-line border.

BorderStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

BorderStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

BorderStyle.NONE

Syntax
public static final int NONE;
Description
The associated window will not have a border.


 Brush Class

Brush Class

This Package | All Packages

public final class Brush

This class encapsulates a Windows brush. Brushes are used for filling areas of a window or a graphics region. You can create a brush whose appearance is based on the constants defined in this class, or you can create a brush based on a bitmap.

Fields
Name | Description
BLACK | Standard black brush.
DARKGRAY | Standard dark gray brush.
GRAY | Standard gray brush.
HALFTONE | Standard halftone brush.
HOLLOW | Hollow brush.
LIGHTGRAY | Light gray brush.
NULL | Null brush.
STYLE_BDIAGONAL | Standard brush style consisting of backward diagonal lines.
STYLE_DIAGCROSS | Standard brush style consisting of diagonal crisscross lines.
STYLE_FDIAGONAL | Standard brush style consisting of forward diagonal lines.
STYLE_HORIZONTAL | Standard brush style consisting of horizontal lines.
STYLE_VERTICAL | Standard brush style consisting of vertical lines.
WHITE | White brush.

Constructors
Name | Description
Brush(Color color) | Creates a new solid brush of the specified color.
Brush(Color color, int style) | Creates a new brush of the style and color.
Brush(Bitmap bmp) | Creates a brush based on the specified bitmap.
Brush(int handle) | Creates a brush based on an existing Win32 handle.

Methods
Name | Description
equals(Object obj) | Retrieves a boolean value that indicates whether the specified object is equivalent to this brush.
finalize() throws Throwable | Cleans up the Win32 resources associated with this brush.
getColor() | Retrieves the color of this brush.
getHandle() | Retrieves the Win32 handle of the brush.
getStyle() | Retrieves the style of the brush.
hashCode() | Computes and returns the hash code for this Brush object.

Fields

Brush.BLACK

Syntax
public static final Brush BLACK;
Description
Standard black brush.

Brush.DARKGRAY

Syntax
public static final Brush DARKGRAY;
Description
Standard dark gray brush.

Brush.GRAY

Syntax
public static final Brush GRAY;
Description
Standard gray brush.

Brush.HALFTONE

Syntax
public static final Brush HALFTONE;
Description
Standard halftone brush.

Brush.HOLLOW

Syntax
public static final Brush HOLLOW;
Description
Hollow brush. This brush paints nothing.

Brush.LIGHTGRAY

Syntax
public static final Brush LIGHTGRAY;
Description
Light gray brush.

Brush.NULL

Syntax
public static final Brush NULL;
Description
Null brush. The behavior of this brush is identical to a hollow brush.

Brush.STYLE_BDIAGONAL

Syntax
public static final int STYLE_BDIAGONAL;
Description
Standard brush style consisting of backward diagonal lines.

Brush.STYLE_DIAGCROSS

Syntax
public static final int STYLE_DIAGCROSS;
Description
Standard brush style consisting of diagonal crisscross lines.

Brush.STYLE_FDIAGONAL

Syntax
public static final int STYLE_FDIAGONAL;
Description
Standard brush style consisting of forward diagonal lines.

Brush.STYLE_HORIZONTAL

Syntax
public static final int STYLE_HORIZONTAL;
Description
Standard brush style consisting of horizontal lines.

Brush.STYLE_VERTICAL

Syntax
public static final int STYLE_VERTICAL;
Description
Standard brush style consisting of vertical lines.

Brush.WHITE

Syntax
public static final Brush WHITE;
Description
White brush.

Constructors

Brush.Brush

Syntax 1
public Brush( Color color );
Parameters
color
The color of the brush.
Description

Creates a new solid brush of the specified color.

Syntax 2
public Brush( Color color, int style );
Parameters
color
The color of the brush.
style
One of the Brush.STYLE_ constants.
Description

Creates a new brush of the style and color.

Syntax 3
public Brush( Bitmap bmp );
Parameters
bmp
The bitmap from which to create the brush.
Description

Creates a brush based on the specified bitmap.

Syntax 4
public Brush( int handle );
Parameters
handle
The Win32 brush handle.
Description

Creates a brush based on an existing Win32 handle. The brush does not own the handle.

Methods

Brush.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The Object to which to compare this brush.
Return Value

Returns true if the specified object is equalivalent to this brush; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified object is equivalent to this brush.

Brush.finalize

Syntax
protected void finalize() throws Throwable;
Description

Cleans up the Win32 resources associated with this brush.

Exceptions

Throwable thrown if resources associated with this brush cannot be freed.

Brush.getColor

Syntax
public Color getColor();
Return Value

Returns the brush color.

Description

Retrieves the color of this brush.

Brush.getHandle

Syntax
public int getHandle();
Return Value

Returns a Win32 handle value.

Description

Retrieves the Win32 handle of the brush.

Brush.getStyle

Syntax
public int getStyle();
Return Value

Returns one of the Brush.STYLE_ constants.

Description

Retrieves the style of the brush.

Brush.hashCode

Syntax
public int hashCode();
Return Value

Returns an integer hash code value.

Description

Computes and returns the hash code for this Brush object.


 Button Class

Button Class

This Package | All Packages

Control
  |
  +--Button
public class Button
extends Control
implements IButtonControl

Encapsulates a Windows button control.

Constructors
Name | Description
Button() | Creates a new instance of a Button control.

Methods
Name | Description
getBackColor() | Retrieves the current background color of the Button.
getBrush() | Retrieves the brush used to display this control.
getDialogResult() | Topic under construction.
getForeColor() | Retrieves the current foreground color of the Button.
hasDefaultBackColor() | Retrieves a boolean value that indicates whether the current value of the background color property is the same as the default value.
hasDefaultForeColor() | Retrieves a boolean value that indicates whether or not the current value of the foreground color property is the same as the default value.
notifyDefault(boolean value) | Topic under construction.
performClick() | Generates a click event for this button, simulating a click by a user.
setDialogResult(int value) | Topic under construction.

Constructors

Button.Button

Syntax
public Button();
Description

Creates a new instance of a Button control. By default, the button has no caption.

Methods

Button.getBackColor

Syntax
public Color getBackColor();
Return Value

Returns the current background color [Color.CONTROL]

Description

Retrieves the current background color of the Button. Because the color of a button is read-only, this method always returns Color.CONTROL

Button.getBrush

Syntax
public Brush getBrush();
Return Value

Returns the default system brush.

Description

Retrieves the brush used to display this control. Because the background color of a control is read-only, this method always returns the default system brush.

Button.getDialogResult

Syntax
public int getDialogResult();
Description

Topic under construction.

Button.getForeColor

Syntax
public Color getForeColor();
Return Value

Returns the current foreground color [Color.WINDOWTEXT]

Description

Retrieves the current foreground color of the Button. Because the foreground color of a button is read-only, the value returned by getForeColor always evaluates to the Color.WINDOWTEXT constant.

Button.hasDefaultBackColor

Syntax
public boolean hasDefaultBackColor();
Return Value

Returns true.

Description

Retrieves a boolean value that indicates whether the current value of the background color property is the same as the default value. Since the background color of a button cannot be changed, this method always returns true. The default background color of a button always evaluates to the Color.CONTROL constant.

Button.hasDefaultForeColor

Syntax
public boolean hasDefaultForeColor();
Return Value

Returns true.

Description

Retrieves a boolean value that indicates whether or not the current value of the foreground color property is the same as the default value. Since the foreground color of a button is read-only, the button always has the default value of Color.WINDOWTEXT, and this method always returns true.

Button.notifyDefault

Syntax
public void notifyDefault( boolean value );
Description

Topic under construction.

Button.performClick

Syntax
public void performClick();
Description

Generates a click event for this button, simulating a click by a user.

Button.setDialogResult

Syntax
public void setDialogResult( int value );
Description

Topic under construction.


 ButtonState Class

ButtonState Class

This Package | All Packages

public final class ButtonState

Enumerator to be used with the drawButton* functions.

Fields
Name | Description
ALL | All viable flags in the bit mask.
CHECKED | Button has a checked or latched appearance.
FLAT | Button has a flat, two-dimensional appearance.
INACTIVE | Button is disabled.
NORMAL | Button is drawn normally.
PUSHED | Button is pressed.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the given value is not possible for this class.
valid(int value) | Determines whether the given value is allowed by this class.

Fields

ButtonState.ALL

Syntax
public static final int ALL;
Description
All viable flags in the bit mask.

ButtonState.CHECKED

Syntax
public static final int CHECKED;
Description
Button has a checked or latched appearance.

ButtonState.FLAT

Syntax
public static final int FLAT;
Description
Button has a flat, two-dimensional appearance.

ButtonState.INACTIVE

Syntax
public static final int INACTIVE;
Description
Button is disabled.

ButtonState.NORMAL

Syntax
public static final int NORMAL;
Description
Button is drawn normally.

ButtonState.PUSHED

Syntax
public static final int PUSHED;
Description
Button is pressed.

Methods

ButtonState.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the given value is not possible for this class.

ButtonState.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Determines whether the given value is allowed by this class.


 CaptionButton Class

CaptionButton Class

This Package | All Packages

Enum
  |
  +--CaptionButton
public final class CaptionButton
extends Enum

Defines that constants that you can pass to the Graphics.drawCaptionButton method. These constants determine the button's appearance.

Also see wfc.ui.Graphics

Fields
Name | Description
CLOSE | Draws the close "X" button.
HELP | Draws the caption help button.
MAX |
MAXIMIZE | Draws the caption maximize button.
MIN |
MINIMIZE | Draws the caption minimize button.
RESTORE | Draws the caption restore button.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the given value is not supported by this class.
valid(int value) | Retrieves a boolean value that indicates whether the specified value is supported by this class.

Fields

CaptionButton.CLOSE

Syntax
public static final int CLOSE;
Description
Draws the close "X" button.

CaptionButton.HELP

Syntax
public static final int HELP;
Description
Draws the caption help button.

CaptionButton.MAX

Syntax
public static final int MAX;
Description

CaptionButton.MAXIMIZE

Syntax
public static final int MAXIMIZE;
Description
Draws the caption maximize button.

CaptionButton.MIN

Syntax
public static final int MIN;
Description

CaptionButton.MINIMIZE

Syntax
public static final int MINIMIZE;
Description
Draws the caption minimize button.

CaptionButton.RESTORE

Syntax
public static final int RESTORE;
Description
Draws the caption restore button.

Methods

CaptionButton.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the given value is not supported by this class.

Exceptions

InvalidEnumArgument thrown if the specified constant is not supported by this class.

CaptionButton.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified value is supported by this class.


 CharacterCasing Class

CharacterCasing Class

This Package | All Packages

Enum
  |
  +--CharacterCasing
public class CharacterCasing
extends Enum

Enumeration class used to specify character casing (uppercased, lowercased, or unchanged).

Fields
Name | Description
LOWER | Indicates that all characters should be converted to lowercase.
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | Indicates that the case of characters should be left unchanged.
UPPER | Indicates that all characters should be converted to uppercase.

Fields

CharacterCasing.LOWER

Syntax
public static final int LOWER;
Description
Indicates that all characters should be converted to lowercase.

CharacterCasing.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

CharacterCasing.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

CharacterCasing.NORMAL

Syntax
public static final int NORMAL;
Description
Indicates that the case of characters should be left unchanged.

CharacterCasing.UPPER

Syntax
public static final int UPPER;
Description
Indicates that all characters should be converted to uppercase.


 Checkbox Class

Checkbox Class

This Package | All Packages

Control
  |
  +--Checkbox
public class Checkbox
extends Control

Encapsulates a standard Windows check box control. The checked status of the control is retrieved by calling the getChecked method and is set using setChecked.

Constructors
Name | Description
Checkbox() | Class constructor.

Methods
Name | Description
addOnCheckStateChanged(EventHandler handler) | Topic under construction.
getAlignText() | Topic under construction.
getAuto() | Topic under construction.
getChecked() | Topic under construction.
getCheckState() | Topic under construction.
getGroupValue(Control group) | Topic under construction.
getPushLike() | Returns the current value of the PushLike property.
getThreeState() | Topic under construction.
removeOnCheckStateChanged(EventHandler handler) | Topic under construction.
setAlignText(int value) | Topic under construction.
setAuto(boolean value) | Topic under construction.
setChecked(boolean value) | Topic under construction.
setCheckState(int value) | Topic under construction.
setGroupValue(Control group, int value) | Topic under construction.
setPushLike(boolean value) | Topic under construction.
setThreeState(boolean value) | Topic under construction.

Constructors

Checkbox.Checkbox

Syntax
public Checkbox();
Description

Class constructor.

Methods

Checkbox.addOnCheckStateChanged

Syntax
public final void addOnCheckStateChanged( EventHandler handler );
Description

Topic under construction.

Checkbox.getAlignText

Syntax
public final int getAlignText();
Description

Topic under construction.

Checkbox.getAuto

Syntax
public boolean getAuto();
Description

Topic under construction.

Checkbox.getChecked

Syntax
public boolean getChecked();
Description

Topic under construction.

Checkbox.getCheckState

Syntax
public int getCheckState();
Description

Topic under construction.

Checkbox.getGroupValue

Syntax
public static int getGroupValue( Control group );
Description

Topic under construction.

Checkbox.getPushLike

Syntax
public final boolean getPushLike();
Return Value

Returns current value of the PushLike property.

Description

Returns the current value of the PushLike property.

See Also
setPushLike

Checkbox.getThreeState

Syntax
public boolean getThreeState();
Description

Topic under construction.

Checkbox.removeOnCheckStateChanged

Syntax
public final void removeOnCheckStateChanged( EventHandler handler );
Description

Topic under construction.

Checkbox.setAlignText

Syntax
public final void setAlignText( int value );
Description

Topic under construction.

Checkbox.setAuto

Syntax
public void setAuto( boolean value );
Description

Topic under construction.

Checkbox.setChecked

Syntax
public void setChecked( boolean value );
Description

Topic under construction.

Checkbox.setCheckState

Syntax
public void setCheckState( int value );
Description

Topic under construction.

Checkbox.setGroupValue

Syntax
public static void setGroupValue( Control group, int value );
Description

Topic under construction.

Checkbox.setPushLike

Syntax
public void setPushLike( boolean value );
Description

Topic under construction.

Checkbox.setThreeState

Syntax
public void setThreeState( boolean value );
Description

Topic under construction.


 CheckedListBox Class

CheckedListBox Class

This Package | All Packages

ListBox
  |
  +--CheckedListBox
public class CheckedListBox
extends ListBox

Provides an extension of the regular ListBox class that adds events and methods for checked list box functionality.

Constructors
Name | Description
CheckedListBox() | Creates a new CheckedListBox.

Methods
Name | Description
addItem(Object item, int check) | Adds an item to the list box with the given initial value for the checked portion of the item.
addOnItemCheck(ItemCheckEventHandler value) | Topic under construction.
getCheckedIndices() | Retrieves an array that contains the indices of checked items.
getCheckOnClick() | Retrieves a boolean value that indicates whether the checkbox state is toggled when an item is selected.
getItemCheck(int index) | Retrieves a value that identifies the checked state of the specified item.
getItemChecked(int index) | Retrieves a Boolean value that indicates whether the specified item is checked.
getOnItemCheck() | Retrieves the current recipient of the OnItemCheck event.
getThreeDCheckBoxes() | Indicates whether the check boxes should have a flat or three-dimensional appearance.
insert(int index, Object item, int check) | Adds a new item to the internal array of items with the given checked state.
insert(int index, Object item) | Adds a new item marked as unchecked.
removeAll() | Removes all items from the list box.
removeOnItemCheck(ItemCheckEventHandler value) | Removes the given handler for the "OnItemCheck" event.
setCheckOnClick(boolean value) | Specifies whether the checkbox should be toggled when an item is selected.
setItemCheck(int index, int value) | Sets the checked state of the specified item.
setSelectionStyle(int value) | Specifies the type of selection permitted with this list box.
setThreeDCheckBoxes(boolean threed) | Determines whether the check boxes should have a flat or three-dimensional appearance.

Constructors

CheckedListBox.CheckedListBox

Syntax
public CheckedListBox();
Description

Creates a new CheckedListBox.

Methods

CheckedListBox.addItem

Syntax
public void addItem( Object item, int check );
Parameters
item
The new item to add to the end of the list box.
check
The initial state for the checked portion of the item.
Description

Adds an item to the list box with the given initial value for the checked portion of the item.

CheckedListBox.addOnItemCheck

Syntax
public void addOnItemCheck( ItemCheckEventHandler value );
Description

Topic under construction.

CheckedListBox.getCheckedIndices

Syntax
public final int [] getCheckedIndices();
Return Value

Returns an array that contains the indices of checked items.

Description

Retrieves an array that contains the indices of checked items.

CheckedListBox.getCheckOnClick

Syntax
public final boolean getCheckOnClick();
Return Value

Returns boolean false, if two clicks are required to toggle checkbox state; otherwise, returns true.

Description

Retrieves a boolean value that indicates whether the checkbox state is toggled when an item is selected. By default, a click on a listbox item selects the item, and a second click toggles the checkbox state.

CheckedListBox.getItemCheck

Syntax
public final int getItemCheck( int index );
Parameters
index
The index of the item.
Return Value

Returns one of the enumeration constants defined in the CheckState class. This value indicates the current checked state of the specified item.

Description

Retrieves a value that identifies the checked state of the specified item.

CheckedListBox.getItemChecked

Syntax
public final boolean getItemChecked( int index );
Parameters
index
The index of the item.
Return Value

Returns true if the item is checked; otherwise, returns false.

Description

Retrieves a Boolean value that indicates whether the specified item is checked.

CheckedListBox.getOnItemCheck

Syntax
public ItemCheckEventHandler getOnItemCheck();
Return Value

Returns the current listener on this event.

Description

Retrieves the current recipient of the OnItemCheck event.

CheckedListBox.getThreeDCheckBoxes

Syntax
public boolean getThreeDCheckBoxes();
Return Value

Returns true if the appearance is three-dimensional, or returns false if the appearance is flat.

Description

Indicates whether the check boxes should have a flat or three-dimensional appearance.

CheckedListBox.insert

Syntax 1
protected void insert( int index, Object item, int check );
Parameters
index
The index at which to insert the item.
item
The value of the item to save.
check
The initial checked state for the item.
Description

Adds a new item to the internal array of items with the given checked state. These are maintained outside of Win32 because of marshalling issues.

Syntax 2
protected void insert( int index, Object item );
Parameters
index
The index at which to insert the item.
item
The item to insert.
Description

Adds a new item marked as unchecked.

CheckedListBox.removeAll

Syntax
public final void removeAll();
Description

Removes all items from the list box. All values and item data are lost.

CheckedListBox.removeOnItemCheck

Syntax
public final void removeOnItemCheck( ItemCheckEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the "OnItemCheck" event. If there are duplicate entries, ALL are removed.

CheckedListBox.setCheckOnClick

Syntax
public final void setCheckOnClick( boolean value );
Parameters
value
If true, the listbox items will be checked when they are clicked. Otherwise, the items must be clicked twice to be checked.
Description

Specifies whether the checkbox should be toggled when an item is selected. The default behaviour of the CheckedListBox selects the item when the user clicks it, then checks the item when the user clicks a second time.

CheckedListBox.setItemCheck

Syntax
public final void setItemCheck( int index, int value );
Parameters
index
Index of the item for which to set the checked state.
value
New value for displaying a check. This must be one of the values defined in the CheckState enumeration.
Description

Sets the checked state of the specified item.

CheckedListBox.setSelectionStyle

Syntax
public final void setSelectionStyle( int value );
Parameters
value
One of the constants defined in the SelectionStyle enumeration.
Description

Specifies the type of selection permitted with this list box. Multiple selections are not supported for checked list boxes; you can select one item or none.

CheckedListBox.setThreeDCheckBoxes

Syntax
public void setThreeDCheckBoxes( boolean threed );
Parameters
threed
Set to true for a three-dimensional appearance; set to false for a flat appearance.
Description

Determines whether the check boxes should have a flat or three-dimensional appearance.


 CheckState Class

CheckState Class

This Package | All Packages

Enum
  |
  +--CheckState
public class CheckState
extends Enum

Represents an enumeration used for various controls that can have checked or selected states (for example, a CheckBox or a CheckedListBox). Items can be completely checked, completely unchecked, or, in some cases, partially checked, in which case a shaded checkbox is typically displayed.

Fields
Name | Description
CHECKED | The item is checked.
MAX | Topic under construction.
MIN | Topic under construction.
PARTIAL | The item is partially checked.
UNCHECKED | The item is unchecked.

Fields

CheckState.CHECKED

Syntax
public static final int CHECKED;
Description
The item is checked.

CheckState.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

CheckState.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

CheckState.PARTIAL

Syntax
public static final int PARTIAL;
Description
The item is partially checked.

CheckState.UNCHECKED

Syntax
public static final int UNCHECKED;
Description
The item is unchecked.


 Color Class

Color Class

This Package | All Packages

public class Color
implements IConstructable

Describes a color in an object. The color can be described by an RGB (red, green, blue) triplet, or it can be a system color constant, such as the color of a command button [Color.CONTROL] To determine the appearance of Color constants with which you are unfamiliar (for example, Color.CONTROLDARKDARK), display a form, and select the color as the background color of the form.

Fields
Name | Description
ACTIVEBORDER | The color for active borders.
ACTIVECAPTION | The color for active captions.
ACTIVECAPTIONTEXT | The color for active caption text.
APPWORKSPACE | The color of the application workspace.
BLACK | The color black.
BLUE | The color blue.
CONTROL | The color for controls.
CONTROLDARK | Topic controldark color.
CONTROLDARKDARK | The controldarkdark color.
CONTROLLIGHT | The controllight color.
CONTROLLIGHTLIGHT | The controllightlight color.
CONTROLTEXT | The color for control text.
DARKGRAY | The color dark gray.
DESKTOP | The desktop color.
GRAY | The color gray.
GRAYTEXT | The color for gray text.
GREEN | The color green.
HIGHLIGHT | The color for highlighted objects.
HIGHLIGHTTEXT | The color for highlighted text.
HOTTRACK | The hottrack color.
INACTIVEBORDER | The color for inactive borders.
INACTIVECAPTION | The color for inactive captions.
INACTIVECAPTIONTEXT | The color for inactive caption text.
INFO | The Info color.
INFOTEXT | The InfoText color.
LIGHTGRAY | The color light gray.
MENU | The color for menus.
MENUTEXT | The color for menu text.
RED | The color red.
SCROLLBAR | The color for scroll bars.
WHITE | The color white.
WINDOW | The color for windows.
WINDOWFRAME | The color for window frames.
WINDOWTEXT | The color for window text.

Constructors
Name | Description
Color(int value) | Creates a new Color object based on a full RGB triplet or system color value in an integer.
Color(int r, int g, int b) | Creates a new Color object given individual red, green, and blue (RGB) values.

Methods
Name | Description
equals(Object obj) | Compares this color object to the color represented in the object you specify.
getBlue() | Retrieves the blue component of the color, even if the color is a system color.
getConstructorArgs() | Used by code generation at design time.
getGreen() | Retrieves the green component of the color, even if the color is a system color.
getRed() | Retrieves the red component of the color.
getRGB() | Retrieves the entire RGB triplet for the color, even if the color is a system color.
getValue() | Retrieves the current value of this Color object.
hashCode() | Retrieves a hash code for this object for use with various sorting and hashtable objects.
toString() | Retrieves a string description of the Color object.

Fields

Color.ACTIVEBORDER

Syntax
public static final Color ACTIVEBORDER;
Description
The color for active borders.

Color.ACTIVECAPTION

Syntax
public static final Color ACTIVECAPTION;
Description
The color for active captions.

Color.ACTIVECAPTIONTEXT

Syntax
public static final Color ACTIVECAPTIONTEXT;
Description
The color for active caption text.

Color.APPWORKSPACE

Syntax
public static final Color APPWORKSPACE;
Description
The color of the application workspace.

Color.BLACK

Syntax
public static final Color BLACK;
Description
The color black.

Color.BLUE

Syntax
public static final Color BLUE;
Description
The color blue.

Color.CONTROL

Syntax
public static final Color CONTROL;
Description
The color for controls.

Color.CONTROLDARK

Syntax
public static final Color CONTROLDARK;
Description
Topic controldark color.

Color.CONTROLDARKDARK

Syntax
public static final Color CONTROLDARKDARK;
Description
The controldarkdark color.

Color.CONTROLLIGHT

Syntax
public static final Color CONTROLLIGHT;
Description
The controllight color.

Color.CONTROLLIGHTLIGHT

Syntax
public static final Color CONTROLLIGHTLIGHT;
Description
The controllightlight color.

Color.CONTROLTEXT

Syntax
public static final Color CONTROLTEXT;
Description
The color for control text.

Color.DARKGRAY

Syntax
public static final Color DARKGRAY;
Description
The color dark gray.

Color.DESKTOP

Syntax
public static final Color DESKTOP;
Description
The desktop color.

Color.GRAY

Syntax
public static final Color GRAY;
Description
The color gray.

Color.GRAYTEXT

Syntax
public static final Color GRAYTEXT;
Description
The color for gray text.

Color.GREEN

Syntax
public static final Color GREEN;
Description
The color green.

Color.HIGHLIGHT

Syntax
public static final Color HIGHLIGHT;
Description
The color for highlighted objects.

Color.HIGHLIGHTTEXT

Syntax
public static final Color HIGHLIGHTTEXT;
Description
The color for highlighted text.

Color.HOTTRACK

Syntax
public static final Color HOTTRACK;
Description
The hottrack color.

Color.INACTIVEBORDER

Syntax
public static final Color INACTIVEBORDER;
Description
The color for inactive borders.

Color.INACTIVECAPTION

Syntax
public static final Color INACTIVECAPTION;
Description
The color for inactive captions.

Color.INACTIVECAPTIONTEXT

Syntax
public static final Color INACTIVECAPTIONTEXT;
Description
The color for inactive caption text.

Color.INFO

Syntax
public static final Color INFO;
Description
The Info color.

Color.INFOTEXT

Syntax
public static final Color INFOTEXT;
Description
The InfoText color.

Color.LIGHTGRAY

Syntax
public static final Color LIGHTGRAY;
Description
The color light gray.

Color.MENU

Syntax
public static final Color MENU;
Description
The color for menus.

Color.MENUTEXT

Syntax
public static final Color MENUTEXT;
Description
The color for menu text.

Color.RED

Syntax
public static final Color RED;
Description
The color red.

Color.SCROLLBAR

Syntax
public static final Color SCROLLBAR;
Description
The color for scroll bars.

Color.WHITE

Syntax
public static final Color WHITE;
Description
The color white.

Color.WINDOW

Syntax
public static final Color WINDOW;
Description
The color for windows.

Color.WINDOWFRAME

Syntax
public static final Color WINDOWFRAME;
Description
The color for window frames.

Color.WINDOWTEXT

Syntax
public static final Color WINDOWTEXT;
Description
The color for window text.

Constructors

Color.Color

Syntax 1
public Color( int value );
Parameters
value
The value for this Color object.
Description

Creates a new Color object based on a full RGB triplet or system color value in an integer.

Syntax 2
public Color( int r, int g, int b );
Parameters
r
The red component of the color.
g
The green component of the color.
b
The blue component of the color.
Description

Creates a new Color object given individual red, green, and blue (RGB) values.

Methods

Color.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The object to evaluate for a match.
Return Value

Returns true if the colors are the same; otherwise, returns false.

Description

Compares this color object to the color represented in the object you specify. If the object you specify is not a Color object, or the colors do not match, returns false.

Color.getBlue

Syntax
public int getBlue();
Return Value

Returns int the blue component of the color.

Description

Retrieves the blue component of the color, even if the color is a system color.

Color.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Return Value

Returns the permissible constructor arguments.

Description

Used by code generation at design time. For more information, see

See Also
wd.core.IConstructable.

Color.getGreen

Syntax
public int getGreen();
Return Value

Returns the green component of the color.

Description

Retrieves the green component of the color, even if the color is a system color.

Color.getRed

Syntax
public int getRed();
Return Value

Returns the red component of the color, even if the color is a system color.

Description

Retrieves the red component of the color.

Color.getRGB

Syntax
public int getRGB();
Return Value

Returns the RGB triplet value.

Description

Retrieves the entire RGB triplet for the color, even if the color is a system color.

Color.getValue

Syntax
public int getValue();
Return Value

Returns int the value of the Color object.

Description

Retrieves the current value of this Color object. If this Color object is a system color, the high byte of the returned value will not be zero.

Color.hashCode

Syntax
public int hashCode();
Return Value

Returns a hashcode for this object.

Description

Retrieves a hash code for this object for use with various sorting and hashtable objects.

Color.toString

Syntax
public String toString();
Return Value

Returns a string describing the Color object.

Description

Retrieves a string description of the Color object.


 ColumnHeader Class

ColumnHeader Class

This Package | All Packages

public class ColumnHeader

Encapsulates the settings on a column in a ListView control. These settings include the width of the column, the image associated with it, its width, and its index within the group of columns associated with a given ListView.

Methods
Name | Description
equals(Object obj) | Retrieves a boolean value that indicates whether the specified object is equivalent to this ColumnHeader object.
getFormat() | Retreives the current format settings for this column header.
getImageIndex() | Retrieves the zero-based index of the image associated with this column header.
getIndex() | Retrieves the index of this column header.
getListView() | Retrieves the ListView object associated with this column header.
getSubItemIndex() | Retrieves the subitem index for this column header.
getText() | Retrieves the text associated with this column header.
getWidth() | Retrieves the width of this column header.
hashCode() | Retrieves a hashcode for this object.
setFormat(int format) | Sets the format for this ColumnHeader object.
setImageIndex(int image) | Specifies the index of the image associated with this ColumnHeader object.
setSubItemIndex(int index) | Specifies the ColumnHeader's subitem index.
setText(String str) | Specifies the text for this ColumnHeader object.
setWidth(int width) | Specifies the width for this ColumnHeader object.
toString() | Retrieves a String object that contains the current settings on this ColumnHeader object.

Methods

ColumnHeader.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The object to compare to this ColumnHeader object.
Return Value

Returns true if obj is equivalent to this ColumnHeader object; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified object is equivalent to this ColumnHeader object.

ColumnHeader.getFormat

Syntax
public int getFormat();
Return Value

Returns a constant that identifies the format for this column header. Possible values include the following: comctl32.LVCFMT_LEFT comctl32.LVCFMT_RIGHT comctl32.LVCFMT_CENTER comctl32.LVCFMT_BITMAP_ON_RIGHT comctl32.LVCFMT_COL_HAS_IMAGES comctl32.LVCFMT_IMAGE

Description

Retreives the current format settings for this column header.

ColumnHeader.getImageIndex

Syntax
public int getImageIndex();
Return Value

Returns the index of the image if one has been set; otherwise, returns -1.

Description

Retrieves the zero-based index of the image associated with this column header.

ColumnHeader.getIndex

Syntax
public int getIndex();
Return Value

Returns the zero-based index of the column header.

Description

Retrieves the index of this column header.

ColumnHeader.getListView

Syntax
public ListView getListView();
Return Value

Returns the ListView object associated with this column header.

Description

Retrieves the ListView object associated with this column header.

ColumnHeader.getSubItemIndex

Syntax
public int getSubItemIndex();
Return Value

Returns the zero-based subitem index for this ColumnHeader.

Description

Retrieves the subitem index for this column header.

ColumnHeader.getText

Syntax
public String getText();
Return Value

Returns a String object that contains the text associated with this column header.

Description

Retrieves the text associated with this column header.

ColumnHeader.getWidth

Syntax
public int getWidth();
Return Value

Returns the width, in pixels, of this ColumnHeader object.

Description

Retrieves the width of this column header.

ColumnHeader.hashCode

Syntax
public int hashCode();
Return Value

Returns an integer that contains the hashcode.

Description

Retrieves a hashcode for this object.

ColumnHeader.setFormat

Syntax
public void setFormat( int format );
Parameters
format
An integer that specifies the ColumnHeader format. The format can be one of the following: comctl32.LVCFMT_LEFT comctl32.LVCFMT_RIGHT comctl32.LVCFMT_CENTER comctl32.LVCFMT_BITMAP_ON_RIGHT comctl32.LVCFMT_COL_HAS_IMAGES comctl32.LVCFMT_IMAGE
Description

Sets the format for this ColumnHeader object.

Exceptions

IllegalArgumentException thrown if the format argument does not evaluate to one of the previously listed constant.

ColumnHeader.setImageIndex

Syntax
public void setImageIndex( int image );
Parameters
image
The zero-based index of the image in the ListView's ImageList.
Description

Specifies the index of the image associated with this ColumnHeader object. This index references the ImageList associated with the ColumnHeader's ListView.

ColumnHeader.setSubItemIndex

Syntax
public void setSubItemIndex( int index );
Parameters
index
The subitem index for this ColumnHeader object.
Description

Specifies the ColumnHeader's subitem index.

ColumnHeader.setText

Syntax
public void setText( String str );
Parameters
str
The ColumnHeader text.
Description

Specifies the text for this ColumnHeader object.

ColumnHeader.setWidth

Syntax
public void setWidth( int width );
Parameters
width
The width of the ColumnHeader.
Description

Specifies the width for this ColumnHeader object.

ColumnHeader.toString

Syntax
public String toString();
Return Value

Returns a String object that contains the ColumnHeader settings.

Description

Retrieves a String object that contains the current settings on this ColumnHeader object.


 ComboBox Class

ComboBox Class

This Package | All Packages

Control
  |
  +--ComboBox
public class ComboBox
extends Control

Encapsulates a standard Windows combo box. This class supports the three basic combo box styles: a drop-down combo box, including an editable text portion; a drop-down list, with a read-only text portion; and a simple combo box, which is a drop-down combo box that is always in a drop-down state, with editable text. To add items to the combo box, you pass in an array of objects. Internally, the ComboBox class calls the toString method on the objects you pass in and inserts them into the combo box.

Constructors
Name | Description
ComboBox() | Creates a new ComboBox control with a default style of ComboBoxStyle.DROPDOWN.

Methods
Name | Description
addItem(Object item) | Adds an item to the combo box and retrieves the index of the new item.
addOnDrawItem(DrawItemEventHandler value) | Adds an event handler for the onDrawItem event notification.
addOnDropDown(EventHandler value) | Adds an event handler for the onDropDown event notification.
addOnMeasureItem(MeasureItemEventHandler value) | Adds an event handler for the onMeasureItem event notification.
addOnSelectionChange(EventHandler value) | Adds an event handler for the onSelectionChange event notification.
beginUpdate() | Temporarily disables any redrawing of the combo box.
endUpdate() | Re-enables redrawing to a combo box (temporarily suspended by a previous call to beginUpdate.
findItem(Object item) | Note This method is obsolete.
findString(String s) | Retrieves the zero-based index of first occurrence of the an item that begins with the specified text.
findString(String s, int startIndex) | Retrieves the zero-based index of the first occurrence of an item that begins with the specified text, beginning the search at the specified index.
findStringExact(String s) | Retrieves the zero-based index of the first occurrence of the specified item.
findStringExact(String s, int startIndex) | Retrieves the zero-based index of the first occurrence of the specified item.
getCreateParams() | Topic under construction.
getDrawMode() | Retrieves the drawing mode of the combo box.
getDroppedDown() | Retrieves a boolean indicating whether the drop-down portion of the combo box is currently displayed.
getItem(int index) | Retrieves the item at the specified index.
getItemCount() | Retrieves the number of items in the combo box.
getItemHeight() | Retrieves the height of each item in the combo box.
getItemHeight(int index) | Returns the height, based on the specified index, of the given item in a combo box in which the DrawMode.OWNERDRAWVARIABLE style is set.
getItems() | Retrieves all the items in the combo box, and returns the items in an array of objects.
getMaxDropDownItems() | Retrieves the maximum number of items that can be displayed in the drop-down portion of the combo box.
getMaxLength() | Retrieves the maximum length of the text the user can type into the edit control of a combo box.
getSelectedIndex() | Retrieves the index of the currently selected item in the combo box.
getSelectedItem() | Retrieves the object that is currently selected in the combo box.
getSelectedText() | Retrieves the text of the currently selected item.
getSelectionEnd() | Retrieves the zero-based index of the last character in the combo box selection.
getSelectionStart() | Retrieves the index of the first character of the currently selected text.
getSorted() | Retrieves a boolean value that indicates whether the contents of the combo box are sorted.
getStyle() | Retrieves the style of the combo box.
insertItem(int index, Object item) | Inserts an item into the combo box at the given index.
removeAll() | Clears the combo box.
removeItem(int index) | Removes the item at the specified index.
removeOnDrawItem(DrawItemEventHandler value) | Removes the specified handler for the onDrawItem event.
removeOnDropDown(EventHandler value) | Removes the specified handler for the onDropDown event.
removeOnMeasureItem(MeasureItemEventHandler value) | Removes the specified handler for the onMeasureItem event.
removeOnSelectionChange(EventHandler value) | Removes the specified handler for the onSelectionChange event.
select(int start, int end) | Selects the text in the specified range.
selectAll() | Selects all the text in the editable portion of the combo box.
setDrawMode(int value) | Sets the drawing style of the combo box.
setDroppedDown(boolean value) | Displays or hides the drop-down portion of the combo box.
setItem(int index, Object item) | Initializes the specified index.
setItemHeight(int value) | Sets the height of an item in a combo box of style ComboBoxStyle.OWNERDRAWFIXED.
setItems(Object[] value) | Initializes a combo box based on the contents of an array of objects.
setMaxDropDownItems(int value) | Sets the maximum number of items that can be displayed in the dropdown portion of the combo box.
setMaxLength(int value) | Sets the maximum allowable length of the text in the editable portion of the combo box.
setSelectedIndex(int index) | Selects the specified item.
setSelectedText(String value) | Replaces the currently selected text with the specified text.
setSelectionEnd(int value) | Specifies the zero-based index of the last character of a text selection in the ComboBox control.
setSelectionStart(int value) | Specifies the zero-based index of the first character of a text selection in the Edit control.
setSorted(boolean value) | Specifies whether the items in the combo box should be sorted.
setStyle(int value) | Sets the style of the combo box.

Constructors

ComboBox.ComboBox

Syntax
public ComboBox();
Description

Creates a new ComboBox control with a default style of ComboBoxStyle.DROPDOWN. To change the style of the ComboBox, use the setStyle method with one of the constants defined in the ComboBoxStyle class.

Methods

ComboBox.addItem

Syntax
public int addItem( Object item );
Parameters
item
The item to add to the ComboBox. Internally, the ComboBox class retrieves the string representation of this item by calling the object's toString method.
Return Value

Returns the zero-based index of the added item.

Description

Adds an item to the combo box and retrieves the index of the new item. For an unsorted combo box, the item is added to the end of the existing list of items. For a sorted combo box, the item is inserted into the list according to its sorted position.

Exceptions

RunTimeException thrown if there is insufficient space in which to store the new item.

ComboBox.addOnDrawItem

Syntax
public void addOnDrawItem( DrawItemEventHandler value );
Parameters
value
A DrawItemEventHandler object.
Description

Adds an event handler for the onDrawItem event notification. The onDrawItem event is fired for combo boxes whose draw mode setting is DrawMode.OWNERDRAWFIXED or DrawMode.OWNERDRAWVARIABLE. The DrawItemEventHandler object passed as a parameter to this event handler contains a Graphics object that you use to paint the item. Duplicate calls to the addOnDrawItem method are not filtered out by the ComboBox class.

ComboBox.addOnDropDown

Syntax
public void addOnDropDown( EventHandler value );
Parameters
value
The new event handler to install for this event.
Description

Adds an event handler for the onDropDown event notification. This event is fired when the drop-down portion of the combo box is displayed. Duplicate calls to addOnDropDown are not filtered out by the ComboBox class.

ComboBox.addOnMeasureItem

Syntax
public void addOnMeasureItem( MeasureItemEventHandler value );
Parameters
value
The new event handler to install for this event.
Description

Adds an event handler for the onMeasureItem event notification. This event is fired for list boxes whose drawMode property is set to DrawMode.OWNERDRAWFIXED or DrawMode.OWNERDRAWVARIABLE. Within this onMeasureItem event, you use the MeasureItemEvent object passed to the handler to notify Windows of the size of a given item in the combo box. If the DrawMode for this combo box is OWNERDRAWFIXED, this event is sent only once. Duplicate calls to addOnMeasureItem are not filtered out by the ComboBox class.

ComboBox.addOnSelectionChange

Syntax
public final void addOnSelectionChange( EventHandler value );
Parameters
value
The new event handler to install for this event.
Description

Adds an event handler for the onSelectionChange event notification. This event is fired when the user changes the selection in the combo box. Duplicate calls to this method are not filtered out by the ComboBox class.

ComboBox.beginUpdate

Syntax
public void beginUpdate();
Description

Temporarily disables any redrawing of the combo box. A call to beginUpdate must be followed by a call to endUpdate. Following the call to beginUpdate, any redrawing that would result by operations performed on the combo box is deferred until the call to endUpdate.

ComboBox.endUpdate

Syntax
public void endUpdate();
Description

Re-enables redrawing to a combo box (temporarily suspended by a previous call to beginUpdate. All redrawing of the combo box occurs after the call to endUpdate.

ComboBox.findItem

Syntax
public int findItem( Object item );
Description

Note This method is obsolete.

ComboBox.findString

Syntax 1
public int findString( String s );
Parameters
s
The index of the string to retrieve.
Return Value

Returns the zero-based index of the first occurrence of the specified item if the item exists; otherwise, returns -1.

Description

Retrieves the zero-based index of first occurrence of the an item that begins with the specified text. The search for this item starts at the beginning of the list of items in the combo box, and the search is case-insensitive.

Syntax 2
public int findString( String s, int startIndex );
Parameters
s
The string for which to search.
startIndex
The index at which to begin the search.
Return Value

Returns the zero-based index of the first item that begins with the specified text if it exists; otherwise, returns -1.

Description

Retrieves the zero-based index of the first occurrence of an item that begins with the specified text, beginning the search at the specified index. This search is case-insensitive.

ComboBox.findStringExact

Syntax 1
public int findStringExact( String s );
Parameters
s
The string for which to search.
Return Value

Returns the zero-based index of the first occurrence of the item if the item exists; therwise, returns -1.

Description

Retrieves the zero-based index of the first occurrence of the specified item. The search for the item begins at the beginning of the list of items stored by the combo box. The specified string must match exactly the string in the combo box, except in regard to case.

Syntax 2
public int findStringExact( String s, int startIndex );
Parameters
s
The string for which to search.
startIndex
The index of the item with which to begin the search.
Return Value

Returns the zero-based index of the first string (after the specified index) that matches the search string if the string exists; otherwise, returns -1.

Description

Retrieves the zero-based index of the first occurrence of the specified item. The search for the item begins at the specified index. The specified string must match the string in the combo box exactly, except in regard to case.

ComboBox.getCreateParams

Syntax
protected CreateParams getCreateParams();
Description

Topic under construction.

ComboBox.getDrawMode

Syntax
public int getDrawMode();
Return Value

Returns an enumeration constant defined DrawMode class.

Description

Retrieves the drawing mode of the combo box. The DrawMode property controls whether the control is drawn by Windows or by the user.

See Also
wfc.ui.DrawMode enumeration.

ComboBox.getDroppedDown

Syntax
public boolean getDroppedDown();
Return Value

Returns true if the drop-down portion of the combo box is displayed; otherwise, returns false.

Description

Retrieves a boolean indicating whether the drop-down portion of the combo box is currently displayed.

ComboBox.getItem

Syntax
public Object getItem( int index );
Parameters
index
The index of the item to retrieve.
Return Value

Returns the item at the index specified.

Description

Retrieves the item at the specified index.

Exceptions

InvalidArgument thrown if the specified index is less than zero or exceeds the number of items in the combo box.

ComboBox.getItemCount

Syntax
public int getItemCount();
Return Value

Returns an integer that specifies the number of items in the combo box.

Description

Retrieves the number of items in the combo box.

ComboBox.getItemHeight

Syntax 1
public int getItemHeight();
Return Value

Returns the height of the items in the combo box.

Description

Retrieves the height of each item in the combo box. For all DrawModes except OWNERDRAWVARIAIBLE, all items have the same height. For OWNERDRAWVARIABLE combo boxes, each item may have a different height.

Syntax 2
public final int getItemHeight( int index );
Parameters
index
The index of the item for which to return the height.
Return Value

Returns the height of the specified item in pixels,.

Description

Returns the height, based on the specified index, of the given item in a combo box in which the DrawMode.OWNERDRAWVARIABLE style is set. This method should not be called for combo boxes in which the item height is fixed.

ComboBox.getItems

Syntax
public Object[] getItems();
Return Value

Returns an array with all the items currently in the combo box.

Description

Retrieves all the items in the combo box, and returns the items in an array of objects.

ComboBox.getMaxDropDownItems

Syntax
public int getMaxDropDownItems();
Return Value

Returns the maximum number of items that can be displayed.

Description

Retrieves the maximum number of items that can be displayed in the drop-down portion of the combo box. This number can be between 1 and 100.

ComboBox.getMaxLength

Syntax
public int getMaxLength();
Return Value

Returns the maximum lengh of the text.

Description

Retrieves the maximum length of the text the user can type into the edit control of a combo box.

ComboBox.getSelectedIndex

Syntax
public int getSelectedIndex();
Return Value

Returns the zero-based index of the currently selected item.

Description

Retrieves the index of the currently selected item in the combo box.

ComboBox.getSelectedItem

Syntax
public Object getSelectedItem();
Return Value

Returns the currently selected object if an item is selected; otherwise, returns null.

Description

Retrieves the object that is currently selected in the combo box.

ComboBox.getSelectedText

Syntax
public String getSelectedText();
Return Value

Returns the text of the currently selected item.

Description

Retrieves the text of the currently selected item.

ComboBox.getSelectionEnd

Syntax
public int getSelectionEnd();
Return Value

Returns the zero-based index of the last character in the current selection.

Description

Retrieves the zero-based index of the last character in the combo box selection.

ComboBox.getSelectionStart

Syntax
public int getSelectionStart();
Return Value

Returns the zero-based index of the start of the first character in current selection.

Description

Retrieves the index of the first character of the currently selected text.

ComboBox.getSorted

Syntax
public boolean getSorted();
Return Value

Returns true if the list is sorted; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the contents of the combo box are sorted.

ComboBox.getStyle

Syntax
public int getStyle();
Return Value

Returns the style of the combo box.

Description

Retrieves the style of the combo box. The returned value is one of the enumeration constants defined in the ComboBoxStyle class.

ComboBox.insertItem

Syntax
public int insertItem( int index, Object item );
Parameters
index
The index at which to insert the item.
item
The item to insert.
Return Value

Returns the index at which the item was inserted.

Description

Inserts an item into the combo box at the given index.

ComboBox.removeAll

Syntax
public void removeAll();
Description

Clears the combo box.

ComboBox.removeItem

Syntax
public void removeItem( int index );
Parameters
index
The index of the item to remove.
Description

Removes the item at the specified index.

ComboBox.removeOnDrawItem

Syntax
public void removeOnDrawItem( DrawItemEventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the specified handler for the onDrawItem event. If there are duplicate entries, all the handlers are removed.

ComboBox.removeOnDropDown

Syntax
public void removeOnDropDown( EventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the specified handler for the onDropDown event. If there are duplicate entries, all the handlers are removed.

ComboBox.removeOnMeasureItem

Syntax
public void removeOnMeasureItem( MeasureItemEventHandler value );
Parameters
value
The event handler to remove.
Description

Removes the specified handler for the onMeasureItem event. If there are duplicate entries, all the handlers are removed.

ComboBox.removeOnSelectionChange

Syntax
public final void removeOnSelectionChange( EventHandler value );
Parameters
value
The event handler to remove.
Description

Removes the specified handler for the onSelectionChange event. If there are duplicate entries, all the handlers are removed.

ComboBox.select

Syntax
public void select( int start, int end );
Parameters
start
The zero-based index of the character with which to begin the selection.
end
The zero-based index of the character with which to end the selection.
Description

Selects the text in the specified range.

ComboBox.selectAll

Syntax
public void selectAll();
Description

Selects all the text in the editable portion of the combo box.

ComboBox.setDrawMode

Syntax
public void setDrawMode( int value );
Parameters
value
One of the enumeration constants defined in the DrawMode class.
Description

Sets the drawing style of the combo box. By setting the drawing mode of the combo box, you specify whether the combo box is owner-draw and whether all items displayed in the combo box are of the same height.

Exceptions

InvalidEnumArgument yhrown if the specified value is less than DrawMode.MIN or exceeds DrawMode.MAX.

ComboBox.setDroppedDown

Syntax
public void setDroppedDown( boolean value );
Parameters
value
If true, the drop-down portion of the combo box is displayed. Otherwise, it is hidden.
Description

Displays or hides the drop-down portion of the combo box.

ComboBox.setItem

Syntax
public void setItem( int index, Object item );
Parameters
index
The index at which to set the data.
item
The data to store at the specified index.
Description

Initializes the specified index. If the item at the specified index already contains data, this data is lost.

ComboBox.setItemHeight

Syntax
public void setItemHeight( int value );
Parameters
value
The height of items in the combo box.
Description

Sets the height of an item in a combo box of style ComboBoxStyle.OWNERDRAWFIXED. If the style of a combo box is DrawMode.NORMAL, a call to this method is ignored.

ComboBox.setItems

Syntax
public void setItems( Object[] value );
Parameters
value
The array of objects to insert.
Description

Initializes a combo box based on the contents of an array of objects. All values currently stored in the combo box are lost.

ComboBox.setMaxDropDownItems

Syntax
public void setMaxDropDownItems( int value );
Parameters
value
The maximum number of items that can be displayed.
Description

Sets the maximum number of items that can be displayed in the dropdown portion of the combo box. This value can be between 1 and 100.

Exceptions

IllegalArgumentException thrown if the specified value is less than zero or more than one hundred.

ComboBox.setMaxLength

Syntax
public void setMaxLength( int value );
Parameters
value
The maximum length of the text.
Description

Sets the maximum allowable length of the text in the editable portion of the combo box.

ComboBox.setSelectedIndex

Syntax
public void setSelectedIndex( int index );
Parameters
index
The zero-based index of the item to select.
Description

Selects the specified item.

ComboBox.setSelectedText

Syntax
public void setSelectedText( String value );
Parameters
value
The text with which to replace the currently selected text.
Description

Replaces the currently selected text with the specified text.

ComboBox.setSelectionEnd

Syntax
public void setSelectionEnd( int value );
Parameters
value
The zero-based index of the character at which the selection ends.
Description

Specifies the zero-based index of the last character of a text selection in the ComboBox control.

ComboBox.setSelectionStart

Syntax
public void setSelectionStart( int value );
Parameters
value
The zero-based index of the first character at which the selection begins.
Description

Specifies the zero-based index of the first character of a text selection in the Edit control.

ComboBox.setSorted

Syntax
public void setSorted( boolean value );
Parameters
value
Set to true if the items should be sorted; otherwise, set to false.
Description

Specifies whether the items in the combo box should be sorted. By default, items in a ComboBox control are not sorted.

ComboBox.setStyle

Syntax
public void setStyle( int value );
Parameters
value
The style of the combo box. This value must be one of the enumeration constants defined in the ComboBoxStyle class.
Description

Sets the style of the combo box.


 ComboBoxStyle Class

ComboBoxStyle Class

This Package | All Packages

Enum
  |
  +--ComboBoxStyle
public class ComboBoxStyle
extends Enum

Defines the constants that you apply to a ComboBox control to determine its appearance.

Fields
Name | Description
DROPDOWN | Defines a drop-down ComboBox.
DROPDOWNLIST | Defines a read-only drop-down ComboBox.
MAX | The maximum style value for a combo box.
MIN | The minimum style value for a combo box.
SIMPLE | Defines a simple ComboBox.

Fields

ComboBoxStyle.DROPDOWN

Syntax
public static final int DROPDOWN;
Description
Defines a drop-down ComboBox. When this style is applied to a ComboBox control, the combo box is displayed with an arrow button to the right of an Edit box. When this arrow is clicked, the drop-down portion of the ComboBox control is displayed.

ComboBoxStyle.DROPDOWNLIST

Syntax
public static final int DROPDOWNLIST;
Description
Defines a read-only drop-down ComboBox. When this style is applied to the ComboBox control, the combo box is displayed as a read-only control with an arrow to the right of it. When this arrow is clicked, the drop-down portion of the ComboBox control is displayed.

ComboBoxStyle.MAX

Syntax
public static final int MAX;
Description
The maximum style value for a combo box.

ComboBoxStyle.MIN

Syntax
public static final int MIN;
Description
The minimum style value for a combo box.

ComboBoxStyle.SIMPLE

Syntax
public static final int SIMPLE;
Description
Defines a simple ComboBox. When this style is applied to a ComboBox control, the combo box is displayed as an Edit box with a list below it.


 Control Class

Control Class

This Package | All Packages

Component
  |
  +--Control
public class Control
extends Component

Defines the base functionality of a Win32 control. All WFC controls are extended from this class.

Fields
Name | Description
dbgControls | Topic under construction.
DROPEFFECT_ALL | Topic under construction.
DROPEFFECT_COPY | Topic under construction.
DROPEFFECT_LINK | Topic under construction.
DROPEFFECT_MOVE | Topic under construction.
DROPEFFECT_NONE | Topic under construction.
DROPEFFECT_SCROLL | Topic under construction.
MB_LEFT | Indicates that the left mouse button has been pressed
MB_MIDDLE | Indicates that the middle mouse button has been pressed
MB_RIGHT | Indicates that the right mouse button has been pressed
PROP_BACKCOLOR | Indicates that the BackColor property has changed.
PROP_CURSOR | Indicates that the Cursor property has changed.
PROP_ENABLED | Indicates that the Enabled property has changed.
PROP_FONT | Indicates that the Font property has changed.
PROP_FORECOLOR | Indicates that the ForeColor property has changed.
PROP_LOCATION | Indicates that the Location property has changed.
PROP_PARENTBACKCOLOR | Indicates that the parent's BackColor property has changed.
PROP_PARENTFONT | Indicates that the parent window's Font property has changed.
PROP_PARENTFORECOLOR | Indicates that the parent window's ForeColor property has changed.
PROP_SIZE | Indicates that the Size property has changed.
PROP_TABSTOP | Indicates that the TabStop property has changed.
PROP_TEXT | Indicates that the Text property has changed.
PROP_VISIBLE | Indicates that the Visible property has changed.
STYLE_ACCEPTSCHILDREN | Indicates whether the control will accept children.
STYLE_FIXED_HEIGHT | Indicates whether the control has a fixed height.
STYLE_FIXED_WIDTH | Indicates whether the control has a fixed width.
STYLE_FORM | Indicates whether the control is a container for other controls.
STYLE_OPAQUE | Indicates whether the control's background should be erased upon invalidation.
STYLE_OPTIMIZE_SIZEPAINT | Indicates whether the control should erase the background when painting during resize.
STYLE_RESIZE_REDRAW | Indicates whether the control should redraw on resize.
STYLE_STDCLICK | Indicates that the control will receive standard click events.
STYLE_USERPAINT | Indicates whether the control does its own painting.

Constructors
Name | Description
Control() | Creates a new control.
createControl() | Topic under construction.
getTopLevelControl() | Topic under construction.
selectNextControl(Control ctl, boolean forward, boolean tabStopOnly, boolean nested, boolean wrap) | Topic under construction.

Methods
Name | Description
add(Control control) | Adds a child control to this control.
addOnChange(EventHandler value) | Adds an event handler for the OnChange event notification.
addOnClick(EventHandler value) | Adds an event handler for the OnClick event notification.
addOnCreate(CreateEventHandler value) | Adds an event handler for the OnCreate event notification.
addOnDoubleClick(EventHandler value) | Adds an event handler for the OnDoubleClick event notification.
addOnDragEnter(DragEventHandler value) | Adds an event handler for the OnDragEnter event notification.
addOnDragLeave(EventHandler value) | Adds an event handler for the OnDragLeave event notification.
addOnDragOver(DragEventHandler value) | Adds an event handler for the OnDragOver event notification.
addOnDrop(DragEventHandler value) | Adds an event handler for the OnDrop event notification.
addOnEnter(EventHandler value) | Adds an event handler for the OnEnter event notification.
addOnGiveFeedback(GiveFeedbackEventHandler value) | Adds an event handler for the OnGiveFeedback event notification.
addOnGotFocus(EventHandler value) | Adds an event handler for the OnGotFocus event notification.
addOnHelp(EventHandler value) | Adds an event handler for the OnHelp event notification.
addOnKeyDown(KeyEventHandler value) | Adds an event handler for the OnKeyDown event notification.
addOnKeyPress(KeyEventHandler value) | Adds an event handler for the OnKeyPress event notification.
addOnKeyUp(KeyEventHandler value) | Adds an event handler for the OnKeyUp event notification.
addOnLeave(EventHandler value) | Adds an event handler for the OnLeave event notification.
addOnLostFocus(EventHandler value) | Adds an event handler for the OnLostFocus event notification.
addOnMouseDown(MouseEventHandler value) | Adds an event handler for the OnMouseDown event notification.
addOnMouseEnter(EventHandler value) | Adds an event handler for the OnMouseEnter event notification.
addOnMouseLeave(EventHandler value) | Adds an event handler for the OnMouseLeave event notification.
addOnMouseMove(MouseEventHandler value) | Adds an event handler for the OnMouseMove event notification.
addOnMouseUp(MouseEventHandler value) | Adds an event handler for the OnMouseUp event notification.
addOnMouseWheel(MouseEventHandler value) | Adds an event handler for the OnMouseWheel event notification.
addOnMove(EventHandler value) | Adds an event handler for the OnMove event notification.
addOnPaint(PaintEventHandler value) | Adds an event handler for the OnPaint event notification.
addOnQueryContinueDrag( QueryContinueDragEventHandler value) | Adds an event handler for the OnQueryContinueDrag event notification.
addOnResize(EventHandler value) | Adds an event handler for the OnResize event notification.
assignParent(Control value) | Assigns a new parent control.
bringToFront() | Brings this control to the front of the z-order.
canFocus() | Checks if this control can receive focus.
canSelect() | Checks if this control can be selected.
contains(Control ctl) | Checks if a control is a child of this control.
createGraphics() | Creates a Graphics for this control.
createGraphics(int dc) | Creates a Graphics for this control.
dispose() | Topic under construction.
doDragDrop(Object data, int allowedEffects) | Topic under construction.
focus() | Topic under construction.
fromChildHandle(int handle) | Topic under construction.
fromHandle(int handle) | Topic under construction.
getAcceleratorTable() | Topic under construction.
getAllowDrop() | Topic under construction.
getAnchor() | Topic under construction.
getAxContainer() | Topic under construction.
getBackColor() | Topic under construction.
getBottom() | Topic under construction.
getBounds() | Topic under construction.
getBrush() | Topic under construction.
getCapture() | Topic under construction.
getChildAtPoint(Point pt) | Topic under construction.
getClientRect() | Topic under construction.
getClientSize() | Topic under construction.
getContextMenu() | Topic under construction.
getControl(int index) | Topic under construction.
getControlCount() | Topic under construction.
getControlIndex() | Topic under construction.
getControls() | Topic under construction.
getCreated() | Topic under construction.
getCursor() | Topic under construction.
getDesktop() | Topic under construction.
getDisplayRect() | Returns the client rectangle of the display area of the control.
getDock() | Topic under construction.
getEnabled() | Topic under construction.
getFocused() | Topic under construction.
getFont() | Topic under construction.
getForeColor() | Topic under construction.
getForm() | Topic under construction.
getHandle() | Topic under construction.
getHandleCreated() | Topic under construction.
getHeight() | Topic under construction.
getIconic() | Topic under construction.
getLeft() | Topic under construction.
getLocation() | Topic under construction.
getMnemonic(char charCode, String text) | Topic under construction.
getModifierKeys() | Topic under construction.
getMouseButtons() | Topic under construction.
getNextControl(Control ctl, boolean forward) | Topic under construction.
getPalette() | Topic under construction.
getParent() | Topic under construction.
getParentHandle() | Topic under construction.
getRecreatingHandle() | Topic under construction.
getRight() | Topic under construction.
getSize() | Topic under construction.
getStyle(int flag) | Topic under construction.
getTabIndex() | Topic under construction.
getTabList() | Topic under construction.
getTabStop() | Topic under construction.
getText() | Topic under construction.
getTop() | Topic under construction.
getTopLevel() | Topic under construction.
getVisible() | Topic under construction.
getWidth() | Topic under construction.
getZoomed() | Topic under construction.
hasDefaultBackColor() | Topic under construction.
hasDefaultFont() | Topic under construction.
hasDefaultForeColor() | Topic under construction.
hide() | Topic under construction.
invalidate() | Topic under construction.
invalidateRect(Rectangle rc) | Topic under construction.
isAncestor(Control ancestor) | Topic under construction.
isDescendant(Control descendant) | Topic under construction.
layout() | Topic under construction.
layout(Control dockLast) | Topic under construction.
onCreate(CreateEvent e) | Inheriting classes should override this method to handle this event.
onDoubleClick(Event e) | Inheriting classes should override this method to handle this event.
onDragEnter(DragEvent event) | Inheriting classes should override this method to handle this event.
onDragLeave(Event event) | Inheriting classes should override this method to handle this event.
onDragOver(DragEvent event) | Inheriting classes should override this method to handle this event.
onDrop(DragEvent event) | Inheriting classes should override this method to handle this event.
onEnter(Event event) | Inheriting classes should override this method to handle this event.
onGiveFeedback(GiveFeedbackEvent event) | Inheriting classes should override this method to handle this event.
onGotFocus(Event e) | Inheriting classes should override this method to handle this event.
onHelp(Event e) | Inheriting classes should override this method to handle this event.
onKeyDown(KeyEvent e) | Inheriting classes should override this method to handle this event.
onKeyPress(KeyEvent e) | Inheriting classes should override this method to handle this event.
onKeyUp(KeyEvent e) | Inheriting classes should override this method to handle this event.
onLeave(Event e) | Inheriting classes should override this method to handle this event.
onLostFocus(Event e) | Inheriting classes should override this method to handle this event.
onMouseDown(MouseEvent e) | Inheriting classes should override this method to handle this event.
onMouseEnter(Event e) | Inheriting classes should override this method to handle this event.
onMouseLeave(Event e) | Inheriting classes should override this method to handle this event.
onMouseMove(MouseEvent e) | Inheriting classes should override this method to handle this event.
onMouseUp(MouseEvent e) | Inheriting classes should override this method to handle this event.
onMouseWheel(MouseEvent e) | Inheriting classes should override this method to handle this event.
onMove(Event e) | Inheriting classes should override this method to handle this event.
onPaint(PaintEvent e) | Inheriting classes should override this method to handle this event.
onQueryContinueDrag(QueryContinueDragEvent event) | Inheriting classes should override this method to handle this event.
onResize(Event e) | Inheriting classes should override this method to handle this event.
pointToClient(Point p) | Topic under construction.
pointToScreen(Point p) | Topic under construction.
preProcessMessage(MSG msg) | This method is called by the application's message loop to preprocess input messages before they are dispatched.
processCmdKey(MSG msg, int keyData) | Processes a command key.
rectToClient(Rectangle r) | Topic under construction.
rectToScreen(Rectangle r) | Topic under construction.
remove(Control control) | Topic under construction.
removeOnChange(EventHandler value) | Removes the given handler for the OnChange event.
removeOnClick(EventHandler value) | Removes the given handler for the OnClick event.
removeOnCreate(CreateEventHandler value) | Removes the given handler for the OnCreate event.
removeOnDoubleClick(EventHandler value) | Removes the given handler for the OnDoubleClick event.
removeOnDragEnter(DragEventHandler value) | Removes the given handler for the OnDragEnter event.
removeOnDragLeave(EventHandler value) | Removes the given handler for the OnDragLeave event.
removeOnDragOver(DragEventHandler value) | Removes the given handler for the OnDragOver event.
removeOnDrop(DragEventHandler value) | Removes the given handler for the OnDragEvent event.
removeOnEnter(EventHandler value) | Removes the given handler for the OnEnter event.
removeOnGiveFeedback(GiveFeedbackEventHandler value) | Removes the given handler for the OnGiveFeedback event.
removeOnGotFocus(EventHandler value) | Removes the given handler for the OnGotFocus event.
removeOnHelp(EventHandler value) | Removes the given handler for the OnHelp event.
removeOnKeyDown(KeyEventHandler value) | Removes the given handler for the OnKeyDown event.
removeOnKeyPress(KeyEventHandler value) | Removes the given handler for the OnKeyPress event.
removeOnKeyUp(KeyEventHandler value) | Removes the given handler for the OnKeyUp event.
removeOnLeave(EventHandler value) | Removes the given handler for the OnLeave event.
removeOnLostFocus(EventHandler value) | Removes the given handler for the OnLostFocus event.
removeOnMouseDown(MouseEventHandler value) | Removes the given handler for the OnMouseDown event.
removeOnMouseEnter(EventHandler value) | Removes the given handler for the OnMouseEnter event.
removeOnMouseLeave(EventHandler value) | Removes the given handler for the OnMouseLeave event.
removeOnMouseMove(MouseEventHandler value) | Removes the given handler for the OnMouseMove event.
removeOnMouseUp(MouseEventHandler value) | Removes the given handler for the OnMouseUp event.
removeOnMouseWheel(MouseEventHandler value) | Removes the given handler for the OnMouseWheel event.
removeOnMove(EventHandler value) | Removes the given handler for the OnMove event.
removeOnPaint(PaintEventHandler value) | Removes the given handler for the OnPaint event.
removeOnQueryContinueDrag( QueryContinueDragEventHandler value) | Removes the given handler for the OnQueryContinueDrag event.
removeOnResize(EventHandler value) | Removes the given handler for the OnResize event.
resumeLayout() | Topic under construction.
scale(float ratio) | Topic under construction.
scale(float dx, float dy) | Topic under construction.
select() | Topic under construction.
select(boolean directed, boolean forward) | Topic under construction.
sendToBack() | sends this control to the back of the z-order
setAcceleratorTable(AcceleratorTable accel) | Topic under construction.
setAllowDrop(boolean allowDrop) | Topic under construction.
setAnchor(int value) | Topic under construction.
setBackColor(Color value) | Topic under construction.
setBounds(Rectangle value) | Topic under construction.
setBounds(int x, int y, int width, int height) | Topic under construction.
setBoundsBatch(ControlRect[] items) | Topic under construction.
setBrush(Brush br) | Topic under construction.
setCapture(boolean value) | Topic under construction.
setClientSize(Point size) | Topic under construction.
setContextMenu(ContextMenu contextMenu) | Topic under construction.
setControlIndex(int value) | Topic under construction.
setControls(Control[] value) | Topic under construction.
setCursor(Cursor value) | Topic under construction.
setDock(int value) | Topic under construction.
setEnabled(boolean enabled) | Topic under construction.
setFont(Font value) | Topic under construction.
setForeColor(Color value) | Topic under construction.
setHeight(int value) | Topic under construction.
setLocation(int x, int y) | Topic under construction.
setLocation(Point value) | Topic under construction.
setNewControls(Control[] value) | Topic under construction.
setParent(Control value) | Topic under construction.
setParentHandle(int value) | Topic under construction.
setPositionInfo(PositionInfo info) | Note Use setBounds(), setDock(), and setAnchor() instead
setSite(ISite value) | Topic under construction.
setSize(int width, int height) | Topic under construction.
setSize(Point value) | Topic under construction.
setStyle(int flag, boolean value) | Topic under construction.
setTabIndex(int value) | Sets the index of this control.
setTabStop(boolean value) | Topic under construction.
setText(String value) | Topic under construction.
setTopLevel(boolean value) | Topic under construction.
setVisible(boolean value) | Topic under construction.
setWidth(int value) | Topic under construction.
show() | Topic under construction.
suspendLayout() | Topic under construction.
update() | Topic under construction.
updateStyles() | Topic under construction.

Fields

Control.dbgControls

Syntax
static public HashTable dbgControls;
Description
Topic under construction.

Control.DROPEFFECT_ALL

Syntax
public static final int DROPEFFECT_ALL;
Description
Topic under construction.

Control.DROPEFFECT_COPY

Syntax
public static final int DROPEFFECT_COPY;
Description
Topic under construction.

Control.DROPEFFECT_LINK

Syntax
public static final int DROPEFFECT_LINK;
Description
Topic under construction.

Control.DROPEFFECT_MOVE

Syntax
public static final int DROPEFFECT_MOVE;
Description
Topic under construction.

Control.DROPEFFECT_NONE

Syntax
public static final int DROPEFFECT_NONE;
Description
Topic under construction.

Control.DROPEFFECT_SCROLL

Syntax
public static final int DROPEFFECT_SCROLL;
Description
Topic under construction.

Control.MB_LEFT

Syntax
public static final int MB_LEFT;
Description
Indicates that the left mouse button has been pressed

Control.MB_MIDDLE

Syntax
public static final int MB_MIDDLE;
Description
Indicates that the middle mouse button has been pressed

Control.MB_RIGHT

Syntax
public static final int MB_RIGHT;
Description
Indicates that the right mouse button has been pressed

Control.PROP_BACKCOLOR

Syntax
public static final int PROP_BACKCOLOR;
Description
Indicates that the BackColor property has changed.

Control.PROP_CURSOR

Syntax
public static final int PROP_CURSOR;
Description
Indicates that the Cursor property has changed.

Control.PROP_ENABLED

Syntax
public static final int PROP_ENABLED;
Description
Indicates that the Enabled property has changed.

Control.PROP_FONT

Syntax
public static final int PROP_FONT;
Description
Indicates that the Font property has changed.

Control.PROP_FORECOLOR

Syntax
public static final int PROP_FORECOLOR;
Description
Indicates that the ForeColor property has changed.

Control.PROP_LOCATION

Syntax
public static final int PROP_LOCATION;
Description
Indicates that the Location property has changed.

Control.PROP_PARENTBACKCOLOR

Syntax
public static final int PROP_PARENTBACKCOLOR;
Description
Indicates that the parent's BackColor property has changed.

Control.PROP_PARENTFONT

Syntax
public static final int PROP_PARENTFONT;
Description
Indicates that the parent window's Font property has changed.

Control.PROP_PARENTFORECOLOR

Syntax
public static final int PROP_PARENTFORECOLOR;
Description
Indicates that the parent window's ForeColor property has changed.

Control.PROP_SIZE

Syntax
public static final int PROP_SIZE;
Description
Indicates that the Size property has changed.

Control.PROP_TABSTOP

Syntax
public static final int PROP_TABSTOP;
Description
Indicates that the TabStop property has changed.

Control.PROP_TEXT

Syntax
public static final int PROP_TEXT;
Description
Indicates that the Text property has changed.

Control.PROP_VISIBLE

Syntax
public static final int PROP_VISIBLE;
Description
Indicates that the Visible property has changed.

Control.STYLE_ACCEPTSCHILDREN

Syntax
public static final int STYLE_ACCEPTSCHILDREN;
Description
Indicates whether the control will accept children.

Control.STYLE_FIXED_HEIGHT

Syntax
public static final int STYLE_FIXED_HEIGHT;
Description
Indicates whether the control has a fixed height.

Control.STYLE_FIXED_WIDTH

Syntax
public static final int STYLE_FIXED_WIDTH;
Description
Indicates whether the control has a fixed width.

Control.STYLE_FORM

Syntax
public static final int STYLE_FORM;
Description
Indicates whether the control is a container for other controls.

Control.STYLE_OPAQUE

Syntax
public static final int STYLE_OPAQUE;
Description
Indicates whether the control's background should be erased upon invalidation.

Control.STYLE_OPTIMIZE_SIZEPAINT

Syntax
public static final int STYLE_OPTIMIZE_SIZEPAINT;
Description
Indicates whether the control should erase the background when painting during resize.

Control.STYLE_RESIZE_REDRAW

Syntax
public static final int STYLE_RESIZE_REDRAW;
Description
Indicates whether the control should redraw on resize.

Control.STYLE_STDCLICK

Syntax
public static final int STYLE_STDCLICK;
Description
Indicates that the control will receive standard click events.

Control.STYLE_USERPAINT

Syntax
public static final int STYLE_USERPAINT;
Description
Indicates whether the control does its own painting.

Constructors

Control.Control

Syntax
public Control();
Description

Creates a new control. This constructor is typically not called directly. Instead, it is called from a the constructor of a descendant class.

Control.createControl

Syntax
public void createControl();
Description

Topic under construction.

Control.getTopLevelControl

Syntax
public boolean getTopLevelControl();
Description

Topic under construction.

Control.selectNextControl

Syntax
public boolean selectNextControl( Control ctl, boolean forward, boolean tabStopOnly, boolean nested, boolean wrap );
Description

Topic under construction.

Methods

Control.add

Syntax
public void add( Control control );
Parameters
control
The child control to be added.
Description

Adds a child control to this control. The control becomes the last control in the child control list. If the control is already a child of another control, it is first removed from that control.

Exceptions

RuntimeException thrown if the specified control is a top-level control or if a circular control reference would result.

See Also
remove, setParent

Control.addOnChange

Syntax
public void addOnChange( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnChange event notification. Duplicates are not filtered out.

See Also
removeOnChange

Control.addOnClick

Syntax
public void addOnClick( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnClick event notification. Duplicates are not filtered out.

See Also
removeOnClick

Control.addOnCreate

Syntax
public void addOnCreate( CreateEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnCreate event notification. Duplicates are not filtered out.

See Also
removeOnCreate

Control.addOnDoubleClick

Syntax
public void addOnDoubleClick( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnDoubleClick event notification. Duplicates are not filtered out.

See Also
removeOnDoubleClick

Control.addOnDragEnter

Syntax
public void addOnDragEnter( DragEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnDragEnter event notification. Duplicates are not filtered out.

See Also
removeOnDragEnter

Control.addOnDragLeave

Syntax
public void addOnDragLeave( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnDragLeave event notification. Duplicates are not filtered out.

See Also
removeOnDragLeave

Control.addOnDragOver

Syntax
public void addOnDragOver( DragEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnDragOver event notification. Duplicates are not filtered out.

See Also
removeOnDragOver

Control.addOnDrop

Syntax
public void addOnDrop( DragEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnDrop event notification. Duplicates are not filtered out.

See Also
removeOnDrop

Control.addOnEnter

Syntax
public void addOnEnter( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnEnter event notification. Duplicates are not filtered out.

See Also
removeOnEnter

Control.addOnGiveFeedback

Syntax
public void addOnGiveFeedback( GiveFeedbackEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnGiveFeedback event notification. Duplicates are not filtered out.

See Also
removeOnGiveFeedback

Control.addOnGotFocus

Syntax
public void addOnGotFocus( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnGotFocus event notification. Duplicates are not filtered out.

See Also
removeOnGotFocus

Control.addOnHelp

Syntax
public void addOnHelp( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnHelp event notification. Duplicates are not filtered out.

See Also
removeOnHelp

Control.addOnKeyDown

Syntax
public void addOnKeyDown( KeyEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnKeyDown event notification. Duplicates are not filtered out.

See Also
removeOnKeyDown

Control.addOnKeyPress

Syntax
public void addOnKeyPress( KeyEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnKeyPress event notification. Duplicates are not filtered out.

See Also
removeOnKeyPress

Control.addOnKeyUp

Syntax
public void addOnKeyUp( KeyEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnKeyUp event notification. Duplicates are not filtered out.

See Also
removeOnKeyUp

Control.addOnLeave

Syntax
public void addOnLeave( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnLeave event notification. Duplicates are not filtered out.

See Also
removeOnLeave

Control.addOnLostFocus

Syntax
public void addOnLostFocus( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnLostFocus event notification. Duplicates are not filtered out.

See Also
removeOnLostFocus

Control.addOnMouseDown

Syntax
public void addOnMouseDown( MouseEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseDown event notification. Duplicates are not filtered out.

See Also
removeOnMouseDown

Control.addOnMouseEnter

Syntax
public void addOnMouseEnter( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseEnter event notification. Duplicates are not filtered out.

See Also
removeOnMouseEnter

Control.addOnMouseLeave

Syntax
public void addOnMouseLeave( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseLeave event notification. Duplicates are not filtered out.

See Also
removeOnMouseLeave

Control.addOnMouseMove

Syntax
public void addOnMouseMove( MouseEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseMove event notification. Duplicates are not filtered out.

See Also
removeOnMouseMove

Control.addOnMouseUp

Syntax
public void addOnMouseUp( MouseEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseUp event notification. Duplicates are not filtered out.

See Also
removeOnMouseUp

Control.addOnMouseWheel

Syntax
public void addOnMouseWheel( MouseEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMouseWheel event notification. Duplicates are not filtered out.

See Also
removeOnMouseWheel

Control.addOnMove

Syntax
public void addOnMove( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnMove event notification. Duplicates are not filtered out.

See Also
removeOnMove

Control.addOnPaint

Syntax
public void addOnPaint( PaintEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnPaint event notification. Duplicates are not filtered out.

See Also
removeOnPaint

Control.addOnQueryContinueDrag

Syntax
public void addOnQueryContinueDrag( QueryContinueDragEventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnQueryContinueDrag event notification. Duplicates are not filtered out.

See Also
removeOnQueryContinueDrag

Control.addOnResize

Syntax
public void addOnResize( EventHandler value );
Parameters
value
New handler to install for this event.
Description

Adds an event handler for the OnResize event notification. Duplicates are not filtered out.

See Also
removeOnResize

Control.assignParent

Syntax
protected void assignParent( Control value );
Parameters
value
The new parent control.
Description

Assigns a new parent control. Sends out the appropriate property change notifications for properties that are affected by the change of parent.

Control.bringToFront

Syntax
public void bringToFront();
Description

Brings this control to the front of the z-order.

Control.canFocus

Syntax
public boolean canFocus();
Return Value

Returns whether this control can receive focus.

Description

Checks if this control can receive focus. The result is true if the control has a handle and if it and all of its parent controls are both visible and enabled.

See Also
focus, isFocused

Control.canSelect

Syntax
public boolean canSelect();
Return Value

Returns whether this control can be selected.

Description

Checks if this control can be selected. The result is true if the control is contained in a form and if all of its parent controls are both visible and enabled.

See Also
isSelected, select

Control.contains

Syntax
public boolean contains( Control ctl );
Parameters
ctl
The control to check.
Return Value

Returns whether ctl is a child of this control.

Description

Checks if a control is a child of this control.

Control.createGraphics

Syntax 1
public Graphics createGraphics();
Return Value

Returns the Graphics for this control.

Description

Creates a Graphics for this control. The control's brush, font, foreground color, and background color become the default values for the Graphics. The returned Graphics must be disposed through a call to its dispose() method when it is no longer needed.

Syntax 2
public Graphics createGraphics( int dc );
Return Value

Returns the Graphics for this control.

Description

Creates a Graphics for this control. This graphic uses the device context (DC) passed to it as its main window's DC. The control's brush, font, foreground color, and background color become the default values for the Graphics. The returned Graphics must be disposed through a call to its dispose() method when it is no longer needed.

Control.dispose

Syntax
public void dispose();
Description

Topic under construction.

Control.doDragDrop

Syntax
public final int doDragDrop( Object data, int allowedEffects );
Description

Topic under construction.

Control.focus

Syntax
public boolean focus();
Description

Topic under construction.

Control.fromChildHandle

Syntax
public static Control fromChildHandle( int handle );
Description

Topic under construction.

Control.fromHandle

Syntax
public static Control fromHandle( int handle );
Description

Topic under construction.

Control.getAcceleratorTable

Syntax
public AcceleratorTable getAcceleratorTable();
Description

Topic under construction.

Control.getAllowDrop

Syntax
public boolean getAllowDrop();
Description

Topic under construction.

Control.getAnchor

Syntax
public int getAnchor();
Description

Topic under construction.

Control.getAxContainer

Syntax
public AxHost.Container getAxContainer();
Description

Topic under construction.

Control.getBackColor

Syntax
public Color getBackColor();
Description

Topic under construction.

Control.getBottom

Syntax
public int getBottom();
Description

Topic under construction.

Control.getBounds

Syntax
public Rectangle getBounds();
Description

Topic under construction.

Control.getBrush

Syntax
public Brush getBrush();
Description

Topic under construction.

Control.getCapture

Syntax
public boolean getCapture();
Description

Topic under construction.

Control.getChildAtPoint

Syntax
public Control getChildAtPoint( Point pt );
Description

Topic under construction.

Control.getClientRect

Syntax
public Rectangle getClientRect();
Description

Topic under construction.

Control.getClientSize

Syntax
public Point getClientSize();
Description

Topic under construction.

Control.getContextMenu

Syntax
public ContextMenu getContextMenu();
Description

Topic under construction.

Control.getControl

Syntax
public Control getControl( int index );
Description

Topic under construction.

Control.getControlCount

Syntax
public int getControlCount();
Description

Topic under construction.

Control.getControlIndex

Syntax
public int getControlIndex();
Description

Topic under construction.

Control.getControls

Syntax
public Control[] getControls();
Description

Topic under construction.

Control.getCreated

Syntax
public boolean getCreated();
Description

Topic under construction.

Control.getCursor

Syntax
public Cursor getCursor();
Description

Topic under construction.

Control.getDesktop

Syntax
public static Control getDesktop();
Description

Topic under construction.

Control.getDisplayRect

Syntax
public Rectangle getDisplayRect();
Return Value

Returns the rectangle representing the client area display region.

Description

Returns the client rectangle of the display area of the control. For the base control class, this is identical to getClientRect. However, extending controls can change this if their client area differs from their display area.

Control.getDock

Syntax
public int getDock();
Description

Topic under construction.

Control.getEnabled

Syntax
public boolean getEnabled();
Description

Topic under construction.

Control.getFocused

Syntax
public boolean getFocused();
Description

Topic under construction.

Control.getFont

Syntax
public Font getFont();
Description

Topic under construction.

Control.getForeColor

Syntax
public Color getForeColor();
Description

Topic under construction.

Control.getForm

Syntax
public Form getForm();
Description

Topic under construction.

Control.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

Control.getHandleCreated

Syntax
public boolean getHandleCreated();
Description

Topic under construction.

Control.getHeight

Syntax
public int getHeight();
Description

Topic under construction.

Control.getIconic

Syntax
public boolean getIconic();
Description

Topic under construction.

Control.getLeft

Syntax
public int getLeft();
Description

Topic under construction.

Control.getLocation

Syntax
public Point getLocation();
Description

Topic under construction.

Control.getMnemonic

Syntax
public static boolean getMnemonic( char charCode, String text );
Description

Topic under construction.

Control.getModifierKeys

Syntax
public static int getModifierKeys();
Description

Topic under construction.

Control.getMouseButtons

Syntax
public static int getMouseButtons();
Description

Topic under construction.

Control.getNextControl

Syntax
public Control getNextControl( Control ctl, boolean forward );
Description

Topic under construction.

Control.getPalette

Syntax
public Palette getPalette();
Description

Topic under construction.

Control.getParent

Syntax
public Control getParent();
Description

Topic under construction.

Control.getParentHandle

Syntax
public int getParentHandle();
Description

Topic under construction.

Control.getRecreatingHandle

Syntax
public boolean getRecreatingHandle();
Description

Topic under construction.

Control.getRight

Syntax
public int getRight();
Description

Topic under construction.

Control.getSize

Syntax
public Point getSize();
Description

Topic under construction.

Control.getStyle

Syntax
public boolean getStyle( int flag );
Description

Topic under construction.

Control.getTabIndex

Syntax
public int getTabIndex();
Description

Topic under construction.

Control.getTabList

Syntax
public Control[] getTabList();
Description

Topic under construction.

Control.getTabStop

Syntax
public boolean getTabStop();
Description

Topic under construction.

Control.getText

Syntax
public String getText();
Description

Topic under construction.

Control.getTop

Syntax
public int getTop();
Description

Topic under construction.

Control.getTopLevel

Syntax
public boolean getTopLevel();
Description

Topic under construction.

Control.getVisible

Syntax
public boolean getVisible();
Description

Topic under construction.

Control.getWidth

Syntax
public int getWidth();
Description

Topic under construction.

Control.getZoomed

Syntax
public boolean getZoomed();
Description

Topic under construction.

Control.hasDefaultBackColor

Syntax
public boolean hasDefaultBackColor();
Description

Topic under construction.

Control.hasDefaultFont

Syntax
public boolean hasDefaultFont();
Description

Topic under construction.

Control.hasDefaultForeColor

Syntax
public boolean hasDefaultForeColor();
Description

Topic under construction.

Control.hide

Syntax
public final void hide();
Description

Topic under construction.

Control.invalidate

Syntax
public void invalidate();
Description

Topic under construction.

Control.invalidateRect

Syntax
public void invalidateRect( Rectangle rc );
Description

Topic under construction.

Control.isAncestor

Syntax
public boolean isAncestor( Control ancestor );
Description

Topic under construction.

Control.isDescendant

Syntax
public boolean isDescendant( Control descendant );
Description

Topic under construction.

Control.layout

Syntax 1
public final void layout();
Description

Topic under construction.

Syntax 2
public final void layout( Control dockLast );
Description

Topic under construction.

Control.onCreate

Syntax
protected void onCreate( CreateEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onCreate to send this event to any registered event listeners.

See Also
addOnCreate, removeOnCreate

Control.onDoubleClick

Syntax
protected void onDoubleClick( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onDoubleClick to send this event to any registered event listeners.

See Also
addOnDoubleClick, removeOnDoubleClick

Control.onDragEnter

Syntax
protected void onDragEnter( DragEvent event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onDragEnter to send this event to any registered event listeners.

See Also
addOnDragEnter, removeOnDragEnter

Control.onDragLeave

Syntax
protected void onDragLeave( Event event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onDragLeave to send this event to any registered event listeners.

See Also
addOnDragLeave, removeOnDragLeave

Control.onDragOver

Syntax
protected void onDragOver( DragEvent event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onDragOver to send this event to any registered event listeners.

See Also
addOnDragOver, removeOnDragOver

Control.onDrop

Syntax
protected void onDrop( DragEvent event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onDrop to send this event to any registered event listeners.

See Also
addOnDrop, removeOnDrop

Control.onEnter

Syntax
protected void onEnter( Event event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onEnter to send this event to any registered event listeners.

See Also
addOnEnter, removeOnEnter

Control.onGiveFeedback

Syntax
protected void onGiveFeedback( GiveFeedbackEvent event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onGiveFeedback to send this event to any registered event listeners.

See Also
addOnGiveFeedback, removeOnGiveFeedback

Control.onGotFocus

Syntax
protected void onGotFocus( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onGotFocus to send this event to any registered event listeners.

See Also
addOnGotFocus, removeOnGotFocus

Control.onHelp

Syntax
protected void onHelp( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onHelp to send this event to any registered event listeners.

See Also
addOnHelp, removeOnHelp

Control.onKeyDown

Syntax
protected void onKeyDown( KeyEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onKeyDown to send this event to any registered event listeners.

See Also
addOnKeyDown, removeOnKeyDown

Control.onKeyPress

Syntax
protected void onKeyPress( KeyEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onKeyPress to send this event to any registered event listeners.

See Also
addOnKeyPress, removeOnKeyPress

Control.onKeyUp

Syntax
protected void onKeyUp( KeyEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onKeyUp to send this event to any registered event listeners.

See Also
addOnKeyUp, removeOnKeyUp

Control.onLeave

Syntax
protected void onLeave( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onLeave to send this event to any registered event listeners.

See Also
addOnLeave, removeOnLeave

Control.onLostFocus

Syntax
protected void onLostFocus( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onLostFocus to send this event to any registered event listeners.

See Also
addOnLostFocus, removeOnLostFocus

Control.onMouseDown

Syntax
protected void onMouseDown( MouseEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseDown to send this event to any registered event listeners.

See Also
addOnMouseDown, removeOnMouseDown

Control.onMouseEnter

Syntax
protected void onMouseEnter( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseEnter to send this event to any registered event listeners.

See Also
addOnMouseEnter, removeOnMouseEnter

Control.onMouseLeave

Syntax
protected void onMouseLeave( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseLeave to send this event to any registered event listeners.

See Also
addOnMouseLeave, removeOnMouseLeave

Control.onMouseMove

Syntax
protected void onMouseMove( MouseEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseMove to send this event to any registered event listeners.

See Also
addOnMouseMove, removeOnMouseMove

Control.onMouseUp

Syntax
protected void onMouseUp( MouseEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseUp to send this event to any registered event listeners.

See Also
addOnMouseUp, removeOnMouseUp

Control.onMouseWheel

Syntax
protected void onMouseWheel( MouseEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMouseWheel to send this event to any registered event listeners.

See Also
addOnMouseWheel, removeOnMouseWheel

Control.onMove

Syntax
protected void onMove( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onMove to send this event to any registered event listeners.

See Also
addOnMove, removeOnMove

Control.onPaint

Syntax
protected void onPaint( PaintEvent e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onPaint to send this event to any registered event listeners.

See Also
addOnPaint, removeOnPaint

Control.onQueryContinueDrag

Syntax
protected void onQueryContinueDrag( QueryContinueDragEvent event );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onQueryContinueDrag to send this event to any registered event listeners.

See Also
addOnQueryContinueDrag, removeOnQueryContinueDrag

Control.onResize

Syntax
protected void onResize( Event e );
Parameters
e
The event.
Description

Inheriting classes should override this method to handle this event. Call super.onResize to send this event to any registered event listeners.

See Also
addOnResize, removeOnResize

Control.pointToClient

Syntax
public Point pointToClient( Point p );
Description

Topic under construction.

Control.pointToScreen

Syntax
public Point pointToScreen( Point p );
Description

Topic under construction.

Control.preProcessMessage

Syntax
public boolean preProcessMessage( MSG msg );
Description

This method is called by the application's message loop to preprocess input messages before they are dispatched. Possible values for the msg.message field are WM_KEYDOWN, WM_SYSKEYDOWN, WM_CHAR, and WM_SYSCHAR. If this method processes the message, it must return true. In this case, the message loop will not dispatch the message. For WM_KEYDOWN and WM_SYSKEYDOWN messages, preProcessMessage() first calls processCmdKey() to check for command keys such as accelerators and menu shortcuts. If processCmdKey() doesn't process the message, then isInputKey() is called to check whether the key message represents an input key for the control. Finally, if isInputKey() indicates that the control isn't interested in the key message, processDialogKey() is called to check for dialog keys such as TAB, arrow keys, and mnemonics. For WM_CHAR messages, preProcessMessage() first calls isInputChar() to check whether the character message represents an input character for the control. If isInputChar() indicates that the control isn't interested in the character message, processDialogChar() is called to check for dialog characters such as mnemonics. For WM_SYSCHAR messages, preProcessMessage() calls processDialogChar() to check for dialog characters such as mnemonics. When overriding preProcessMessage(), a control should return true to indicate that it has processed the message. For messages that aren't processed by the control, the result of super.preProcessMessage() should be returned. Controls will typically override one of the more specialized methods (isInputChar(), isInputKey(), processCmdKey(), processDialogChar(), or processDialogKey()) instead of overriding preProcessMessage().

Control.processCmdKey

Syntax
protected boolean processCmdKey( MSG msg, int keyData );
Description

Processes a command key. Command keys are keys that take precedence over regular input keys. Examples of command keys are accelerators and menu shortcuts. The method must return true to indicate that it has processed the command key or return false to indicate that the key is not a command key. The processCmdKey() method first checks if the control has a context menu. If it does, it calls the menu's processCmdKey() to check for menu shortcuts. Next, the control's accelerator table (if present) is given a chance to process the key. Finally, if the control has a parent, the key is passed to the parent's processCmdKey() method. The net effect is that command keys are bubbled up the control hierarchy. When overriding processCmdKey(), a control should return true to indicate that it has processed the key. For keys that aren't processed by the control, the return of super.processCmdKey() should be returned.

Control.rectToClient

Syntax
public Rectangle rectToClient( Rectangle r );
Description

Topic under construction.

Control.rectToScreen

Syntax
public Rectangle rectToScreen( Rectangle r );
Description

Topic under construction.

Control.remove

Syntax
public void remove( Control control );
Description

Topic under construction.

Control.removeOnChange

Syntax
public void removeOnChange( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnChange event. If there are duplicate entries, all are removed.

See Also
addOnChange

Control.removeOnClick

Syntax
public void removeOnClick( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnClick event. If there are duplicate entries, all are removed.

See Also
addOnClick

Control.removeOnCreate

Syntax
public void removeOnCreate( CreateEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnCreate event. If there are duplicate entries, all are removed.

See Also
addOnCreate

Control.removeOnDoubleClick

Syntax
public void removeOnDoubleClick( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDoubleClick event. If there are duplicate entries, all are removed.

See Also
addOnDoubleClick

Control.removeOnDragEnter

Syntax
public void removeOnDragEnter( DragEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDragEnter event. If there are duplicate entries, all are removed.

See Also
addOnDragEnter

Control.removeOnDragLeave

Syntax
public void removeOnDragLeave( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDragLeave event. If there are duplicate entries, all are removed.

See Also
addOnDragLeave

Control.removeOnDragOver

Syntax
public void removeOnDragOver( DragEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDragOver event. If there are duplicate entries, all are removed.

See Also
addOnDragOver

Control.removeOnDrop

Syntax
public void removeOnDrop( DragEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDragEvent event. If there are duplicate entries, all are removed.

See Also
addOnDrop

Control.removeOnEnter

Syntax
public void removeOnEnter( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnEnter event. If there are duplicate entries, all are removed.

See Also
addOnEnter

Control.removeOnGiveFeedback

Syntax
public void removeOnGiveFeedback( GiveFeedbackEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnGiveFeedback event. If there are duplicate entries, all are removed.

See Also
addOnGiveFeedback

Control.removeOnGotFocus

Syntax
public void removeOnGotFocus( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnGotFocus event. If there are duplicate entries, all are removed.

See Also
addOnGotFocus

Control.removeOnHelp

Syntax
public void removeOnHelp( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnHelp event. If there are duplicate entries, all are removed.

See Also
addOnHelp

Control.removeOnKeyDown

Syntax
public void removeOnKeyDown( KeyEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnKeyDown event. If there are duplicate entries, all are removed.

See Also
addOnKeyDown

Control.removeOnKeyPress

Syntax
public void removeOnKeyPress( KeyEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnKeyPress event. If there are duplicate entries, all are removed.

See Also
addOnKeyPress

Control.removeOnKeyUp

Syntax
public void removeOnKeyUp( KeyEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnKeyUp event. If there are duplicate entries, all are removed.

See Also
addOnKeyUp

Control.removeOnLeave

Syntax
public void removeOnLeave( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnLeave event. If there are duplicate entries, all are removed.

See Also
addOnLeave

Control.removeOnLostFocus

Syntax
public void removeOnLostFocus( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnLostFocus event. If there are duplicate entries, all are removed.

See Also
addOnLostFocus

Control.removeOnMouseDown

Syntax
public void removeOnMouseDown( MouseEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseDown event. If there are duplicate entries, all are removed.

See Also
addOnMouseDown

Control.removeOnMouseEnter

Syntax
public void removeOnMouseEnter( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseEnter event. If there are duplicate entries, all are removed.

See Also
addOnMouseEnter

Control.removeOnMouseLeave

Syntax
public void removeOnMouseLeave( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseLeave event. If there are duplicate entries, all are removed.

See Also
addOnMouseLeave

Control.removeOnMouseMove

Syntax
public void removeOnMouseMove( MouseEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseMove event. If there are duplicate entries, all are removed.

See Also
addOnMouseMove

Control.removeOnMouseUp

Syntax
public void removeOnMouseUp( MouseEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseUp event. If there are duplicate entries, all are removed.

See Also
addOnMouseUp

Control.removeOnMouseWheel

Syntax
public void removeOnMouseWheel( MouseEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMouseWheel event. If there are duplicate entries, all are removed.

See Also
addOnMouseWheel

Control.removeOnMove

Syntax
public void removeOnMove( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMove event. If there are duplicate entries, all are removed.

See Also
addOnMove

Control.removeOnPaint

Syntax
public void removeOnPaint( PaintEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnPaint event. If there are duplicate entries, all are removed.

See Also
addOnPaint

Control.removeOnQueryContinueDrag

Syntax
public void removeOnQueryContinueDrag( QueryContinueDragEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnQueryContinueDrag event. If there are duplicate entries, all are removed.

See Also
addOnQueryContinueDrag

Control.removeOnResize

Syntax
public void removeOnResize( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnResize event. If there are duplicate entries, all are removed.

See Also
addOnResize

Control.resumeLayout

Syntax
public void resumeLayout();
Description

Topic under construction.

Control.scale

Syntax 1
public final void scale( float ratio );
Description

Topic under construction.

Syntax 2
public final void scale( float dx, float dy );
Description

Topic under construction.

Control.select

Syntax 1
public void select();
Description

Topic under construction.

Syntax 2
public void select( boolean directed, boolean forward );
Description

Topic under construction.

Control.sendToBack

Syntax
public void sendToBack();
Description

sends this control to the back of the z-order

Control.setAcceleratorTable

Syntax
public void setAcceleratorTable( AcceleratorTable accel );
Description

Topic under construction.

Control.setAllowDrop

Syntax
public void setAllowDrop( boolean allowDrop );
Description

Topic under construction.

Control.setAnchor

Syntax
public void setAnchor( int value );
Description

Topic under construction.

Control.setBackColor

Syntax
public void setBackColor( Color value );
Description

Topic under construction.

Control.setBounds

Syntax 1
public final void setBounds( Rectangle value );
Description

Topic under construction.

Syntax 2
public final void setBounds( int x, int y, int width, int height );
Description

Topic under construction.

Control.setBoundsBatch

Syntax
public void setBoundsBatch( ControlRect[] items );
Description

Topic under construction.

Control.setBrush

Syntax
public void setBrush( Brush br );
Description

Topic under construction.

Control.setCapture

Syntax
public void setCapture( boolean value );
Description

Topic under construction.

Control.setClientSize

Syntax
public void setClientSize( Point size );
Description

Topic under construction.

Control.setContextMenu

Syntax
public void setContextMenu( ContextMenu contextMenu );
Description

Topic under construction.

Control.setControlIndex

Syntax
public void setControlIndex( int value );
Description

Topic under construction.

Control.setControls

Syntax
public void setControls( Control[] value );
Description

Topic under construction.

Control.setCursor

Syntax
public void setCursor( Cursor value );
Description

Topic under construction.

Control.setDock

Syntax
public void setDock( int value );
Description

Topic under construction.

Control.setEnabled

Syntax
public void setEnabled( boolean enabled );
Description

Topic under construction.

Control.setFont

Syntax
public void setFont( Font value );
Description

Topic under construction.

Control.setForeColor

Syntax
public void setForeColor( Color value );
Description

Topic under construction.

Control.setHeight

Syntax
public void setHeight( int value );
Description

Topic under construction.

Control.setLocation

Syntax 1
public void setLocation( int x, int y );
Description

Topic under construction.

Syntax 2
public void setLocation( Point value );
Description

Topic under construction.

Control.setNewControls

Syntax
public void setNewControls( Control[] value );
Description

Topic under construction.

Control.setParent

Syntax
public void setParent( Control value );
Description

Topic under construction.

Control.setParentHandle

Syntax
public void setParentHandle( int value );
Description

Topic under construction.

Control.setPositionInfo

Syntax
public void setPositionInfo( PositionInfo info );
Description

Note Use setBounds(), setDock(), and setAnchor() instead

Control.setSite

Syntax
public void setSite( ISite value );
Description

Topic under construction.

Control.setSize

Syntax 1
public void setSize( int width, int height );
Description

Topic under construction.

Syntax 2
public void setSize( Point value );
Description

Topic under construction.

Control.setStyle

Syntax
public void setStyle( int flag, boolean value );
Description

Topic under construction.

Control.setTabIndex

Syntax
public void setTabIndex( int value );
Parameters
index
The index to set the control to.
Description

Sets the index of this control. The index must be between 0 and parent.getControlCount() - 1. A tab index determines the tabbing order of child controls.

Control.setTabStop

Syntax
public void setTabStop( boolean value );
Description

Topic under construction.

Control.setText

Syntax
public void setText( String value );
Description

Topic under construction.

Control.setTopLevel

Syntax
public void setTopLevel( boolean value );
Description

Topic under construction.

Control.setVisible

Syntax
public void setVisible( boolean value );
Description

Topic under construction.

Control.setWidth

Syntax
public void setWidth( int value );
Description

Topic under construction.

Control.show

Syntax
public final void show();
Description

Topic under construction.

Control.suspendLayout

Syntax
public void suspendLayout();
Description

Topic under construction.

Control.update

Syntax
public void update();
Description

Topic under construction.

Control.updateStyles

Syntax
public void updateStyles();
Description

Topic under construction.


 ControlDock Class

ControlDock Class

This Package | All Packages

Enum
  |
  +--ControlDock
public class ControlDock
extends Enum

Control Dock values. When a control is docked to an edge of its container, it is always positioned flush against that edge while the container resizes. If more than one control is docked to an edge, the controls are not placed on top of each other.

Fields
Name | Description
BOTTOM | Topic under construction.
FILL | Topic under construction.
LEFT | Topic under construction.
NONE | Topic under construction.
RIGHT | Topic under construction.
TOP | Topic under construction.

Methods
Name | Description
ensureValid(int dock) | Topic under construction.
valid(int dock) | Topic under construction.

Fields

ControlDock.BOTTOM

Syntax
public static final int BOTTOM;
Description
Topic under construction.

ControlDock.FILL

Syntax
public static final int FILL;
Description
Topic under construction.

ControlDock.LEFT

Syntax
public static final int LEFT;
Description
Topic under construction.

ControlDock.NONE

Syntax
public static final int NONE;
Description
Topic under construction.

ControlDock.RIGHT

Syntax
public static final int RIGHT;
Description
Topic under construction.

ControlDock.TOP

Syntax
public static final int TOP;
Description
Topic under construction.

Methods

ControlDock.ensureValid

Syntax
public static void ensureValid( int dock );
Description

Topic under construction.

ControlDock.valid

Syntax
public static boolean valid( int dock );
Description

Topic under construction.


 CreateEvent Class

CreateEvent Class

This Package | All Packages

Event
  |
  +--CreateEvent
public class CreateEvent
extends Event

Topic under construction.

Fields
Name | Description
hWnd | Topic under construction.

Constructors
Name | Description
CreateEvent(int hWnd) | Topic under construction.

Fields

CreateEvent.hWnd

Syntax
public final int hWnd;
Description
Topic under construction.

Constructors

CreateEvent.CreateEvent

Syntax
public CreateEvent( int hWnd );
Description

Topic under construction.


 Cursor Class

Cursor Class

This Package | All Packages

Image
  |
  +--Cursor
public final class Cursor
extends Image

Implements a Windows cursor as a WFC object.

Fields
Name | Description
APPSTARTING | Topic under construction.
ARROW | Topic under construction.
CROSS | Topic under construction.
DEFAULT | Topic under construction.
HELP | Topic under construction.
HSPLIT | Topic under construction.
IBEAM | Topic under construction.
NO | Topic under construction.
SIZEALL | Topic under construction.
SIZENESW | Topic under construction.
SIZENS | Topic under construction.
SIZENWSE | Topic under construction.
SIZEWE | Topic under construction.
UPARROW | Topic under construction.
VSPLIT | Topic under construction.
WAIT | Topic under construction.

Constructors
Name | Description
Cursor(int handle) | Topic under construction.
Cursor(int handle, boolean fOwned) | Topic under construction.
Cursor(String fileName) | Topic under construction.
Cursor(Class type, String resource) | Topic under construction.
Cursor(IDataStream stream) | Topic under construction.
Cursor(IStream stream) | Topic under construction.
Cursor(IPicture picture) | Topic under construction.

Methods
Name | Description
copyHandle(int h) | Retrieves a copy of the cursor.
copyHandle() | Retrieves a copy of the cursor.
drawStretchTo(Graphics g, int x, int y, int width, int height, int rop) | Draws this image to the given DC and stretches it to the given width and height.
drawTo(Graphics g, int x, int y, int width, int height, int rop) | Draws this image to the given device context (DC).
finalize() | Topic under construction.
getClipRect() | Returns the current cursor clipping rectangle in screen coordinates.
getExtension() | Topic under construction.
getHandle() | Topic under construction.
getPICTDESC() | Topic under construction.
getPosition() | Returns the current cursor position in screen coordinates.
getSize() | Topic under construction.
hide() | Hides the cursor.
setClipRect(Rectangle r) | Sets the cursor clipping rectangle.
setCurrent() | sets the current system cursor to be this cursor
setPosition(Point p) | Moves the cursor to the specified screen coordinates.
show() | Displays the cursor.
toString() | Topic under construction.

Fields

Cursor.APPSTARTING

Syntax
public static final Cursor APPSTARTING;
Description
Topic under construction.

Cursor.ARROW

Syntax
public static final Cursor ARROW;
Description
Topic under construction.

Cursor.CROSS

Syntax
public static final Cursor CROSS;
Description
Topic under construction.

Cursor.DEFAULT

Syntax
public static final Cursor DEFAULT;
Description
Topic under construction.

Cursor.HELP

Syntax
public static final Cursor HELP;
Description
Topic under construction.

Cursor.HSPLIT

Syntax
public static final Cursor HSPLIT;
Description
Topic under construction.

Cursor.IBEAM

Syntax
public static final Cursor IBEAM;
Description
Topic under construction.

Cursor.NO

Syntax
public static final Cursor NO;
Description
Topic under construction.

Cursor.SIZEALL

Syntax
public static final Cursor SIZEALL;
Description
Topic under construction.

Cursor.SIZENESW

Syntax
public static final Cursor SIZENESW;
Description
Topic under construction.

Cursor.SIZENS

Syntax
public static final Cursor SIZENS;
Description
Topic under construction.

Cursor.SIZENWSE

Syntax
public static final Cursor SIZENWSE;
Description
Topic under construction.

Cursor.SIZEWE

Syntax
public static final Cursor SIZEWE;
Description
Topic under construction.

Cursor.UPARROW

Syntax
public static final Cursor UPARROW;
Description
Topic under construction.

Cursor.VSPLIT

Syntax
public static final Cursor VSPLIT;
Description
Topic under construction.

Cursor.WAIT

Syntax
public static final Cursor WAIT;
Description
Topic under construction.

Constructors

Cursor.Cursor

Syntax 1
public Cursor( int handle );
Description

Topic under construction.

Syntax 2
public Cursor( int handle, boolean fOwned );
Description

Topic under construction.

Syntax 3
public Cursor( String fileName );
Description

Topic under construction.

Syntax 4
public Cursor( Class type, String resource );
Description

Topic under construction.

Syntax 5
public Cursor( IDataStream stream );
Description

Topic under construction.

Syntax 6
public Cursor( IStream stream );
Description

Topic under construction.

Syntax 7
public Cursor( IPicture picture );
Description

Topic under construction.

Methods

Cursor.copyHandle

Syntax 1
public static int copyHandle( int h );
Parameters
h
The handle to the cursor.
Description

Retrieves a copy of the cursor.

Syntax 2
public static int copyHandle();
Description

Retrieves a copy of the cursor.

Cursor.drawStretchTo

Syntax
public void drawStretchTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
dc
The HDC to draw to (supplied by Graphics).
x
The x cooridnate to start drawing.
width
The width to stretch to.
height
The height to stretch to.
rop
The ROP code.
Description

Draws this image to the given DC and stretches it to the given width and height. This is used by Graphics to draw any type of image.

Cursor.drawTo

Syntax
public void drawTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
dc
The HDC to draw to (supplied by Graphics).
x
The x coordinate to start drawing.
y
The y coordinate to start drawing.
width
The width to draw to.
height
The height to draw to.
rop
The ROP code.
Description

Draws this image to the given device context (DC). This is used by Graphics to draw any type of image.

Cursor.finalize

Syntax
public void finalize();
Description

Topic under construction.

Cursor.getClipRect

Syntax
public static Rectangle getClipRect();
Description

Returns the current cursor clipping rectangle in screen coordinates. If the cursor is not currently clipped, the resulting rectangle contains the dimensions of the entire screen.

Cursor.getExtension

Syntax
public String getExtension();
Description

Topic under construction.

Cursor.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

Cursor.getPICTDESC

Syntax
public PICTDESC getPICTDESC();
Description

Topic under construction.

Cursor.getPosition

Syntax
public static Point getPosition();
Description

Returns the current cursor position in screen coordinates.

Cursor.getSize

Syntax
public Point getSize();
Description

Topic under construction.

Cursor.hide

Syntax
public static void hide();
Description

Hides the cursor. For every call to Cursor.hide(), there must be a balancing call to Cursor.show().

Cursor.setClipRect

Syntax
public static void setClipRect( Rectangle r );
Parameters
r
The clipping rectangle. If this parameter is null, the cursor is free to move anywhere on the screen.
Description

Sets the cursor clipping rectangle. The cursor is confined to the given rectangular area on the screen. If a subsequent cursor position (set by the setClipRect() method or the mouse) lies outside the rectangle, Windows automatically adjusts the position to keep the cursor inside the rectangular area.

Cursor.setCurrent

Syntax
public void setCurrent();
Description

sets the current system cursor to be this cursor

Cursor.setPosition

Syntax
public static void setPosition( Point p );
Description

Moves the cursor to the specified screen coordinates. If the new coordinates are not within the screen rectangle set by the most recent setClipRect() call, Windows automatically adjusts the coordinates so that the cursor stays within the rectangle.

Cursor.show

Syntax
public static void show();
Description

Displays the cursor. For every call to Cursor.hide(), there must be a balancing call to Cursor.show().

Cursor.toString

Syntax
public String toString();
Description

Topic under construction.


 DateTimeChangeEvent Class

DateTimeChangeEvent Class

This Package | All Packages

Event
  |
  +--DateTimeChangeEvent
public class DateTimeChangeEvent
extends Event

The DateTimeChangeEvent is fired when the time changes in the DateTimePicker.

Fields
Name | Description
time | The new time in the DateTimePicker.

Constructors
Name | Description
DateTimeChangeEvent(long time) | Topic under construction.

Fields

DateTimeChangeEvent.time

Syntax
public final long time;
Description
The new time in the DateTimePicker.

Constructors

DateTimeChangeEvent.DateTimeChangeEvent

Syntax
public DateTimeChangeEvent( long time );
Description

Topic under construction.


 DateTimeFormatEvent Class

DateTimeFormatEvent Class

This Package | All Packages

Event
  |
  +--DateTimeFormatEvent
public class DateTimeFormatEvent
extends Event

The DateTimeFormatEvent is fired when the DateTimePicker is formatting time to display to the user.

Fields
Name | Description
display | This value can be set to change what string is displayed to the user.
format | Format string associated with the DateTimePicker.
time | Time to display.

Constructors
Name | Description
DateTimeFormatEvent(String format, long time, String display) | Topic under construction.

Fields

DateTimeFormatEvent.display

Syntax
public String display;
Description
This value can be set to change what string is displayed to the user.

DateTimeFormatEvent.format

Syntax
public final String format;
Description
Format string associated with the DateTimePicker.

DateTimeFormatEvent.time

Syntax
public final long time;
Description
Time to display.

Constructors

DateTimeFormatEvent.DateTimeFormatEvent

Syntax
public DateTimeFormatEvent( String format, long time, String display );
Description

Topic under construction.


 DateTimeFormatQueryEvent Class

DateTimeFormatQueryEvent Class

This Package | All Packages

Event
  |
  +--DateTimeFormatQueryEvent
public class DateTimeFormatQueryEvent
extends Event

The DateTimeFormatQueryEvent is fired when the DateTimePicker needs to determine the maximum size of text to be displayed.

Fields
Name | Description
format | Format string associated with the DateTimePicker.
maxSize | Maximum dimensions needed to display the time given the specified format.

Constructors
Name | Description
DateTimeFormatQueryEvent(String format, Point maxSize) | Topic under construction.

Fields

DateTimeFormatQueryEvent.format

Syntax
public final String format;
Description
Format string associated with the DateTimePicker.

DateTimeFormatQueryEvent.maxSize

Syntax
public Point maxSize;
Description
Maximum dimensions needed to display the time given the specified format.

Constructors

DateTimeFormatQueryEvent.DateTimeFormatQueryEvent

Syntax
public DateTimeFormatQueryEvent( String format, Point maxSize );
Description

Topic under construction.


 DateTimePicker Class

DateTimePicker Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--DateTimePicker
public class DateTimePicker
extends Control

Implements a date and time picker control.

Constructors
Name | Description
DateTimePicker() | Creates a DateTimePicker.

Methods
Name | Description
addOnCloseUp(EventHandler value) | Adds a new listener to the CloseUp event.
addOnDropDown(EventHandler value) | Adds a new listener to the DropDown event.
addOnFormat(DateTimeFormatEventHandler value) | Adds a new listener to the Format event.
addOnFormatQuery( DateTimeFormatQueryEventHandler value) | Adds a new listener to the FormatQuery event.
addOnUserString(DateTimeUserStringEventHandler value) | Adds a new listener to the UserString event.
addOnValueChange(DateTimeChangeEventHandler value) | Adds a new listener to the DateTimeChange event.
addOnWmKeyDown(DateTimeWmKeyDownEventHandler value) | Adds a new listener to the WmKeyDown event.
createHandle() | Creates the physical window handle.
destroyHandle() | Destroys the physical window handle.
getAppCanParse() | Returns the current value of the AppCanParse property.
getCalendarBackColor() | Returns the current value of the CalendarBackColor property.
getCalendarFont() | Returns the current value of the CalendarFont property.
getCalendarForeColor() | Returns the current value of the CalendarForeColor property.
getCalendarMonthBackground() | Returns the current value of the CalendarMonthBackground property.
getCalendarTitleBackColor() | Returns the current value of the CalendarTitleBackColor property.
getCalendarTitleForeColor() | Returns the current value of the CalendarTitleForeColor property.
getCalendarTrailingForeColor() | Returns the current value of the CalendarTrailingForeColor property.
getCreateParams() | Returns the CreateParams used to create this window.
getCustomFormat() | Returns the custom format.
getFormat() | Returns the current value of the format property.
getMaxDate() | Returns the maximum date selectable in the control.
getMinDate() | Returns the minimum date selectable in the control.
getRightAlign() | Returns the current value of the RightAlign property.
getShowNone() | Returns the current value of the ShowNone property.
getUpDown() | Returns the current value of the UpDown property.
getValue() | Return the current value displayed in the control.
hasDefaultText() | Determines if the control contains the default text.
onCloseUp(Event event) | Occurs when the drop-down calendar is dismissed and disappears.
onDropDown(Event event) | Occurs when the drop-down calendar is shown.
onFormat(DateTimeFormatEvent event) | Occurs when the DateTimePicker needs to convert the time value to a string format.
onFormatQuery(DateTimeFormatQueryEvent event) | Occurs when the DateTimePicker needs to determine the dimensions of the string that would be displayed for a given value.
onUserString(DateTimeUserStringEvent event) | Occurs when the user has finished entering a string in the control.
onValueChange(DateTimeChangeEvent event) | Occurs when the value for the control changes.
onWmKeyDown(DateTimeWmKeyDownEvent event) | Occurs when the user presses a key in a custom format field.
removeOnCloseUp(EventHandler value) | Removes a listener of the CloseUp event.
removeOnDropDown(EventHandler value) | Removes a listener of the DropDown event.
removeOnFormat(DateTimeFormatEventHandler value) | Removes a listener of the Format event.
removeOnFormatQuery( DateTimeFormatQueryEventHandler value) | Removes a listener of the FormatQuery event.
removeOnUserString( DateTimeUserStringEventHandler value) | Removes a listener of the UserString event.
removeOnValueChange(DateTimeChangeEventHandler value) | Removes a listener of the ValueChange event.
removeOnWmKeyDown( DateTimeWmKeyDownEventHandler value) | Removes a listener of the WmKeyDown event.
setAppCanParse(boolean b) | Sets the AppCanParse property.
setCalendarBackColor(Color value) | Sets the CalendarBackColor property.
setCalendarFont(Font font) | Sets the CalendarFont.
setCalendarForeColor(Color value) | Sets the CalendarForeColor property.
setCalendarMonthBackground(Color value) | Sets the CalendarMonthBackground.
setCalendarTitleBackColor(Color value) | Sets the CalendarTitleBackColor property.
setCalendarTitleForeColor(Color value) | Sets the CalendarTitleForeColor property.
setCalendarTrailingForeColor(Color value) | Sets the CalendarTrailingForeColor.
setCustomFormat(String sz) | Sets the custom format used when the format mode for the control is CUSTOM.
setFormat(int format) | Sets the format mode for the control.
setMaxDate(long date) | Sets the Maximum displayable date for the control.
setMinDate(long date) | Sets the Minimum displayable date for the control.
setRightAlign(boolean b) | Sets the RightAlign property.
setShowNone(boolean b) | Sets the ShowNone property.
setUpDown(boolean b) | Sets the UpDown property.
setValue(long time) | Sets the value displayed in the control.

Constructors

DateTimePicker.DateTimePicker

Syntax
public DateTimePicker();
Description

Creates a DateTimePicker.

Methods

DateTimePicker.addOnCloseUp

Syntax
public void addOnCloseUp( EventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the CloseUp event.

DateTimePicker.addOnDropDown

Syntax
public void addOnDropDown( EventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the DropDown event.

DateTimePicker.addOnFormat

Syntax
public void addOnFormat( DateTimeFormatEventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the Format event.

DateTimePicker.addOnFormatQuery

Syntax
public void addOnFormatQuery( DateTimeFormatQueryEventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the FormatQuery event.

DateTimePicker.addOnUserString

Syntax
public void addOnUserString( DateTimeUserStringEventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the UserString event.

DateTimePicker.addOnValueChange

Syntax
public void addOnValueChange( DateTimeChangeEventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the DateTimeChange event.

DateTimePicker.addOnWmKeyDown

Syntax
public void addOnWmKeyDown( DateTimeWmKeyDownEventHandler value );
Parameters
value
Delegate to call when event is fired.
Description

Adds a new listener to the WmKeyDown event.

DateTimePicker.createHandle

Syntax
protected void createHandle();
Description

Creates the physical window handle.

Overrides

createHandle() in Control.

See Also
Control.createHandle

DateTimePicker.destroyHandle

Syntax
protected void destroyHandle();
Description

Destroys the physical window handle.

Overrides

destroyHandle() in Control.

See Also
Control.destroyHandle

DateTimePicker.getAppCanParse

Syntax
public boolean getAppCanParse();
Return Value

Returns the current AppCanParse value.

Description

Returns the current value of the AppCanParse property.

See Also
setAppCanParse

DateTimePicker.getCalendarBackColor

Syntax
public Color getCalendarBackColor();
Return Value

Returns the Current CalendarBackColor.

Description

Returns the current value of the CalendarBackColor property.

See Also
setCalendarBackColor

DateTimePicker.getCalendarFont

Syntax
public Font getCalendarFont();
Return Value

Returns the current CalendarFont.

Description

Returns the current value of the CalendarFont property.

See Also
setCalendarFont

DateTimePicker.getCalendarForeColor

Syntax
public Color getCalendarForeColor();
Return Value

Returns the current CalendarForeColor.

Description

Returns the current value of the CalendarForeColor property.

See Also
setCalendarForeColor

DateTimePicker.getCalendarMonthBackground

Syntax
public Color getCalendarMonthBackground();
Return Value

Returns the current CalendarMonthBackground.

Description

Returns the current value of the CalendarMonthBackground property.

See Also
setCalendarMonthBackground

DateTimePicker.getCalendarTitleBackColor

Syntax
public Color getCalendarTitleBackColor();
Return Value

Returns the current CalendarTitleBackColor.

Description

Returns the current value of the CalendarTitleBackColor property.

See Also
setCalendarTitleBackColor

DateTimePicker.getCalendarTitleForeColor

Syntax
public Color getCalendarTitleForeColor();
Return Value

Returns the current CalendarTitleForeColor.

Description

Returns the current value of the CalendarTitleForeColor property.

See Also
setCalendarTitleForeColor

DateTimePicker.getCalendarTrailingForeColor

Syntax
public Color getCalendarTrailingForeColor();
Return Value

Returns the current CalendarTrailingForeColor.

Description

Returns the current value of the CalendarTrailingForeColor property.

See Also
setCalendarTrailingForeColor

DateTimePicker.getCreateParams

Syntax
protected CreateParams getCreateParams();
Return Value

Returns the CreateParams.

Description

Returns the CreateParams used to create this window.

Overrides

getCreateParams() in Control.

DateTimePicker.getCustomFormat

Syntax
public String getCustomFormat();
Return Value

Returns the custom format string.

Description

Returns the custom format.

See Also
setCustomFormat, setFormat

DateTimePicker.getFormat

Syntax
public int getFormat();
Description

Returns the current value of the format property. This determines the style of format the date is displayed in.

See Also
DataTimePicker.Formats

DateTimePicker.getMaxDate

Syntax
public long getMaxDate();
Return Value

Returns the maximum allowed date.

Description

Returns the maximum date selectable in the control. A -1 is returned if there is no maximum value.

See Also
setMaxDate, setMinDate

DateTimePicker.getMinDate

Syntax
public long getMinDate();
Return Value

Returns the minimum allowed date.

Description

Returns the minimum date selectable in the control. A -1 is returned if there is no minimum value.

See Also
setMinDate, setMaxDate

DateTimePicker.getRightAlign

Syntax
public boolean getRightAlign();
Return Value

Returns the current value of the RightAlign property.

Description

Returns the current value of the RightAlign property.

See Also
setRightAlign

DateTimePicker.getShowNone

Syntax
public boolean getShowNone();
Return Value

Returns the current value of the ShowNone property.

Description

Returns the current value of the ShowNone property.

See Also
setShowNone

DateTimePicker.getUpDown

Syntax
public boolean getUpDown();
Return Value

Returns the current value of the UpDown property.

Description

Returns the current value of the UpDown property.

See Also
setUpDown

DateTimePicker.getValue

Syntax
public long getValue();
Return Value

Returns the current value.

Description

Return the current value displayed in the control. A -1 is returned if there is no value selected.

See Also
setValue

DateTimePicker.hasDefaultText

Syntax
public boolean hasDefaultText();
Description

Determines if the control contains the default text.

DateTimePicker.onCloseUp

Syntax
protected void onCloseUp( Event event );
Parameters
event
The event data.
Description

Occurs when the drop-down calendar is dismissed and disappears.

See Also
addOnCloseUp, removeOnCloseUp, ms.com.wfc.core.Event

DateTimePicker.onDropDown

Syntax
protected void onDropDown( Event event );
Parameters
event
The event data.
Description

Occurs when the drop-down calendar is shown.

See Also
addOnDropDown, removeOnDropDown, cor.Event

DateTimePicker.onFormat

Syntax
protected void onFormat( DateTimeFormatEvent event );
Parameters
event
The event data.
Description

Occurs when the DateTimePicker needs to convert the time value to a string format.

See Also
addOnFormat, removeOnFormat, cor.comctl.DateTimeFormatEvent

DateTimePicker.onFormatQuery

Syntax
protected void onFormatQuery( DateTimeFormatQueryEvent event );
Parameters
event
The event data.
Description

Occurs when the DateTimePicker needs to determine the dimensions of the string that would be displayed for a given value.

See Also
addOnFormatQuery, removeOnFormatQuery, cor.comctl.DateTimeFormatQueryEvent

DateTimePicker.onUserString

Syntax
protected void onUserString( DateTimeUserStringEvent event );
Parameters
event
The event data.
Description

Occurs when the user has finished entering a string in the control. This event will be fired only if AppCanParse is set to true.

See Also
addOnUserString, removeOnUserString, setAppCanParse, cor.comctl.DateTimeUserStringEvent

DateTimePicker.onValueChange

Syntax
protected void onValueChange( DateTimeChangeEvent event );
Parameters
event
The event data.
Description

Occurs when the value for the control changes.

See Also
addOnValueChange, removeOnValueChange, cor.comctl.DateTimeChangeEvent

DateTimePicker.onWmKeyDown

Syntax
protected void onWmKeyDown( DateTimeWmKeyDownEvent event );
Parameters
event
The event data.
Description

Occurs when the user presses a key in a custom format field.

See Also
addOnWmKeyDown, removeOnWmKeyDown, cor.comctl.DateTimeWmKeyDownEvent

DateTimePicker.removeOnCloseUp

Syntax
public void removeOnCloseUp( EventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the CloseUp event.

DateTimePicker.removeOnDropDown

Syntax
public void removeOnDropDown( EventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the DropDown event.

DateTimePicker.removeOnFormat

Syntax
public void removeOnFormat( DateTimeFormatEventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the Format event.

DateTimePicker.removeOnFormatQuery

Syntax
public void removeOnFormatQuery( DateTimeFormatQueryEventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the FormatQuery event.

DateTimePicker.removeOnUserString

Syntax
public void removeOnUserString( DateTimeUserStringEventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the UserString event.

DateTimePicker.removeOnValueChange

Syntax
public void removeOnValueChange( DateTimeChangeEventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the ValueChange event.

DateTimePicker.removeOnWmKeyDown

Syntax
public void removeOnWmKeyDown( DateTimeWmKeyDownEventHandler value );
Parameters
value
Delegate not to fire on when the event is fired.
Description

Removes a listener of the WmKeyDown event.

DateTimePicker.setAppCanParse

Syntax
public void setAppCanParse( boolean b );
Parameters
b
The new value.
Description

Sets the AppCanParse property. When set to true, the user can edit the value in the control by pressing F2. When the user has finished editing, the UserString event occurs, and the control user can interpret the userstring.

See Also
getAppCanParse, OnUserString

DateTimePicker.setCalendarBackColor

Syntax
public void setCalendarBackColor( Color value );
Parameters
value
Color to set the CalendarBackColor to.
Description

Sets the CalendarBackColor property. This color is displayed between the months on the calendar.

See Also
getCalendarBackColor

DateTimePicker.setCalendarFont

Syntax
public void setCalendarFont( Font font );
Parameters
font
Font to set the CalendarFont to.
Description

Sets the CalendarFont. The calendar font is used to display text on the pop-up calendar.

See Also
getCalendarFont

DateTimePicker.setCalendarForeColor

Syntax
public void setCalendarForeColor( Color value );
Parameters
value
Color to set the CalendarForeColor to.
Description

Sets the CalendarForeColor property. This color is used to display text within the month.

See Also
getCalendarForeColor

DateTimePicker.setCalendarMonthBackground

Syntax
public void setCalendarMonthBackground( Color value );
Parameters
value
Color to set the CalendarMonthBackground to.
Description

Sets the CalendarMonthBackground. This color is used to display the background within the month.

See Also
getCalendarMonthBackground

DateTimePicker.setCalendarTitleBackColor

Syntax
public void setCalendarTitleBackColor( Color value );
Parameters
value
Color to set the CalendarTitleBackColor to.
Description

Sets the CalendarTitleBackColor property. This color is used as the background for the calendar's title.

See Also
getCalendarTitleBackColor

DateTimePicker.setCalendarTitleForeColor

Syntax
public void setCalendarTitleForeColor( Color value );
Parameters
value
Color to set the CalendarTitleForeColor to.
Description

Sets the CalendarTitleForeColor property. This color is used to display the text in the calendar's title.

See Also
getCalendarTitleForeColor

DateTimePicker.setCalendarTrailingForeColor

Syntax
public void setCalendarTrailingForeColor( Color value );
Parameters
value
Color to set the CalendarTrailingForeColor to.
Description

Sets the CalendarTrailingForeColor. This color is used to display the text for the header and trailing day text. Header and trailing days are the days from the previous and following months that appear on the current month's calendar.

See Also
getCalendarTrailingForeColor

DateTimePicker.setCustomFormat

Syntax
public void setCustomFormat( String sz );
Parameters
sz
The custom format string.
Description

Sets the custom format used when the format mode for the control is CUSTOM.

See Also
getCustomFormat, setFormat

DateTimePicker.setFormat

Syntax
public void setFormat( int format );
Parameters
format
The new format
Description

Sets the format mode for the control. Valid values are:

cor.comctl.DateTimePicker.Formats.LONG
cor.comctl.DateTimePicker.Formats.SHORT
cor.comctl.DateTimePicker.Formats.TIME
cor.comctl.DateTimePicker.Formats.CUSTOM

See Also
getFormat, setCustomFormat, cor.comctl.DateTimePicker.Formats

DateTimePicker.setMaxDate

Syntax
public void setMaxDate( long date );
Parameters
date
The maximum date value.
Description

Sets the Maximum displayable date for the control. There is no maximum value if Maximum is set to -1.

See Also
getMaxDate, setMinDate

DateTimePicker.setMinDate

Syntax
public void setMinDate( long date );
Parameters
date
The minimum date value.
Description

Sets the Minimum displayable date for the control. There is no minimum value if Minimum is set to -1.

See Also
getMinDate, setMaxDate

DateTimePicker.setRightAlign

Syntax
public void setRightAlign( boolean b );
Parameters
b
New value for RightAlign.
Description

Sets the RightAlign property. When RightAlign is set to true, the text in the control is right aligned.

See Also
getRightAlign

DateTimePicker.setShowNone

Syntax
public void setShowNone( boolean b );
Parameters
b
New value for ShowNone.
Description

Sets the ShowNone property. When ShowNone is set to true a checkbox is displayed to the left of the date in the control. When the checkbox is unchecked the value of the control is -1 indicating no date is selected.

See Also
getShowNone

DateTimePicker.setUpDown

Syntax
public void setUpDown( boolean b );
Parameters
b
New value for UpDown.
Description

Sets the UpDown property. If UpDown is set to true, a spin control is used to adjust time values instead of the drop-down calendar.

See Also
getUpDown

DateTimePicker.setValue

Syntax
public void setValue( long time );
Parameters
time
Time to display.
Description

Sets the value displayed in the control. Setting the value to -1 has the effect of selecting a null date. Null dates are allowed only if ShowNone is set to true.

See Also
getValue, setShowNone


 DateTimeUserStringEvent Class

DateTimeUserStringEvent Class

This Package | All Packages

Event
  |
  +--DateTimeUserStringEvent
public class DateTimeUserStringEvent
extends Event

The DateTimeUserStringEvent is fired when the DateTimePicker needs to parse a user-entered string.

Fields
Name | Description
time | The time that userString represents.
userString | The string the user entered.

Constructors
Name | Description
DateTimeUserStringEvent(String userString, long time) | Topic under construction.

Fields

DateTimeUserStringEvent.time

Syntax
public long time;
Description
The time that userString represents.

DateTimeUserStringEvent.userString

Syntax
public final String userString;
Description
The string the user entered.

Constructors

DateTimeUserStringEvent.DateTimeUserStringEvent

Syntax
public DateTimeUserStringEvent( String userString, long time );
Description

Topic under construction.


 DateTimeWmKeyDownEvent Class

DateTimeWmKeyDownEvent Class

This Package | All Packages

Event
  |
  +--DateTimeWmKeyDownEvent
public class DateTimeWmKeyDownEvent
extends Event

The DateTimeWmKeyDownEvent is fired when the user presses a key in a custom field.

Fields
Name | Description
format | Format string associated with the DateTimePicker.
time | Time that the DateTimePicker should be set to.
virtualKey | Keycode of the key that was pressed.

Constructors
Name | Description
DateTimeWmKeyDownEvent(int virtualKey, String format, long time) | Topic under construction.

Fields

DateTimeWmKeyDownEvent.format

Syntax
public final String format;
Description
Format string associated with the DateTimePicker.

DateTimeWmKeyDownEvent.time

Syntax
public long time;
Description
Time that the DateTimePicker should be set to.

DateTimeWmKeyDownEvent.virtualKey

Syntax
public final int virtualKey;
Description
Keycode of the key that was pressed.

Constructors

DateTimeWmKeyDownEvent.DateTimeWmKeyDownEvent

Syntax
public DateTimeWmKeyDownEvent( int virtualKey, String format, long time );
Description

Topic under construction.


 DialogResult Class

DialogResult Class

This Package | All Packages

Enum
  |
  +--DialogResult
public class DialogResult
extends Enum

Topic under construction.

Fields
Name | Description
ABORT | Topic under construction.
CANCEL | Topic under construction.
IGNORE | Topic under construction.
NO | Topic under construction.
NONE | Topic under construction.
OK | Topic under construction.
RETRY | Topic under construction.
YES | Topic under construction.

Fields

DialogResult.ABORT

Syntax
public static final int ABORT;
Description
Topic under construction.

DialogResult.CANCEL

Syntax
public static final int CANCEL;
Description
Topic under construction.

DialogResult.IGNORE

Syntax
public static final int IGNORE;
Description
Topic under construction.

DialogResult.NO

Syntax
public static final int NO;
Description
Topic under construction.

DialogResult.NONE

Syntax
public static final int NONE;
Description
Topic under construction.

DialogResult.OK

Syntax
public static final int OK;
Description
Topic under construction.

DialogResult.RETRY

Syntax
public static final int RETRY;
Description
Topic under construction.

DialogResult.YES

Syntax
public static final int YES;
Description
Topic under construction.


 DragEvent Class

DragEvent Class

This Package | All Packages

Event
  |
  +--DragEvent
public class DragEvent
extends Event

The DragEvent is fired in response to drag-and-drop events in a control.

Fields
Name | Description
data | The data associated with this event.
effect | The effect that should be applied to the mouse cursor.
keyState | The current state of the SHIFT, CTRL, and ALT keys.
x | The x-coordinate location of the mouse.
y | The y-coordinate location of the mouse.

Constructors
Name | Description
DragEvent(IDataObject data, int keyState, int x, int y, int effect) | Topic under construction.

Fields

DragEvent.data

Syntax
public final IDataObject data;
Description
The data associated with this event.

DragEvent.effect

Syntax
public int effect;
Description
The effect that should be applied to the mouse cursor.

DragEvent.keyState

Syntax
public final int keyState;
Description
The current state of the SHIFT, CTRL, and ALT keys.

DragEvent.x

Syntax
public final int x;
Description
The x-coordinate location of the mouse.

DragEvent.y

Syntax
public final int y;
Description
The y-coordinate location of the mouse.

Constructors

DragEvent.DragEvent

Syntax
public DragEvent( IDataObject data, int keyState, int x, int y, int effect );
Description

Topic under construction.


 DrawItemEvent Class

DrawItemEvent Class

This Package | All Packages

Event
  |
  +--DrawItemEvent
public class DrawItemEvent
extends Event

Topic under construction.

Fields
Name | Description
COMBOBOXEDIT | Topic under construction.
FOCUS | Topic under construction.
graphics | Topic under construction.
index | Topic under construction.
rect | Topic under construction.
SELECTED | Topic under construction.
state | Topic under construction.

Constructors
Name | Description
DrawItemEvent(Graphics graphics, Rectangle rect, int index, int state) | Topic under construction.

Methods
Name | Description
drawBackground() | Topic under construction.
drawFocusRect() | Topic under construction.

Fields

DrawItemEvent.COMBOBOXEDIT

Syntax
public static final int COMBOBOXEDIT;
Description
Topic under construction.

DrawItemEvent.FOCUS

Syntax
public static final int FOCUS;
Description
Topic under construction.

DrawItemEvent.graphics

Syntax
public final Graphics graphics;
Description
Topic under construction.

DrawItemEvent.index

Syntax
public final int index;
Description
Topic under construction.

DrawItemEvent.rect

Syntax
public final Rectangle rect;
Description
Topic under construction.

DrawItemEvent.SELECTED

Syntax
public static final int SELECTED;
Description
Topic under construction.

DrawItemEvent.state

Syntax
public final int state;
Description
Topic under construction.

Constructors

DrawItemEvent.DrawItemEvent

Syntax
public DrawItemEvent( Graphics graphics, Rectangle rect, int index, int state );
Description

Topic under construction.

Methods

DrawItemEvent.drawBackground

Syntax
public void drawBackground();
Description

Topic under construction.

DrawItemEvent.drawFocusRect

Syntax
public void drawFocusRect();
Description

Topic under construction.


 DrawMode Class

DrawMode Class

This Package | All Packages

Enum
  |
  +--DrawMode
public class DrawMode
extends Enum

Enumeration class used to specify the draw modes of a list box

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | All the items in the list box are painted by the system and are the same size.
OWNERDRAWFIXED | The user paints the items in the list box manually, but they are all the same size (height).
OWNERDRAWVARIABLE | The user paints the items in the list box manually, and they are not necessarily the same size.

Fields

DrawMode.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

DrawMode.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

DrawMode.NORMAL

Syntax
public static final int NORMAL;
Description
All the items in the list box are painted by the system and are the same size.

DrawMode.OWNERDRAWFIXED

Syntax
public static final int OWNERDRAWFIXED;
Description
The user paints the items in the list box manually, but they are all the same size (height).

DrawMode.OWNERDRAWVARIABLE

Syntax
public static final int OWNERDRAWVARIABLE;
Description
The user paints the items in the list box manually, and they are not necessarily the same size.


 Edit Class

Edit Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Edit
public class Edit
extends Control

Creates a standard Windows edit control. This control supports multiline editing, password character masking, and so forth.

Constructors
Name | Description
Edit() | Creates a new Edit control, using parent control's current font and color settings.

Methods
Name | Description
clear() | Clears the edit control.
getAutoSize() | Retrieves a booolean value that indicates whether the control is configured to support auto-sizing.
getBorderStyle() | Returns the border style of the Edit control.
getCharacterCasing() | Retrieves a constant that indicates whether the control modifies the case of characters as they are typed into the control.
getCreateParams() | Topic under construction.
getHideSelection() | Retrieves a boolean value that indicates whether the control currently hides selected text when the control loses input focus.
getInputKey(int keyData) | Topic under construction.
getLines() | Retrieves the text in the Edit control, and returns the text in an array of String objects.
getMaxLength() | Retrieves the maximum number of characters that can be typed into the Edit control.
getMultiline() | Retrieves a boolean value that indicates whether this is a multiline edit control.
getPasswordChar() | Retrieves the character used to display passwords for a single-line Edit control.
getPreferredHeight() | Retrieves the preferred height of the Edit control.
getReadOnly() | Retrieves a boolean value that indicates whether the Edit control is read-only.
getReturnWanted() | Retrieves a boolean value that indicates whether a multiline Edit control allows RETURN keys to be processed as input.
getScrollBars() | Retrieves the current scroll bar settings for a multiline Edit control.
getSelectedText() | Retrieves the currently selected text, and returns it in a String object.
getSelectionEnd() | Retrieves the zero-based index of the last character in the current selection.
getSelectionStart() | Retrieves the zero-based index of the first character in the current selection.
getTabWanted() | Retrieves a boolean value that indicates whether a multiline Edit control allows TAB keys to be processed as input.
getTextAlign() | Retrieves a constant that indicates the current text-alignment settings on the control.
getWordWrap() | Retrieves a boolean value that indicates whether word-wrapping is set on a multiline Edit control.
onCreateHandle() | Overridden to update the newly created handle with the settings of the MaxLength and PasswordChar properties.
select(int start, int end) | Selects the text within the specified range.
selectAll() | Selects all characters in the Edit control.
setAutoSize(boolean value) | Controls whether the height of a single-line Edit control is automatically adjusted when the control's font changes.
setBorderStyle(int value) | Sets the border for the Edit control.
setBoundsCore(int x, int y, int width, int height) | Overrides Control.setBoundsCore to enforce autoSize.
setCharacterCasing(int value) | Specifies whether the case of characters should be modified as they are typed into the Edit control.
setHideSelection(boolean value) | Controls whether the Edit control hides selected text when the control loses input focus.
setLines(String[] lines) | Initializes a multiline Edit control to contain the contents of an array of String objects, where one string is displayed on each line.
setMaxLength(int value) | Specifies the maximum number of characters that can be entered into an Edit control.
setMultiline(boolean value) | Specifies whether the Edit control is multiline.
setPasswordChar(char value) | Sets the password character for a single-line Edit control.
setReadOnly(boolean value) | Specifies whether the edit control is read-only.
setReturnWanted(boolean value) | Specifies whether a multiline Edit control processes the RETURN key as an input character.
setScrollBars(int value) | Specifies how scroll bars will be displayed in multiline Edit controls.
setSelectedText(String value) | Replaces the currently selected text with the specified text.
setSelectionEnd(int value) | Specifies the zero-based index of the last character of a text selection in the Edit control.
setSelectionStart(int value) | Specifies the zero-based index of the first character of a text selection in the Edit control.
setTabWanted(boolean value) | Specifies whether a multiline Edit control processes the TAB key as an input character.
setTextAlign(int value) | Specifies the alignment of the text in the Edit control.
setWordWrap(boolean value) | Specifies whether word-wrapping is on in a multiline Edit control.

Constructors

Edit.Edit

Syntax
public Edit();
Description

Creates a new Edit control, using parent control's current font and color settings.

Methods

Edit.clear

Syntax
public void clear();
Description

Clears the edit control.

Edit.getAutoSize

Syntax
public boolean getAutoSize();
Return Value

Returns true if the control is currently set to auto-size; otherwise, returns false.

Description

Retrieves a booolean value that indicates whether the control is configured to support auto-sizing. If auto-sizing is on, the size of the control is automatically adjusted when the font is changed.

Edit.getBorderStyle

Syntax
public int getBorderStyle();
Return Value

Returns one of the constants defined in the BorderStyle class. The two possible values are BorderStyle.NONE and BorderStyle.FIXED_SINGLE.

Description

Returns the border style of the Edit control.

Edit.getCharacterCasing

Syntax
public int getCharacterCasing();
Return Value

Returns one of the values defined in the CharacterCasing enumeration.

Description

Retrieves a constant that indicates whether the control modifies the case of characters as they are typed into the control. Characters can be converted to uppercase, lowercase, or not converted.

Edit.getCreateParams

Syntax
protected CreateParams getCreateParams();
Description

Topic under construction.

Overrides

getCreateParams() in Control.

Edit.getHideSelection

Syntax
public boolean getHideSelection();
Return Value

Returns true if the control hides the text; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the control currently hides selected text when the control loses input focus.

Edit.getInputKey

Syntax
protected boolean getInputKey( int keyData );
Description

Topic under construction.

Overrides

getInputKey(int) in Control.

Edit.getLines

Syntax
public String[] getLines();
Return Value

Returns an arry of strings that contains the contents of the Edit control.

Description

Retrieves the text in the Edit control, and returns the text in an array of String objects. Each line of the text box is returned as a new element in the array. For single-line Edit controls, this array consists of a single element.

Edit.getMaxLength

Syntax
public int getMaxLength();
Return Value

Returns zero or an integer that indicates the maximum character capacity of the control.

Description

Retrieves the maximum number of characters that can be typed into the Edit control. A return value of zero indicates that the maximum capacity of the Edit control is limited only to available memory.

Edit.getMultiline

Syntax
public boolean getMultiline();
Return Value

Returns true if this is a multiline control; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this is a multiline edit control. By default, the Edit control is a single-line control.

Edit.getPasswordChar

Syntax
public char getPasswordChar();
Return Value

Returns zero or the text of the character used to mask passwords.

Description

Retrieves the character used to display passwords for a single-line Edit control. A return value of zero indicates that the Edit control is not currently being used to enter passwords.

Edit.getPreferredHeight

Syntax
public int getPreferredHeight();
Return Value

Returns an integer indicating the preferred height of the control. To adjust the preferred height, use the adjustHeight method.

Description

Retrieves the preferred height of the Edit control. This calculation is based on the assumption that a single line of text will be displayed in the control.

Edit.getReadOnly

Syntax
public boolean getReadOnly();
Return Value

Returns true if the control is read-only; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the Edit control is read-only. If the control is read-only,the system beeps when a user attempts to type text into the control.

Edit.getReturnWanted

Syntax
public boolean getReturnWanted();
Return Value

Returns true if the RETURN key can be processed as input; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether a multiline Edit control allows RETURN keys to be processed as input.

Edit.getScrollBars

Syntax
public int getScrollBars();
Return Value

Returns one of the ScrollBars enumeration constants.

Description

Retrieves the current scroll bar settings for a multiline Edit control. These settings are defined in the ScrollBars enumeration.

Edit.getSelectedText

Syntax
public String getSelectedText();
Return Value

Returns the currently selected text if text is selected; otherwise, returns null.

Description

Retrieves the currently selected text, and returns it in a String object.

Edit.getSelectionEnd

Syntax
public int getSelectionEnd();
Return Value

Returns the zero-based index of the last character in the selection

Description

Retrieves the zero-based index of the last character in the current selection.

Edit.getSelectionStart

Syntax
public int getSelectionStart();
Description

Retrieves the zero-based index of the first character in the current selection.

Edit.getTabWanted

Syntax
public boolean getTabWanted();
Return Value

Returns true if TAB keys can be processed as input; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether a multiline Edit control allows TAB keys to be processed as input.

Edit.getTextAlign

Syntax
public int getTextAlign();
Return Value

Returns one of the constants defined in the HorizontalAlignment enumeration.

Description

Retrieves a constant that indicates the current text-alignment settings on the control. This setting applies only to multiline Edit controls.

Edit.getWordWrap

Syntax
public boolean getWordWrap();
Return Value

Returns true if word-wrapping is on; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether word-wrapping is set on a multiline Edit control.

Edit.onCreateHandle

Syntax
protected void onCreateHandle();
Description

Overridden to update the newly created handle with the settings of the MaxLength and PasswordChar properties.

Overrides

onCreateHandle() in Control.

Edit.select

Syntax
public void select( int start, int end );
Parameters
start
The zero-based index of the character with which to begin the selection.
end
The zero-based index of the character with which to end the selection.
Description

Selects the text within the specified range.

Edit.selectAll

Syntax
public void selectAll();
Description

Selects all characters in the Edit control.

Edit.setAutoSize

Syntax
public void setAutoSize( boolean value );
Parameters
value
If set to true, the control is automatically resized when the control's font is changed. Otherwise, the control is not resized.
Description

Controls whether the height of a single-line Edit control is automatically adjusted when the control's font changes.

Edit.setBorderStyle

Syntax
public void setBorderStyle( int value );
Parameters
value
Specifies the BorderStyle constant for the border. The only acceptable values for this parameter are NONE and FIXED_SINGLE.
Description

Sets the border for the Edit control.

Edit.setBoundsCore

Syntax
protected void setBoundsCore( int x, int y, int width, int height );
Parameters
x
The x position of the top-left corner of the Edit control.
y
The y position of the top-left corner of the Edit control.
width
The width of the Edit control.
height
The height of the Edit control.
Description

Overrides Control.setBoundsCore to enforce autoSize.

Overrides

setBoundsCore(int,int,int,int) in Control.

Edit.setCharacterCasing

Syntax
public void setCharacterCasing( int value );
Parameters
One
of the CharacterCasing enumeration constants. Acceptable values for this parameter include CharacterCasing.NORMAL, CharacterCasing.UPPER, and CharacterCasing.LOWER.
Description

Specifies whether the case of characters should be modified as they are typed into the Edit control.

Exceptions

IllegalArgumentException thrown if the specified value is less than CharacterCasing.MIN or greater than CharacterCasing.MAX.

Edit.setHideSelection

Syntax
public void setHideSelection( boolean value );
Parameters
value
A boolean value that indicates whether the selection should be hidden.
Description

Controls whether the Edit control hides selected text when the control loses input focus.

Edit.setLines

Syntax
public void setLines( String[] lines );
Parameters
String[]
The array of String objects to display in the Edit control.
Description

Initializes a multiline Edit control to contain the contents of an array of String objects, where one string is displayed on each line. A carriage return/newline within a single element of the array results in the creation of a new line in the control.

Edit.setMaxLength

Syntax
public void setMaxLength( int value );
Parameters
value
Zero or a number that specifies the character capacity of the control.
Description

Specifies the maximum number of characters that can be entered into an Edit control. A value of zero indicates that the Edit control's capacity should be limited only by available memory.

Edit.setMultiline

Syntax
public void setMultiline( boolean value );
Parameters
value
A boolean value indicating whether the Edit control is a multi-line control.
Description

Specifies whether the Edit control is multiline. By default, the Edit control is a single-line control that ignores ENTER characters.

Edit.setPasswordChar

Syntax
public void setPasswordChar( char value );
Parameters
value
The character to be substituted for the characters that the user types. If you specify a zero, no character masking is applied to text entered in the control; the control functions normally.
Description

Sets the password character for a single-line Edit control.

Edit.setReadOnly

Syntax
public void setReadOnly( boolean value );
Parameters
value
A boolean value that indicates whether the control is read-only.
Description

Specifies whether the edit control is read-only.

Edit.setReturnWanted

Syntax
public void setReturnWanted( boolean value );
Parameters
value
A boolean value that specifies whether RETURN keys should be processed as characters.
Description

Specifies whether a multiline Edit control processes the RETURN key as an input character.

Edit.setScrollBars

Syntax
public void setScrollBars( int value );
Parameters
value
One of the constants defined in the ScrollBars enumeration.
Description

Specifies how scroll bars will be displayed in multiline Edit controls.

Edit.setSelectedText

Syntax
public void setSelectedText( String value );
Parameters
value
The text with which to replace the selected text.
Description

Replaces the currently selected text with the specified text.

Edit.setSelectionEnd

Syntax
public void setSelectionEnd( int value );
Parameters
value
The zero-based index of the character at which the selection ends.
Description

Specifies the zero-based index of the last character of a text selection in the Edit control.

Edit.setSelectionStart

Syntax
public void setSelectionStart( int value );
Parameters
value
The zero-based index of the character at which the selection begins.
Description

Specifies the zero-based index of the first character of a text selection in the Edit control.

Edit.setTabWanted

Syntax
public void setTabWanted( boolean value );
Parameters
value
A boolean value that indicates whether the Edit control should process TAB keys as input characters.
Description

Specifies whether a multiline Edit control processes the TAB key as an input character.

Edit.setTextAlign

Syntax
public void setTextAlign( int value );
Parameters
value
One of the enumeration constants defined in the HorizontalAlign class.
Description

Specifies the alignment of the text in the Edit control. This method applies only to multiline Edit controls.

Edit.setWordWrap

Syntax
public void setWordWrap( boolean value );
Parameters
value
A boolean value that indicates whether word-wrapping is set on this control.
Description

Specifies whether word-wrapping is on in a multiline Edit control.


 FileDialog Class

FileDialog Class

This Package | All Packages

CommonDialog
  |
  +--FileDialog
public abstract class FileDialog
extends CommonDialog

Represents the abstract base class for the OpenFileDialog and SaveFileDialog classes.

Fields
Name | Description
ALLOWMULTISELECT | Specifies that the File Name list box allows multiple selections.
CREATEPROMPT | If the user specifies a file that does not exist, this flag causes the dialog box to prompt the user for permission to create the file.
EXTENSIONDIFFERENT | Specifies that the user has typed a filename extension that differs from the extension specified by the DefaultExt property.
FILEMUSTEXIST | Specifies that the user can type only names of existing files in the File Name entry field.
HIDEREADONLY | Hides the Read Only check box.
NOCHANGEDIR | Restores the current directory to its original value if the user changed the directory while searching for files.
NODEREFERENCELINKS | Directs the dialog box to return the path and filename of the selected shortcut (.LNK) file.
NONETWORKBUTTON | Hides and disables the Network button.
NOREADONLYRETURN | Specifies that the returned file does not have the Read Only check box checked and is not in a write-protected directory.
NOTESTFILECREATE | Specifies that the file is not created before the dialog box is closed.
NOVALIDATE | Specifies that the common dialog boxes allow invalid characters in the returned filename.
OVERWRITEPROMPT | Causes the Save As dialog box to generate a message box if the selected file already exists.
PATHMUSTEXIST | Specifies that the user can type only valid paths and filenames.
READONLY | Causes the Read Only check box to be checked initially when the dialog box is created.
SHAREAWARE | Specifies that if opening the selected file fails because of a network sharing violation, the error is ignored and the dialog box returns the selected filename.
SHOWHELP | Causes the dialog box to display the Help button.

Constructors
Name | Description
FileDialog() | Constructs a new FileDialog.

Methods
Name | Description
getDefaultExt() | Returns the default file extension.
getFilename() | Returns the filename selected in the file dialog.
getFilenames() | Returns the list of filenames selected in the file dialog.
getFilter() | Returns the current filter string.
getFilterIndex() | Returns the index of the filter currently selected in the file dialog.
getInitialDir() | Returns the initial directory set for the file dialog.
getOptions() | Returns the option flags currently set for the file dialog.
getTitle() | Returns the title set for the file dialog.
hookProc(int hWnd, int msg, int wParam, int lParam) | Common dialog hook procedure.
reset() | Resets all properties to their default values.
runDialog(int hookProcPtr) | Implements running of a file dialog.
setDefaultExt(String value) | Sets the default extension.
setFilename(String value) | Sets the filename used to initialize the File Name edit control.
setFilter(String value) | Sets the filters for the file dialog.
setFilterIndex(int value) | Sets the current filter index.
setInitialDir(String value) | Sets the initial file dialog directory.
setOptions(int value) | Sets the option flags for the file dialog.
setTitle(String value) | Sets the file dialog title.

Fields

FileDialog.ALLOWMULTISELECT

Syntax
public static final int ALLOWMULTISELECT;
Description
Specifies that the File Name list box allows multiple selections. To access the full list of selected filenames, use the getFilenames method.

FileDialog.CREATEPROMPT

Syntax
public static final int CREATEPROMPT;
Description
If the user specifies a file that does not exist, this flag causes the dialog box to prompt the user for permission to create the file. If the user chooses to create the file, the dialog box closes and the function returns the specified name; otherwise, the dialog box remains open.

FileDialog.EXTENSIONDIFFERENT

Syntax
public static final int EXTENSIONDIFFERENT;
Description
Specifies that the user has typed a filename extension that differs from the extension specified by the DefaultExt property. The file dialog does not update this flag if DefaultExt is an empty string.

FileDialog.FILEMUSTEXIST

Syntax
public static final int FILEMUSTEXIST;
Description
Specifies that the user can type only names of existing files in the File Name entry field. If this flag is specified and the user enters an invalid name, the dialog box procedure displays a warning in a message box. If this flag is specified, the PATHMUSTEXIST flag is also used.

FileDialog.HIDEREADONLY

Syntax
public static final int HIDEREADONLY;
Description
Hides the Read Only check box.

FileDialog.NOCHANGEDIR

Syntax
public static final int NOCHANGEDIR;
Description
Restores the current directory to its original value if the user changed the directory while searching for files.

FileDialog.NODEREFERENCELINKS

Syntax
public static final int NODEREFERENCELINKS;
Description
Directs the dialog box to return the path and filename of the selected shortcut (.LNK) file. If this value is not given, the dialog box returns the path and filename of the file referenced by the shortcut

FileDialog.NONETWORKBUTTON

Syntax
public static final int NONETWORKBUTTON;
Description
Hides and disables the Network button.

FileDialog.NOREADONLYRETURN

Syntax
public static final int NOREADONLYRETURN;
Description
Specifies that the returned file does not have the Read Only check box checked and is not in a write-protected directory.

FileDialog.NOTESTFILECREATE

Syntax
public static final int NOTESTFILECREATE;
Description
Specifies that the file is not created before the dialog box is closed. This flag should be specified if the application saves the file on a create-nonmodify network sharepoint. When an application specifies this flag, the library does not check for write protection, a full disk, an open drive door, or network protection. Applications using this flag must perform file operations carefully, because a file cannot be reopened once it is closed.

FileDialog.NOVALIDATE

Syntax
public static final int NOVALIDATE;
Description
Specifies that the common dialog boxes allow invalid characters in the returned filename. If the edit control contains anything but spaces when the user clicks OK, the dialog returns the filename, whether it is valid or not. No default extension is added to the text.

FileDialog.OVERWRITEPROMPT

Syntax
public static final int OVERWRITEPROMPT;
Description
Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.

FileDialog.PATHMUSTEXIST

Syntax
public static final int PATHMUSTEXIST;
Description
Specifies that the user can type only valid paths and filenames. If this flag is used and the user types an invalid path and filename in the File Name entry field, the dialog box function displays a warning in a message box.

FileDialog.READONLY

Syntax
public static final int READONLY;
Description
Causes the Read Only check box to be checked initially when the dialog box is created. This flag indicates the state of the Read Only check box when the dialog box is closed.

FileDialog.SHAREAWARE

Syntax
public static final int SHAREAWARE;
Description
Specifies that if opening the selected file fails because of a network sharing violation, the error is ignored and the dialog box returns the selected filename.

FileDialog.SHOWHELP

Syntax
public static final int SHOWHELP;
Description
Causes the dialog box to display the Help button.

Constructors

FileDialog.FileDialog

Syntax
protected FileDialog();
Description

Constructs a new FileDialog.

Methods

FileDialog.getDefaultExt

Syntax
public final String getDefaultExt();
Description

Returns the default file extension.

See Also
setDefaultExt

FileDialog.getFilename

Syntax
public final String getFilename();
Description

Returns the filename selected in the file dialog. If multiple files are selected, the return value is the first filename in the list. If no file is selected, the return value is an empty string.

See Also
getFilenames, setFilename

FileDialog.getFilenames

Syntax
public final String[] getFilenames();
Description

Returns the list of filenames selected in the file dialog. If no files are selected, the return value is an empty array.

See Also
getFilename, setFilenames

FileDialog.getFilter

Syntax
public final String getFilter();
Description

Returns the current filter string.

See Also
setFilter

FileDialog.getFilterIndex

Syntax
public final int getFilterIndex();
Description

Returns the index of the filter currently selected in the file dialog.

See Also
setFilterIndex

FileDialog.getInitialDir

Syntax
public final String getInitialDir();
Description

Returns the initial directory set for the file dialog.

See Also
setInitialDir

FileDialog.getOptions

Syntax
public final int getOptions();
Description

Returns the option flags currently set for the file dialog. The READONLY and EXTENSIONDIFFERENT flags are updated by the file dialog when the user clicks OK.

See Also
setOptions

FileDialog.getTitle

Syntax
public final String getTitle();
Description

Returns the title set for the file dialog.

See Also
setTitle

FileDialog.hookProc

Syntax
protected int hookProc( int hWnd, int msg, int wParam, int lParam );
Description

Common dialog hook procedure. Centers the dialog on the screen in response to a CDN_INITDONE notification.

FileDialog.reset

Syntax
public void reset();
Description

Resets all properties to their default values.

FileDialog.runDialog

Syntax
protected boolean runDialog( int hookProcPtr );
Description

Implements running of a file dialog.

FileDialog.setDefaultExt

Syntax
public final void setDefaultExt( String value );
Description

Sets the default extension. The file dialog append this extension to the filename if the user fails to type an extension. This string can be any length, but only the first three characters are appended. The string should not contain a period. The default value for the default extension is an empty string, which causes no extension to be appended.

See Also
getDefaultExt

FileDialog.setFilename

Syntax
public final void setFilename( String value );
Description

Sets the filename used to initialize the File Name edit control.

See Also
getFilename

FileDialog.setFilter

Syntax
public final void setFilter( String value );
Description

Sets the filters for the file dialog. The filter string must consist of a number of filter pairs, separated by "|" characters. The first string in each pair is a display string that describes the filter (for example, "Text files"), and the second string specifies the filter pattern (for example, "*.txt"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.txt;*.doc;*.bak"). A pattern string can be a combination of valid filename characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. The following is an example of a filter string:

  "Java files (*.java)|*.java|All files (*.*)|*.*"

The file dialog does not change the order of the filters. It displays them in the File Types combo box in the order specified by setFilter().

See Also
getFilter, setFilterIndex

FileDialog.setFilterIndex

Syntax
public final void setFilterIndex( int value );
Description

Sets the current filter index. The first pair of filter strings has an index value of 1, the second pair 2, and so on. You can specify an index on input to indicate the initial filter description and filter pattern for the dialog box. When the file dialog returns, getFilterIndex() returns the index of the currently displayed filter.

See Also
getFilterIndex, setFilter

FileDialog.setInitialDir

Syntax
public final void setInitialDir( String value );
Description

Sets the initial file dialog directory. If the specified directory is an empty string, the system uses the current directory as the initial directory.

See Also
getInitialDir

FileDialog.setOptions

Syntax
public final void setOptions( int value );
Description

Sets the option flags for the file dialog. The default value for the option flags is 0.

See Also
getOptions

FileDialog.setTitle

Syntax
public final void setTitle( String value );
Description

Sets the file dialog title. The given string is placed in the title bar of the dialog box. If specified title is an empty string, the system uses the default title (that is, "Save As" or "Open").

See Also
getTitle


 Font Class

Font Class

This Package | All Packages

public final class Font
implements IConstructable, IPersistable

Encapsulates a Win32 font. Fonts are used to draw text on video displays and other output devices.

Fields
Name | Description
ANSI_FIXED | Standard ANSI fixed-width font.
ANSI_VAR | Standard ANSI variable-width font.
DEFAULT_GUI | Default font for the current user interface.
DEVICE_DEFAULT | Standard font for the current graphics device.
OEM_FIXED | Standard original equipment manufacturer (OEM) fixed font.
SYSTEM | Standard Windows variable-width system font.
SYSTEM_FIXED | Standard Windows fixed-width system font.

Constructors
Name | Description
Font(int handle) | Creates a Font object based on an existing Win32 font handle.
Font(String name, int size) | Creates a new font based on a specified font face name and size.
Font(String name, int size, int weight, boolean italic, boolean underline, boolean strikeOut) | Creates a new font given a font face, size, and style.
Font(String name, int size, int weight, boolean italic, boolean underline, boolean strikeOut, int charSet, int orientation) | Creates a new font.
Font(Font font, int size) | Creates a new font from an existing one.
Font(Font font, int weight, boolean italic, boolean underline, boolean strikeOut) | Creates a new font from an existing one.
Font(Font font, int size, int weight, boolean italic, boolean underline, boolean strikeOut) | Creates a new font from an existing one.
Font(int family, int pitch, int size) | Creates a new font based on a specified font family, pitch and size.
Font(int family, int pitch, int size, int weight, boolean italic, boolean underline, boolean strikeOut) | Creates a new font based on a specified font face, size, and style.
Font(int family, int pitch, int size, int weight, boolean italic, boolean underline, boolean strikeOut, int charSet, int orientation) | Creates a new font, based on the specified family, pitch, size, and weight.
Font(IDataStream stream) | Creates a new font from a specified datastream.

Methods
Name | Description
equals(Object obj) | Determines if one object equates to another.
equalsBase(Font font) | Determines if one font shares the same base font as another.
finalize() throws Throwable | Releases all resources allocated by this object.
getBold() | Retrieves a boolean value that indicates if the font is bold.
getCharacterSet() | Retrieves the character set the font is using.
getConstructorArgs() | Retrieves the ConstructorArgs needed to persist this object.
getExtension() | Retrieves a file name extension with which to save this object's persistance data.
getFontMetrics() | Retrieves a FontMetrics object for this font.
getFontMetrics(Graphics gr) | Retrieves a FontMetrics object for this font.
getHandle() | Retrieves the Win32 HFONT handle.
getItalic() | Retrieves a boolean value that indicates whether the font is italicized.
getLogicalUnits(float points) | Converts a font's Point value to a logical unit.
getLogicalUnits(float points, Graphics gr) | Converts a font's Point value to a logical unit.
getName() | Retrieves the face name of the font, and returns the name in a String object.
getOrientation() | Rerieves the orientation of the font, in tenths of a degree, from the x-axis of the device.
getPoints(int units) | Converts a font's logical unit to a point.
getPoints(int units, Graphics gr) | Converts a font's logical unit to a point.
getSize() | Retrieves the size of the font in logical units.
getStock(int index) | Retrieves a stock font, based on a specified index.
getStrikeout() | Retrieves a boolean value that indicates whether the current font is a strike-through font.
getUnderline() | Retrieves a boolean value that indicates whether the font is underlined.
getWeight() | Retrieves the weight associated with this font.
hashCode() | Retrieves a hash code value for this font.
save(IDataStream stream) | Persists this font to the given datastream.

Fields

Font.ANSI_FIXED

Syntax
public static final Font ANSI_FIXED;
Description
Standard ANSI fixed-width font.

Font.ANSI_VAR

Syntax
public static final Font ANSI_VAR;
Description
Standard ANSI variable-width font.

Font.DEFAULT_GUI

Syntax
public static final Font DEFAULT_GUI;
Description
Default font for the current user interface. This font automatically adapts its character set to the locale of the user.

Font.DEVICE_DEFAULT

Syntax
public static final Font DEVICE_DEFAULT;
Description
Standard font for the current graphics device.

Font.OEM_FIXED

Syntax
public static final Font OEM_FIXED;
Description
Standard original equipment manufacturer (OEM) fixed font.

Font.SYSTEM

Syntax
public static final Font SYSTEM;
Description
Standard Windows variable-width system font.

Font.SYSTEM_FIXED

Syntax
public static final Font SYSTEM_FIXED;
Description
Standard Windows fixed-width system font.

Constructors

Font.Font

Syntax 1
public Font( int handle );
Parameters
handle
The handle of the font.
Description

Creates a Font object based on an existing Win32 font handle. The handle is not owned by this object.

Syntax 2
public Font( String name, int size );
Parameters
name
The face name of the font to create.
size
The size of the font in logical units.
Description

Creates a new font based on a specified font face name and size.

Syntax 3
public Font( String name, int size, int weight, boolean italic, boolean underline, boolean strikeOut );
Parameters
name
The face name of the font to create.
size
The size of the font in logical units.
weight
The weight of the font. This must be one of the enumeration values defined in the FontWeight class.
italic
Set to true if the font is to be italicized; otherwise, set to false.
underline
Set to true if the font is to be underlined; therwise, false.
strikeOut
Set to true if the font is to be struck through; otherwise, set to false.
Description

Creates a new font given a font face, size, and style.

Syntax 4
public Font( String name, int size, int weight, boolean italic, boolean underline, boolean strikeOut, int charSet, int orientation );
Parameters
name
The face name of the font to create.
size
The size of the font in logical units.
weight
The weight of the font. This must be one of the enumeration values defined by the FontWeight class.
italic
Set to true if the font is to be italicized; otherwise, set to false.
underline
Set to true if the font is to be underlined; otherwise, set to false.
strikeOut
Set to true if the font is to be struck through; otherwise, det to false.
charSet
The character set of the font. This value must be one of the enumeration values defined in the wfc.app.CharacterSet class.
orientation
Orientation of the font. This is the angle, in tenths of a degree, between a character's baseline and the x-axis of a device.
Description

Creates a new font.

Syntax 5
public Font( Font font, int size );
Parameters
font
The existing font to use as a template.
size
The size of the new font in logical units.
Description

Creates a new font from an existing one.

Syntax 6
public Font( Font font, int weight, boolean italic, boolean underline, boolean strikeOut );
Parameters
font
The existing font to use as a template.
weight
The weight of the font. This must be one of the enumeration values defined in the FontWeight class.
italic
Set to true if the font is to be italicized; otherwise, set to false.
underline
Set to true if the font is to be underlined; otherwise, set to false.
strikeOut
Set to true if the font is to be struck through; otherwise, set to false.
Description

Creates a new font from an existing one.

Syntax 7
public Font( Font font, int size, int weight, boolean italic, boolean underline, boolean strikeOut );
Parameters
font
The existing font you want to use as a template.
size
The size of the new font in logical units.
weight
The weight of the font. This must be one of the enumeration values defined in the FontWeight class.
italic
Set to true if the font is to be underlined; otherwise, set to false.
underline
Set to true if the font is to be underlined; otherwise, set to false.
strikeOut
Set to true if the font is to be struck through; otherwise, set to false.
Description

Creates a new font from an existing one.

Syntax 8
public Font( int family, int pitch, int size );
Parameters
family
The family of the font you want to create. This value must be one of the enumeration values defined in the FontFamily class.
pitch
The pitch of the font you want to create. This value must be one of the enumeration values defined in the FontPitch class.
size
The size of the font in logical units.
Description

Creates a new font based on a specified font family, pitch and size. Usually, you use this method if you do not know the name of the font you want to create.

Syntax 9
public Font( int family, int pitch, int size, int weight, boolean italic, boolean underline, boolean strikeOut );
Parameters
family
The family of the font you want to create. This must be one of the enumeration values defined in the FontFamily class.
pitch
The pitch of the font you want to create. This must be one of the enumeration values defined in the FontPitch class.
size
The size of the font in logical units.
weight
The weight of the font. This must be one of the enumeration values defined in the FontWeight class.
italic
Set to true if the font is to be underlined; otherwise, set to false.
underline
Set to true if the font is to be underlined; otherwise, set to false.
strikeOut
Set to true if the font is to be struck through; otherwise, set to false.
Description

Creates a new font based on a specified font face, size, and style. Usually, you use this method if you do not know the name of the font you want to create.

Syntax 10
public Font( int family, int pitch, int size, int weight, boolean italic, boolean underline, boolean strikeOut, int charSet, int orientation );
Parameters
family
The family of the font you want to create.
pitch
The pitch of the font you want to create.
size
The size of the font in logical units.
weight
The weight of the font. This value must be one of the enumeration values defined in the FontWeight class.
italic
Set to true if the font is to be italicized; otherwise, set to false.
underline
Set to true if the font is to be underlined; otherwise, set to false.
strikeOut
Set to true if the font is to be struck through; otherwise, set to false.
charSet
The character set of the font. This must be one of the enumeration values defined in the wfc.app.CharacterSet class.
orientation
Orientation of the font. This is the angle, in tenths of a degree, between a character's baseline and the x-axis of a device.
Description

Creates a new font, based on the specified family, pitch, size, and weight. Usually, you use this method when you do not know the name of the font you want to create.

Syntax 11
public Font( IDataStream stream );
Parameters
stream
The IDataStream from which to read the font.
Description

Creates a new font from a specified datastream.

See Also
IDataStream, IPersistable

Methods

Font.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The object to test.
Return Value

Returns true if the given object equals this object; otherwise, returns false.

Description

Determines if one object equates to another.

Font.equalsBase

Syntax
public boolean equalsBase( Font font );
Parameters
font
The font to test.
Return Value

Returns true if the given font has the same base characteristics as this font; otherwise, returns false.

Description

Determines if one font shares the same base font as another.

Font.finalize

Syntax
protected void finalize() throws Throwable;
Description

Releases all resources allocated by this object.

Exceptions

Throwable Thrown if a problem occurs while freeing the object's resources.

Font.getBold

Syntax
public boolean getBold();
Return Value

Returns true if the font is bold; otherwise, returns false.

Description

Retrieves a boolean value that indicates if the font is bold.

Font.getCharacterSet

Syntax
public int getCharacterSet();
Return Value

Returns a wfc.app.CharacterSet enumeration value.

Description

Retrieves the character set the font is using.

Font.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Return Value

Returns a ConstructorArg array.

Description

Retrieves the ConstructorArgs needed to persist this object.

See Also
ConstructorArg, IConstructable

Font.getExtension

Syntax
public String getExtension();
Return Value

Returns a file name extension to use during object persistence. Because Font objects do not use an extension, this method always returns null.

Description

Retrieves a file name extension with which to save this object's persistance data.

See Also
IPersistable

Font.getFontMetrics

Syntax 1
public FontMetrics getFontMetrics();
Return Value

Returns a FontMetrics object with the physical characteristics of the font.

Description

Retrieves a FontMetrics object for this font. While a Font object maintains the requested characteristics of a font, a FontMetrics contains information about the actual font as it will be rendered to a Graphics object. This information may or may not match the requested characteristics, depending on what font information is available. This function assumes a default Graphics object of the screen.

Syntax 2
public FontMetrics getFontMetrics( Graphics gr );
Parameters
gr
The Graphics object to which to map the font.
Return Value

Returns a FontMetrics object that describes the physical characteristics of the font.

Description

Retrieves a FontMetrics object for this font. While a Font object maintains the requested characteristics of a font, a FontMetrics object contains information about the font as it will be rendered to a Graphics object. This information may or may not match the requested Font object characteristics, depending on font information that is available.

Font.getHandle

Syntax
public int getHandle();
Return Value

Returns a Win32 handle to the font.

Description

Retrieves the Win32 HFONT handle.

Font.getItalic

Syntax
public boolean getItalic();
Return Value

Returns true if the font is italicized; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the font is italicized.

Font.getLogicalUnits

Syntax 1
public static final int getLogicalUnits( float points );
Parameters
points
The point size to convert.
Return Value

Returns the number of logical units.

Description

Converts a font's Point value to a logical unit. A font's logical units are independent of a given Graphics object's resolution. Points, on the other hand, are dependent on the resolution of the target object.

Syntax 2
public static final int getLogicalUnits( float points, Graphics gr );
Parameters
points
The point size to convert.
gr
The Graphics object on which to base the conversion.
Return Value

Returns the number of logical units.

Description

Converts a font's Point value to a logical unit. A font's logical units are independent of a given Graphics object's resolution. Points, on the other hand, are dependent on the resolution of the target object.

Font.getName

Syntax
public String getName();
Return Value

Returns the font's face name.

Description

Retrieves the face name of the font, and returns the name in a String object.

Font.getOrientation

Syntax
public int getOrientation();
Return Value

Returns the orientation of the font.

Description

Rerieves the orientation of the font, in tenths of a degree, from the x-axis of the device.

Font.getPoints

Syntax 1
public static final float getPoints( int units );
Parameters
units
The logical unit number to convert to points.
Return Value

Returns the number of points in the logical unit.

Description

Converts a font's logical unit to a point. Logical units are independent of a Graphics object's resolution. Points, on the other hand, depend on the resolution of the target object.

Syntax 2
public static final float getPoints( int units, Graphics gr );
Parameters
units
The logical unit number to convert to points.
gr
The Graphics object on which to base the conversion.
Return Value

Returns the number of points in the logical unit.

Description

Converts a font's logical unit to a point. Logical units are independent of a Graphics object's resolution. Points, on the other hand, depend on the resolution of the target object.

Font.getSize

Syntax
public int getSize();
Return Value

Returns the font size in logical units.

Description

Retrieves the size of the font in logical units. Windows defines a positive font size as the cell height of the font, which is usually the distance from the bottom of a "g" to the top of an "M". Windows defines a negative font size as the character height of the font, which is typically the height of an "M".

Font.getStock

Syntax
public static Font getStock( int index );
Parameters
index
The stock font index as defined in wfc.win32.Windows.
Return Value

Returns the stock font that corresponds to the specified index.

Description

Retrieves a stock font, based on a specified index.

Font.getStrikeout

Syntax
public boolean getStrikeout();
Return Value

Returns true if the font is a strike-through font; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current font is a strike-through font.

Font.getUnderline

Syntax
public boolean getUnderline();
Return Value

Returns true if the font is underlined; Otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the font is underlined.

Font.getWeight

Syntax
public int getWeight();
Return Value

Returns one of the enumeration values defined in the FontWeight class.

Description

Retrieves the weight associated with this font.

See Also
FontWeight

Font.hashCode

Syntax
public int hashCode();
Return Value

Returns a hash code value for this font.

Description

Retrieves a hash code value for this font.

Font.save

Syntax
public void save( IDataStream stream );
Parameters
stream
The stream to which to persist the font information.
Description

Persists this font to the given datastream.

See Also
IPersistable


 Form Class

Form Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Form
public class Form
extends Control

Represents the basic top-level window.

Constructors
Name | Description
Form() | Creates a new form.
addOwnedForm(Form ownedForm) | Adds an owned form to this form.
removeOwnedForm(Form ownedForm) | Removes a form from the list of owned forms.

Methods
Name | Description
add(Control control) | Adds a control to the form.
addOnClosed(EventHandler value) | Adds an event handler for the Closed event.
addOnClosing(CancelEventHandler value) | Adds an event handler for the Closing event.
addOnInputLangChange( InputLangChangeEventHandler value) | Adds an event handler for the InputLangChange event.
addOnInputLangChangeRequest( InputLangChangeRequestEventHandler value) | Adds an event handler for the InputLangChangeRequest event.
addOnMDIChildActivate(EventHandler value) | Adds an event handler for the MDIChildActivate event.
adjustFormScrollbars( boolean displayScrollbars) | Adjust the automatic scroll bars on the form based on current control positions and the current selected control.
createControl() | Topic under construction.
createHandle() | Creates the handle for the form.
defWndProc(Message m) | Calls the default window proc for the form.
dispose() | Releases all the system resources associated with the form.
fillInCreateParamsBorderIcons(CreateParams cp) | Adjusts the window style of the CreateParams to reflect the border icons.
fillInCreateParamsBorderStyles(CreateParams cp) | Adjusts the window style of the CreateParams to reflect the border style.
fillInCreateParamsStartPosition(CreateParams cp) | Adjusts the CreateParams to reflect the window bounds and start position.
fillInCreateParamsWindowState(CreateParams cp) | Adjusts the Createparams to reflect the window state.
getAcceptButton() | Retrieves the current acceptButton.
getActiveControl() | Retrieves the current active control.
getActiveMDIChild() | Retrieves the current MDIChild window that is active.
getAutoScale() | Retrieves the current value of the AutoScale property.
getAutoScaleBaseSize() | Retrieves the base size used for autoscaling.
getAutoScroll() | Retrieves the current value of the AutoScroll property.
getAutoScrollMargin() | Retrieves the current value of the AutoScrollMargin property.
getAutoScrollPosition() | Retrieves the current value of the AutoScrollPosition property.
getAxContainer() | Topic under construction.
getBorderStyle() | Retrieves the current value of the BorderStyle property.
getCancelButton() | Retrieves the current CancelButton.
getClientSize() | Retrieves the current clientSize of the form.
getControlBox() | Retrieves the current value of the ControlBox property.
getCreateParams() | Retrieves the CreateParams used to create the window.
getDesktopBounds() | Retrieves the bounds of the form in desktop coordinates.
getDesktopLocation() | Retrieves the location of the form in desktop coordinates.
getDialogResult() | Retrieves the current value of the DialogResult property.
getDisplayRect() | Retreives the current display rectangle.
getForm() | Retrieves the form that this control is parented to.
getFormState(int flag) | Retrieves the bits associated with the requested formstate.
getHelpButton() | Retrieves the current value of the HelpButton property.
getHScroll() | Retrieves the current value of the HScroll property.
getIcon() | Returns the current value of the Icon property.
getIsMDIChild() | Returns a boolean indicating whether this form is an MDI child form.
getIsMDIContainer() | Returns a boolean indicating whether this form is an MDI container.
getIsMenuBarContainer() | Returns a boolean indicating whether this form is a Menu Bar Container.
getKeyPreview() | Returns the current value of the KeyPreview property.
getMaxButton() | Returns the current value of the MaxButton property.
getMaximizedBounds() | Returns the maximized bounds of the form.
getMaxTrackSize() | Returns the maximum size the form can be resized to.
getMDIClient() | Returns the control that is the MDI Client region.
getMDIParent() | Returns the current MDI parent of this form.
getMenu() | Returns the current Menu for this form.
getMergedMenu() | Returns the merged menu for the form.
getMinButton() | Returns the current value of the MinButton property.
getMinTrackSize() | Returns the minimum size the form can be resized to.
getModal() | Returns the modal status of the form.
getOwnedForms() | Returns an array of forms that are owned by this form.
getOwner() | Returns the owner of this form.
getPalette() | Returns the palette currently being used by the form.
getPaletteMode() | Returns the current value of the PaletteMode property.
getPaletteSource() | Returns the current value of the PaletteSource property.
getParentForm() | Returns the form that is the visual parent of this form.
getShowInTaskbar() | Returns the current value of the ShowInTaskbar property.
getStartPosition() | Returns the current value of the StartPosition property.
getWindowState() | Returns the current value of the WindowState property.
hasDefaultAutoScrollPosition() | Topic under construction.
hasFormState(int flag) | Returns whether any of the bits in the mask are on.
invalidateFrame() | Forces a WM_WINDOWPOSCHANGED message to be sent that tells the form that the frame has changed.
invalidateMergedMenu() | Invalidates the merged menu, forcing the menu to be re-created if needed again.
layoutCore(Control dockLast) | Forces the layout of any docked or anchored child controls.
layoutMDI(int value) | Arranges the MDI child forms according to value, which should be a member of the MDILayout enum.
menuChanged(int change, Menu menu) | Topic under construction.
menuChanged(int change, Menu menu, Form form) | Topic under construction.
onClosed(Event e) | The Closed event is fired when the form is closed.
onClosing(CancelEvent e) | The Closing event is fired when the form is closed.
onInputLangChange(InputLangChangeEvent e) | The InputLangChange event is fired after the input language has changed for this form.
onInputLangChangeRequest( InputLangChangeRequestEvent e) | The InputLangChangeRequest event is fired when the user attempts to change the input language for this form.
onMDIChildActivate(Form form) | This function handles the activation of a MDI child form.
onMDIChildActivate(Event e) | The MDIChildActivate event is fired when a MDI Child window is activated.
onNewPalette(boolean fForceBackground) | Topic under construction.
onResize(Event event) | The Resize event is fired when the form is resized.
pointToScreen(Point p) | Topic under construction.
processCmdKey(MSG msg, int keyData) | Topic under construction.
processDialogChar(char charCode) | Topic under construction.
processDialogKey(int keyData) | Topic under construction.
processKeyPreview(Message m) | Topic under construction.
processMnemonic(char charCode) | Topic under construction.
propertyChanged(int property) | Topic under construction.
rectToClient(Rectangle r) | Topic under construction.
rectToScreen(Rectangle r) | Topic under construction.
removeOnClosed(EventHandler value) | Removes an event handler for the Closed event.
removeOnClosing(CancelEventHandler value) | Removes an event handler for the Closing event.
removeOnInputLangChange( InputLangChangeEventHandler value) | Removes an event handler for the InputLangChange event.
removeOnInputLangChangeRequest( InputLangChangeRequestEventHandler value) | Removes an event handler for the InputLangChangeRequest event.
removeOnMDIChildActivate(EventHandler value) | Removes an event handler for the MDIChildActivate event.
resumeUpdateMenuHandles() | Decrements updateMenuHandleSuspendCount.
scaleCore(float x, float y) | Base function that performs scaling of the form.
select(boolean directed, boolean forward) | Selects this form, and optionally selects the next/previous control.
setAcceptButton(IButtonControl button) | Sets the control that is the AcceptButton.
setActiveControl(Control value) | Sets the control that is currently active.
setAutoScale(boolean value) | Sets the AutoScale property.
setAutoScaleBaseSize(int value) | Sets the AutoScaleBaseSize.
setAutoScroll(boolean value) | Sets the AutoScroll property.
setAutoScrollMargin(Point value) | Sets the margins used during AutoScrolling.
setAutoScrollPosition(Point value) | Sets the default position of the AutoScroll region.
setBorderStyle(int borderStyle) | Sets the border style for the form.
setCancelButton(IButtonControl button) | Sets the cancelButton for the Form.
setClientSize(Point clientSize) | Sets the clientSize of the form.
setControlBox(boolean controlBox) | Sets the value for the ControlBox property.
setDesktopBounds(Rectangle bounds) | Sets the bounds of the Form in desktop coordinates.
setDesktopBounds(int x, int y, int width, int height) | Sets the bounds of the form in desktop coordinates.
setDesktopLocation(Point loc) | Sets the location of the form in desktop coordinates.
setDesktopLocation(int x, int y) | Sets the location of the form in desktop coordinates.
setDialogResult(int value) | Sets the value that will be returned from the form when it is displayed as a modal dialog.
setFormState(int flag, boolean value) | This will turn all the bits on or off for the specified FORMSTATE_* property.
setFormState(int flag, int value) | This will set the value of the specified FORMSTATE_* property.
setHelpButton(boolean helpButton) | Sets the HelpButton property.
setIcon(Icon icon) | Sets the icon to be displayed in the caption bar of the form.
setIsMDIContainer(boolean value) | Sets the value for the IsMDIContainer property.
setKeyPreview(boolean keyPreview) | Sets the KeyPreview property.
setMaxButton(boolean maxButton) | Sets the value for the MaxButton property.
setMDIParent(Form form) | Sets the MDIParent for this form.
setMenu(MainMenu value) | Sets the main menu for this form.
setMinButton(boolean minButton) | Sets the value for the MinButton property.
setNewControls(Control[] ctls) | Topic under construction.
setOwner(Form owner) | Sets the owner for this form.
setPaletteMode(int paletteMode) | Sets the PaletteMode for the Form.
setPaletteSource(Control paletteSource) | Sets the source for the form's palette if the Form PaletteMode is FormPaletteMode.USE_CONTROL.
setParentHandle(int value) | Sets the HWND parent of this form.
setShowInTaskbar(boolean showInTaskbar) | Sets the ShowInTaskbar property.
setStartPosition(int startPosition) | Sets the StartPosition for the form.
setVisible(boolean value) | Sets the visibility of the form.
setWindowState(int windowState) | Sets the WindowState of the form.
showDialog() | Shows this form as a modal dialog with no owner.
showDialog(Form owner) | Shows this form as a modal dialog with the specified owner.
suspendUpdateMenuHandles() | Increments updateMenuHandleSuspendCount.
updateMenuHandles(MainMenu menu, boolean forceRedraw) | Topic under construction.
updateStyles() | Topic under construction.
wndProc(Message m) | Base wndProc encapsulation.

Constructors

Form.Form

Syntax
public Form();
Description

Creates a new form.

Form.addOwnedForm

Syntax
public void addOwnedForm( Form ownedForm );
Parameters
ownedForm
Form to make owned by this form.
Description

Adds an owned form to this form. Owned forms are other top-level forms that are children of this form.

Form.removeOwnedForm

Syntax
public void removeOwnedForm( Form ownedForm );
Parameters
ownedForm
Form to remove.
Description

Removes a form from the list of owned forms. Also sets the owner of the removed form to null.

See Also
addOwnedForm

Methods

Form.add

Syntax
public void add( Control control );
Parameters
control
Control to add to the form.
Description

Adds a control to the form. This visually parents the specified control to the form.

Overrides

add(Control) in Control.

See Also
remove

Form.addOnClosed

Syntax
public void addOnClosed( EventHandler value );
Parameters
value
Delegate to call when the event is fired.
Description

Adds an event handler for the Closed event. The Closed event is fired when the form is closed.

See Also
wfc.core.EventHandler, removeOnClosed

Form.addOnClosing

Syntax
public void addOnClosing( CancelEventHandler value );
Parameters
value
Delegate to call when the event is fired.
Description

Adds an event handler for the Closing event. The Closing event is fired when the form is closed.

See Also
wfc.core.CancelEventHandler, removeOnClosing

Form.addOnInputLangChange

Syntax
public void addOnInputLangChange( InputLangChangeEventHandler value );
Parameters
value
Delegate to call when the event is fired.
Description

Adds an event handler for the InputLangChange event. The InputLangChange event is fired after the input language has changed for this form.

See Also
wfc.ui.InputLangChangeEventHandler, removeOnInputLangChange

Form.addOnInputLangChangeRequest

Syntax
public void addOnInputLangChangeRequest( InputLangChangeRequestEventHandler value );
Parameters
value
Delegate to call when the event is fired.
Description

Adds an event handler for the InputLangChangeRequest event. The InputLangChangeRequest event is fired when the user attempts to change the input language for this form. If the event is canceled, the input language will not change.

See Also
wfc.ui.InputLangChangeRequestEventHandler, removeOnInputLangChangeRequest

Form.addOnMDIChildActivate

Syntax
public void addOnMDIChildActivate( EventHandler value );
Parameters
value
Delegate to call when the event is fired.
Description

Adds an event handler for the MDIChildActivate event. The MDIChildActivate occurs when a MDIChild window is activated.

See Also
wfc.core.EventHandler, removeOnMDIChildActivate

Form.adjustFormScrollbars

Syntax
protected final void adjustFormScrollbars( boolean displayScrollbars );
Parameters
displayScrollbars
Determines if the scroll bars should be displayed.
Description

Adjust the automatic scroll bars on the form based on current control positions and the current selected control.

See Also
getAutoScroll

Form.createControl

Syntax
public void createControl();
Description

Topic under construction.

Overrides

createControl() in Control.

Form.createHandle

Syntax
protected void createHandle();
Description

Creates the handle for the form. If a subclass overrides this function, it must call the super implementation.

Overrides

createHandle() in Control.

See Also
Control.createHandle

Form.defWndProc

Syntax
protected void defWndProc( Message m );
Description

Calls the default window proc for the form. If a subclass overrides this function, it must call the super implementation.

Overrides

defWndProc(Message) in Control.

See Also
Control.defWndProc

Form.dispose

Syntax
public void dispose();
Description

Releases all the system resources associated with the form. If a subclass overrides this function, it must call the super implementation.

Overrides

dispose() in Control.

Form.fillInCreateParamsBorderIcons

Syntax
protected void fillInCreateParamsBorderIcons( CreateParams cp );
Parameters
cp
CreateParams to modify.
Description

Adjusts the window style of the CreateParams to reflect the border icons. If a subclass overrides this function, it must call the super implementation.

Form.fillInCreateParamsBorderStyles

Syntax
protected void fillInCreateParamsBorderStyles( CreateParams cp );
Parameters
cp
CreateParams to modify.
Description

Adjusts the window style of the CreateParams to reflect the border style. If a subclass overrides this function, it must call the super implementation.

Form.fillInCreateParamsStartPosition

Syntax
protected void fillInCreateParamsStartPosition( CreateParams cp );
Parameters
cp
CreateParams to modify.
Description

Adjusts the CreateParams to reflect the window bounds and start position. If a subclass overrides this function, it must call the super implementation.

Form.fillInCreateParamsWindowState

Syntax
protected void fillInCreateParamsWindowState( CreateParams cp );
Parameters
cp
CreateParams to modify.
Description

Adjusts the Createparams to reflect the window state. If a subclass overrides this function, it must call the super implementation.

Form.getAcceptButton

Syntax
public IButtonControl getAcceptButton();
Return Value

Returns control that current is the acceptButton.

Description

Retrieves the current acceptButton.

See Also
setAcceptButton

Form.getActiveControl

Syntax
public Control getActiveControl();
Return Value

Returns current active control.

Description

Retrieves the current active control.

See Also
setActiveControl

Form.getActiveMDIChild

Syntax
public Form getActiveMDIChild();
Return Value

Returns active MDIChild window.

Description

Retrieves the current MDIChild window that is active. Returns null if there are no MDIChild windows.

Form.getAutoScale

Syntax
public boolean getAutoScale();
Return Value

Returns current value of the AutoScale property.

Description

Retrieves the current value of the AutoScale property. When AutoScale is set to true, the form will adjust the size of the form to fit the height of the font that is used on the form. All child controls will also be scaled. This allows the form to resize to fit systems with Large Fonts and international systems.

See Also
setAutoScale

Form.getAutoScaleBaseSize

Syntax
public final int getAutoScaleBaseSize();
Return Value

Returns base autoScaling size.

Description

Retrieves the base size used for autoscaling. The AutoScaleBaseSize is used internally to determine how much to scale the form when AutoScaling is used.

See Also
getAutoScaleBaseSize, setAutoScale

Form.getAutoScroll

Syntax
public boolean getAutoScroll();
Return Value

Returns current value of the AutoScroll property.

Description

Retrieves the current value of the AutoScroll property. When AutoScroll is set to true, the form will allow the user to scroll the contents of the form if any child controls are placed outside the bounds of the form. This allows the form to have a virtual size that is larger than the current form bounds.

See Also
setAutoScroll

Form.getAutoScrollMargin

Syntax
public Point getAutoScrollMargin();
Return Value

Returns current value of the AutoScrollMargin property.

Description

Retrieves the current value of the AutoScrollMargin property. The margins define the width and height of the border around each control. This border is used to determine when scroll bars are needed on the form and where to scroll to when a control is selected.

See Also
setAutoScrollMargin

Form.getAutoScrollPosition

Syntax
public final Point getAutoScrollPosition();
Return Value

Returns current value of the AutoScrollPosition property.

Description

Retrieves the current value of the AutoScrollPosition property. The AutoScrollPosition property is used internally to adjust the position of controls that are placed on the form through the form designer.

See Also
setAutoScrollPosition

Form.getAxContainer

Syntax
public AxHost.Container getAxContainer();
Description

Topic under construction.

Overrides

getAxContainer() in Control.

Form.getBorderStyle

Syntax
public int getBorderStyle();
Return Value

Returns current value of the BorderStyle property.

Description

Retrieves the current value of the BorderStyle property. The border style of the form determines how the outer edge of the form appears. In addition, certain border styles prevent the form from being sized.

See Also
setBorderStyle

Form.getCancelButton

Syntax
public IButtonControl getCancelButton();
Return Value

Returns current cancelButton.

Description

Retrieves the current CancelButton. The cancel button will be "clicked" when the user presses ESC.

See Also
setCancelButton

Form.getClientSize

Syntax
public Point getClientSize();
Return Value

Returns current clientSize of the form.

Description

Retrieves the current clientSize of the form. The clientSize of a form is the width and height of it's clientRect. The distinction between the clientRect and clientSize is that the clientSize can be set. It also represents the requested size of the clientRect.

Overrides

getClientSize() in Control.

See Also
setClientSize

Form.getControlBox

Syntax
public boolean getControlBox();
Return Value

Returns current value of the ControlBox property.

Description

Retrieves the current value of the ControlBox property. If ControlBox is set to true, the control box will be displayed in the upper- left corner of the caption bar. The control box is where the user can click to access the system menu.

See Also
setControlBox

Form.getCreateParams

Syntax
protected CreateParams getCreateParams();
Return Value

Returns CreateParams used to create the window.

Description

Retrieves the CreateParams used to create the window. If a subclass overrides this function, it must call the super implementation.

Overrides

getCreateParams() in Control.

See Also
Control.getCreateParams

Form.getDesktopBounds

Syntax
public Rectangle getDesktopBounds();
Return Value

Returns bounds of the form in desktop coordinates.

Description

Retrieves the bounds of the form in desktop coordinates.

See Also
setDesktopBounds

Form.getDesktopLocation

Syntax
public Point getDesktopLocation();
Return Value

Returns location of the form in desktop coordinates.

Description

Retrieves the location of the form in desktop coordinates.

See Also
setDesktopLocation

Form.getDialogResult

Syntax
public int getDialogResult();
Return Value

Returns current value of the DialogResult property.

Description

Retrieves the current value of the DialogResult property.

See Also
setDialogResult

Form.getDisplayRect

Syntax
public Rectangle getDisplayRect();
Return Value

Returns current display rectangle.

Description

Retreives the current display rectangle. The display rectangle is the virtual display area that is used to lay out components. The position and dimensions of the form's display rectangle change during autoScroll.

Overrides

getDisplayRect() in Control.

Form.getForm

Syntax
public Form getForm();
Return Value

Returns form that this form is parented to.

Description

Retrieves the form that this control is parented to.

Overrides

getForm() in Control.

Form.getFormState

Syntax
protected final int getFormState( int flag );
Return Value

Returns value of the formState property.

Description

Retrieves the bits associated with the requested formstate.

See Also
setFormState, hasFormState

Form.getHelpButton

Syntax
public boolean getHelpButton();
Return Value

Returns current value of the HelpButton property.

Description

Retrieves the current value of the HelpButton property. If HelpButton is set to true, a small question mark will appear in the caption bar to the left of the minimize, maximize, and close buttons.

See Also
setHelpButton

Form.getHScroll

Syntax
protected final boolean getHScroll();
Return Value

Returns true if the Auto-HorizScrollbar is visible.

Description

Retrieves the current value of the HScroll property.

See Also
setHScroll

Form.getIcon

Syntax
public Icon getIcon();
Return Value

Returns current value of the Icon property.

Description

Returns the current value of the Icon property.

See Also
setIcon

Form.getIsMDIChild

Syntax
public boolean getIsMDIChild();
Return Value

Returns true if this is an MDI child.

Description

Returns a boolean indicating whether this form is an MDI child form.

See Also
setMDIParent

Form.getIsMDIContainer

Syntax
public boolean getIsMDIContainer();
Return Value

Returns true if this form is an MDI container.

Description

Returns a boolean indicating whether this form is an MDI container.

Form.getIsMenuBarContainer

Syntax
public boolean getIsMenuBarContainer();
Return Value

Returns true if this form is a menu bar container

Description

Returns a boolean indicating whether this form is a Menu Bar Container.

Form.getKeyPreview

Syntax
public boolean getKeyPreview();
Return Value

Returns current value of the KeyPreview property.

Description

Returns the current value of the KeyPreview property.

See Also
setKeyPreview

Form.getMaxButton

Syntax
public boolean getMaxButton();
Return Value

Returns current value of the MaxButton property.

Description

Returns the current value of the MaxButton property.

See Also
setMaxButton

Form.getMaximizedBounds

Syntax
protected Rectangle getMaximizedBounds();
Return Value

Returns bounds of the form when it is maximized.

Description

Returns the maximized bounds of the form. Classes that extend form can override this function to provide new bounds for the form when it is maximized. This function is called when the form is being resized.

See Also
getMaxTrackSize, getMinTrackSize, SystemInformation.getPrimaryMonitorMaximizedWindowSize

Form.getMaxTrackSize

Syntax
protected Point getMaxTrackSize();
Return Value

Returns maximum size the form can be sized to.

Description

Returns the maximum size the form can be resized to. Classes that extend form can override this function to provide a new maximum size for the form. This function is called when the form is being resized.

See Also
getMaximizedBounds, getMinTrackSize, SystemInformation.getMaxWindowTrackSize

Form.getMDIClient

Syntax
public Control getMDIClient();
Return Value

Returns MDI Client control.

Description

Returns the control that is the MDI Client region.

Form.getMDIParent

Syntax
public Form getMDIParent();
Return Value

Returns current MDI parent of this form.

Description

Returns the current MDI parent of this form.

See Also
setMDIParent

Form.getMenu

Syntax
public MainMenu getMenu();
Return Value

Returns current Menu for this form.

Description

Returns the current Menu for this form.

See Also
setMenu

Form.getMergedMenu

Syntax
public MainMenu getMergedMenu();
Return Value

Returns merged menu.

Description

Returns the merged menu for the form. This is primarily used when this form is an MDI child that merges its menu with the parent form's menu.

Form.getMinButton

Syntax
public boolean getMinButton();
Return Value

Returns current value of the MinButton property.

Description

Returns the current value of the MinButton property.

See Also
setMinButton

Form.getMinTrackSize

Syntax
protected Point getMinTrackSize();
Return Value

Returns minimum size the form can be sized to.

Description

Returns the minimum size the form can be resized to. Classes that extend form can override this function to provide a new minimum size for the form. This function is called when the form is being resized.

See Also
getMaximizedBounds, getMaxTrackSize, SystemInformation.getMinWindowTrackSize

Form.getModal

Syntax
public boolean getModal();
Return Value

Returns s true if this form is currently modal.

Description

Returns the modal status of the form.

See Also
showDialog

Form.getOwnedForms

Syntax
public Form[] getOwnedForms();
Return Value

Returns s array of forms that are owned by this form.

Description

Returns an array of forms that are owned by this form.

See Also
addOwnedForm, removeOwnedForm

Form.getOwner

Syntax
public Form getOwner();
Return Value

Returns form that currently owns this form.

Description

Returns the owner of this form.

Form.getPalette

Syntax
public Palette getPalette();
Description

Returns the palette currently being used by the form.

Overrides

getPalette() in Control.

See Also
setPaletteMode, setPaletteSource

Form.getPaletteMode

Syntax
public int getPaletteMode();
Return Value

Returns current value of the PaletteMode property.

Description

Returns the current value of the PaletteMode property.

See Also
setPaletteMode

Form.getPaletteSource

Syntax
public Control getPaletteSource();
Return Value

Returns current value of the PaletteSource property.

Description

Returns the current value of the PaletteSource property.

See Also
setPaletteSource

Form.getParentForm

Syntax
public Form getParentForm();
Return Value

Returns current value of the ParentForm property.

Description

Returns the form that is the visual parent of this form.

See Also
setParent

Form.getShowInTaskbar

Syntax
public boolean getShowInTaskbar();
Return Value

Returns current value of the ShowInTaskbar property.

Description

Returns the current value of the ShowInTaskbar property.

See Also
setShowInTaskbar

Form.getStartPosition

Syntax
public int getStartPosition();
Return Value

Returns Current value of teh StartPosition property.

Description

Returns the current value of the StartPosition property.

See Also
setStartPosition

Form.getWindowState

Syntax
public int getWindowState();
Return Value

Returns current value of the WindowState property.

Description

Returns the current value of the WindowState property.

See Also
setWindowState

Form.hasDefaultAutoScrollPosition

Syntax
public boolean hasDefaultAutoScrollPosition();
Description

Topic under construction.

Form.hasFormState

Syntax
protected final boolean hasFormState( int flag );
Return Value

Returns true if any of the bits are on.

Description

Returns whether any of the bits in the mask are on.

See Also
setFormState, getFormState

Form.invalidateFrame

Syntax
protected void invalidateFrame();
Description

Forces a WM_WINDOWPOSCHANGED message to be sent that tells the form that the frame has changed.

Form.invalidateMergedMenu

Syntax
protected void invalidateMergedMenu();
Description

Invalidates the merged menu, forcing the menu to be re-created if needed again.

Form.layoutCore

Syntax
protected void layoutCore( Control dockLast );
Description

Forces the layout of any docked or anchored child controls.

Overrides

layoutCore(Control) in Control.

Form.layoutMDI

Syntax
public void layoutMDI( int value );
Description

Arranges the MDI child forms according to value, which should be a member of the MDILayout enum.

See Also
wfc.ui.MDILayout

Form.menuChanged

Syntax 1
public void menuChanged( int change, Menu menu );
Description

Topic under construction.

Syntax 2
public void menuChanged( int change, Menu menu, Form form );
Description

Topic under construction.

Form.onClosed

Syntax
protected void onClosed( Event e );
Description

The Closed event is fired when the form is closed.

See Also
addOnClosed, removeOnClosed, wfc.core.Event

Form.onClosing

Syntax
protected void onClosing( CancelEvent e );
Description

The Closing event is fired when the form is closed.

See Also
addOnClosing, removeOnClosing, wfc.core.CancelEvent

Form.onInputLangChange

Syntax
protected void onInputLangChange( InputLangChangeEvent e );
Description

The InputLangChange event is fired after the input language has changed for this form.

See Also
addOnInputLangChange, removeOnInputLangChange, wfc.ui.InputLangChangeEvent

Form.onInputLangChangeRequest

Syntax
protected void onInputLangChangeRequest( InputLangChangeRequestEvent e );
Description

The InputLangChangeRequest event is fired when the user attempts to change the input language for this form. If the event is canceled, the input language will not change.

See Also
addOnInputLangChangeRequest, removeOnInputLangChangeRequest, wfc.ui.InputLangChangeRequestEvent

Form.onMDIChildActivate

Syntax 1
protected void onMDIChildActivate( Form form );
Parameters
form
Form that is being activated.
Description

This function handles the activation of a MDI child form. If a subclass overrides this function, it must call super.onMDIChildActivate.

Syntax 2
protected void onMDIChildActivate( Event e );
Description

The MDIChildActivate event is fired when a MDI Child window is activated.

See Also
addOnMDIChildActivate, removeOnMDIChildActivate, Event

Form.onNewPalette

Syntax
protected boolean onNewPalette( boolean fForceBackground );
Description

Topic under construction.

Form.onResize

Syntax
protected void onResize( Event event );
Description

The Resize event is fired when the form is resized.

Overrides

onResize(Event) in Control.

See Also
addOnResize, removeOnResize, Event

Form.pointToScreen

Syntax
public Point pointToScreen( Point p );
Description

Topic under construction.

Overrides

pointToScreen(Point) in Control.

Form.processCmdKey

Syntax
protected boolean processCmdKey( MSG msg, int keyData );
Description

Topic under construction.

Overrides

processCmdKey(MSG,int) in Control.

Form.processDialogChar

Syntax
protected boolean processDialogChar( char charCode );
Description

Topic under construction.

Overrides

processDialogChar(char) in Control.

Form.processDialogKey

Syntax
protected boolean processDialogKey( int keyData );
Description

Topic under construction.

Overrides

processDialogKey(int) in Control.

Form.processKeyPreview

Syntax
protected boolean processKeyPreview( Message m );
Description

Topic under construction.

Form.processMnemonic

Syntax
protected boolean processMnemonic( char charCode );
Description

Topic under construction.

Overrides

processMnemonic(char) in Control.

Form.propertyChanged

Syntax
protected void propertyChanged( int property );
Description

Topic under construction.

Overrides

propertyChanged(int) in Control.

Form.rectToClient

Syntax
public Rectangle rectToClient( Rectangle r );
Description

Topic under construction.

Overrides

rectToClient(Rectangle) in Control.

Form.rectToScreen

Syntax
public Rectangle rectToScreen( Rectangle r );
Description

Topic under construction.

Overrides

rectToScreen(Rectangle) in Control.

Form.removeOnClosed

Syntax
public void removeOnClosed( EventHandler value );
Parameters
value
Delegate to remove from the list of delegates to fire for this event.
Description

Removes an event handler for the Closed event.

See Also
onClose

Form.removeOnClosing

Syntax
public void removeOnClosing( CancelEventHandler value );
Parameters
value
Delegate to remove from the list of delegates to fire for this event.
Description

Removes an event handler for the Closing event.

See Also
onClose

Form.removeOnInputLangChange

Syntax
public void removeOnInputLangChange( InputLangChangeEventHandler value );
Parameters
value
Delegate to remove from the list of delegates to fire for this event.
Description

Removes an event handler for the InputLangChange event.

See Also
onInputLangChange

Form.removeOnInputLangChangeRequest

Syntax
public void removeOnInputLangChangeRequest( InputLangChangeRequestEventHandler value );
Parameters
value
Delegate to remove from the list of delegates to fire for this event.
Description

Removes an event handler for the InputLangChangeRequest event.

See Also
onInputLangChangeRequest

Form.removeOnMDIChildActivate

Syntax
public void removeOnMDIChildActivate( EventHandler value );
Parameters
value
Delegate to remove from the list of delegates to fire for this event.
Description

Removes an event handler for the MDIChildActivate event.

See Also
onMDIChildActivate

Form.resumeUpdateMenuHandles

Syntax
protected void resumeUpdateMenuHandles();
Description

Decrements updateMenuHandleSuspendCount. If updateMenuHandleSuspendCount becomes zero and updateMenuHandlesDeferred is true, updateMenuHandles is called.

See Also
suspendUpdateMenuHandles

Form.scaleCore

Syntax
protected void scaleCore( float x, float y );
Parameters
x
Percentage to scale the form horizontally.
y
Percentage to scale the form vertically.
Description

Base function that performs scaling of the form.

Overrides

scaleCore(float,float) in Control.

See Also
Control.scaleCore

Form.select

Syntax
public void select( boolean directed, boolean forward );
Parameters
directed
If set to true, the active control is changed
forward
Controls the direction in which focus is moved. If set to true, the next control is selected; otherwise, the previous control is selected.
Description

Selects this form, and optionally selects the next/previous control.

Overrides

select(boolean,boolean) in Control.

Form.setAcceptButton

Syntax
public void setAcceptButton( IButtonControl button );
Parameters
button
Control to use as the AcceptButton.
Description

Sets the control that is the AcceptButton. This control must implement IButtonControl to be used as the acceptButton.

See Also
getAcceptButton

Form.setActiveControl

Syntax
public void setActiveControl( Control value );
Parameters
value
Control to make active.
Description

Sets the control that is currently active.

See Also
getActiveControl

Form.setAutoScale

Syntax
public void setAutoScale( boolean value );
Parameters
value
Value for the AutoScale property.
Description

Sets the AutoScale property. When AutoScalling is turned on, the form will rescale the form based on the base font size when it is created. This makes the form display correctly on large font systems and systems that have a larger default font than what the form was designed on.

See Also
getAutoScale

Form.setAutoScaleBaseSize

Syntax
public void setAutoScaleBaseSize( int value );
Parameters
value
Value for AutoScaleBaseSize
Description

Sets the AutoScaleBaseSize. This value is used at form display time to compute the scaling factor for the form.

See Also
getAutoScaleBaseSize, setAutoScale

Form.setAutoScroll

Syntax
public void setAutoScroll( boolean value );
Parameters
value
Value for the AutoScroll property.
Description

Sets the AutoScroll property. When AutoScrolling is turned, scroll bars will be displayed on the form if any controls are located outside the client region of the form. This allows the user to scroll the client region to make the controls visible.

In addition, when AutoScrolling is on, the client region will automatically scroll to make the control with focus visible. This lets the user tab around the form and always see the control that has focus.

See Also
getAutoScroll, setAutoScrollMargin

Form.setAutoScrollMargin

Syntax
public void setAutoScrollMargin( Point value );
Parameters
value
Value for the AutoScrollMargin property.
Description

Sets the margins used during AutoScrolling. The margins define the width and height of the border around each control. This border is used to determine when scroll bars are needed on the form and where to scroll to when a control is selected.

See Also
getAutoAcrollMargin, setAutoScroll

Form.setAutoScrollPosition

Syntax
public void setAutoScrollPosition( Point value );
Parameters
value
Position for the AutoScroll region.
Description

Sets the default position of the AutoScroll region. This will not move the scroll region once the form has been created.

Form.setBorderStyle

Syntax
public void setBorderStyle( int borderStyle );
Parameters
borderStyle
New border style for the form. Must be a value from the FormBorderStyle class.
Description

Sets the border style for the form. Valid values are:

  FormBorderSytle.NONE
  FormBorderSytle.FIXED_SINGLE
  FormBorderSytle.SIZABLE
  FormBorderSytle.FIXED_DIALOG
  FormBorderSytle.FIXED_TOOLWINDOW
  FormBorderSytle.SIZABLE_TOOLWINDOW

See Also
getBorderStyle, wfc.ui.FormBorderStyle

Form.setCancelButton

Syntax
public void setCancelButton( IButtonControl button );
Parameters
button
Button to treat as the cancelButton.
Description

Sets the cancelButton for the Form. The cancelButton is "clicked" when the user presses ESC.

See Also
getCancelButton

Form.setClientSize

Syntax
public void setClientSize( Point clientSize );
Parameters
clientSize
Requested size of the client region.
Description

Sets the clientSize of the form. This will adjust the bounds of the form to make the clientSize the requested size.

Overrides

setClientSize(Point) in Control.

See Also
getClientSize

Form.setControlBox

Syntax
public void setControlBox( boolean controlBox );
Parameters
controlBox
Value for the ControlBox property.
Description

Sets the value for the ControlBox property. If ControlBox is set to true, there is an icon in the upper-left corner of the form that has the System menu on it.

See Also
getControlBox

Form.setDesktopBounds

Syntax 1
public void setDesktopBounds( Rectangle bounds );
Parameters
bounds
New bounds for the Form in desktop coordinates.
Description

Sets the bounds of the Form in desktop coordinates.

See Also
setDesktopBounds(int, int, int, int)

Syntax 2
public void setDesktopBounds( int x, int y, int width, int height );
Parameters
x
The x location for the form.
y
The y location for the form.
width
Width for the form.
height
Height for the form.
Description

Sets the bounds of the form in desktop coordinates. Desktop coordinates are based on the working area of the screen, which excludes the taskbar.

See Also
setDesktopBounds(Rectangle)

Form.setDesktopLocation

Syntax 1
public void setDesktopLocation( Point loc );
Parameters
loc
Location for the form.
Description

Sets the location of the form in desktop coordinates.

See Also
setDesktopLocation(int, int), setDesktopBounds(int, int, int, int)

Syntax 2
public void setDesktopLocation( int x, int y );
Parameters
x
The x location for the form.
y
The y location for the form.
Description

Sets the location of the form in desktop coordinates.

See Also
setDesktopLocation(Point), setDesktopBounds(int, int, int, int)

Form.setDialogResult

Syntax
public void setDialogResult( int value );
Parameters
value
Value to return.
Description

Sets the value that will be returned from the form when it is displayed as a modal dialog.

See Also
getDialogResult, showDialog

Form.setFormState

Syntax 1
protected final void setFormState( int flag, boolean value );
Parameters
flag
FORMSTATE_* property.
value
Set to true to turn property on; set to false to turn it off.
Description

This will turn all the bits on or off for the specified FORMSTATE_* property.

See Also
setFormState(int, int), getFormState, hasFormState

Syntax 2
protected final void setFormState( int flag, int value );
Parameters
flag
FORMSTATE_* property.
value
Value to set the property to.
Description

This will set the value of the specified FORMSTATE_* property.

See Also
setFormState(int, boolean), getFormState, hasFormState

Form.setHelpButton

Syntax
public void setHelpButton( boolean helpButton );
Parameters
helpButton
New value for the HelpButton property.
Description

Sets the HelpButton property. If HelpButton is true, a "What's This" Help icon will be displayed in the caption bar of the form.

See Also
getHelpButton

Form.setIcon

Syntax
public void setIcon( Icon icon );
Parameters
icon
Icon to display.
Description

Sets the icon to be displayed in the caption bar of the form.

See Also
getIcon

Form.setIsMDIContainer

Syntax
public void setIsMDIContainer( boolean value );
Parameters
value
New value for the IsMDIContainer property.
Description

Sets the value for the IsMDIContainer property. If this is set to true, this form can contain other forms in an MDI fashion.

See Also
getIsMDIContainer

Form.setKeyPreview

Syntax
public void setKeyPreview( boolean keyPreview );
Parameters
keyPreview
New value for the KeyPreview property.
Description

Sets the KeyPreview property. When KeyPreview is set to true, the form will recieve key events for all the contained controls before the control. This allows the form to catch events such as ENTER, and so forth.

See Also
getKeyPreview

Form.setMaxButton

Syntax
public void setMaxButton( boolean maxButton );
Parameters
maxButton
New value for the MaxButton property.
Description

Sets the value for the MaxButton property. If MaxButton is true, the maximize button is displayed in the caption bar of the form.

See Also
getMaxButton

Form.setMDIParent

Syntax
public void setMDIParent( Form form );
Parameters
form
Form to make this MDI parent of this form.
Description

Sets the MDIParent for this form. The MDIParent must be marked as an MDI container for this to succeed.

See Also
getMDIParent

Form.setMenu

Syntax
public void setMenu( MainMenu value );
Parameters
value
Menu for this form.
Description

Sets the main menu for this form.

See Also
getMenu

Form.setMinButton

Syntax
public void setMinButton( boolean minButton );
Parameters
minButton
New value for the MinButton property.
Description

Sets the value for the MinButton property. If MinButton is true, the minimize button is displayed in the caption bar of the form.

See Also
getMinButton

Form.setNewControls

Syntax
public void setNewControls( Control[] ctls );
Description

Topic under construction.

Overrides

setNewControls(Control[]) in Control.

Form.setOwner

Syntax
public void setOwner( Form owner );
Parameters
owner
New owner for this form.
Description

Sets the owner for this form. This is the same as calling owner.addOwnedForm(this).

See Also
getOwner, addOwnedForm, removeOwnedForm

Form.setPaletteMode

Syntax
public void setPaletteMode( int paletteMode );
Description

Sets the PaletteMode for the Form. Valid values are:

  FormPaletteMode.HALFTONE
  FormPaletteMode.NONE
  FormPaletteMode.USE_CONTORL

See Also
getPaletteMode, wfc.ui.FormPaletteMode

Form.setPaletteSource

Syntax
public void setPaletteSource( Control paletteSource );
Description

Sets the source for the form's palette if the Form PaletteMode is FormPaletteMode.USE_CONTROL.

See Also
getPaletteSource, setPaletteMode

Form.setParentHandle

Syntax
public void setParentHandle( int value );
Parameters
value
HWND of the new parent for this form.
Description

Sets the HWND parent of this form.

Overrides

setParentHandle(int) in Control.

Form.setShowInTaskbar

Syntax
public void setShowInTaskbar( boolean showInTaskbar );
Parameters
showInTaskbar
New value for the ShowInTaskbar property.
Description

Sets the ShowInTaskbar property. If ShowInTaskbar is true, the form will be displayed in the Windows taskbar.

See Also
getShowInTaskbar

Form.setStartPosition

Syntax
public void setStartPosition( int startPosition );
Parameters
startPosition
New value for the StartPosition.
Description

Sets the StartPosition for the form. Valid values are:

  FormStartPosition.MANUAL
  FormStartPosition.WINDOWS_DEFAULT_LOCATION
  FormStartPosition.WINDOWS_DEFAULT_BOUNDS
  FormStartPosition.CENTER_SCREEN

See Also
getStartPosition, wfc.ui.FormStartPosition

Form.setVisible

Syntax
public void setVisible( boolean value );
Parameters
value
Set to true if the form should be visible.
Description

Sets the visibility of the form.

Overrides

setVisible(boolean) in Control.

See Also
getVisible

Form.setWindowState

Syntax
public void setWindowState( int windowState );
Description

Sets the WindowState of the form. Valid values are:

  FormWindowState.NORMAL
  FormWindowState.MAXIMIZED
  FormWindowState.MINIMIZED

See Also
getWindowState, wfc.ui.FormWindowState

Form.showDialog

Syntax 1
public final int showDialog();
Return Value

Returns The DialogResult from the form.

Description

Shows this form as a modal dialog with no owner.

See Also
showDialog(Form)

Syntax 2
public final int showDialog( Form owner );
Parameters
owner
Form that will own the modal dialog.
Return Value

Returns The DialogResult from the form.

Description

Shows this form as a modal dialog with the specified owner.

See Also
showDialog()

Form.suspendUpdateMenuHandles

Syntax
protected void suspendUpdateMenuHandles();
Description

Increments updateMenuHandleSuspendCount.

See Also
resumeUpdateMenuHandles

Form.updateMenuHandles

Syntax
protected void updateMenuHandles( MainMenu menu, boolean forceRedraw );
Description

Topic under construction.

Form.updateStyles

Syntax
public void updateStyles();
Description

Topic under construction.

Overrides

updateStyles() in Control.

Form.wndProc

Syntax
protected void wndProc( Message m );
Parameters
m
Message sent.
Description

Base wndProc encapsulation.

Overrides

wndProc(Message) in Control.


 FormBorderStyle Class

FormBorderStyle Class

This Package | All Packages

Enum
  |
  +--BorderStyle
    |
    +--FormBorderStyle
public class FormBorderStyle
extends BorderStyle

Enumeration class that represents the border styles of a form.

Fields
Name | Description
FIXED_DIALOG | The associated form will have a thick, fixed dialog-style border.
FIXED_TOOLWINDOW | The associated form will have a nonresizable tool window border.
MAX | Topic under construction.
MIN | Topic under construction.
SIZABLE | The associated form will have a fully resizable border.
SIZABLE_TOOLWINDOW | The associated form will have a resizable tool window border.

Fields

FormBorderStyle.FIXED_DIALOG

Syntax
public static final int FIXED_DIALOG;
Description
The associated form will have a thick, fixed dialog-style border.

FormBorderStyle.FIXED_TOOLWINDOW

Syntax
public static final int FIXED_TOOLWINDOW;
Description
The associated form will have a nonresizable tool window border.

FormBorderStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

FormBorderStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

FormBorderStyle.SIZABLE

Syntax
public static final int SIZABLE;
Description
The associated form will have a fully resizable border.

FormBorderStyle.SIZABLE_TOOLWINDOW

Syntax
public static final int SIZABLE_TOOLWINDOW;
Description
The associated form will have a resizable tool window border.


 FormPaletteMode Class

FormPaletteMode Class

This Package | All Packages

Enum
  |
  +--FormPaletteMode
public class FormPaletteMode
extends Enum

Topic under construction.

Fields
Name | Description
HALFTONE | Topic under construction.
NONE | Topic under construction.
USE_CONTROL | Topic under construction.

Fields

FormPaletteMode.HALFTONE

Syntax
public static final int HALFTONE;
Description
Topic under construction.

FormPaletteMode.NONE

Syntax
public static final int NONE;
Description
Topic under construction.

FormPaletteMode.USE_CONTROL

Syntax
public static final int USE_CONTROL;
Description
Topic under construction.


 FormStartPosition Class

FormStartPosition Class

This Package | All Packages

Enum
  |
  +--FormStartPosition
public class FormStartPosition
extends Enum

Specifies form start position values.

Fields
Name | Description
CENTER_SCREEN | The form will be centered on the primary monitor and will have the dimensions specified in the form's size.
MANUAL | The location and size of the form will determine the starting position.
WINDOWS_DEFAULT_BOUNDS | The form will be positioned at the Windows default location and will have the bounds determined by Windows default.
WINDOWS_DEFAULT_LOCATION | The form will be positioned at the Windows default location and will have the dimensions specified in the form's size.

Fields

FormStartPosition.CENTER_SCREEN

Syntax
public static final int CENTER_SCREEN;
Description
The form will be centered on the primary monitor and will have the dimensions specified in the form's size.

FormStartPosition.MANUAL

Syntax
public static final int MANUAL;
Description
The location and size of the form will determine the starting position.

FormStartPosition.WINDOWS_DEFAULT_BOUNDS

Syntax
public static final int WINDOWS_DEFAULT_BOUNDS;
Description
The form will be positioned at the Windows default location and will have the bounds determined by Windows default.

FormStartPosition.WINDOWS_DEFAULT_LOCATION

Syntax
public static final int WINDOWS_DEFAULT_LOCATION;
Description
The form will be positioned at the Windows default location and will have the dimensions specified in the form's size.


 FormWindowState Class

FormWindowState Class

This Package | All Packages

Enum
  |
  +--FormWindowState
public class FormWindowState
extends Enum

Topic under construction.

Fields
Name | Description
MAXIMIZED | Topic under construction.
MINIMIZED | Topic under construction.
NORMAL | Topic under construction.

Fields

FormWindowState.MAXIMIZED

Syntax
public static final int MAXIMIZED;
Description
Topic under construction.

FormWindowState.MINIMIZED

Syntax
public static final int MINIMIZED;
Description
Topic under construction.

FormWindowState.NORMAL

Syntax
public static final int NORMAL;
Description
Topic under construction.


 GiveFeedbackEvent Class

GiveFeedbackEvent Class

This Package | All Packages

Event
  |
  +--GiveFeedbackEvent
public class GiveFeedbackEvent
extends Event

Topic under construction.

Fields
Name | Description
effect | Topic under construction.
useDefaultCursors | Topic under construction.

Constructors
Name | Description
GiveFeedbackEvent(int effect, boolean useDefaultCursors) | Topic under construction.

Fields

GiveFeedbackEvent.effect

Syntax
public final int effect;
Description
Topic under construction.

GiveFeedbackEvent.useDefaultCursors

Syntax
public boolean useDefaultCursors;
Description
Topic under construction.

Constructors

GiveFeedbackEvent.GiveFeedbackEvent

Syntax
public GiveFeedbackEvent( int effect, boolean useDefaultCursors );
Description

Topic under construction.


 Graphics Class

Graphics Class

This Package | All Packages

public class Graphics

Encapsulates a Win 32 device context (DC) and the drawing operations that are typically performed on a DC. These operations include the drawing of standard shapes, such as pies and arcs, as well as the drawing of Windows controls, such as buttons and check boxes. The Graphics object automatically performs garbage collection, freeing the resources allocated for various drawing objects. In addition, you can call the object's dispose method to enforce the cleanup of these resources. A Graphics object that is connected to a Windows control is valid only as long as that control continues to process its messages. For example, if a control processes its onPaint message, the Graphics object that is passed as a parameter to onPaint is valid only until onPaint returns.

Constructors
Name | Description
Graphics(int dc) | The class constructor.
Graphics(int dc, int hWnd, Brush brush, Font font, Color textColor, Color backColor) | This constructor makes it possible for a Control object to construct a Graphics object and to initialize the object with the contol's device context, font, brush, and color values.

Methods
Name | Description
clearClipRect() | Clears the clip rectangle
clearRect(Rectangle rect) | Clears the specified rectangle by filling with the background color for the Grapics object.
clearRect(int x, int y, int width, int height) | Clears the specified rectangle by filling it with the background color for the Graphics object.
dispose() | Disposes of this Graphics object, freeing all resources allocated internally by the object.
drawAngleArc(Point center, int radius, float startAngle, float endAngle) | Draws a line segment and an arc.
drawAngleArc(int centerX, int centerY, int radius, float startAngle, float endAngle) | Draws a line segment and an arc.
drawAngleArc(Point center, int radius, float startAngle, float endAngle, RasterOp op) | Draws a line segment and an arc, and then applies a raster operation to the drawing.
drawAngleArc(int centerX, int centerY, int radius, float startAngle, float endAngle, RasterOp op) | Draws a line segment and an arc, and applies a raster operation to the drawing.
drawArc(Rectangle rect, Point start, Point end) | Draws an elliptical arc in the specified bounding rectangle.
drawArc(Rectangle rect, Point start, Point end, RasterOp op) | Draws an elliptical arc in the specified bounding rectangle, and applies a raster operation to the drawing.
drawArc(int x, int y, int width, int height, int startX, int startY, int endX, int endY) | Draws an elliptical arc.
drawArc(int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op) | Draws an elliptical arc, and applies a raster operation to the drawing.
drawBezier(Point [] points) | Draws one or more cubic B&#-23;zier curves by using the endpoints and control points specified by the array of Point objects.
drawBezier(Point [] points, RasterOp op) | Draws one or more cubic B&#-23;zier curves by using the endpoints and control points specified by the array of Point objects.
drawBorder3D(Rectangle rect) | Draws a three-dimensional style border around the specified rectangle, using the default three-dimensional style of Border3DStyle.ETCHED.
drawBorder3D(Rectangle rect, int style) | Draws a three-dimensional style border around a rectangle, using the specified style.
drawBorder3D(Rectangle rect, int style, int sides) | Draws a three-dimensional style border around the specified rectangle.
drawBorder3D(int x, int y, int width, int height) | Draws a three-dimensional style border around a rectangle, using the default three-dimensional style of Border3DStyle.ETCHED.
drawBorder3D(int x, int y, int width, int height, int style) | Draws a three-dimensional style border around a rectangle, using a specified style.
drawBorder3D(int x, int y, int width, int height, int style, int sides) | Draws a three-dimensional style border around the specified rectangle.
drawButton(Rectangle rect, int state) | Draws a button control in the specified rectangle.
drawButton(int x, int y, int width, int height, int state) | Draws a Win32 button control in the specified rectangle.
drawCaptionButton(Rectangle rect, int button, int state) | Draws a Win32 window caption button in the specified rectangle.
drawCaptionButton(int x, int y, int width, int height, int button, int state) | Draws a Win32 window caption button in the specified rectangle.
drawCheckBox(Rectangle rect, int state) | Draws a Win32 checkbox control in the specified rectangle.
drawCheckBox(int x, int y, int width, int height, int state) | Draws a Win32 checkbox control in the specified rectangle.
drawChord(Rectangle rect, Point start, Point end) | Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant").
drawChord(Rectangle rect, Point start, Point end, RasterOp op) | Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"), and applies a raster operation to the drawing.
drawChord(int x, int y, int width, int height, int startX, int startY, int endX, int endY) | Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant").
drawChord(int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op) | Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant").
drawComboButton(Rectangle rect, int state) | Draws the drop-down button of a Win32 combo box in the specified rectangle.
drawComboButton(int x, int y, int width, int height, int state) | Draws the drop-down button of a Win32 combo box in the specified rectangle.
drawDragRect(Rectangle lpRect, Point size, Rectangle lpRectLast, Point sizeLast, Brush pBrush, Brush pBrushLast) drawEllipse
public final void drawEllipse(Rectangle rect);

Draws an ellipse in the specified bounding rectangle.

drawEllipse(Rectangle rect) | Draws an ellipse in the specified bounding box.
drawEllipse(int x, int y, int width, int height) | Draws an ellipse inside the specified bounding box, and applies a raster operation to the drawing.
drawEllipse(Rectangle rect, RasterOp op) | Draws an ellipse inside the specified bounding box, and applies the specified raster operation to the drawing.
drawEllipse(int x, int y, int width, int height, RasterOp op) | Draws a Windows "focus rectangle," which is a dotted rectangle that Windows uses to indicate that a specified control has the focus.
drawFocusRect(Rectangle r) | Draws a Windows "focus rectangle," which is a dotted rectangle that Windows uses to indicate that a specified control has the focus.
drawFocusRect(int x, int y, int width, int height) | Draws an image at the specified point.
drawImage(Image i, Point pt) | Draws the specified image at the specified point.
drawImage(Image i, int x, int y) | Draws an image at the specified point, and applies a raster to the drawing.
drawImage(Image i, Point pt, RasterOp op) | Draws an image at the specified point, and applies raster operation to the drawing.
drawImage(Image i, int x, int y, RasterOp op) | Draws an image in the specified rectangle.
drawImage(Image i, Rectangle r, boolean scale) | Draws the specified image in the specified rectangle.
drawImage(Image i, int x, int y, int width, int height, boolean scale) | Draws an image in the specified rectangle.
drawImage(Image i, Rectangle r, RasterOp op, boolean scale) | Draws an image in the specified rectangle.
drawImage(Image i, int x, int y, int width, int height, RasterOp op, boolean scale) | Draws a line between two points, using the current pen.
drawLine(Point p1, Point p2) | Draws a line from the first set of points to the second, using the current pen.
drawLine(int x1, int y1, int x2, int y2) | Draws a line from the first point to the second using the current pen, and applies a raster operation to the drawing.
drawLine(Point p1, Point p2, RasterOp op) | Draws a line from the first set of points to the second using the current pen, and applies raster operation to the drawing.
drawLine(int x1, int y1, int x2, int y2, RasterOp op) | Draws a series of connected lines based on an array of points.
drawLines(Point [] points) | Draws a series of connected lines based on an array of points, and applies a raster operation to the drawing.
drawLines(Point [] points, RasterOp op) | Draws a line from the current mouse position to the specified position.
drawLineTo(Point p) | Draws a line from the current mouse position to the specified position.
drawLineTo(int x, int y) | Draws a line from the current mouse position to the specified position, and applies a raster operation to the drawing.
drawLineTo(Point p, RasterOp op) | Draws a line from the current mouse position to the specified position, and then applies a raster operation to the drawing.
drawLineTo(int x, int y, RasterOp op) | Draws a menu glyph for a Win32 menu in the specified rectangle.
drawMenuGlyph(Rectangle rect, int glyph) | Draws a menu glyph for a Win32 menu in the specified rectangle.
drawMenuGlyph(int x, int y, int width, int height, int glyph) | Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials.
drawPie(Rectangle rect, Point start, Point end) | Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials, and then applies a raster operation to the drawing.
drawPie(Rectangle rect, Point start, Point end, RasterOp op) | Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials.
drawPie(int x, int y, int width, int height, int startX, int startY, int endX, int endY) | Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials, and then applies a raster operation to the drawing.
drawPie(int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op) | Draws a polygon based on a specified array of vertices.
drawPolygon(Point [] vertices) | Draws a polygon based on a specified array of vertices.
drawPolygon(Point [] vertices, RasterOp op) | Draws a polygon based on a specified array of vertices.
drawPolygon(Point [] vertices, RasterOp op, boolean alternate) | Draws a Win32 radio button in the specified rectangle.
drawRadioButton(Rectangle rect, int state) | Draws a Win32 radio button in the specified rectangle.
drawRadioButton(int x, int y, int width, int height, int state) | Draws a rectangle using the specified rectangle.
drawRect(Rectangle rect) | Draws a rectangle using the specified coordinates.
drawRect(int x, int y, int width, int height) | Draws a rectangle using the specified rectangle.
drawRect(Rectangle rect, RasterOp op) | Draws a rectangle using the specified coordinates, and then applies a raster operation to the drawing.
drawRect(int x, int y, int width, int height, RasterOp op) | Draws a rectangle with rounded corners using the current pen and fill brush.
drawRoundedRect(Rectangle rect, int radius) | Draws a rectangle with rounded corners using the current pen and fill brush.
drawRoundedRect(Rectangle rect, int radius, RasterOp op) | Draws a rectangle with rounded corners using the current pen and fill brush.
drawRoundedRect(int x, int y, int width, int height, int radius) | Draws a rectangle with rounded corners, using the current pen and fill brush, and then applies a raster operation to the drawing.
drawRoundedRect(int x, int y, int width, int height, int radius, RasterOp op) | Draws a button for a Win32 scroll bar.
drawScrollButton(Rectangle rect, int button, int state) | Draws a button for a Win32 scroll bar.
drawScrollButton(int x, int y, int width, int height, int button, int state) | Draws a sizing grip at the specified location.
drawSizeGrip(Rectangle rect) | Draws a sizing grip at the specified location.
drawSizeGrip(int x, int y, int width, int height) | Draws a string at the specified point.
drawString(String s, Point p) | Draws a string at the specified point.
drawString(String s, int x, int y) | Draws and formats a string in the specified bounding rectangle.
drawString(String s, Rectangle rect, int format) | Draws and formats a string within the specified bounding rectangle.
drawString(String s, int x, int y, int width, int height, int format) | Draws a string at a point in the specified clipping rectangle.
drawString(String s, Point p, Rectangle clip) | Draws a string at the specified point in a clipping rectangle.
drawString(String s, int x, int y, int clipX, int clipY, int clipWidth, int clipHeight) | Draws a string at the specified point using an array of tab stops to determine the tab positions.
drawString(String s, Point p, int [] tabStops) | Draws a string at the specified point using an array of tab stops to determine the tab positions.
drawString(String s, int x, int y, int [] tabStops) excludeClipRect
public int excludeClipRect(Rectangle lpRect);
excludeClipRect(int x1, int y1, int x2, int y2) | Fills an area of the display surface with the current brush.
excludeClipRect(Rectangle lpRect) | Fills an area of the display surface with the current brush.
fillBorder(Point start, Color color) | Fills an area of the display surface with the current brush.
fillBorder(int x, int y, Color color) | Fills an area of the display surface with the current brush.
fillSurface(Point start, Color color) | Ensures that all resources allocated by the Graphics object have been freed.
fillSurface(int x, int y, Color color) | Retrieves the current background color for the Graphics object.
finalize() | Retrieves the current brush for the Graphics object.
getBackColor() | Retrieves the origin Graphics object's current brush.
getBrush() | Retrieves the current font for the Graphics object.
getBrushOrigin() | Retrieves an array of FontDescriptor objects, which contains an entry for each font installed on the system.
getFont() | Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified character set.
getFontDescriptors() | Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified face name.
getFontDescriptors(int charSet) | Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified name and character set.
getFontDescriptors(String name) | Retrieves the handle to the device context used to construct the Graphics object.
getFontDescriptors(int charSet, String name) | Retrieves a boolean value that indicates whether the current background setting is opaque.
getHandle() | Retrieves the current pen for the Graphics object.
getOpaque() | Retrieves the color of the pixel at the specified point.
getPen() | Retrieves the color of the pixel at the specified point.
getPixel(Point pt) | Retrieves the closest solid color that the hardware will use for the specified color.
getPixel(int x, int y) | Retrieves the current text color for the Graphics object.
getSolidColor(Color color) | Retrieves the area required to display the specified text using the current font settings.
getTextColor() | Retrieves the area required to display the specified string, using the current font settings.
getTextSize(String text) | Retrieves the area required to display the specified text string, using the current font settings.
getTextSize(String text, int [] tabStops) | Retrieves the amount of extra space to be used between characters when drawing text.
getTextSize(String text, int width, int format) intersectClipRect
public int intersectClipRect(Rectangle lpRect);
getTextSpace() | Inverts the pixels in the specified rectangle.
intersectClipRect(int x1, int y1, int x2, int y2) | Inverts the pixels in the specified rectangle.
intersectClipRect(Rectangle lpRect) | Scrolls an area of the graphics object.
invertRect(Rectangle rect) | Sets the background color used to fill empty regions.
invertRect(int x, int y, int width, int height) | Sets the current brush for the Graphics object.
scroll(int scrollX, int scrollY, Rectangle scrollArea, Rectangle clipArea) | Sets the brush origin for the Graphics object.
setBackColor(Color color) | Sets the brush origin for the Graphics object.
setBrush(Brush brush) | Sets the current font for the Graphics object.
setBrushOrigin(Point pt) | Sets the background fill mode for this Graphics object.
setBrushOrigin(int x, int y) | Sets the drawing pen for the Graphics object.
setFont(Font font) | Sets a pixel to the current foreground (text) color.
setOpaque(boolean opaque) | Sets a pixel to the current foreground (text) color.
setPen(Pen pen) | Sets a pixel to the specified color.
setPixel(Point pt) | Sets a pixel to the specified color.
setPixel(int x, int y) | Sets a pixel to the specified color, and applies a raster operation to the pixel.
setPixel(Point pt, Color color) | Sets the color to be used when drawing text.
setPixel(int x, int y, Color color) | Sets the amount of extra space to be used between characters when drawing text.
setPixel(int x, int y, Color color, RasterOp op)
setTextColor(Color color) | Clears the clip rectangle
setTextSpace(int space) | Clears the specified rectangle by filling with the background color for the Grapics object.

Constructors

Graphics.Graphics

Syntax 1
public Graphics( int dc );
Parameters
dc
The handle to a device context (HDC).
Description

The class constructor. The Graphics class constructor initializes a Graphics object based on the specified device context handle.

Syntax 2
protected Graphics( int dc, int hWnd, Brush brush, Font font, Color textColor, Color backColor );
Parameters
dc
The handle to a device context.
hWnd
The handle to the window that owns the device context.
brush
The brush to use with this Graphics object.
font
The font to use with this Graphics object.
textColor
The default text color for the Graphics object.
backColor
The background color to use when painting this Graphics object.
Description

This constructor makes it possible for a Control object to construct a Graphics object and to initialize the object with the contol's device context, font, brush, and color values. If the device context passed to this constructor is null, the constructor verifies that sufficient resources are available to create a device context and then retrieves the device context based on the specified window handle. Finally, this constructor verifies that sufficient resources are available for the creation of the device context.

Methods

Graphics.clearClipRect

Syntax
public final void clearClipRect();
Description

Clears the clip rectangle

Graphics.clearRect

Syntax 1
public final void clearRect( Rectangle rect );
Parameters
rect
The Rectangle to clear.
Description

Clears the specified rectangle by filling with the background color for the Grapics object.

Syntax 2
public final void clearRect( int x, int y, int width, int height );
Parameters
x
The x coordinate of the top left of the rectangle.
y
The y coordinate of the top left of the rectangle.
width
The width of the rectangle.
height
The height of the rectangle.
Description

Clears the specified rectangle by filling it with the background color for the Graphics object.

Graphics.dispose

Syntax
public void dispose();
Description

Disposes of this Graphics object, freeing all resources allocated internally by the object. Because the garbage collector automatically performs object cleanup, it is usually unnecessary for you to call this method.

Graphics.drawAngleArc

Syntax 1
public final void drawAngleArc( Point center, int radius, float startAngle, float endAngle );
Parameters
center
The center of the arc circle.
radius
The radius of the circle.
startAngle
The start angle, in degrees, relative to the x-axis.
endAngle
The end angle, in degrees, relative to the starting angle.
Description

Draws a line segment and an arc. The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the specified radius and center. The length of the arc is defined by the specified start and end angles. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees specified in startAngle. Similarly, the ending point is located by measuring counterclockwise from the starting point by the number of degrees specified in endAngle.

Syntax 2
public final void drawAngleArc( int centerX, int centerY, int radius, float startAngle, float endAngle );
Parameters
centerX
The x coordinate of the center of the arc circle.
centerY
The y coordinate of the center of the arc circle.
radius
The radius of the circle.
startAngle
The start angle, in degrees, relative to the x-axis.
endAngle
The end angle, in degrees, relative to startAngle.
Description

Draws a line segment and an arc. The line segment is drawn from the current position to the beginning of the arc. The arc is drawn along the perimeter of a circle with the specified radius and center. The length of the arc is defined by the specified start and end angles. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees specified in the start angle. Similarly, the ending point is located by measuring counterclockwise from the starting point by the number of degrees specified in the end angle.

Syntax 3
public final void drawAngleArc( Point center, int radius, float startAngle, float endAngle, RasterOp op );
Parameters
center
A Point object that specifies the x and y positions of the center of the circle.
radius
The radius of the circle.
startAngle
The start angle, in degrees, relative to the x-axis.
endAngle
The end angle, in degrees, relative to startAngle.
op
The raster operation to apply to the line.
Description

Draws a line segment and an arc, and then applies a raster operation to the drawing. The line segment is drawn from the current position to the beginning of the arc and is drawn along the perimeter of a circle with the specified radius and center. The length of the arc is defined by the specified start and end angles. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees in startAngle. Similarly, the ending point is located by measuring counterclockwise from the starting point by the number of degrees specified in endAngle.

Syntax 4
public final void drawAngleArc( int centerX, int centerY, int radius, float startAngle, float endAngle, RasterOp op );
Parameters
centerX
The x coorinate of the center of the arc circle.
centerY
The y coorinate of the center of the arc circle.
radius
The radius of the circle.
startAngle
The start angle, in degrees, relative to the x-axis.
endAngle
The end angle, in degrees, relative to the starting angle.
op
The raster operation to apply to the line.
Description

Draws a line segment and an arc, and applies a raster operation to the drawing. The line segment is drawn from the current position to the beginning of the arc and is drawn along the perimeter of a circle with the specified radius and center. The length of the arc is defined by the specified start and end angles. The starting point of the arc is determined by measuring counterclockwise from the x-axis of the circle by the number of degrees specified in startAngle. Similarly, the ending point is located by measuring counterclockwise from the starting point by the number of degrees specified in endAngle.

Graphics.drawArc

Syntax 1
public final void drawArc( Rectangle rect, Point start, Point end );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the arc.
end
The ending point for the arc.
Description

Draws an elliptical arc in the specified bounding rectangle. The center of the arc is the center of the specified bounding rectangle. From the center, the arc extends in the current drawing direction to the specified starting point. Next,the arc declines from the center to the specified ending point. If the starting point and ending point are the same, a complete ellipse is drawn. The arc is always drawn counterclockwise.

Syntax 2
public final void drawArc( Rectangle rect, Point start, Point end, RasterOp op );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the arc.
end
The ending point for the arc.
op
The raster operation to apply to the drawing.
Description

Draws an elliptical arc in the specified bounding rectangle, and applies a raster operation to the drawing. The center of the arc is the center of the specified bounding rectangle. The arc extends in the current drawing direction from the point at which it intersects the center of the bounding rectangle to the specified starting point. The arc declines from the point at which it intersects the radial at the center of the bounding rectangle to the specified ending point. If the starting point and ending point are the same, a complete ellipse is drawn. The arc is always drawn counterclockwise.

Syntax 3
public final void drawArc( int x, int y, int width, int height, int startX, int startY, int endX, int endY );
Parameters
x
The x coordinate of the top left of the bounding rectangle for the ellipse.
y
The y coordinate of the top left of the bounding rectangle for the ellipse.
width
The width of the bounding rectangle for the ellipse.
height
The height of the bounding rectangle for the ellipse.
startX
The x coordinate of the starting point for the arc.
startY
The y coordinate of the starting point for the arc.
endX
The x coordinate of the ending point for the arc.
endY
The y coordinate of the ending point for the arc.
Description

Draws an elliptical arc. The center of the arc is the center of the rectangle whose origin (x, y) and whose size is specified by the width and height arguments. The arc extends in the current drawing direction from the point at which it intersects the center of the rectangle to the specified starting point. The arc declines from the point at which it intersects the radial at the center of the bounding rectangle to the specified ending point. If the starting point and ending point are the same, a complete ellipse is drawn. The arc is always drawn counterclockwise.

Syntax 4
public final void drawArc( int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op );
Parameters
x
The x coordinate of the top left of the bounding rectangle for the ellipse.
y
The y coordinate of the top left of the bounding rectangle for the ellipse.
width
The width of the bounding rectangle for the ellipse.
height
The height of the bounding rectangle for the ellipse.
startX
The x coordinate of the starting point for the arc.
startY
The y coordinate of the starting point for the arc.
endX
The x coordinate of the ending point for the arc.
endY
The y coordinate of the ending point for the arc.
op
The raster operation to apply to the drawing.
Description

Draws an elliptical arc, and applies a raster operation to the drawing. The center of the arc is the center of the rectangle whose origin (x, y) and whose size is specified by the width and height arguments. The arc extends in the current drawing direction from the point at which it intersects the center of the rectangle to the specified starting point. The arc declines from the point at which it intersects the radial at the center of the bounding rectangle to the specified ending point. If the starting point and ending point are the same, a complete ellipse is drawn. The arc is always drawn counterclockwise.

Graphics.drawBezier

Syntax 1
public final void drawBezier( Point [] points );
Parameters
points
An array of points used to draw the curves.
Description

Draws one or more cubic B&#-23;zier curves by using the endpoints and control points specified by the array of Point objects. The first curve is drawn from the first point to the fourth point using the second and third points as control points. Each subsequent curve in the sequence needs exactly three more points: the ending point of the previous curve is used as the starting point, the next two points in the sequence are control points, and the third point is used as the ending point.

Syntax 2
public final void drawBezier( Point [] points, RasterOp op );
Parameters
points
An array of points used to draw the curves.
op
The raster operation to apply to the lines being drawn.
Description

Draws one or more cubic B&#-23;zier curves by using the endpoints and control points specified by the array of Point objects. The first curve is drawn from the first point to the fourth point using the second and third points as control points. Each subsequent curve in the sequence needs exactly three more points: the ending point of the previous curve is used as the starting point, the next two points in the sequence are control points, and the third point is used as the ending point.

Graphics.drawBorder3D

Syntax 1
public final void drawBorder3D( Rectangle rect );
Parameters
rect
The rectangle around which to draw the border.
Description

Draws a three-dimensional style border around the specified rectangle, using the default three-dimensional style of Border3DStyle.ETCHED.

Syntax 2
public final void drawBorder3D( Rectangle rect, int style );
Parameters
rect
The rectangle around which to draw the border.
style
The three-dimensional style to use when drawing the border. This value must be one of the values defined in the Border3DStyle enumeration.
Description

Draws a three-dimensional style border around a rectangle, using the specified style.

Syntax 3
public final void drawBorder3D( Rectangle rect, int style, int sides );
Parameters
rect
The rectangle around which to draw the border.
style
The three-dimensional style to use when drawing the border. This value must be one of the values defined in the Border3DStyle enumeration.
sides
The sides of the rectangle you want to draw. This value must be one or more of the values defined in the Border3DSide enumeration.
Description

Draws a three-dimensional style border around the specified rectangle. You can specify the style of the three-dimensional appearance. You can also identify the sides of the three-dimensional rectangle you want to draw.

Syntax 4
public final void drawBorder3D( int x, int y, int width, int height );
Parameters
x
The x coordinate of the top left of the border rectangle.
y
The y coordinate of the top left of the border rectangle.
width
The width of the border rectangle.
height
The height of the border rectangle.
Description

Draws a three-dimensional style border around a rectangle, using the default three-dimensional style of Border3DStyle.ETCHED.

Syntax 5
public final void drawBorder3D( int x, int y, int width, int height, int style );
Parameters
x
The x coordinate of the top left of the border rectangle.
y
The y coordinate of the top left of the border rectangle.
width
The width of the border rectangle.
height
The height of the border rectangle.
style
The three-dimensional style to use when drawing the border. This value be one of the values defined in the Border3DStyle.
Description

Draws a three-dimensional style border around a rectangle, using a specified style.

Syntax 6
public final void drawBorder3D( int x, int y, int width, int height, int style, int sides );
Parameters
x
The x coordinate of the top left of the border rectangle.
y
The y coordinate of the top left of the border rectangle.
width
The width of the border rectangle.
height
The height of the border rectangle.
style
The three-dimensional style to use when drawing the border. This value must be one of the values defined in the Border3DStyle enumeration.
sides
The sides of the rectangle you want to draw. This value must be one or more of the values defined in the Border3DSide enumeration.
Description

Draws a three-dimensional style border around the specified rectangle. You can specify the style of the three-dimensional appearance. You can also identify the sides of the three-dimensional rectangle you want to draw.

Graphics.drawButton

Syntax 1
public final void drawButton( Rectangle rect, int state );
Parameters
rect
The coordiniates of the button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a button control in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawButton( int x, int y, int width, int height, int state );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 button control in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawCaptionButton

Syntax 1
public final void drawCaptionButton( Rectangle rect, int button, int state );
Parameters
rect
The coordiniates of the button to draw.
button
A CaptionButton enumeration value that identifies the caption button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 window caption button in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawCaptionButton( int x, int y, int width, int height, int button, int state );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
button
A CaptionButton enumeration value that identifies the caption button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 window caption button in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawCheckBox

Syntax 1
public final void drawCheckBox( Rectangle rect, int state );
Parameters
rect
The coordiniates of the button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 checkbox control in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawCheckBox( int x, int y, int width, int height, int state );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 checkbox control in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawChord

Syntax 1
public final void drawChord( Rectangle rect, Point start, Point end );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the chord.
end
The ending point for the chord.
Description

Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"). The chord is outlined using the current pen and filled using the current brush. The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point at which the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line segment drawn from the center of the ellipse to a specified endpoint on the ellipse.) The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

Syntax 2
public final void drawChord( Rectangle rect, Point start, Point end, RasterOp op );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the chord.
end
The ending point for the chord.
op
The raster operation to apply to the drawing.
Description

Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"), and applies a raster operation to the drawing. The chord is outlined using the current pen and filled using the current brush. The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point at which the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line segment drawn from the center of the ellipse to a specified endpoint on the ellipse.) The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

Syntax 3
public final void drawChord( int x, int y, int width, int height, int startX, int startY, int endX, int endY );
Parameters
x
The x coordinate of the top left of the bounding rect for the ellipse.
y
The y coordinate of the top left of the bounding rect for the ellipse.
width
The width of the bounding rectangle for the ellipse.
height
The height of the bounding rect for the ellipse.
startX
The x coordinate of the starting point for the chord.
startY
The y coordinate of the starting point for the chord.
endX
The x coordinate of the ending point for the chord.
endY
The y coordinate of the ending point for the chord.
Description

Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"). The chord is outlined using the current pen and filled using the current brush. The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point at which the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line segment drawn from the center of the ellipse to a specified endpoint on the ellipse.) The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

Syntax 4
public final void drawChord( int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op );
Parameters
x
The x coordinate of the top left of the bounding rectangle for the ellipse.
y
The y coordinate of the top left of the bounding rectangle for the ellipse.
width
The width of the bounding rectangle for the ellipse.
height
The height of the bounding rectangle for the ellipse.
startX
The x coordinate of the starting point for the chord.
startY
The y coordinate of the starting point for the chord.
endX
The x coordinate of the ending point for the chord.
endY
The y coordinate of the ending point for the chord.
op
The raster operation to apply to the drawing.
Description

Draws a chord (a region bounded by the intersection of an ellipse and a line segment, called a "secant"). The chord is outlined using the current pen and filled using the current brush. The curve of the chord is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point at which the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line segment drawn from the center of the ellipse to a specified endpoint on the ellipse.) The chord is closed by drawing a line from the intersection of the first radial and the curve to the intersection of the second radial and the curve.

Graphics.drawComboButton

Syntax 1
public final void drawComboButton( Rectangle rect, int state );
Parameters
rect
The coordiniates of the button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws the drop-down button of a Win32 combo box in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawComboButton( int x, int y, int width, int height, int state );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws the drop-down button of a Win32 combo box in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawDragRect

Syntax
public void drawDragRect( Rectangle lpRect, Point size, Rectangle lpRectLast, Point sizeLast, Brush pBrush, Brush pBrushLast );
Description

Graphics.drawEllipse

Syntax 1
public final void drawEllipse( Rectangle rect );
Parameters
rect
The bounding rectangle in which to draw the ellipse.
Description

Draws an ellipse in the specified bounding rectangle.

Syntax 2
public final void drawEllipse( int x, int y, int width, int height );
Parameters
x
The x coordinate of the top left corner of the bounding box.
y
The y coordinate of the top left corner of the bounding box.
width
The width of the bounding box.
height
The height of the bounding box.
Description

Draws an ellipse in the specified bounding box.

Syntax 3
public final void drawEllipse( Rectangle rect, RasterOp op );
Parameters
rect
The bounding rectangle in which to draw the ellipse.
op
The raster operation to apply to the drawing.
Description

Draws an ellipse inside the specified bounding box, and applies a raster operation to the drawing.

Syntax 4
public final void drawEllipse( int x, int y, int width, int height, RasterOp op );
Parameters
x
The x coordinate of the top left corner of the bounding box.
y
The y coordinate of the top left corner of the bounding box.
width
The width of the bounding box.
height
The height of the bounding box.
op
The raster operation to apply to the drawing.
Description

Draws an ellipse inside the specified bounding box, and applies the specified raster operation to the drawing.

Graphics.drawFocusRect

Syntax 1
public final void drawFocusRect( Rectangle r );
Parameters
r
The rectangle to draw.
Description

Draws a Windows "focus rectangle," which is a dotted rectangle that Windows uses to indicate that a specified control has the focus.

Syntax 2
public final void drawFocusRect( int x, int y, int width, int height );
Parameters
x
The x coordinate of upper-left corner of rectangle to draw.
y
The y coordinate of upper-left corner of rectangle to draw.
width
The width of rectangle to draw.
height
The height of rectangle to draw.
Description

Draws a Windows "focus rectangle," which is a dotted rectangle that Windows uses to indicate that a specified control has the focus.

Graphics.drawImage

Syntax 1
public final void drawImage( Image i, Point pt );
Parameters
i
The image to draw.
pt
The location at which to draw the image.
Description

Draws an image at the specified point.

Syntax 2
public final void drawImage( Image i, int x, int y );
Parameters
i
The image to be drawn.
x
The x coordinate of top left of image.
y
The y coordinate of top left of image.
Description

Draws the specified image at the specified point.

Syntax 3
public final void drawImage( Image i, Point pt, RasterOp op );
Parameters
i
The image to be drawn.
pt
The point at which to draw the image.
op
The raster operation to use to draw the image.
Description

Draws an image at the specified point, and applies a raster to the drawing.

Syntax 4
public final void drawImage( Image i, int x, int y, RasterOp op );
Parameters
i
The image to be drawn.
x
The x coordinate of top left of image.
y
The y coordinate of top left of image.
op
The raster operation to use to draw the image.
Description

Draws an image at the specified point, and applies raster operation to the drawing.

Syntax 5
public final void drawImage( Image i, Rectangle r, boolean scale );
Parameters
i
The image to draw.
r
The rectangle to which the image should be stretched or cropped.
scale
If scale is true, the image is scaled. Otherwise, the image is cropped.
Description

Draws an image in the specified rectangle. If scale is true, drawImage stretches or shrinks the image to fit the specified rectangle. Otherwise, drawImage crops the image.

Syntax 6
public final void drawImage( Image i, int x, int y, int width, int height, boolean scale );
Parameters
i
The image to be drawn.
x
The x coordinate of top left of the bounding rectangle.
y
The y coordiniate of top left of the bounding rectangle
width
The width of the bounding rectangle.
height
The height of the bounding rectangle.
scale
If scale is true, the image is scaled. Otherwise, the image is cropped.
Description

Draws the specified image in the specified rectangle. If scale is true, drawImage stretches or shrinks the image to fit the rectangle. Otherwise, drawImage crops the image.

Syntax 7
public final void drawImage( Image i, Rectangle r, RasterOp op, boolean scale );
Parameters
i
The image to be drawn.
r
The rectangle to which the image should be stretched or cropped.
op
The raster operation to use to draw the image.
scale
If scale is true, the image is scaled. Otherwise, the image is cropped.
Description

Draws an image in the specified rectangle. If scale is true, drawImage stretches or shrinks the image to fit the rectangle. Otherwise, drawImage crops the image.

Syntax 8
public final void drawImage( Image i, int x, int y, int width, int height, RasterOp op, boolean scale );
Parameters
i
The image to be drawn.
x
The x coordinate of top left of the bounding rectangle.
y
The y coordiniate of top left of the bounding rectangle.
width
The width of the bounding rectangle.
height
The height of the bounding rectangle.
op
The raster operation to use to draw the image.
scale
If scale is true, the image is scaled to fit the bounding rectangle. Otherwise, it is cropped.
Description

Draws an image in the specified rectangle. If scale is true, drawImage stretches or shrinks the image to fit the rectangle. Otherwise, drawImage crops the image.

Graphics.drawLine

Syntax 1
public final void drawLine( Point p1, Point p2 );
Parameters
p1
The starting point of the line.
p2
The ending point of the line.
Description

Draws a line between two points, using the current pen.

Syntax 2
public final void drawLine( int x1, int y1, int x2, int y2 );
Parameters
x1
The x coordinate of the line starting point.
y1
The y coordinate of the line starting point.
x2
The x coordinate of the line ending point.
y2
The y coordinate of the line ending point.
Description

Draws a line from the first set of points to the second, using the current pen.

Syntax 3
public final void drawLine( Point p1, Point p2, RasterOp op );
Parameters
p1
The starting point of the line.
p2
The ending point of the line.
op
The raster operation to use to draw the line.
Description

Draws a line from the first point to the second using the current pen, and applies a raster operation to the drawing.

Syntax 4
public final void drawLine( int x1, int y1, int x2, int y2, RasterOp op );
Parameters
x1
The x coordinate of the starting point of the line.
y1
The y coordinate of the starting point of the line.
x2
The x coordinate of line ending point.
y2
The y coordinate of line ending point.
op
The raster operation to use to draw the line.
Description

Draws a line from the first set of points to the second using the current pen, and applies raster operation to the drawing.

Graphics.drawLines

Syntax 1
public final void drawLines( Point [] points );
Parameters
points
An array of points to draw.
Description

Draws a series of connected lines based on an array of points.

Syntax 2
public final void drawLines( Point [] points, RasterOp op );
Parameters
points
An array of points to draw.
op
The raster operation to use to draw the lines.
Description

Draws a series of connected lines based on an array of points, and applies a raster operation to the drawing.

Graphics.drawLineTo

Syntax 1
public final void drawLineTo( Point p );
Parameters
p
The line ending position.
Description

Draws a line from the current mouse position to the specified position.

Syntax 2
public final void drawLineTo( int x, int y );
Parameters
x
The x coordinate of the line ending point.
y
The y coordinate of the line ending point.
Description

Draws a line from the current mouse position to the specified position.

Syntax 3
public final void drawLineTo( Point p, RasterOp op );
Parameters
p
The ending position of the line.
op
The raster operation to use to draw the line.
Description

Draws a line from the current mouse position to the specified position, and applies a raster operation to the drawing.

Syntax 4
public final void drawLineTo( int x, int y, RasterOp op );
Parameters
x
The x coordinate of the line ending point.
y
The y coordinate of the line ending point.
op
The raster operation to use to draw the line.
Description

Draws a line from the current mouse position to the specified position, and then applies a raster operation to the drawing.

Graphics.drawMenuGlyph

Syntax 1
public final void drawMenuGlyph( Rectangle rect, int glyph );
Parameters
rect
The coordiniates of the button to draw.
glyph
A MenuGlyph constant that determines the menu glyph to draw.
Description

Draws a menu glyph for a Win32 menu in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawMenuGlyph( int x, int y, int width, int height, int glyph );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
glyph
A MenuGlyph constant that determines the menu glyph to draw.
Description

Draws a menu glyph for a Win32 menu in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawPie

Syntax 1
public final void drawPie( Rectangle rect, Point start, Point end );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the pie.
end
The ending point for the pie.
Description

Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined using the current pen and is filled using the current brush. The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line drawn from the center of the ellipse to the specified endpoint on the ellipse.)

Syntax 2
public final void drawPie( Rectangle rect, Point start, Point end, RasterOp op );
Parameters
rect
The bounding rectangle for the ellipse.
start
The starting point for the pie.
end
The ending point for the pie.
op
The raster operation to apply to the drawing.
Description

Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials, and then applies a raster operation to the drawing. The pie is outlined using the current pen and is filled using the current brush. The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line drawn from the center of the ellipse to the specified endpoint on the ellipse.)

Syntax 3
public final void drawPie( int x, int y, int width, int height, int startX, int startY, int endX, int endY );
Parameters
x
The x coordinate of the top left of the bounding rect for the ellipse.
y
The y coordinate of the top left of the bounding rect for the ellipse.
width
The width of the bounding rect for the ellipse.
height
The height of the bounding rect for the ellipse.
startX
The x coordinate of the starting point for the pie.
startY
The y coordinate of the starting point for the pie.
endX
The x coordinate of the ending point for the pie.
endY
The y coordinate of the ending point for the pie.
Description

Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials. The pie is outlined using the current pen and is filled using the current brush. The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line drawn from the center of the ellipse to the specified endpoint on the ellipse.)

Syntax 4
public final void drawPie( int x, int y, int width, int height, int startX, int startY, int endX, int endY, RasterOp op );
Parameters
x
The x coordinate of the top left of the bounding rectangle for the ellipse.
y
The y coordinate of the top left of the bounding rectangle for the ellipse.
width
The width of the bounding rectangle for the ellipse.
height
The height of the bounding rectangle for the ellipse.
startX
The x coordinate of the starting point for the pie.
startY
The y coordinate of the starting point for the pie.
endX
The x coordinate of the ending point for the pie.
endY
The y coordinate of the ending point for the pie.
op
The raster operation to apply to the drawing.
Description

Draws a pie-shaped wedge bounded by the intersection of an ellipse and two radials, and then applies a raster operation to the drawing. The pie is outlined using the current pen and is filled using the current brush. The curve of the pie is defined by an ellipse that fits the specified bounding rectangle. The curve begins at the point where the ellipse intersects the first radial and extends counterclockwise to the point at which the ellipse intersects the second radial. (A radial is a line drawn from the center of the ellipse to the specified endpoint on the ellipse.)

Graphics.drawPolygon

Syntax 1
public final void drawPolygon( Point [] vertices );
Parameters
vertices
Array of points that define the vertices of the polygon. The array must consist of at least two points.
Description

Draws a polygon based on a specified array of vertices. This array must contain at least two elements. The polygon is drawn using the current pen and brush and is automatically closed.

Syntax 2
public final void drawPolygon( Point [] vertices, RasterOp op );
Parameters
vertices
Array of points that define the vertices of the polygon. The array must consist of at least two points.
op
A raster operation that determines how to draw the polygon lines.
Description

Draws a polygon based on a specified array of vertices. This array must contain at least two elements. The polygon is drawn using the current pen and brush, and is automatically closed.

Syntax 3
public final void drawPolygon( Point [] vertices, RasterOp op, boolean alternate );
Parameters
vertices
Array of points that define the vertices of the polygon. The array must consist of at least two points.
op
A raster operation that determines how to draw the polygon lines.
alternate
If true, the overlapping portions of the polygon are alternately filled. If false, the entire polygon is filled.
Description

Draws a polygon based on a specified array of vertices. This array must contain at least two elements. The polygon is automatically closed.

Graphics.drawRadioButton

Syntax 1
public final void drawRadioButton( Rectangle rect, int state );
Parameters
rect
The coordiniates of the button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 radio button in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawRadioButton( int x, int y, int width, int height, int state );
Parameters
x
The x coordinate of the upper left corner of the drawing rectangle.
y
The y coordinate of the upper left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a Win32 radio button in the specified rectangle.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawRect

Syntax 1
public final void drawRect( Rectangle rect );
Parameters
rect
The coordinates of the rectangle. The x and y coordinates specify the upper-left corner of the rectangle
Description

Draws a rectangle using the specified rectangle. The rectangle filled using the current brush, and the current pen is used to draw the rectangle's edge.

Syntax 2
public final void drawRect( int x, int y, int width, int height );
Parameters
x
The x coordinate of top left corner of rectangle.
y
The y coordinate of top left corner of rectangle.
width
The width of the rectangle.
height
The height of the rectangle.
Description

Draws a rectangle using the specified coordinates. The rectangle filled using the current brush, and the current pen is used to draw the rectangle's edge.

Syntax 3
public final void drawRect( Rectangle rect, RasterOp op );
Parameters
rect
The coordinates of the rectangle. The x and y are the upper-left corner of the rectangle.
op
The raster operation to apply to the rectangle's pen and brush.
Description

Draws a rectangle using the specified rectangle. The rectangle is filled using the current brush, and the current pen is used to draw the rectangle's edge.

Syntax 4
public final void drawRect( int x, int y, int width, int height, RasterOp op );
Parameters
x
The x coordinate of top left corner of rectangle.
y
The y coordinate of top left corner of rectangle.
width
The width of the rectangle.
height
The height of the rectangle.
op
The raster operation to apply to the rectangle's pen and brush.
Description

Draws a rectangle using the specified coordinates, and then applies a raster operation to the drawing. The rectangle is filled using the current brush, and the current pen is used to draw the rectangle's edge.

Graphics.drawRoundedRect

Syntax 1
public final void drawRoundedRect( Rectangle rect, int radius );
Parameters
rect
The rectangle to draw.
radius
The radius of each of the corners.
Description

Draws a rectangle with rounded corners using the current pen and fill brush.

Syntax 2
public final void drawRoundedRect( Rectangle rect, int radius, RasterOp op );
Parameters
rect
The rectangle to draw.
radius
The radius of each of the corners.
op
The raster operation to apply to the drawing.
Description

Draws a rectangle with rounded corners using the current pen and fill brush.

Syntax 3
public final void drawRoundedRect( int x, int y, int width, int height, int radius );
Parameters
x
The x coordinate of the rectangle's upper-left corner.
y
The y coordinate of the rectangle's upper-left corner.
width
The width of the rectangle.
height
The height of the rectangle.
radius
The radius of each of the corners.
Description

Draws a rectangle with rounded corners using the current pen and fill brush.

Syntax 4
public final void drawRoundedRect( int x, int y, int width, int height, int radius, RasterOp op );
Parameters
x
The x coordinate of the rectangle's upper-left corner.
y
The y coordinate of the rectangle's upper-left corner.
width
The width of the rectangle.
height
The height of the rectangle.
radius
The radius of each of the corners.
op
The raster operation to apply to the drawing.
Description

Draws a rectangle with rounded corners, using the current pen and fill brush, and then applies a raster operation to the drawing.

Graphics.drawScrollButton

Syntax 1
public final void drawScrollButton( Rectangle rect, int button, int state );
Parameters
rect
The coordiniates of the button to draw.
button
A ScrollButton enumeration value to determine the scroll bar button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a button for a Win32 scroll bar.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawScrollButton( int x, int y, int width, int height, int button, int state );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
button
A ScrollButton enumeration value to determine the scroll bar button to draw.
state
One or more ButtonState flags that determine how to draw the button.
Description

Draws a button for a Win32 scroll bar.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawSizeGrip

Syntax 1
public final void drawSizeGrip( Rectangle rect );
Parameters
rect
The coordiniates of the button to draw.
Description

Draws a sizing grip at the specified location. A sizing grip is usually located at the lower right corner of a window.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Syntax 2
public final void drawSizeGrip( int x, int y, int width, int height );
Parameters
x
The x coordinate of the upper-left corner of the drawing rectangle.
y
The y coordinate of the upper-left corner of the drawing rectangle.
width
The width of the button.
height
The height of the button.
Description

Draws a sizing grip at the specified location. A sizing grip is usually located at the lower-right corner of a window.

See Also
drawButton, drawCaptionButton, drawCheckBox, drawComboButton, drawMenuGlyph, drawRadioButton, drawScrollButton, drawSizeGrip

Graphics.drawString

Syntax 1
public final void drawString( String s, Point p );
Parameters
s
The string to draw.
p
The point at which to draw the string.
Description

Draws a string at the specified point.

Syntax 2
public final void drawString( String s, int x, int y );
Parameters
s
The string to draw.
x
The x coordinate at which to draw the string.
y
The y coordinate at which to draw the string.
Description

Draws a string at the specified point.

Syntax 3
public final void drawString( String s, Rectangle rect, int format );
Parameters
s
The string to draw.
rect
The rectangle in which to draw the string.
format
One or more TextFormat flags that describe how to format the string.
Description

Draws and formats a string in the specified bounding rectangle.

Syntax 4
public final void drawString( String s, int x, int y, int width, int height, int format );
Parameters
s
The string to draw
x
The x coordinate of the top left of the text bounding rectangle
y
wThe y coordinate of the top left of the text bounding rectangle
width
The width of text bounding rectangle.
height
The height of text bounding rectangle.
format
One or more TextFormat flags.
Description

Draws and formats a string within the specified bounding rectangle.

Syntax 5
public final void drawString( String s, Point p, Rectangle clip );
Parameters
s
The string to draw.
p
The point at which to draw the string.
clip
The clipping rectangle in which to draw the string.
Description

Draws a string at a point in the specified clipping rectangle.

Syntax 6
public final void drawString( String s, int x, int y, int clipX, int clipY, int clipWidth, int clipHeight );
Parameters
s
The string to draw.
x
The x coordinate at which to draw the string.
y
The y coordinate at which to draw the string.
clipX
The x coordinate of the top left of the clipping rectangle
clipY
The y coordinate of the top left of the clipping rectangle
clipWidth
The width of the clipping rectangle.
clipHeight
The height of the clipping rectangle.
Description

Draws a string at the specified point in a clipping rectangle.

Syntax 7
public final void drawString( String s, Point p, int [] tabStops );
Parameters
s
The string to draw.
p
The point at which to draw the string.
tabStops
An array of tab positions. If the array contains a single value, that value is used for all tab stops. If tabStops is null, a default of 8 is used for the tab width.
Description

Draws a string at the specified point using an array of tab stops to determine the tab positions.

Syntax 8
public final void drawString( String s, int x, int y, int [] tabStops );
Parameters
s
The string to draw
x
The x coordinate at which to draw the string.
y
The y coordinate at which to draw the string.
tabStops
An array of tab positions. If there is a single value in the array, that value is used for all tab stops. If tabStops is null, a default value of 8 is used for the tab width.
Description

Draws a string at the specified point using an array of tab stops to determine the tab positions.

Graphics.excludeClipRect

Syntax 1
public int excludeClipRect( int x1, int y1, int x2, int y2 );
Description

Syntax 2
public int excludeClipRect( Rectangle lpRect );
Description

Graphics.fillBorder

Syntax 1
public final void fillBorder( Point start, Color color );
Parameters
start
The starting point for the fill.
color
The color of the border on which the fill should stop.
Description

Fills an area of the display surface with the current brush. Windows assumes that the area to be filled is completely bounded by the color specified by the "color" parameter. The function begins filling at the point specified and continues in all directions until it reaches the boundary.

Syntax 2
public final void fillBorder( int x, int y, Color color );
Parameters
x
The x coordinate of the starting point for the fill.
y
The y coordinate of the starting point for the fill.
color
The color of the border on which the fill should stop.
Description

Fills an area of the display surface with the current brush. Windows assumes that the area to be filled is completely bounded by the color specified by the color parameter. The function begins filling at the point specified and continues in all directions until it reaches the boundary.

Graphics.fillSurface

Syntax 1
public final void fillSurface( Point start, Color color );
Parameters
start
The starting point for the fill.
color
The color of the area to fill.
Description

Fills an area of the display surface with the current brush. Windows assumes that the area to be filled is a single color. The fillSurface method begins to fill the area at the point specified and continues in all directions, filling all adjacent regions containing the specified color. The starting point must already be filled with the color specified in the color parameter.

Syntax 2
public final void fillSurface( int x, int y, Color color );
Parameters
x
The x coordinate of the starting point for the fill.
y
The y coordinate of the starting point for the fill.
color
The color of the area to fill.
Description

Fills an area of the display surface with the current brush. Windows assumes that the area to be filled is a single color. The fillSurface method begins to fill the area at the point specified and continues in all directions, filling all adjacent regions containing the specified color. The starting point must already be filled with the color specified in the color parameter.

Graphics.finalize

Syntax
public void finalize();
Description

Ensures that all resources allocated by the Graphics object have been freed.

Graphics.getBackColor

Syntax
public final Color getBackColor();
Return Value

Returns the current background color.

Description

Retrieves the current background color for the Graphics object.

Graphics.getBrush

Syntax
public final Brush getBrush();
Return Value

Returns the current brush if one is set; otherwise, returns null.

Description

Retrieves the current brush for the Graphics object.

Graphics.getBrushOrigin

Syntax
public final Point getBrushOrigin();
Return Value

Returns the current brush origin.

Description

Retrieves the origin Graphics object's current brush.

Graphics.getFont

Syntax
public final Font getFont();
Return Value

Returns the current font.

Description

Retrieves the current font for the Graphics object.

Graphics.getFontDescriptors

Syntax 1
public final FontDescriptor[] getFontDescriptors();
Return Value

Returns an array of FontDescriptor objects.

Description

Retrieves an array of FontDescriptor objects, which contains an entry for each font installed on the system.

See Also
FontDescriptor

Syntax 2
public final FontDescriptor[] getFontDescriptors( int charSet );
Parameters
charSet
The character set for which to search.
Return Value

Returns an array of FontDescriptor objects.

Description

Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified character set.

See Also
FontDescriptor

Syntax 3
public final FontDescriptor[] getFontDescriptors( String name );
Parameters
name
The font's face name.
Return Value

Returns an array of FontDescriptor objects.

Description

Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified face name.

See Also
FontDescriptor

Syntax 4
public final FontDescriptor[] getFontDescriptors( int charSet, String name );
Parameters
charSet
The character set for which to search.
name
The font's face name.
Return Value

Returns an array of FontDescriptor objects.

Description

Retrieves an array of FontDescriptor objects, which contains an entry for each font that matches the specified name and character set.

See Also
FontDescriptor

Graphics.getHandle

Syntax
public final int getHandle();
Return Value

Returns the handle to the device context (HDC).

Description

Retrieves the handle to the device context used to construct the Graphics object.

Graphics.getOpaque

Syntax
public final boolean getOpaque();
Return Value

Returns true if the background color should be used as a fill before drawing; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current background setting is opaque.

Graphics.getPen

Syntax
public final Pen getPen();
Return Value

Returns the current pen, if a pen is set; Otherwise, returns null.

Description

Retrieves the current pen for the Graphics object.

Graphics.getPixel

Syntax 1
public final Color getPixel( Point pt );
Parameters
pt
The point to retrieve.
Return Value

Returns the color of the pixel.

Description

Retrieves the color of the pixel at the specified point.

Syntax 2
public final Color getPixel( int x, int y );
Parameters
x
The x coordinate of the pixel to get.
y
The y coordinate of the pixel to get.
Return Value

Returns the color of the pixel.

Description

Retrieves the color of the pixel at the specified point.

Graphics.getSolidColor

Syntax
public final Color getSolidColor( Color color );
Parameters
color
The color you want to use to draw.
Return Value

Returns the color that will be used to draw.

Description

Retrieves the closest solid color that the hardware will use for the specified color.

Graphics.getTextColor

Syntax
public final Color getTextColor();
Return Value

Returns the text color for the Graphics object.

Description

Retrieves the current text color for the Graphics object.

Graphics.getTextSize

Syntax 1
public Point getTextSize( String text );
Parameters
text
The text for which to retrieve the size.
Return Value

Returns a Point with the width and height of the text.

Description

Retrieves the area required to display the specified text using the current font settings.

Syntax 2
public Point getTextSize( String text, int [] tabStops );
Parameters
text
A String that contains the text for which the size should be returned.
tabStops
Array of integers that specify the tabstops to use to format this text.
Return Value

Returns a point with the width and height of the text.

Description

Retrieves the area required to display the specified string, using the current font settings.

Syntax 3
public Point getTextSize( String text, int width, int format );
Parameters
text
A string that contains the text for which the size should be returned.
width
The margin width where text wrapping, if specified, will be applied.
format
The text format options that specify how the text should be drawn.
Return Value

Returns a point that specifies the width and height of the text on the Graphics object.

Description

Retrieves the area required to display the specified text string, using the current font settings.

Graphics.getTextSpace

Syntax
public final int getTextSpace();
Return Value

Returns an integer that specifies the amount of extra space.

Description

Retrieves the amount of extra space to be used between characters when drawing text.

Graphics.intersectClipRect

Syntax 1
public int intersectClipRect( int x1, int y1, int x2, int y2 );
Description

Syntax 2
public int intersectClipRect( Rectangle lpRect );
Description

Graphics.invertRect

Syntax 1
public final void invertRect( Rectangle rect );
Parameters
rect
The rectangle to invert.
Description

Inverts the pixels in the specified rectangle.

Syntax 2
public final void invertRect( int x, int y, int width, int height );
Parameters
x
The x coordinate of top left of rectangle.
y
The y coordinate of top left of rectangle.
width
The width of rectangle.
height
The height of rectangle.
Description

Inverts the pixels in the specified rectangle.

Graphics.scroll

Syntax
public final void scroll( int scrollX, int scrollY, Rectangle scrollArea, Rectangle clipArea );
Parameters
scrollX
The amount to scroll in the x direction. Negative values will scroll to the left.
scrollY
The amount to scroll in the y direction. Negative values will scroll up.
scrollArea
The rectangular area to scroll.
clipArea
The area beyond which no scrolling occurs.
Description

Scrolls an area of the graphics object.

Graphics.setBackColor

Syntax
public final void setBackColor( Color color );
Parameters
color
The color to use.
Description

Sets the background color used to fill empty regions.

Graphics.setBrush

Syntax
public final void setBrush( Brush brush );
Parameters
brush
The brush to use.
Description

Sets the current brush for the Graphics object.

Graphics.setBrushOrigin

Syntax 1
public final void setBrushOrigin( Point pt );
Parameters
pt
The point to which the brush origin should be set.
Description

Sets the brush origin for the Graphics object.

Syntax 2
public final void setBrushOrigin( int x, int y );
Parameters
x
The x coordinate of the brush origin.
y
The y coordinate of the brush origin.
Description

Sets the brush origin for the Graphics object.

Graphics.setFont

Syntax
public final void setFont( Font font );
Parameters
font
The font to use.
Description

Sets the current font for the Graphics object.

Graphics.setOpaque

Syntax
public final void setOpaque( boolean opaque );
Parameters
opaque
If set to true, the background will be filled with the current background color before drawing; otherwise, no fill will occur.
Description

Sets the background fill mode for this Graphics object.

Graphics.setPen

Syntax
public final void setPen( Pen pen );
Parameters
pen
The drawing pen.
Description

Sets the drawing pen for the Graphics object.

Graphics.setPixel

Syntax 1
public final void setPixel( Point pt );
Parameters
pt
The pixel point to set.
Description

Sets a pixel to the current foreground (text) color.

Syntax 2
public final void setPixel( int x, int y );
Parameters
The
x coordinate of the pixel to set.
The
y coordinate of the pixel to set.
Description

Sets a pixel to the current foreground (text) color.

Syntax 3
public final void setPixel( Point pt, Color color );
Parameters
pt
The pixel point to set.
color
The color to use to set the pixel.
Description

Sets a pixel to the specified color.

Syntax 4
public final void setPixel( int x, int y, Color color );
Parameters
The
x coordinate of the pixel to set.
The
y coordinate of the pixel to set.
color
The color to use to set the pixel.
Description

Sets a pixel to the specified color.

Syntax 5
public final void setPixel( int x, int y, Color color, RasterOp op );
Parameters
The
x coordinate of the pixel to set.
The
y coordinate of the pixel to set.
color
The color to use.
op
The raster operation to use to set the pixel.
Description

Sets a pixel to the specified color, and applies a raster operation to the pixel.

Graphics.setTextColor

Syntax
public final void setTextColor( Color color );
Parameters
color
The color to use to draw the text.
Description

Sets the color to be used when drawing text.

Graphics.setTextSpace

Syntax
public final void setTextSpace( int space );
Parameters
space
The amount of extra space.
Description

Sets the amount of extra space to be used between characters when drawing text.


 GroupBox Class

GroupBox Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--GroupBox
public class GroupBox
extends Control

A GroupBox is a simple container that holds other controls and wraps a a frame around them. Its text is displayed in the upper-left corner of the frame.

Constructors
Name | Description
GroupBox() | Creates a new GroupBox.

Constructors

GroupBox.GroupBox

Syntax
public GroupBox();
Description

Creates a new GroupBox.


 HorizontalAlignment Class

HorizontalAlignment Class

This Package | All Packages

Enum
  |
  +--HorizontalAlignment
public class HorizontalAlignment
extends Enum

Enumeration class that represents horizontal alignment values.

Fields
Name | Description
CENTER | The data is aligned in the center of the region.
LEFT | The data is aligned to the left of the region.
MAX | Topic under construction.
MIN | Topic under construction.
RIGHT | The data is aligned on the right edge of the region.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the given value is not possible for this class.
valid(int value) | Determines whether the given value is allowed by this class.

Fields

HorizontalAlignment.CENTER

Syntax
public static final int CENTER;
Description
The data is aligned in the center of the region.

HorizontalAlignment.LEFT

Syntax
public static final int LEFT;
Description
The data is aligned to the left of the region.

HorizontalAlignment.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

HorizontalAlignment.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

HorizontalAlignment.RIGHT

Syntax
public static final int RIGHT;
Description
The data is aligned on the right edge of the region.

Methods

HorizontalAlignment.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the given value is not possible for this class.

HorizontalAlignment.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Determines whether the given value is allowed by this class.


 HScrollBar Class

HScrollBar Class

This Package | All Packages

ScrollBar
  |
  +--HScrollBar
public class HScrollBar
extends ScrollBar

Topic under construction.

Constructors
Name | Description
HScrollBar() | Topic under construction.

Constructors

HScrollBar.HScrollBar

Syntax
public HScrollBar();
Description

Topic under construction.


 Icon Class

Icon Class

This Package | All Packages

Image
  |
  +--Icon
public class Icon
extends Image
implements IPersistable

Implements a Windows icon as a WFC object.

Constructors
Name | Description
Icon(int handle) | Topic under construction.
Icon(int handle, boolean fOwned) | Topic under construction.
Icon(String fileName) | Topic under construction.
Icon(Class type, String resource) | Topic under construction.
Icon(IDataStream stream) | Topic under construction.
Icon(IStream stream) | Topic under construction.
Icon(IPicture picture) | Topic under construction.

Methods
Name | Description
copyHandle(int h) | Retrieves a copy of the icon.
copyHandle() | Retrieves a copy of the icon.
drawStretchTo(Graphics g, int x, int y, int width, int height, int rop) | Draws the icon to the given DC and stretches it to the given width and height.
drawTo(Graphics g, int x, int y, int width, int height, int rop) | Draws the icon to the given device context (DC).
finalize() | Clean up our HBITMAP.
getExtension() | Topic under construction.
getHandle() | Topic under construction.
getPICTDESC() | Topic under construction.
getSize() | Topic under construction.
toString() | Topic under construction.

Constructors

Icon.Icon

Syntax 1
public Icon( int handle );
Description

Topic under construction.

Syntax 2
public Icon( int handle, boolean fOwned );
Description

Topic under construction.

Syntax 3
public Icon( String fileName );
Description

Topic under construction.

Syntax 4
public Icon( Class type, String resource );
Description

Topic under construction.

Syntax 5
public Icon( IDataStream stream );
Description

Topic under construction.

Syntax 6
public Icon( IStream stream );
Description

Topic under construction.

Syntax 7
public Icon( IPicture picture );
Description

Topic under construction.

Methods

Icon.copyHandle

Syntax 1
public static int copyHandle( int h );
Parameters
h
The handle to the icon.
Description

Retrieves a copy of the icon.

Syntax 2
public static int copyHandle();
Description

Retrieves a copy of the icon.

Icon.drawStretchTo

Syntax
public void drawStretchTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
g
The HDC to draw to (supplied by Graphics).
x
The x-coordinate at which to start drawing.
y
The y-coordinate at which to start drawing.
width
The width to stretch the icon to.
height
The height to stretch the icon to.
rop
The ROP code.
Description

Draws the icon to the given DC and stretches it to the given width and height.

Icon.drawTo

Syntax
public void drawTo( Graphics g, int x, int y, int width, int height, int rop );
Parameters
g
The HDC to draw to (supplied by Graphics).
x
The x-coordinate at which to start drawing.
y
The y-coordinate at which to start drawing.
width
The width of the icon.
height
The height of the icon.
rop
The ROP code.
Description

Draws the icon to the given device context (DC).

Icon.finalize

Syntax
public void finalize();
Description

Clean up our HBITMAP.

Icon.getExtension

Syntax
public String getExtension();
Description

Topic under construction.

Icon.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

Icon.getPICTDESC

Syntax
public PICTDESC getPICTDESC();
Description

Topic under construction.

Icon.getSize

Syntax
public Point getSize();
Description

Topic under construction.

Icon.toString

Syntax
public String toString();
Description

Topic under construction.


 IconArrange Class

IconArrange Class

This Package | All Packages

Enum
  |
  +--IconArrange
public class IconArrange
extends Enum

Topic under construction.

Fields
Name | Description
DEFAULT | Topic under construction.
LEFT | Topic under construction.
SNAP_TO_GRID | Topic under construction.
TOP | Topic under construction.

Fields

IconArrange.DEFAULT

Syntax
public static final int DEFAULT;
Description
Topic under construction.

IconArrange.LEFT

Syntax
public static final int LEFT;
Description
Topic under construction.

IconArrange.SNAP_TO_GRID

Syntax
public static final int SNAP_TO_GRID;
Description
Topic under construction.

IconArrange.TOP

Syntax
public static final int TOP;
Description
Topic under construction.


 Image Class

Image Class

This Package | All Packages

public abstract class Image
implements IPersistable

Represents the base class for image classes such as Bitmap, Cursor, Metafile, and Icon.

Constructors
Name | Description
Image() | Topic under construction.
Image(IPicture picture) | Topic under construction.

Methods
Name | Description
copyHandle() | Topic under construction.
finalize() | Topic under construction.
getPICTDESC() | Topic under construction.
getSize() | Topic under construction.
loadImage(IDataStream stream) | Topic under construction.
loadImage(IStream stream) | Topic under construction.
loadPicture(IStream stream) | Topic under construction.
releasePicture(IPicture picture) | Topic under construction.
save(IDataStream outputStream) | Topic under construction.
toString() | Topic under construction.

Constructors

Image.Image

Syntax 1
public Image();
Description

Topic under construction.

Syntax 2
public Image( IPicture picture );
Description

Topic under construction.

Methods

Image.copyHandle

Syntax
public abstract int copyHandle();
Description

Topic under construction.

Image.finalize

Syntax
public void finalize();
Description

Topic under construction.

Image.getPICTDESC

Syntax
public abstract PICTDESC getPICTDESC();
Description

Topic under construction.

Image.getSize

Syntax
public abstract Point getSize();
Description

Topic under construction.

Image.loadImage

Syntax 1
public static Image loadImage( IDataStream stream );
Description

Topic under construction.

Syntax 2
public static Image loadImage( IStream stream );
Description

Topic under construction.

Image.loadPicture

Syntax
public static IPicture loadPicture( IStream stream );
Description

Topic under construction.

Image.releasePicture

Syntax
public static void releasePicture( IPicture picture );
Description

Topic under construction.

Image.save

Syntax
public void save( IDataStream outputStream );
Description

Topic under construction.

Image.toString

Syntax
public String toString();
Description

Topic under construction.


 ImageButton Class

ImageButton Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ImageButton
public class ImageButton
extends Control
implements IButtonControl

Topic under construction.

Constructors
Name | Description
ImageButton() | Topic under construction.

Methods
Name | Description
getAutoSize() | Topic under construction.
getBorderHeight() | Topic under construction.
getBorderWidth() | Topic under construction.
getImage() | Topic under construction.
getRadio() | Topic under construction.
getValue() | Topic under construction.
notifyDefault(boolean fDefault) | Topic under construction.
onMouseUp(MouseEvent e) | Topic under construction.
performClick() | Topic under construction.
setAutoSize(boolean fAutoSize) | Topic under construction.
setBorderHeight(int borderHeight) | Topic under construction.
setBorderWidth(int borderWidth) | Topic under construction.
setImage(Bitmap bitmap) | Topic under construction.
setRadio(boolean fRadio) | Topic under construction.
setValue(boolean fValue) | Topic under construction.

Constructors

ImageButton.ImageButton

Syntax
public ImageButton();
Description

Topic under construction.

Methods

ImageButton.getAutoSize

Syntax
public boolean getAutoSize();
Description

Topic under construction.

ImageButton.getBorderHeight

Syntax
public int getBorderHeight();
Description

Topic under construction.

ImageButton.getBorderWidth

Syntax
public int getBorderWidth();
Description

Topic under construction.

ImageButton.getImage

Syntax
public Bitmap getImage();
Description

Topic under construction.

ImageButton.getRadio

Syntax
public boolean getRadio();
Description

Topic under construction.

ImageButton.getValue

Syntax
public boolean getValue();
Description

Topic under construction.

ImageButton.notifyDefault

Syntax
public void notifyDefault( boolean fDefault );
Description

Topic under construction.

ImageButton.onMouseUp

Syntax
public void onMouseUp( MouseEvent e );
Description

Topic under construction.

ImageButton.performClick

Syntax
public void performClick();
Description

Topic under construction.

ImageButton.setAutoSize

Syntax
public void setAutoSize( boolean fAutoSize );
Description

Topic under construction.

ImageButton.setBorderHeight

Syntax
public void setBorderHeight( int borderHeight );
Description

Topic under construction.

ImageButton.setBorderWidth

Syntax
public void setBorderWidth( int borderWidth );
Description

Topic under construction.

ImageButton.setImage

Syntax
public void setImage( Bitmap bitmap );
Description

Topic under construction.

ImageButton.setRadio

Syntax
public void setRadio( boolean fRadio );
Description

Topic under construction.

ImageButton.setValue

Syntax
public void setValue( boolean fValue );
Description

Topic under construction.


 ImageList Class

ImageList Class

This Package | All Packages

Component
  |
  +--ImageList
public class ImageList
extends Component

ImageList common control.

Constructors
Name | Description
ImageList() | Topic under construction.
ImageList(Point size) | Topic under construction.
ImageList(Bitmap image, Point size, Color maskColor) | Topic under construction.

Methods
Name | Description
addImage(Bitmap image) | Adds the given image to the ImageList.
addImage(Bitmap image, Color maskColor) | Adds the given image to the ImageList using the given color to generate the mask.
addImage(Bitmap image, Bitmap mask) | Adds the given image and mask to the ImageList.
addImage(Icon icon) | Adds the given icon to the ImageList.
destroyHandle() | Releases all resources held by the ImageList control.
draw(Graphics g, Point pt, int index) | Draws the image at the specified index.
draw(Graphics g, int x, int y, int index) | Draws the image indicated by the given index.
finalize() throws Throwable | Topic under construction.
getBackColor() | Retrieves the ImageList background color.
getBlendColor() | Retrieves the color used for blended drawing modes.
getDrawMode() | Retrieves the current drawing mode.
getHandle() | Topic under construction.
getHandleCreated() | Topic under construction.
getIcon(int index) | Creates an icon based on the image and mask at the given index.
getImage() | Retrieves the single wide bitmap that contains all images managed by the ImageList.
getImage(int index) | Retrieves the image at the specified index.
getImageCount() | Retrieves the count of images in the ImageList.
getImages() | Retrieves all images managed by the ImageList.
getMask() | Retrieves the single wide monocrome bitmap that contains all image masks managed by the ImageList.
getMask(int index) | Topic under construction.
getMaskColor() | Retrieves the color used to generate masks for images when added to the ImageList.
getMasks() | Retrieves an array of all masks managed by the ImageList.
getOverlayImage() | Retrieves the current overlay image.
getSize() | Retrieves the size of the images in the ImageList.
getUseMask() | Indicates whether the ImageList uses a mask.
removeAll() | Removes all images and masks from the ImageList.
removeImage(int index) | Removes the image at the specified index.
replaceImage(int index, Bitmap image) | Replaces the image at the specified index.
replaceImage(int index, Bitmap image, Bitmap mask) | Replaces the image and mask sat the pecified index.
replaceImage(int index, Icon icon) | Replaces the image at the specified index with the given icon.
setBackColor(Color value) | Sets the background color of the ImageList.
setBlendColor(Color value) | Sets the color used for blended drawing modes.
setDrawMode(int value) | Sets the drawing mode.
setImage(Bitmap value) | Assigns a single wide bitmap of images to the ImageList.
setMaskColor(Color value) | Topic under construction.
setOverlayImage(Bitmap value) | Topic under construction.
setSize(Point value) | Topic under construction.
setUseMask(boolean value) | Topic under construction.

Constructors

ImageList.ImageList

Syntax 1
public ImageList();
Description

Topic under construction.

Syntax 2
public ImageList( Point size );
Description

Topic under construction.

Syntax 3
public ImageList( Bitmap image, Point size, Color maskColor );
Description

Topic under construction.

Methods

ImageList.addImage

Syntax 1
public int addImage( Bitmap image );
Parameters
image
The image to be added.
Return Value

Returns the zero-based index of the first image added.

Description

Adds the given image to the ImageList. The number of images to add is determined by the width of the image.

Syntax 2
public int addImage( Bitmap image, Color maskColor );
Parameters
image
The image to be added.
maskColor
The color of the mask.
Return Value

Returns the zero-based index of the first image added.

Description

Adds the given image to the ImageList using the given color to generate the mask. The number of images to add is determined by the width of the image. If UseMask is false, the maskColor parameter will be ignored.

Syntax 3
public int addImage( Bitmap image, Bitmap mask );
Parameters
image
The image to be added.
mask
The mask to be used.
Return Value

Returns the zero-based index of the first image added.

Description

Adds the given image and mask to the ImageList. The number of images to add is determined by the width of the given image. If UseMask is false, the mask parameter is ignored.

Syntax 4
public int addImage( Icon icon );
Return Value

Returns the zero-based index of the new image.

Description

Adds the given icon to the ImageList.

ImageList.destroyHandle

Syntax
protected void destroyHandle();
Description

Releases all resources held by the ImageList control.

ImageList.draw

Syntax 1
public void draw( Graphics g, Point pt, int index );
Parameters
g
The Graphics object to draw to.
pt
The coordinates at which to draw the image.
index
The index of the image to be drawn.
Description

Draws the image at the specified index.

Syntax 2
public void draw( Graphics g, int x, int y, int index );
Parameters
g
The Graphics object to draw to.
x
The x-coordinate at which to draw the image.
y
The y-coordinate at which to draw the image.
index
The index of the image to be drawn.
Description

Draws the image indicated by the given index.

ImageList.finalize

Syntax
public void finalize() throws Throwable;
Description

Topic under construction.

ImageList.getBackColor

Syntax
public Color getBackColor();
Return Value

Returns the background color.

Description

Retrieves the ImageList background color.

ImageList.getBlendColor

Syntax
public Color getBlendColor();
Return Value

Returns the color used for blended drawing modes.

Description

Retrieves the color used for blended drawing modes.

ImageList.getDrawMode

Syntax
public int getDrawMode();
Return Value

Returns the drawing mode.

Description

Retrieves the current drawing mode.

ImageList.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

ImageList.getHandleCreated

Syntax
public boolean getHandleCreated();
Description

Topic under construction.

ImageList.getIcon

Syntax
public Icon getIcon( int index );
Parameters
index
The index at which to create the icon.
Return Value

Returns the icon that was created.

Description

Creates an icon based on the image and mask at the given index. The icon is created using the current drawing mode.

ImageList.getImage

Syntax 1
public Bitmap getImage();
Return Value

Returns the bitmap containing all images.

Description

Retrieves the single wide bitmap that contains all images managed by the ImageList.

Syntax 2
public Bitmap getImage( int index );
Parameters
index
The index of the image to be retrieved.
Return Value

Returns the image at the specified index.

Description

Retrieves the image at the specified index.

ImageList.getImageCount

Syntax
public int getImageCount();
Return Value

Returns the number of images.

Description

Retrieves the count of images in the ImageList.

ImageList.getImages

Syntax
public Bitmap[] getImages();
Return Value

Returns an array of images.

Description

Retrieves all images managed by the ImageList.

ImageList.getMask

Syntax 1
public Bitmap getMask();
Return Value

Returns the bitmap containing the image masks.

Description

Retrieves the single wide monocrome bitmap that contains all image masks managed by the ImageList. Returns null if the ImageList has no mask.

Syntax 2
public Bitmap getMask( int index );
Description

Topic under construction.

ImageList.getMaskColor

Syntax
public Color getMaskColor();
Return Value

Returns the mask color.

Description

Retrieves the color used to generate masks for images when added to the ImageList.

ImageList.getMasks

Syntax
public Bitmap[] getMasks();
Return Value

Returns an array of masks.

Description

Retrieves an array of all masks managed by the ImageList.

ImageList.getOverlayImage

Syntax
public Bitmap getOverlayImage();
Return Value

Returns the overlay image.

Description

Retrieves the current overlay image.

ImageList.getSize

Syntax
public Point getSize();
Return Value

Returns the image size.

Description

Retrieves the size of the images in the ImageList.

ImageList.getUseMask

Syntax
public boolean getUseMask();
Return Value

Returns true if a mask is used; otherwise, returns false.

Description

Indicates whether the ImageList uses a mask.

ImageList.removeAll

Syntax
public void removeAll();
Description

Removes all images and masks from the ImageList.

ImageList.removeImage

Syntax
public void removeImage( int index );
Parameters
index
The index of the image to be removed.
Description

Removes the image at the specified index.

ImageList.replaceImage

Syntax 1
public void replaceImage( int index, Bitmap image );
Parameters
index
The index of the image to be replaced.
image
The replacement image.
Description

Replaces the image at the specified index.

Syntax 2
public void replaceImage( int index, Bitmap image, Bitmap mask );
Parameters
index
The index of the image and mask to be replaced.
image
The replacement image.
mask
The replacement mask.
Description

Replaces the image and mask sat the pecified index.

Syntax 3
public void replaceImage( int index, Icon icon );
Parameters
index
The index of the image to be replaced.
icon
The replacement icon.
Description

Replaces the image at the specified index with the given icon.

ImageList.setBackColor

Syntax
public void setBackColor( Color value );
Parameters
value
The new background color.
Description

Sets the background color of the ImageList.

ImageList.setBlendColor

Syntax
public void setBlendColor( Color value );
Parameters
value
The color to be used.
Description

Sets the color used for blended drawing modes.

ImageList.setDrawMode

Syntax
public void setDrawMode( int value );
Parameters
value
The drawing mode.
Description

Sets the drawing mode.

ImageList.setImage

Syntax
public void setImage( Bitmap value );
Parameters
value
The bitmap containing the images.
Description

Assigns a single wide bitmap of images to the ImageList.

ImageList.setMaskColor

Syntax
public void setMaskColor( Color value );
Description

Topic under construction.

ImageList.setOverlayImage

Syntax
public void setOverlayImage( Bitmap value );
Description

Topic under construction.

ImageList.setSize

Syntax
public void setSize( Point value );
Description

Topic under construction.

ImageList.setUseMask

Syntax
public void setUseMask( boolean value );
Description

Topic under construction.


 ImageListDrawMode Class

ImageListDrawMode Class

This Package | All Packages

Enum
  |
  +--ImageListDrawMode
public class ImageListDrawMode
extends Enum

ImageList drawing modes.

Fields
Name | Description
BLEND | Topic under construction.
BLEND25 | Topic under construction.
BLEND50 | Topic under construction.
IMAGE | Topic under construction.
MASK | Topic under construction.
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | Topic under construction.
TRANSPARENT | Topic under construction.

Fields

ImageListDrawMode.BLEND

Syntax
public final static int BLEND;
Description
Topic under construction.

ImageListDrawMode.BLEND25

Syntax
public final static int BLEND25;
Description
Topic under construction.

ImageListDrawMode.BLEND50

Syntax
public final static int BLEND50;
Description
Topic under construction.

ImageListDrawMode.IMAGE

Syntax
public final static int IMAGE;
Description
Topic under construction.

ImageListDrawMode.MASK

Syntax
public final static int MASK;
Description
Topic under construction.

ImageListDrawMode.MAX

Syntax
public final static int MAX;
Description
Topic under construction.

ImageListDrawMode.MIN

Syntax
public final static int MIN;
Description
Topic under construction.

ImageListDrawMode.NORMAL

Syntax
public final static int NORMAL;
Description
Topic under construction.

ImageListDrawMode.TRANSPARENT

Syntax
public final static int TRANSPARENT;
Description
Topic under construction.


 InputLangChangeEvent Class

InputLangChangeEvent Class

This Package | All Packages

Event
  |
  +--InputLangChangeEvent
public class InputLangChangeEvent
extends Event

The InputLangChangeEvent is fired after the input language has changed.

Fields
Name | Description
charSet | The character set associated with the new input language.
locale | The locale of the input language.

Constructors
Name | Description
InputLangChangeEvent(Locale locale, byte charSet) | Topic under construction.

Fields

InputLangChangeEvent.charSet

Syntax
public final byte charSet;
Description
The character set associated with the new input language.

InputLangChangeEvent.locale

Syntax
public final Locale locale;
Description
The locale of the input language.

Constructors

InputLangChangeEvent.InputLangChangeEvent

Syntax
public InputLangChangeEvent( Locale locale, byte charSet );
Description

Topic under construction.


 InputLangChangeRequestEvent Class

InputLangChangeRequestEvent Class

This Package | All Packages

Event
  |
  +--InputLangChangeRequestEvent
public class InputLangChangeRequestEvent
extends Event

The InputLangChangeRequestEvent is fired before the input language changes.

Fields
Name | Description
acceptRequest | If set to false, the request is denied and the input language will not change.
locale | The locale of the requested input langugage.
sysCharSet | Set to true if the system default font supports the character set required for the requested input language.

Constructors
Name | Description
InputLangChangeRequestEvent(Locale locale, boolean sysCharSet, boolean acceptRequest) | Topic under construction.

Fields

InputLangChangeRequestEvent.acceptRequest

Syntax
public boolean acceptRequest;
Description
If set to false, the request is denied and the input language will not change.

InputLangChangeRequestEvent.locale

Syntax
public final Locale locale;
Description
The locale of the requested input langugage.

InputLangChangeRequestEvent.sysCharSet

Syntax
public final boolean sysCharSet;
Description
Set to true if the system default font supports the character set required for the requested input language.

Constructors

InputLangChangeRequestEvent.InputLangChangeRequestEvent

Syntax
public InputLangChangeRequestEvent( Locale locale, boolean sysCharSet, boolean acceptRequest );
Description

Topic under construction.


 ItemCheckEvent Class

ItemCheckEvent Class

This Package | All Packages

Event
  |
  +--ItemCheckEvent
public class ItemCheckEvent
extends Event

An event sent to a CheckedListBox when the state of one of the check boxes is about to change. You can set the new check state by using the newValue field.

Fields
Name | Description
currentValue | The current state of the check box.
index | The index of the item that is about to change.
newValue | The proposed new value of the check box.

Constructors
Name | Description
ItemCheckEvent(int index, int newCheckValue, int currentValue) | Topic under construction.

Fields

ItemCheckEvent.currentValue

Syntax
public final int currentValue;
Description
The current state of the check box.

ItemCheckEvent.index

Syntax
public final int index;
Description
The index of the item that is about to change.

ItemCheckEvent.newValue

Syntax
public int newValue;
Description
The proposed new value of the check box.

Constructors

ItemCheckEvent.ItemCheckEvent

Syntax
public ItemCheckEvent( int index, int newCheckValue, int currentValue );
Description

Topic under construction.


 Key Class

Key Class

This Package | All Packages

public class Key

Contains constants to use for processing keyboard input. Keys are identified by key values, which consist of a key code and a set of modifiers combined into a single integer value. The low order word of a key value contains the key code (which is the same as a Windows virtual key code). The high order word of a key value contains modifier bits for the SHIFT, CONTROL, and ALT keys.

Fields
Name | Description
A | Topic under construction.
ADD | Topic under construction.
ALT | Topic under construction.
APPS | Topic under construction.
ATTN | Topic under construction.
B | Topic under construction.
BACK | Topic under construction.
C | Topic under construction.
CANCEL | Topic under construction.
CAPITAL | Topic under construction.
CLEAR | Topic under construction.
CONTROL | Topic under construction.
CONTROL_KEY | Topic under construction.
CRSEL | Topic under construction.
D | Topic under construction.
D0 | Topic under construction.
D1 | Topic under construction.
D2 | Topic under construction.
D3 | Topic under construction.
D4 | Topic under construction.
D5 | Topic under construction.
D6 | Topic under construction.
D7 | Topic under construction.
D8 | Topic under construction.
D9 | Topic under construction.
DECIMAL | Topic under construction.
DELETE | Topic under construction.
DIVIDE | Topic under construction.
DOWN | Topic under construction.
E | Topic under construction.
END | Topic under construction.
EREOF | Topic under construction.
ESCAPE | Topic under construction.
EXECUTE | Topic under construction.
EXSEL | Topic under construction.
F | Topic under construction.
F1 | Topic under construction.
F10 | Topic under construction.
F11 | Topic under construction.
F12 | Topic under construction.
F13 | Topic under construction.
F14 | Topic under construction.
F15 | Topic under construction.
F16 | Topic under construction.
F17 | Topic under construction.
F18 | Topic under construction.
F19 | Topic under construction.
F2 | Topic under construction.
F20 | Topic under construction.
F21 | Topic under construction.
F22 | Topic under construction.
F23 | Topic under construction.
F24 | Topic under construction.
F3 | Topic under construction.
F4 | Topic under construction.
F5 | Topic under construction.
F6 | Topic under construction.
F7 | Topic under construction.
F8 | Topic under construction.
F9 | Topic under construction.
G | Topic under construction.
H | Topic under construction.
HELP | Topic under construction.
HOME | Topic under construction.
I | Topic under construction.
INSERT | Topic under construction.
J | Topic under construction.
K | Topic under construction.
KEYCODE | Bit mask to extract the key code from a key value.
L | Topic under construction.
LBUTTON | Key codes.
LCONTROL_KEY | Topic under construction.
LEFT | Topic under construction.
LMENU | Topic under construction.
LSHIFT_KEY | Topic under construction.
LWIN | Topic under construction.
M | Topic under construction.
MBUTTON | Topic under construction.
MENU | Topic under construction.
MODIFIERS | Bit mask to extract the modifiers from a key value.
MULTIPLY | Topic under construction.
N | Topic under construction.
NEXT | Topic under construction.
NONAME | Topic under construction.
NUMLOCK | Topic under construction.
NUMPAD0 | Topic under construction.
NUMPAD1 | Topic under construction.
NUMPAD2 | Topic under construction.
NUMPAD3 | Topic under construction.
NUMPAD4 | Topic under construction.
NUMPAD5 | Topic under construction.
NUMPAD6 | Topic under construction.
NUMPAD7 | Topic under construction.
NUMPAD8 | Topic under construction.
NUMPAD9 | Topic under construction.
O | Topic under construction.
OEM_CLEAR | Topic under construction.
P | Topic under construction.
PA1 | Topic under construction.
PAUSE | Topic under construction.
PLAY | Topic under construction.
PRINT | Topic under construction.
PRIOR | Topic under construction.
PROCESSKEY | Topic under construction.
Q | Topic under construction.
R | Topic under construction.
RBUTTON | Topic under construction.
RCONTROL_KEY | Topic under construction.
RETURN | Topic under construction.
RIGHT | Topic under construction.
RMENU | Topic under construction.
RSHIFT_KEY | Topic under construction.
RWIN | Topic under construction.
S | Topic under construction.
SCROLL | Topic under construction.
SELECT | Topic under construction.
SEPARATOR | Topic under construction.
SHIFT | Key modifiers.
SHIFT_KEY | Topic under construction.
SNAPSHOT | Topic under construction.
SPACE | Topic under construction.
SUBTRACT | Topic under construction.
T | Topic under construction.
TAB | Topic under construction.
U | Topic under construction.
UP | Topic under construction.
V | Topic under construction.
W | Topic under construction.
X | Topic under construction.
Y | Topic under construction.
Z | Topic under construction.
ZOOM | Topic under construction.

Fields

Key.A

Syntax
public static final int A;
Description
Topic under construction.

Key.ADD

Syntax
public static final int ADD;
Description
Topic under construction.

Key.ALT

Syntax
public static final int ALT;
Description
Topic under construction.

Key.APPS

Syntax
public static final int APPS;
Description
Topic under construction.

Key.ATTN

Syntax
public static final int ATTN;
Description
Topic under construction.

Key.B

Syntax
public static final int B;
Description
Topic under construction.

Key.BACK

Syntax
public static final int BACK;
Description
Topic under construction.

Key.C

Syntax
public static final int C;
Description
Topic under construction.

Key.CANCEL

Syntax
public static final int CANCEL;
Description
Topic under construction.

Key.CAPITAL

Syntax
public static final int CAPITAL;
Description
Topic under construction.

Key.CLEAR

Syntax
public static final int CLEAR;
Description
Topic under construction.

Key.CONTROL

Syntax
public static final int CONTROL;
Description
Topic under construction.

Key.CONTROL_KEY

Syntax
public static final int CONTROL_KEY;
Description
Topic under construction.

Key.CRSEL

Syntax
public static final int CRSEL;
Description
Topic under construction.

Key.D

Syntax
public static final int D;
Description
Topic under construction.

Key.D0

Syntax
public static final int D0;
Description
Topic under construction.

Key.D1

Syntax
public static final int D1;
Description
Topic under construction.

Key.D2

Syntax
public static final int D2;
Description
Topic under construction.

Key.D3

Syntax
public static final int D3;
Description
Topic under construction.

Key.D4

Syntax
public static final int D4;
Description
Topic under construction.

Key.D5

Syntax
public static final int D5;
Description
Topic under construction.

Key.D6

Syntax
public static final int D6;
Description
Topic under construction.

Key.D7

Syntax
public static final int D7;
Description
Topic under construction.

Key.D8

Syntax
public static final int D8;
Description
Topic under construction.

Key.D9

Syntax
public static final int D9;
Description
Topic under construction.

Key.DECIMAL

Syntax
public static final int DECIMAL;
Description
Topic under construction.

Key.DELETE

Syntax
public static final int DELETE;
Description
Topic under construction.

Key.DIVIDE

Syntax
public static final int DIVIDE;
Description
Topic under construction.

Key.DOWN

Syntax
public static final int DOWN;
Description
Topic under construction.

Key.E

Syntax
public static final int E;
Description
Topic under construction.

Key.END

Syntax
public static final int END;
Description
Topic under construction.

Key.EREOF

Syntax
public static final int EREOF;
Description
Topic under construction.

Key.ESCAPE

Syntax
public static final int ESCAPE;
Description
Topic under construction.

Key.EXECUTE

Syntax
public static final int EXECUTE;
Description
Topic under construction.

Key.EXSEL

Syntax
public static final int EXSEL;
Description
Topic under construction.

Key.F

Syntax
public static final int F;
Description
Topic under construction.

Key.F1

Syntax
public static final int F1;
Description
Topic under construction.

Key.F10

Syntax
public static final int F10;
Description
Topic under construction.

Key.F11

Syntax
public static final int F11;
Description
Topic under construction.

Key.F12

Syntax
public static final int F12;
Description
Topic under construction.

Key.F13

Syntax
public static final int F13;
Description
Topic under construction.

Key.F14

Syntax
public static final int F14;
Description
Topic under construction.

Key.F15

Syntax
public static final int F15;
Description
Topic under construction.

Key.F16

Syntax
public static final int F16;
Description
Topic under construction.

Key.F17

Syntax
public static final int F17;
Description
Topic under construction.

Key.F18

Syntax
public static final int F18;
Description
Topic under construction.

Key.F19

Syntax
public static final int F19;
Description
Topic under construction.

Key.F2

Syntax
public static final int F2;
Description
Topic under construction.

Key.F20

Syntax
public static final int F20;
Description
Topic under construction.

Key.F21

Syntax
public static final int F21;
Description
Topic under construction.

Key.F22

Syntax
public static final int F22;
Description
Topic under construction.

Key.F23

Syntax
public static final int F23;
Description
Topic under construction.

Key.F24

Syntax
public static final int F24;
Description
Topic under construction.

Key.F3

Syntax
public static final int F3;
Description
Topic under construction.

Key.F4

Syntax
public static final int F4;
Description
Topic under construction.

Key.F5

Syntax
public static final int F5;
Description
Topic under construction.

Key.F6

Syntax
public static final int F6;
Description
Topic under construction.

Key.F7

Syntax
public static final int F7;
Description
Topic under construction.

Key.F8

Syntax
public static final int F8;
Description
Topic under construction.

Key.F9

Syntax
public static final int F9;
Description
Topic under construction.

Key.G

Syntax
public static final int G;
Description
Topic under construction.

Key.H

Syntax
public static final int H;
Description
Topic under construction.

Key.HELP

Syntax
public static final int HELP;
Description
Topic under construction.

Key.HOME

Syntax
public static final int HOME;
Description
Topic under construction.

Key.I

Syntax
public static final int I;
Description
Topic under construction.

Key.INSERT

Syntax
public static final int INSERT;
Description
Topic under construction.

Key.J

Syntax
public static final int J;
Description
Topic under construction.

Key.K

Syntax
public static final int K;
Description
Topic under construction.

Key.KEYCODE

Syntax
public static final int KEYCODE;
Description
Bit mask to extract the key code from a key value.

Key.L

Syntax
public static final int L;
Description
Topic under construction.

Key.LBUTTON

Syntax
public static final int LBUTTON;
Description
Key codes.

Key.LCONTROL_KEY

Syntax
public static final int LCONTROL_KEY;
Description
Topic under construction.

Key.LEFT

Syntax
public static final int LEFT;
Description
Topic under construction.

Key.LMENU

Syntax
public static final int LMENU;
Description
Topic under construction.

Key.LSHIFT_KEY

Syntax
public static final int LSHIFT_KEY;
Description
Topic under construction.

Key.LWIN

Syntax
public static final int LWIN;
Description
Topic under construction.

Key.M

Syntax
public static final int M;
Description
Topic under construction.

Key.MBUTTON

Syntax
public static final int MBUTTON;
Description
Topic under construction.

Key.MENU

Syntax
public static final int MENU;
Description
Topic under construction.

Key.MODIFIERS

Syntax
public static final int MODIFIERS;
Description
Bit mask to extract the modifiers from a key value.

Key.MULTIPLY

Syntax
public static final int MULTIPLY;
Description
Topic under construction.

Key.N

Syntax
public static final int N;
Description
Topic under construction.

Key.NEXT

Syntax
public static final int NEXT;
Description
Topic under construction.

Key.NONAME

Syntax
public static final int NONAME;
Description
Topic under construction.

Key.NUMLOCK

Syntax
public static final int NUMLOCK;
Description
Topic under construction.

Key.NUMPAD0

Syntax
public static final int NUMPAD0;
Description
Topic under construction.

Key.NUMPAD1

Syntax
public static final int NUMPAD1;
Description
Topic under construction.

Key.NUMPAD2

Syntax
public static final int NUMPAD2;
Description
Topic under construction.

Key.NUMPAD3

Syntax
public static final int NUMPAD3;
Description
Topic under construction.

Key.NUMPAD4

Syntax
public static final int NUMPAD4;
Description
Topic under construction.

Key.NUMPAD5

Syntax
public static final int NUMPAD5;
Description
Topic under construction.

Key.NUMPAD6

Syntax
public static final int NUMPAD6;
Description
Topic under construction.

Key.NUMPAD7

Syntax
public static final int NUMPAD7;
Description
Topic under construction.

Key.NUMPAD8

Syntax
public static final int NUMPAD8;
Description
Topic under construction.

Key.NUMPAD9

Syntax
public static final int NUMPAD9;
Description
Topic under construction.

Key.O

Syntax
public static final int O;
Description
Topic under construction.

Key.OEM_CLEAR

Syntax
public static final int OEM_CLEAR;
Description
Topic under construction.

Key.P

Syntax
public static final int P;
Description
Topic under construction.

Key.PA1

Syntax
public static final int PA1;
Description
Topic under construction.

Key.PAUSE

Syntax
public static final int PAUSE;
Description
Topic under construction.

Key.PLAY

Syntax
public static final int PLAY;
Description
Topic under construction.

Key.PRINT

Syntax
public static final int PRINT;
Description
Topic under construction.

Key.PRIOR

Syntax
public static final int PRIOR;
Description
Topic under construction.

Key.PROCESSKEY

Syntax
public static final int PROCESSKEY;
Description
Topic under construction.

Key.Q

Syntax
public static final int Q;
Description
Topic under construction.

Key.R

Syntax
public static final int R;
Description
Topic under construction.

Key.RBUTTON

Syntax
public static final int RBUTTON;
Description
Topic under construction.

Key.RCONTROL_KEY

Syntax
public static final int RCONTROL_KEY;
Description
Topic under construction.

Key.RETURN

Syntax
public static final int RETURN;
Description
Topic under construction.

Key.RIGHT

Syntax
public static final int RIGHT;
Description
Topic under construction.

Key.RMENU

Syntax
public static final int RMENU;
Description
Topic under construction.

Key.RSHIFT_KEY

Syntax
public static final int RSHIFT_KEY;
Description
Topic under construction.

Key.RWIN

Syntax
public static final int RWIN;
Description
Topic under construction.

Key.S

Syntax
public static final int S;
Description
Topic under construction.

Key.SCROLL

Syntax
public static final int SCROLL;
Description
Topic under construction.

Key.SELECT

Syntax
public static final int SELECT;
Description
Topic under construction.

Key.SEPARATOR

Syntax
public static final int SEPARATOR;
Description
Topic under construction.

Key.SHIFT

Syntax
public static final int SHIFT;
Description
Key modifiers.

Key.SHIFT_KEY

Syntax
public static final int SHIFT_KEY;
Description
Topic under construction.

Key.SNAPSHOT

Syntax
public static final int SNAPSHOT;
Description
Topic under construction.

Key.SPACE

Syntax
public static final int SPACE;
Description
Topic under construction.

Key.SUBTRACT

Syntax
public static final int SUBTRACT;
Description
Topic under construction.

Key.T

Syntax
public static final int T;
Description
Topic under construction.

Key.TAB

Syntax
public static final int TAB;
Description
Topic under construction.

Key.U

Syntax
public static final int U;
Description
Topic under construction.

Key.UP

Syntax
public static final int UP;
Description
Topic under construction.

Key.V

Syntax
public static final int V;
Description
Topic under construction.

Key.W

Syntax
public static final int W;
Description
Topic under construction.

Key.X

Syntax
public static final int X;
Description
Topic under construction.

Key.Y

Syntax
public static final int Y;
Description
Topic under construction.

Key.Z

Syntax
public static final int Z;
Description
Topic under construction.

Key.ZOOM

Syntax
public static final int ZOOM;
Description
Topic under construction.


 KeyEvent Class

KeyEvent Class

This Package | All Packages

Event
  |
  +--KeyEvent
public class KeyEvent
extends Event

Topic under construction.

Fields
Name | Description
handled | Topic under construction.
keyChar | Topic under construction.
keyData | Topic under construction.

Constructors
Name | Description
KeyEvent(int keyData, char keyChar) | Topic under construction.

Methods
Name | Description
getAlt() | Topic under construction.
getControl() | Topic under construction.
getKeyCode() | Topic under construction.
getModifiers() | Topic under construction.
getShift() | Topic under construction.

Fields

KeyEvent.handled

Syntax
public boolean handled;
Description
Topic under construction.

KeyEvent.keyChar

Syntax
public final char keyChar;
Description
Topic under construction.

KeyEvent.keyData

Syntax
public final int keyData;
Description
Topic under construction.

Constructors

KeyEvent.KeyEvent

Syntax
public KeyEvent( int keyData, char keyChar );
Description

Topic under construction.

Methods

KeyEvent.getAlt

Syntax
public boolean getAlt();
Description

Topic under construction.

KeyEvent.getControl

Syntax
public boolean getControl();
Description

Topic under construction.

KeyEvent.getKeyCode

Syntax
public int getKeyCode();
Description

Topic under construction.

KeyEvent.getModifiers

Syntax
public int getModifiers();
Description

Topic under construction.

KeyEvent.getShift

Syntax
public boolean getShift();
Description

Topic under construction.


 Label Class

Label Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Label
public class Label
extends Control

Implements a simple static label control. Label controls are typically used to either display status text to the user or to identify the purpose of other controls that don't have an associated label. When a Label control gets the focus, it passes that focus to the next control in the tab order. This allows you to specify a mnemonic key for the label and have this key jump to other controls.

Constructors
Name | Description
Label() | Default constructor.

Methods
Name | Description
getAlignment() | Retrieves the alignment mode of the label.
getBorder() | Indicates whether the label has a visible border.
getUseMnemonic() | Indicates whether the label interprets the first ampersand (&) character as a hotkey mnemonic.
setAlignment(int alignment) | Sets the alignment mode for the label.
setBorder(boolean border) | Determines whether this control has a visible border.
setUseMnemonic(boolean useMnemonic) | Determines whether this control will use the first ampersand (&) in its text as a hotkey mnemonic.

Constructors

Label.Label

Syntax
public Label();
Description

Default constructor.

Methods

Label.getAlignment

Syntax
public int getAlignment();
Return Value

Returns a HorizontalAlignment enum.

Description

Retrieves the alignment mode of the label. This will be one of the HorizontalAlignment enum values.

Label.getBorder

Syntax
public boolean getBorder();
Return Value

Returns true if the label has a visible border; otherwise, returns false.

Description

Indicates whether the label has a visible border.

Label.getUseMnemonic

Syntax
public boolean getUseMnemonic();
Return Value

Returns true if the label uses mnemonics defined in its text; otherwise, returns false.

Description

Indicates whether the label interprets the first ampersand (&) character as a hotkey mnemonic.

Label.setAlignment

Syntax
public void setAlignment( int alignment );
Parameters
alignment
A value from the HorizontalAlignmnent enum.
Description

Sets the alignment mode for the label.

Label.setBorder

Syntax
public void setBorder( boolean border );
Parameters
border
Set to true if the control is to have a visible border; otherwise, set to false.
Description

Determines whether this control has a visible border.

Label.setUseMnemonic

Syntax
public void setUseMnemonic( boolean useMnemonic );
Parameters
useMnemonic
Set to true if the control is to interpret its text as a mnemonic; otherwise, set to false.
Description

Determines whether this control will use the first ampersand (&) in its text as a hotkey mnemonic.


 ListBox Class

ListBox Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ListBox
public class ListBox
extends Control

Encapsulates the Windows list box control.

Fields
Name | Description
NOMATCHES | While doing a search, if no matches are found, this is returned

Constructors
Name | Description
ListBox() | Creates a basic win32 list box with default values for everything.

Methods
Name | Description
addItem(Object item) | Adds an item to the list box.
addOnDrawItem(DrawItemEventHandler value) | Adds an event handler for the OnDrawItem event notification.
addOnMeasureItem(MeasureItemEventHandler value) | Adds an event handler for the OnMeasureItem event notification.
addOnSelectionChange(EventHandler value) | Adds an event handler for the OnSelectionChange event notification.
findString(String findString) | Finds the first item in the list that starts with the specified string.
findString(String findString, int indexStart) | Finds the first item after the specified index that starts with the specified string.
findStringExact(String findString) | Finds the first item in the list that is the same string as that specified in the findString parameter.
findStringExact(String findString, int indexStart) | Finds the first item after the speicified index that is the same string as that specified in the findString parameter.
getBorder() | Retrieves the current border setting.
getColumnWidth() | In a multicolumn list box, returns the current width of each column in the list.
getCreateParams() getDrawMode
public final int getDrawMode();

Returns the style of the list box.

getDrawMode() | Indicates if the list box should avoid showing partial items.
getIntegralHeight() | Returns the item at the given index.
getItem(int index) | Returns a count of the total number of items in the list box.
getItemCount() | Returns the height of an item in the list box if the drawMode is either NORMAL or OWNERDRAWFIXED.
getItemHeight() | Returns the height of the given item in an OWNERDRAWVARIABLE style list box.
getItemHeight(int index) | Returns a Rectangle object which describes the bounding rectangle around an item in the list.
getItemRect(int index) | Returns an object array with all the items in the ListBox.
getItems() | Indicates if the list box is multicolumn or not.
getMultiColumn() | Returns the total height of the items in the list box.
getPreferredHeight() | For normal list boxes, this indicates if the scroll bar will always be shown on the right side of the list, even if the number of list items is not enough to fill the entire list.
getScrollAlwaysVisible() | Indicates whether the item at the supplied index is selected.
getSelected(int index) | Returns the index of the currently selected item in the list if there is one.
getSelectedIndex() | If multiselection is allowed, returns an array of all items that are currently selected.
getSelectedIndices() | Returns the value of the currently selected item in the list,if there is one.
getSelectedItem() | Controls how many items in the list box can be selected at a time.
getSelectionStyle() | Indicates if the list box is sorted or not.
getSorted() | Retrieves the index of the first visible item in a list box.
getTopIndex() | Enables a list box to recognize and expand tab characters when drawing its strings.
getUseTabStops() | Allows you to add an Item to the ListBox in a location you specify, as opposed to the end of the list.
insertItem(int index, Object item) | Returns the index of the item at the given coordinates.
itemFromPoint(Point p) | Returns the index of the item at the given coordinates.
itemFromPoint(int x, int y) | Override this to guarantee that the list is refilled when necessary.
recreateHandle() | Removes all items from the list box.
removeAll() | Removes an individual item from the list box at the supplied index.
removeItem(int index) | Removes the given handler for the OnDrawItem event.
removeOnDrawItem(DrawItemEventHandler value) | Removes the given handler for the OnMeasureItem event.
removeOnMeasureItem( MeasureItemEventHandler value) | Removes the given handler for the OnSelectionChange event.
removeOnSelectionChange(EventHandler value) | Sets the current border setting.
setBorder(boolean value) | Sets the width of each column in a multicolumn list box.
setColumnWidth(int value) | Sets the style of the list.
setDrawMode(int value) | Indicates if the list box should avoid showing partial items.
setIntegralHeight(boolean value) | Allows you to change the value at the given index.
setItem(int index, Object item) | Sets the height of an item in an OWNERDRAWFIXED list box.
setItemHeight(int value) | Allows the user to set all the items in the list box at once by passing in an array with all their values.
setItems(Object[] value) | Indicates if the list box is multicolumn.
setMultiColumn(boolean value) | For normal listboxes, indicates if the scroll bar will always be shown on the right side of the list, even if the number of list items is not enough to fill up the entire list.
setScrollAlwaysVisible(boolean value) | Allows the user to set an item as being selected or not.
setSelected(int index, boolean value) | Sets the item at the supplied index as being the selected item in the list.
setSelectedIndex(int index) | Controls how many items in the list box can be selected at a time.
setSelectionStyle(int value) | When the list box is sorted, all values in the list are sorted alphbaetically.
setSorted(boolean value) | Enables a list box to recognize and expand tab characters when drawing its strings.
setUseTabStops(boolean value)

Fields

ListBox.NOMATCHES

Syntax
public static final int NOMATCHES;
Description
While doing a search, if no matches are found, this is returned

Constructors

ListBox.ListBox

Syntax
public ListBox();
Description

Creates a basic win32 list box with default values for everything.

Methods

ListBox.addItem

Syntax
public final int addItem( Object item );
Parameters
item
Object-typed value that we'll call toString() on to get the text to insert into the list box.
Return Value

Returns index of where the item was inserted.

Description

Adds an item to the list box. The code that adds the item will call toString() on it and inserts that value into the list box. If the sorted property is set to true, the item is properly sorted in the list. The actual index where the item was inserted is returned to the caller.

ListBox.addOnDrawItem

Syntax
public final void addOnDrawItem( DrawItemEventHandler value );
Parameters
value
New Event Handler to install for this event.
Description

Adds an event handler for the OnDrawItem event notification. This event is called for list boxes whose drawMode property is set to DrawMode.OWNERDRAWFIXED or DrawMode.OWNERDRAWVARIABLE and contains a Graphics object in which people should paint the item. Duplicates adds are not filtered out.

ListBox.addOnMeasureItem

Syntax
public final void addOnMeasureItem( MeasureItemEventHandler value );
Parameters
value
New Event Handler to install for this event.
Description

Adds an event handler for the OnMeasureItem event notification. This event is called for list boxes whose drawMode property is set to DrawMode.OWNERDRAWFIXED or DrawMode.OWNERDRAWVARIABLE and asks the programmer for the size of the given item in the list box. If the DrawMode is OWNERDRAWFIXED, this event is sent only once. Duplicates adds are not filtered out.

ListBox.addOnSelectionChange

Syntax
public final void addOnSelectionChange( EventHandler value );
Parameters
value
New Event Handler to install for this event.
Description

Adds an event handler for the OnSelectionChange event notification. This event is sent whenever the selection changes. Duplicates are not filtered out.

ListBox.findString

Syntax 1
public final int findString( String findString );
Parameters
findString
The string to match.
Return Value

Returns index of the item found, or returns ListBox.NOMATCHES if no match is found

Description

Finds the first item in the list that starts with the specified string. The search is case insensitive

Syntax 2
public final int findString( String findString, int indexStart );
Parameters
findString
The string to match.
indexStart
The index to start at. A -1 means start from the beginning.
Return Value

Returns an index of the item found, or returns ListBox.NOMATCHES if no match is found.

Description

Finds the first item after the specified index that starts with the specified string. This search is case insensitive.

ListBox.findStringExact

Syntax 1
public final int findStringExact( String findString );
Parameters
findString
The string to match in its entirety.
Return Value

Returns an index of the item found, or returns ListBox.NOMATCHES if no match is found.

Description

Finds the first item in the list that is the same string as that specified in the findString parameter. The search is still, however, case insensitive.

Syntax 2
public final int findStringExact( String findString, int indexStart );
Parameters
findString
The string to match in its entirety.
indexStart
The index to start at. A -1 means start from the beginning.
Return Value

Returns an index of the item found, or returns ListBox.NOMATCHES if no match is found.

Description

Finds the first item after the speicified index that is the same string as that specified in the findString parameter. The search is still, however, case insensitive.

ListBox.getBorder

Syntax
public boolean getBorder();
Return Value

Returns border setting.

Description

Retrieves the current border setting. If the border is set to true a 3D border is drawn around the list box.

See Also
setBorder

ListBox.getColumnWidth

Syntax
public final int getColumnWidth();
Return Value

Returns int The width, in pixels, of each column in the list box.

Description

In a multicolumn list box, returns the current width of each column in the list. A value of zero [0] means that Windows will choose a default width for each column.

ListBox.getCreateParams

Syntax
protected CreateParams getCreateParams();
Description

ListBox.getDrawMode

Syntax
public final int getDrawMode();
Return Value

Returns integer with the style.

Description

Returns the style of the list box. This indicates if the system draws it, or if the user paints each item manually. It also indicates whether items have to be of the same height.

ListBox.getIntegralHeight

Syntax
public final boolean getIntegralHeight();
Return Value

Returns boolean value indicating if only full items will be shown.

Description

Indicates if the list box should avoid showing partial items. If so, only full items will be displayed, and the list box will be resized to prevent partial items from being shown. Otherwise, they will be shown.

ListBox.getItem

Syntax
public final Object getItem( int index );
Parameters
index
Integer value with the index of the item to retrieve.
Return Value

Returns an Object handle with the item at that index in the list box.

Description

Returns the item at the given index. All indexes are zero-based.

ListBox.getItemCount

Syntax
public final int getItemCount();
Return Value

Returns the number of items in the list box.

Description

Returns a count of the total number of items in the list box.

ListBox.getItemHeight

Syntax 1
public final int getItemHeight();
Return Value

Returns an integer with the height, in pixels, of an item in the list.

Description

Returns the height of an item in the list box if the drawMode is either NORMAL or OWNERDRAWFIXED. For OWNERDRAWVARIABLE type list boxes, this routine returns the height of the first item. To determine the height of other items, use the other version of this routine.

Syntax 2
public final int getItemHeight( int index );
Parameters
index
Item to return the height for.
Return Value

Returns an integer with the height, in pixels, of the given item in the list.

Description

Returns the height of the given item in an OWNERDRAWVARIABLE style list box. This routine should not be called for fixed-item height style lists.

ListBox.getItemRect

Syntax
public final Rectangle getItemRect( int index );
Parameters
index
An index of item to return bounding rectangle for.
Return Value

Returns a rectangle.

Description

Returns a Rectangle object which describes the bounding rectangle around an item in the list.

ListBox.getItems

Syntax
public final Object[] getItems();
Return Value

Returns Object[]. The first item is the 0th element, and the last item in the list is last in the array.

Description

Returns an object array with all the items in the ListBox.

ListBox.getMultiColumn

Syntax
public final boolean getMultiColumn();
Return Value

Returns a boolean value indicating whether the list box is multicolumn.

Description

Indicates if the list box is multicolumn or not. If it's multicolumn, the list box uses the columnWidth property to determine how wide to make each column and displays the data horizontally in columns instead of vertically.

ListBox.getPreferredHeight

Syntax
public final int getPreferredHeight();
Return Value

Returns int with the height, in pixels, of all items in the list box.

Description

Returns the total height of the items in the list box.

ListBox.getScrollAlwaysVisible

Syntax
public final boolean getScrollAlwaysVisible();
Return Value

Returns a boolean value indicating whether the scroll bar should always be visible.

Description

For normal list boxes, this indicates if the scroll bar will always be shown on the right side of the list, even if the number of list items is not enough to fill the entire list. By default, Windows will show a scroll bar only when there are enough items to warrant it. For multicolumn list boxes, Windows does not show a horizontal scroll bar. Setting this value indicates that a horizontal scroll bar should be added. There is never a vertical scroll bar.

ListBox.getSelected

Syntax
public final boolean getSelected( int index );
Parameters
index
Indicates whether this item is selected or not.
Return Value

Returns a boolean value indicating whether it is true or not false.

Description

Indicates whether the item at the supplied index is selected.

ListBox.getSelectedIndex

Syntax
public final int getSelectedIndex();
Return Value

Returns an integer.

Description

Returns the index of the currently selected item in the list if there is one. If the value is -1, there is currently no selection. If the value is 0 or greater, the value is the index of the currently selected item. If the MultiSelect property on the list box is true, a non-zero value for this property is the index of the first selection

ListBox.getSelectedIndices

Syntax
public final int [] getSelectedIndices();
Return Value

Returns int [] Array with all the selected indexes.

Description

If multiselection is allowed, returns an array of all items that are currently selected. If in a single selection list box, then the currently selected item is returned in a single element array, or if the selection is not allowed, returns null.

ListBox.getSelectedItem

Syntax
public final Object getSelectedItem();
Return Value

Returns an object with either null or the current selection.

Description

Returns the value of the currently selected item in the list,if there is one. If the value is null, there is currently no selection. If the value is non-null, the value is that of the currently selected item. If the MultiSelect property on the list box is true, a non-null return value for this method is the value of the first item selected.

ListBox.getSelectionStyle

Syntax
public final int getSelectionStyle();
Return Value

Returns int with the current value.

Description

Controls how many items in the list box can be selected at a time. Valid values are: SelectionStyle.NONE [0] - No items can be selected in the list. SelectionStyle.ONE [1] - Only one item at a time can be selected. SelectionStyle.MULIT_SIMPLE [2] - More than one item at a time can be selected. SelectionStyle.MULTI_EXTENDED [3] - More than one item at a time can be selected and keyboard characters. such as SHIFT and CTRL can be used to assist in selection.

ListBox.getSorted

Syntax
public final boolean getSorted();
Return Value

Returns boolean with the current value.

Description

Indicates if the list box is sorted or not. If set to true, the strings in the list will be sorted alphabetically.

ListBox.getTopIndex

Syntax
public final int getTopIndex();
Return Value

Returns int Index of the topmost visible item.

Description

Retrieves the index of the first visible item in a list box. Initially, the item with index 0 is at the top of the list box, If the list box contents have been scrolled, another item may be at the top.

ListBox.getUseTabStops

Syntax
public final boolean getUseTabStops();
Return Value

Returns boolean indicating whether or not the list box will honor tabs.

Description

Enables a list box to recognize and expand tab characters when drawing its strings.

ListBox.insertItem

Syntax
public final int insertItem( int index, Object item );
Parameters
index
Where in the list [zero-based] it should be inserted.
item
The value of the item you want inserted.
Description

Allows you to add an Item to the ListBox in a location you specify, as opposed to the end of the list. Note that if the sorted property is set to true, values inserted by this method are not property sorted. The

See Also
addItem method should be used instead.

ListBox.itemFromPoint

Syntax 1
public final int itemFromPoint( Point p );
Parameters
point
Point object with the coordinates to test.
Return Value

Returns index of item that is under said point, or returns ListBox.NOMATCHES if there is no item in this location.

Description

Returns the index of the item at the given coordinates.

Syntax 2
public final int itemFromPoint( int x, int y );
Parameters
x
x coordinate of point to test.
y
y coordinate of point to test.
Return Value

Returns index of item that is at the specified point, or returns ListBox.NOMATCHES if there is no item in this location.

Description

Returns the index of the item at the given coordinates.

ListBox.recreateHandle

Syntax
public void recreateHandle();
Description

Override this to guarantee that the list is refilled when necessary.

ListBox.removeAll

Syntax
public void removeAll();
Description

Removes all items from the list box. All values and item data are lost.

ListBox.removeItem

Syntax
public final void removeItem( int index );
Parameters
index
Index of item to removed.
Description

Removes an individual item from the list box at the supplied index. The item and its values are discarded.

ListBox.removeOnDrawItem

Syntax
public final void removeOnDrawItem( DrawItemEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnDrawItem event. If there are duplicate entries, all are removed.

ListBox.removeOnMeasureItem

Syntax
public final void removeOnMeasureItem( MeasureItemEventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnMeasureItem event. If there are duplicate entries, all are removed.

ListBox.removeOnSelectionChange

Syntax
public final void removeOnSelectionChange( EventHandler value );
Parameters
value
Event handler to be removed.
Description

Removes the given handler for the OnSelectionChange event. If there are duplicate entries, all are removed.

ListBox.setBorder

Syntax
public void setBorder( boolean value );
Parameters
value
New border setting.
Description

Sets the current border setting. If the border is set to true, a three-dimensisonal border is drawn around the list box.

See Also
setBorder

ListBox.setColumnWidth

Syntax
public final void setColumnWidth( int value );
Parameters
int
The new width of each column, in pixels.
Description

Sets the width of each column in a multicolumn list box. A value of zero [0] means that Windows will pick a width.

ListBox.setDrawMode

Syntax
public final void setDrawMode( int value );
Parameters
value
New value of the list box style.
Description

Sets the style of the list. This lets users control whether to paint the items themselves [default is not] and whether the items are all the same height [default yes]

ListBox.setIntegralHeight

Syntax
public final void setIntegralHeight( boolean value );
Parameters
value
The new value for this property.
Description

Indicates if the list box should avoid showing partial items. If so, only full items will be displayed, and the list box will be resized to prevent partial items from being shown. Otherwise, they will be shown.

ListBox.setItem

Syntax
public final void setItem( int index, Object item );
Parameters
index
Index of item to change the value for
item
New value for said index
Description

Allows you to change the value at the given index. If there is no value at the supplied index, an exception is thrown. Otherwise, the value becomes the newly supplied one

Exceptions

IllegalArgument thrown if the index is not currently assigned a value.

ListBox.setItemHeight

Syntax
public final void setItemHeight( int value );
Parameters
value
The height of an item in an OWNERDRAWFIXED list.
Description

Sets the height of an item in an OWNERDRAWFIXED list box. Users can use this instead of the OnMeasureItem event, which is best used by OWNERDRAWVARIABLE list boxes. This method is ignored by list boxes whose style is DrawMode.NORMAL

ListBox.setItems

Syntax
public final void setItems( Object[] value );
Parameters
value
Array of objects that will be inserted into the list box.
Description

Allows the user to set all the items in the list box at once by passing in an array with all their values. All old values in the list box are discarded and lost

ListBox.setMultiColumn

Syntax
public final void setMultiColumn( boolean value );
Parameters
value
New value indicating whether the list box is multi-column.
Description

Indicates if the list box is multicolumn. If it's multicolumn, the list box uses the columnWidth property to determine how wide to make each column and displays the data horizontally in columns instead of vertically.

ListBox.setScrollAlwaysVisible

Syntax
public final void setScrollAlwaysVisible( boolean value );
Parameters
value
The new value indicating if this should be set.
Description

For normal listboxes, indicates if the scroll bar will always be shown on the right side of the list, even if the number of list items is not enough to fill up the entire list. By default, Windows will show only a scroll bar when there are enough items to warrant it. For multicolumn list boxes, Windows does not show a horizontal scroll bar at all. Setting this value indicates that a horizontal scroll bar should be added. There is never a vertical scroll bar.

ListBox.setSelected

Syntax
public final void setSelected( int index, boolean value );
Parameters
index
Index of the item to mark as selected.
value
A boolean value indicating whether the item should be selected.
Description

Allows the user to set an item as being selected or not.

ListBox.setSelectedIndex

Syntax
public final void setSelectedIndex( int index );
Parameters
index
Index of item to select.
Description

Sets the item at the supplied index as being the selected item in the list. If the MultiSelect property is set to true, then this clears all other selections

ListBox.setSelectionStyle

Syntax
public final void setSelectionStyle( int value );
Return Value

Returns an integer with the current value.

Description

Controls how many items in the list box can be selected at a time. Valid values are: SelectionStyle.NONE [0] - No items can be selected in the list. SelectionStyle.ONE [1] - Only one item at a time can be selected. SelectionStyle.MULIT_SIMPLE [2] - More than one item at a time can be selected. SelectionStyle.MULTI_EXTENDED [3] - More than one item at a time can be selected, and keyboard characters such as SHIFT and CTRL can be used to assist in selection.

ListBox.setSorted

Syntax
public final void setSorted( boolean value );
Parameters
sorted
A boolean value indicating whether sorting should be on.
Description

When the list box is sorted, all values in the list are sorted alphbaetically. When the list box is not sorted, the values are displayed in the list in the order they were added.

ListBox.setUseTabStops

Syntax
public final void setUseTabStops( boolean value );
Parameters
value
New value indciating whether the list box should honor tab characters.
Description

Enables a list box to recognize and expand tab characters when drawing its strings.


 ListItem Class

ListItem Class

This Package | All Packages

public class ListItem

Manages items in a listview.

Methods
Name | Description
equals(Object obj) | Returns whether two list items are equal.
getData() | Returns data handle associated with this list item.
getImageIndex() | Returns the ListItem's currently set image index.
getIndex() | Returns ListItem's current index in the listview.
getListView() | Returns the ListView associated with this ListItem.
getRect() | Returns the ListItems bounding rectangle.
getSubItem(int index) | Returns a specific subitem for this ListItem.
getSubItemCount() | Returns the number of subitems in this ListItem.
getSubItems() | Returns SubItem array.
getText() | Returns text associated with this ListItem.
hashCode() | Topic under construction.
setData(int data) | Sets a new data handle for this ListItem.
setImageIndex(int image) | Sets the image index for this item.
setSubItem(int index, String text) | Sets SubItem text string to this ListItem at the given index.
setSubItems(String[] subItems) | Sets the internal SubItems array to the new array and sets the ListView to match accordingly.
setText(String text) | Sets the text for this ListItem.
toString() | Topic under construction.

Methods

ListItem.equals

Syntax
public boolean equals( Object obj );
Parameters
li
ListItem to test against.
Description

Returns whether two list items are equal.

ListItem.getData

Syntax
public int getData();
Return Value

Returns a previously set data handle.

Description

Returns data handle associated with this list item.

ListItem.getImageIndex

Syntax
public int getImageIndex();
Return Value

Returns an image index.

Description

Returns the ListItem's currently set image index.

ListItem.getIndex

Syntax
public int getIndex();
Return Value

Returns the ListItem's index in ListView.

Description

Returns ListItem's current index in the listview.

ListItem.getListView

Syntax
public ListView getListView();
Return Value

Returns ListView associated with this item.

Description

Returns the ListView associated with this ListItem.

ListItem.getRect

Syntax
public Rectangle getRect();
Return Value

Returns the rectangle associated with the ListItem.

Description

Returns the ListItems bounding rectangle.

ListItem.getSubItem

Syntax
public String getSubItem( int index );
Return Value

Returns the text of selected subitem

Description

Returns a specific subitem for this ListItem.

Exceptions

IllegalArgumentException hrown if SubItem index is out of bounds.

ListItem.getSubItemCount

Syntax
public int getSubItemCount();
Return Value

Returns the count of SubItems.

Description

Returns the number of subitems in this ListItem.

ListItem.getSubItems

Syntax
public String[] getSubItems();
Return Value

Returns SubItem array.

Description

Returns SubItem array.

ListItem.getText

Syntax
public String getText();
Return Value

Returns ListItem's text.

Description

Returns text associated with this ListItem.

ListItem.hashCode

Syntax
public int hashCode();
Description

Topic under construction.

ListItem.setData

Syntax
public void setData( int data );
Parameters
data
handle for the data to be saved with this ListItem.
Description

Sets a new data handle for this ListItem.

ListItem.setImageIndex

Syntax
public void setImageIndex( int image );
Parameters
image
Index in the ListView's imagelist.
Description

Sets the image index for this item.

ListItem.setSubItem

Syntax
public void setSubItem( int index, String text );
Parameters
index
Index to set SubItem at.
text
Text of the subitem to set.
Description

Sets SubItem text string to this ListItem at the given index. If index greater than or equal to SubItemCount, then the SubItem array is grown to match the index. Anything in between the old array bounds and the new is declared as null.

Exceptions

IllegalArgumentException thrown if Index is less than 0 or if Index is greater than the number of current columns in the ListView.

ListItem.setSubItems

Syntax
public void setSubItems( String[] subItems );
Parameters
subItems
Array of strings representing the text for the new subitems.
Description

Sets the internal SubItems array to the new array and sets the ListView to match accordingly.

Exceptions

IllegalArgumentException thrown if the number of subitems in new array greater than the number of current columns in the ListView.

ListItem.setText

Syntax
public void setText( String text );
Parameters
txt
Text to set to this ListItem.
Description

Sets the text for this ListItem.

ListItem.toString

Syntax
public String toString();
Description

Topic under construction.


 ListStyle Class

ListStyle Class

This Package | All Packages

Enum
  |
  +--ListStyle
public class ListStyle
extends Enum

Topic under construction.

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | All the items in the list box are painted by the system and have the same size.
OWNERDRAWFIXED | The user paints the items in the list box manually, but they are all the same size (height).
OWNERDRAWVARIABLE | The user paints the items in the list box manually, but they are not necessarily the same size.

Fields

ListStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ListStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ListStyle.NORMAL

Syntax
public static final int NORMAL;
Description
All the items in the list box are painted by the system and have the same size.

ListStyle.OWNERDRAWFIXED

Syntax
public static final int OWNERDRAWFIXED;
Description
The user paints the items in the list box manually, but they are all the same size (height).

ListStyle.OWNERDRAWVARIABLE

Syntax
public static final int OWNERDRAWVARIABLE;
Description
The user paints the items in the list box manually, but they are not necessarily the same size.


 ListView Class

ListView Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ListView
public class ListView
extends Control

Topic under construction.

Methods
Name | Description
addOnAfterLabelEdit(EventHandler eh) | Topic under construction.
addOnBeforeLabelEdit(EventHandler handler) | Topic under construction.
addOnColumnClick(EventHandler handler) | Topic under construction.
addOnItemClick(EventHandler handler) | Topic under construction.
clear() | Clear the ListView of all columns and ListItems.
getAlignment() | Returns the Alignment style the ListView is curently using.
getAllowColumnReorder() | Indicates whether the Column Reordering style is set.
getAutoArrange() | Indicates whether the AutoArrange style is set.
getBorderStyle() | Returns current BorderStyle setting.
getCheckBoxes() | Indicates whether the CheckBox style is set.
getColumnCount() | Returns the number of columns the ListView currently has.
getColumnHeader(int index) | Given a zero-based index, returns the ColumnHeader object for the column at that index.
getFirstVisible() | Retrieves the first visible ListItem in the list view.
getFullRowSelect() | Indicates whether the FullRowSelect style is set.
getGridLines() | Indicates whether the GridLines style is set.
getHideColumnHeaders() | Indicates whether ColumnHeaders are visible.
getHideSelection() | Indicates whether the currently selected item is always visible, even when focus is lost.
getIconArrange() | Topic under construction.
getImageList() | Returns the currently set ImageList for Large Icon mode.
getItemCount() | Returns the total number of items within the list view.
getLabelEdit() | Indicates whether the LabelEdit style is currently set.
getLabelWrap() | Indicates whether the LabelWrap style is currently set.
getListItem(int index) | Returns a ListItem given its zero-based index into the ListView.
getMultiSelect() | Indicates whether the MultiSelect style is currently set.
getOneClickActivate() | Indicates whether the OneClickActivet style is currently set.
getScrollbar() | Indicates whether the ScrollBars are visible or not.
getSelectedItems() | Returns an array of currently selected list items.
getSmallImageList() | Returns the currently set SmallIcon image list.
getSortByHeader() | Indicates whether the SortByHeader style is currently set.
getSorting() | Returns currently selected sorting styles.
getStateImageList() | Returns the currently set State image list.
getStyleEx() | Topic under construction.
getTag() | Returns the current tag object.
getTrackSelect() | Indicates whether the TrackSelect style is currently set.
getTwoClickActivate() | Indicates whether the TwoClickActivet style is currently set.
getView() | Returns currently selected ListView View style.
hitTest(int x, int y) | Returns the current ListItem corresponding to the specific x,y co-ordinate.
insertColumn(int index, String str, int width, int subItemIndex, int columnformat) Inserts a new column into the ListView

Return Value:

Returns the ColumnHeader object representing the new column.

insertItem(int index, String text, int imageIndex, int data) | Inserts a new ListItem into the ListView.
removeAll() | Removes all elements from the ListView.
removeColumn(int index) | removes a column from the ListView.
removeItem(int index) | Removes an item from the ListView.
setAlignment(int alignflag) | Sets Alignment style for ListView.
setAllowColumnReorder(boolean flag) | Sets Column Reorder style on the ListView.
setAutoArrange(boolean value) | Sets AutoArrange style on the ListView.
setBorderStyle(int borderstyle) | Sets BorderStyle style on the ListView.
setCheckBoxes(boolean flag) | Sets CheckBoxes style on the ListView.
setFullRowSelect(boolean flag) | Sets Full Row Select style on the ListView.
setGridLines(boolean flag) | Sets Grid LInes style on the ListView.
setHideColumnHeaders(boolean flag) | Sets Hide Column Headers style on the ListView.
setHideSelection (boolean flag) | Sets Selection Always Visible style on the ListView.
setIconArrange(int flag) | Sets Icon arrangement options in Large/Small Icon view.
setImageList(ImageList v) | Sets the Large Icon Image list.
setLabelEdit (boolean flag) | Sets Label Edit style on the ListView.
setLabelWrap(boolean flag) | Sets Label Wrap style on the ListView.
setMultiSelect(boolean flag) | Sets MultiSelection style on the ListView.
setOneClickActivate(boolean flag) | Sets One Click Activate style on the ListView.
setScrollbar(boolean flag) | Sets Scroll Bar visible style on the ListView.
setSmallImageList(ImageList v) | Sets the Small Icon Image list.
setSortByHeader(boolean flag) | Sets Column Sort style on the ListView.
setSorting(int sortflag) | Sets Sorting style for the ListView.
setStateImageList(ImageList v) | Sets the State Image list.
setTag(Object tag) | Sets Tag value of the ListView.
setTrackSelect(boolean flag) Sets Track Select style on the ListView

Parameter | Description
setTwoClickActivate(boolean flag) | Sets Two Click Activate style on the ListView.
setView(int viewflag) | Sets View style for the ListView.

Methods

ListView.addOnAfterLabelEdit

Syntax
public void addOnAfterLabelEdit( EventHandler eh );
Description

Topic under construction.

ListView.addOnBeforeLabelEdit

Syntax
public void addOnBeforeLabelEdit( EventHandler handler );
Description

Topic under construction.

ListView.addOnColumnClick

Syntax
public void addOnColumnClick( EventHandler handler );
Description

Topic under construction.

ListView.addOnItemClick

Syntax
public void addOnItemClick( EventHandler handler );
Description

Topic under construction.

ListView.clear

Syntax
public void clear();
Description

Clear the ListView of all columns and ListItems.

ListView.getAlignment

Syntax
public int getAlignment();
Return Value

Returns Integer ListView Aligment style.

Description

Returns the Alignment style the ListView is curently using.

ListView.getAllowColumnReorder

Syntax
public boolean getAllowColumnReorder();
Return Value

Returns Boolean whether Column Reording is set.

Description

Indicates whether the Column Reordering style is set.

ListView.getAutoArrange

Syntax
public boolean getAutoArrange();
Return Value

Returns a boolean value indicating whether AutoArrange is set.

Description

Indicates whether the AutoArrange style is set.

ListView.getBorderStyle

Syntax
public int getBorderStyle();
Return Value

Returns int A value representing the BorderStyle setting.

Description

Returns current BorderStyle setting.

ListView.getCheckBoxes

Syntax
public boolean getCheckBoxes();
Return Value

Returns A boolean indicating whether the CheckBox style is set.

Description

Indicates whether the CheckBox style is set.

ListView.getColumnCount

Syntax
public int getColumnCount();
Return Value

Returns an interger indicating the number of columns in ListView.

Description

Returns the number of columns the ListView currently has.

ListView.getColumnHeader

Syntax
public ColumnHeader getColumnHeader( int index );
Parameters
index
Zero-based index of specific column.
Return Value

Returns a ColumnHeader object.

Description

Given a zero-based index, returns the ColumnHeader object for the column at that index.

Exceptions

IllegalArgumenException thrown if index is out of bounds.

ListView.getFirstVisible

Syntax
public ListItem getFirstVisible();
Return Value

Returns the first Visible ListItem, or returns null if no ListItems exist.

Description

Retrieves the first visible ListItem in the list view.

ListView.getFullRowSelect

Syntax
public boolean getFullRowSelect();
Return Value

Returns a boolean value indicating whether FullRowSelect is set.

Description

Indicates whether the FullRowSelect style is set.

ListView.getGridLines

Syntax
public boolean getGridLines();
Return Value

Returns a boolean value indicating whether GridLines is set.

Description

Indicates whether the GridLines style is set.

ListView.getHideColumnHeaders

Syntax
public boolean getHideColumnHeaders();
Return Value

Returns Boolean whther ColumnHeaders are visible or not.

Description

Indicates whether ColumnHeaders are visible.

ListView.getHideSelection

Syntax
public boolean getHideSelection();
Return Value

Returns a boolean value indicating whether the selected item is always visible.

Description

Indicates whether the currently selected item is always visible, even when focus is lost.

ListView.getIconArrange

Syntax
public int getIconArrange();
Description

Topic under construction.

ListView.getImageList

Syntax
public ImageList getImageList();
Return Value

Returns the ImageList, or returns null if none is set.

Description

Returns the currently set ImageList for Large Icon mode.

ListView.getItemCount

Syntax
public int getItemCount();
Return Value

Returns the integer count of items.

Description

Returns the total number of items within the list view.

ListView.getLabelEdit

Syntax
public boolean getLabelEdit();
Return Value

Returns a boolean value indicating whether LabelEdit is set.

Description

Indicates whether the LabelEdit style is currently set.

ListView.getLabelWrap

Syntax
public boolean getLabelWrap();
Return Value

Returns a boolean value indicating whether LabelWrap is set.

Description

Indicates whether the LabelWrap style is currently set.

ListView.getListItem

Syntax
public ListItem getListItem( int index );
Parameters
index
Zero-based index into ListView's list of items.
Return Value

Returns a ListItem representing item at specified index.

Description

Returns a ListItem given its zero-based index into the ListView.

Exceptions

IllegalArgumentException thrown if index is out of bounds.

ListView.getMultiSelect

Syntax
public boolean getMultiSelect();
Return Value

Returns a boolean value indicating whether MultiSelect is set.

Description

Indicates whether the MultiSelect style is currently set.

ListView.getOneClickActivate

Syntax
public boolean getOneClickActivate();
Return Value

Returns a boolean value indicating whether OneClickActivate is set.

Description

Indicates whether the OneClickActivet style is currently set. If not, the ListView resorts to double clicking to activate an item.

ListView.getScrollbar

Syntax
public boolean getScrollbar();
Return Value

Returns a boolean value indicating whether ScrollBars are visible.

Description

Indicates whether the ScrollBars are visible or not.

ListView.getSelectedItems

Syntax
public ListItem[] getSelectedItems();
Return Value

Returns ListItem[] array of currently selected list items.

Description

Returns an array of currently selected list items.

Exceptions

RuntimeException yhrown if the number of selected items < the number of actual items selected.

ListView.getSmallImageList

Syntax
public ImageList getSmallImageList();
Return Value

Returns ImageList representing SmallIcon image list, or returns null if not set.

Description

Returns the currently set SmallIcon image list.

ListView.getSortByHeader

Syntax
public boolean getSortByHeader();
Return Value

Returns a boolean value indicating whether SortByHeader is set.

Description

Indicates whether the SortByHeader style is currently set. If this is false, column headers do not sort list items.

ListView.getSorting

Syntax
public int getSorting();
Return Value

Returns Integer Current sorting style. Possibilites are: Ascending Descending None

Description

Returns currently selected sorting styles.

ListView.getStateImageList

Syntax
public ImageList getStateImageList();
Return Value

Returns ImageList representing State image list, or returns null if not set.

Description

Returns the currently set State image list.

ListView.getStyleEx

Syntax
public int getStyleEx();
Description

Topic under construction.

ListView.getTag

Syntax
public Object getTag();
Return Value

Returns the object representing current tag.

Description

Returns the current tag object.

ListView.getTrackSelect

Syntax
public boolean getTrackSelect();
Return Value

Returns a boolean value indicating whether TrackSelect is set.

Description

Indicates whether the TrackSelect style is currently set.

ListView.getTwoClickActivate

Syntax
public boolean getTwoClickActivate();
Return Value

Returns a boolean value indicating whether TwoClickActivate is set.

Description

Indicates whether the TwoClickActivet style is currently set. If not, th the ListView resorts to double clicking to activate an item.

ListView.getView

Syntax
public int getView();
Return Value

Returns the current view style. Possibilites are: Icon SmallIcon List Report

Description

Returns currently selected ListView View style.

ListView.hitTest

Syntax
public ListItem hitTest( int x, int y );
Parameters
x
x position to check against.
y
y position to check against.
Return Value

Returns ListItem ListItem at position, or returns null if no item exists there.

Description

Returns the current ListItem corresponding to the specific x,y co-ordinate.

ListView.insertColumn

Syntax
public ColumnHeader insertColumn( int index, String str, int width, int subItemIndex, int columnformat );
Parameters
index
Index for the new column.
str
Text for new column.
width
Width of new column.
subItemIndex
SubItem associated with this column.
columnFormat
Format for this column. This may be one of the following: Left, Center, Right.
Return Value

Returns the ColumnHeader object representing the new column.

Description

Inserts a new column into the ListView

Exceptions

IllegalArgumentException hrown is ColumnFormat is not one of the specified.

runtimeException thrown if there is a problem creating the new column.

ListView.insertItem

Syntax
public ListItem insertItem( int index, String text, int imageIndex, int data );
Parameters
index
Index for new item.
text
Text for new item.
imageIndex
Index into ImageList for this item.
data
Handle to external data to be stored by this item.
Return Value

Returns the ListItem object representing the new item.

Description

Inserts a new ListItem into the ListView.

Exceptions

runtimeException thrown if there is a problem creating the new item.

ListView.removeAll

Syntax
public void removeAll();
Description

Removes all elements from the ListView.

ListView.removeColumn

Syntax
public void removeColumn( int index );
Parameters
index
Zero-based index of the column that is to be removed.
Description

removes a column from the ListView.

Exceptions

ArrayIndexOutOfBoundsException thrown is index is out of bounds.

ListView.removeItem

Syntax
public void removeItem( int index );
Parameters
index
Zero-based index of the item that is to be removed.
Description

Removes an item from the ListView.

Exceptions

ArrayIndexOutOfBoundsException thrown is index is out of bounds.

ListView.setAlignment

Syntax
public void setAlignment( int alignflag );
Parameters
alignflag
Specifies alignment style for ListView.
Description

Sets Alignment style for ListView.

Exceptions

IllegalArgumentException thrown if alignment style is unknown.

ListView.setAllowColumnReorder

Syntax
public void setAllowColumnReorder( boolean flag );
Parameters
flag
Sets Column Reorder on or off.
Description

Sets Column Reorder style on the ListView.

ListView.setAutoArrange

Syntax
public void setAutoArrange( boolean value );
Parameters
flag
Sets AutoArrange Reorder on or off.
Description

Sets AutoArrange style on the ListView.

ListView.setBorderStyle

Syntax
public void setBorderStyle( int borderstyle );
Parameters
flag
Sets BorderStyle to one of the following: NONE SUNKEN3D
Description

Sets BorderStyle style on the ListView.

ListView.setCheckBoxes

Syntax
public void setCheckBoxes( boolean flag );
Parameters
flag
Sets CheckBoxes on or off.
Description

Sets CheckBoxes style on the ListView.

ListView.setFullRowSelect

Syntax
public void setFullRowSelect( boolean flag );
Parameters
flag
Sets Full Row Select on or off.
Description

Sets Full Row Select style on the ListView.

ListView.setGridLines

Syntax
public void setGridLines( boolean flag );
Parameters
flag
Sets GridLines on or off.
Description

Sets Grid LInes style on the ListView.

ListView.setHideColumnHeaders

Syntax
public void setHideColumnHeaders( boolean flag );
Parameters
flag
Sets Hide Column Headers on or off.
Description

Sets Hide Column Headers style on the ListView.

ListView.setHideSelection

Syntax
public void setHideSelection ( boolean flag );
Parameters
flag
Sets Selection Always Visible on or off.
Description

Sets Selection Always Visible style on the ListView.

ListView.setIconArrange

Syntax
public void setIconArrange( int flag );
Parameters
flag
Icon Arangement styles. Styles can be: Default Align Left Align Top Snap To Grid
Description

Sets Icon arrangement options in Large/Small Icon view.

Exceptions

IllegalArgumentException thrown if flag is not one of the supported Icon Arrangement styles.

ListView.setImageList

Syntax
public void setImageList( ImageList v );
Parameters
v
ImageList containing Large Icons.
Description

Sets the Large Icon Image list.

ListView.setLabelEdit

Syntax
public void setLabelEdit ( boolean flag );
Parameters
flag
Sets Label Edit on or off.
Description

Sets Label Edit style on the ListView.

ListView.setLabelWrap

Syntax
public void setLabelWrap( boolean flag );
Parameters
flag
Sets Label Wrap on or off.
Description

Sets Label Wrap style on the ListView.

ListView.setMultiSelect

Syntax
public void setMultiSelect( boolean flag );
Parameters
flag
Sets MultiSelection on or off.
Description

Sets MultiSelection style on the ListView.

ListView.setOneClickActivate

Syntax
public void setOneClickActivate( boolean flag );
Parameters
flag
Sets One Click Activate on or off.
Description

Sets One Click Activate style on the ListView.

ListView.setScrollbar

Syntax
public void setScrollbar( boolean flag );
Parameters
flag
Sets Scroll Bar visible on or off.
Description

Sets Scroll Bar visible style on the ListView.

ListView.setSmallImageList

Syntax
public void setSmallImageList( ImageList v );
Parameters
v
ImageList containing Small Icons.
Description

Sets the Small Icon Image list.

ListView.setSortByHeader

Syntax
public void setSortByHeader( boolean flag );
Parameters
flag
Sets Column Sort on or off.
Description

Sets Column Sort style on the ListView.

ListView.setSorting

Syntax
public void setSorting( int sortflag );
Parameters
sortflag
Sets Sort style on the ListView. Style can be one of the following: None Ascending Descending
Description

Sets Sorting style for the ListView.

ListView.setStateImageList

Syntax
public void setStateImageList( ImageList v );
Parameters
v
ImageList containing State Icons.
Description

Sets the State Image list.

ListView.setTag

Syntax
public void setTag( Object tag );
Parameters
tag
Object to set the tag on.
Description

Sets Tag value of the ListView.

ListView.setTrackSelect

Syntax
public void setTrackSelect( boolean flag );
Parameters
flag
Sets Track Select on or off.
Description

Sets Track Select style on the ListView

ListView.setTwoClickActivate

Syntax
public void setTwoClickActivate( boolean flag );
Parameters
flag
Sets Two Click Activate on or off.
Description

Sets Two Click Activate style on the ListView.

ListView.setView

Syntax
public void setView( int viewflag );
Parameters
viewflag
Sets View style on the ListView. Style can be one of the following: Icon SmallIcon List Report
Description

Sets View style for the ListView.


 MainMenu Class

MainMenu Class

This Package | All Packages

Menu
  |
  +--MainMenu
public class MainMenu
extends Menu

Topic under construction.

Constructors
Name | Description
MainMenu() | Topic under construction.
MainMenu(MenuItem[] items) | Topic under construction.

Methods
Name | Description
cloneMenu() | Topic under construction.
dispose() | Topic under construction.
getForm() | Topic under construction.

Constructors

MainMenu.MainMenu

Syntax 1
public MainMenu();
Description

Topic under construction.

Syntax 2
public MainMenu( MenuItem[] items );
Description

Topic under construction.

Methods

MainMenu.cloneMenu

Syntax
public MainMenu cloneMenu();
Description

Topic under construction.

MainMenu.dispose

Syntax
public void dispose();
Description

Topic under construction.

MainMenu.getForm

Syntax
public Form getForm();
Description

Topic under construction.


 MDIClient Class

MDIClient Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--MDIClient
public class MDIClient
extends Control

Topic under construction.

Constructors
Name | Description
MDIClient() | Topic under construction.

Methods
Name | Description
add(Control ctl) | Topic under construction.
layoutMDI(int value) | Topic under construction.

Constructors

MDIClient.MDIClient

Syntax
public MDIClient();
Description

Topic under construction.

Methods

MDIClient.add

Syntax
public void add( Control ctl );
Description

Topic under construction.

Overrides

add(Control) in Control.

MDIClient.layoutMDI

Syntax
public void layoutMDI( int value );
Description

Topic under construction.


 MDILayout Class

MDILayout Class

This Package | All Packages

Enum
  |
  +--MDILayout
public class MDILayout
extends Enum

Topic under construction.

Fields
Name | Description
ARRANGE_ICONS | Topic under construction.
CASCADE | Topic under construction.
MAX | Topic under construction.
MIN | Topic under construction.
TILE_HORIZONTAL | Topic under construction.
TILE_VERTICAL | Topic under construction.

Methods
Name | Description
ensureValid(int value) | Topic under construction.
valid(int value) | Topic under construction.

Fields

MDILayout.ARRANGE_ICONS

Syntax
public static final int ARRANGE_ICONS;
Description
Topic under construction.

MDILayout.CASCADE

Syntax
public static final int CASCADE;
Description
Topic under construction.

MDILayout.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

MDILayout.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

MDILayout.TILE_HORIZONTAL

Syntax
public static final int TILE_HORIZONTAL;
Description
Topic under construction.

MDILayout.TILE_VERTICAL

Syntax
public static final int TILE_VERTICAL;
Description
Topic under construction.

Methods

MDILayout.ensureValid

Syntax
public static void ensureValid( int value );
Description

Topic under construction.

MDILayout.valid

Syntax
public static boolean valid( int value );
Description

Topic under construction.


 MeasureItemEvent Class

MeasureItemEvent Class

This Package | All Packages

Event
  |
  +--MeasureItemEvent
public class MeasureItemEvent
extends Event

This event is sent by controls, such as the ListBox and ComboBox, that need users to tell them how large a given item is to be.

Fields
Name | Description
index | The index of the item for which the height is needed.
itemHeight | The height of the item at the specified index.

Constructors
Name | Description
MeasureItemEvent(int index, int itemHeight) | Topic under construction.

Fields

MeasureItemEvent.index

Syntax
public final int index;
Description
The index of the item for which the height is needed.

MeasureItemEvent.itemHeight

Syntax
public int itemHeight;
Description
The height of the item at the specified index.

Constructors

MeasureItemEvent.MeasureItemEvent

Syntax
public MeasureItemEvent( int index, int itemHeight );
Description

Topic under construction.


 Menu Class

Menu Class

This Package | All Packages

Component
  |
  +--Menu
public abstract class Menu
extends Component

Topic under construction.

Fields
Name | Description
CHANGE_ITEMS | Topic under construction.
CHANGE_MDI | Topic under construction.
CHANGE_MERGE | Topic under construction.
CHANGE_VISIBLE | Topic under construction.
FIND_HANDLE | Topic under construction.
FIND_SHORTCUT | Topic under construction.

Constructors
Name | Description
mergeMenu(Menu menuSrc, boolean first) | Topic under construction.

Methods
Name | Description
add(MenuItem item) | Topic under construction.
clear() | Topic under construction.
dispose() | Topic under construction.
findMenuItem(int type, int value) | Topic under construction.
getHandle() | Topic under construction.
getMainMenu() | Topic under construction.
getMDIListItem() | Topic under construction.
getMenuItem(int index) | Topic under construction.
getMenuItemCount() | Topic under construction.
getMenuItems() | Topic under construction.
getParent() | Topic under construction.
insert(int index, MenuItem item) | Topic under construction.
processCmdKey(MSG msg, int keyData) | Topic under construction.
remove(int index) | Topic under construction.
remove(MenuItem item) | Topic under construction.
setMenuItems(MenuItem[] value) | Topic under construction.

Fields

Menu.CHANGE_ITEMS

Syntax
public static final int CHANGE_ITEMS;
Description
Topic under construction.

Menu.CHANGE_MDI

Syntax
public static final int CHANGE_MDI;
Description
Topic under construction.

Menu.CHANGE_MERGE

Syntax
public static final int CHANGE_MERGE;
Description
Topic under construction.

Menu.CHANGE_VISIBLE

Syntax
public static final int CHANGE_VISIBLE;
Description
Topic under construction.

Menu.FIND_HANDLE

Syntax
public static final int FIND_HANDLE;
Description
Topic under construction.

Menu.FIND_SHORTCUT

Syntax
public static final int FIND_SHORTCUT;
Description
Topic under construction.

Constructors

Menu.mergeMenu

Syntax
public void mergeMenu( Menu menuSrc, boolean first );
Description

Topic under construction.

Methods

Menu.add

Syntax
public void add( MenuItem item );
Description

Topic under construction.

Menu.clear

Syntax
public void clear();
Description

Topic under construction.

Menu.dispose

Syntax
public void dispose();
Description

Topic under construction.

Menu.findMenuItem

Syntax
public MenuItem findMenuItem( int type, int value );
Description

Topic under construction.

Menu.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

Menu.getMainMenu

Syntax
public MainMenu getMainMenu();
Description

Topic under construction.

Menu.getMDIListItem

Syntax
public MenuItem getMDIListItem();
Description

Topic under construction.

Menu.getMenuItem

Syntax
public MenuItem getMenuItem( int index );
Description

Topic under construction.

Menu.getMenuItemCount

Syntax
public int getMenuItemCount();
Description

Topic under construction.

Menu.getMenuItems

Syntax
public MenuItem[] getMenuItems();
Description

Topic under construction.

Menu.getParent

Syntax
public boolean getParent();
Description

Topic under construction.

Menu.insert

Syntax
public void insert( int index, MenuItem item );
Description

Topic under construction.

Menu.processCmdKey

Syntax
public boolean processCmdKey( MSG msg, int keyData );
Description

Topic under construction.

Menu.remove

Syntax 1
public MenuItem remove( int index );
Description

Topic under construction.

Syntax 2
public void remove( MenuItem item );
Description

Topic under construction.

Menu.setMenuItems

Syntax
public void setMenuItems( MenuItem[] value );
Description

Topic under construction.


 MenuGlyph Class

MenuGlyph Class

This Package | All Packages

Enum
  |
  +--MenuGlyph
public final class MenuGlyph
extends Enum

Enum to be used with the drawMenuGlyph function.

Fields
Name | Description
ARROW | Draws a submenu arrow.
BULLET | Draws a menu bullet.
CHECKMARK | Draws a menu check mark.
MAX | Topic under construction.
MIN |

Methods
Name | Description
ensureValid(int value) | Throws an exception if the given value is not possible for this class.
valid(int value) | Determines whether the given value is allowed by this class.

Fields

MenuGlyph.ARROW

Syntax
public static final int ARROW;
Description
Draws a submenu arrow.

MenuGlyph.BULLET

Syntax
public static final int BULLET;
Description
Draws a menu bullet.

MenuGlyph.CHECKMARK

Syntax
public static final int CHECKMARK;
Description
Draws a menu check mark.

MenuGlyph.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

MenuGlyph.MIN

Syntax
public static final int MIN;
Description

Methods

MenuGlyph.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
The value to check.
Description

Throws an exception if the given value is not possible for this class.

MenuGlyph.valid

Syntax
public static boolean valid( int value );
Parameters
value
The value to check.
Return Value

Returns true if the value is valid; otherwise, returns false.

Description

Determines whether the given value is allowed by this class.


 MenuItem Class

MenuItem Class

This Package | All Packages

Component
  |
  +--Menu
    |
    +--MenuItem
public class MenuItem
extends Menu

Topic under construction.

Constructors
Name | Description
MenuItem() | Topic under construction.
MenuItem(String text) | Topic under construction.
MenuItem(String text, EventHandler onClick) | Topic under construction.
MenuItem(String text, EventHandler onClick, MenuItem[] items) | Topic under construction.
MenuItem(int mergeType, int mergeOrder, int shortCut, String text, EventHandler onClick, EventHandler onInit, MenuItem[] items) | Topic under construction.

Methods
Name | Description
addOnClick(EventHandler value) | Topic under construction.
addOnInit(EventHandler value) | Topic under construction.
cloneMenu() | Topic under construction.
dispose() | Topic under construction.
getBarBreak() | Topic under construction.
getBreak() | Topic under construction.
getChecked() | Topic under construction.
getDefault() | Topic under construction.
getEnabled() | Topic under construction.
getIndex() | Topic under construction.
getMDIList() | Topic under construction.
getMenu() | Topic under construction.
getMergeOrder() | Topic under construction.
getMergeType() | Topic under construction.
getParent() | Topic under construction.
getRadioCheck() | Topic under construction.
getShortCut() | Topic under construction.
getText() | Topic under construction.
getVisible() | Topic under construction.
mergeMenu() | Topic under construction.
mergeMenu(MenuItem itemSrc, boolean first) | Topic under construction.
removeOnClick(EventHandler value) | Topic under construction.
removeOnInit(EventHandler value) | Topic under construction.
setBarBreak(boolean value) | Topic under construction.
setBreak(boolean value) | Topic under construction.
setChecked(boolean value) | Topic under construction.
setDefault(boolean value) | Topic under construction.
setEnabled(boolean value) | Topic under construction.
setIndex(int value) | Topic under construction.
setMDIList(boolean value) | Topic under construction.
setMergeOrder(int value) | Topic under construction.
setMergeType(int value) | Topic under construction.
setRadioCheck(boolean value) | Topic under construction.
setShortCut(int value) | Topic under construction.
setText(String value) | Topic under construction.
setVisible(boolean value) | Topic under construction.

Constructors

MenuItem.MenuItem

Syntax 1
public MenuItem();
Description

Topic under construction.

Syntax 2
public MenuItem( String text );
Description

Topic under construction.

Syntax 3
public MenuItem( String text, EventHandler onClick );
Description

Topic under construction.

Syntax 4
public MenuItem( String text, EventHandler onClick, MenuItem[] items );
Description

Topic under construction.

Syntax 5
public MenuItem( int mergeType, int mergeOrder, int shortCut, String text, EventHandler onClick, EventHandler onInit, MenuItem[] items );
Description

Topic under construction.

Methods

MenuItem.addOnClick

Syntax
public void addOnClick( EventHandler value );
Description

Topic under construction.

MenuItem.addOnInit

Syntax
public void addOnInit( EventHandler value );
Description

Topic under construction.

MenuItem.cloneMenu

Syntax
public MenuItem cloneMenu();
Description

Topic under construction.

MenuItem.dispose

Syntax
public void dispose();
Description

Topic under construction.

Overrides

dispose() in Menu.

MenuItem.getBarBreak

Syntax
public boolean getBarBreak();
Description

Topic under construction.

MenuItem.getBreak

Syntax
public boolean getBreak();
Description

Topic under construction.

MenuItem.getChecked

Syntax
public boolean getChecked();
Description

Topic under construction.

MenuItem.getDefault

Syntax
public boolean getDefault();
Description

Topic under construction.

MenuItem.getEnabled

Syntax
public boolean getEnabled();
Description

Topic under construction.

MenuItem.getIndex

Syntax
public int getIndex();
Description

Topic under construction.

MenuItem.getMDIList

Syntax
public boolean getMDIList();
Description

Topic under construction.

MenuItem.getMenu

Syntax
public Menu getMenu();
Description

Topic under construction.

MenuItem.getMergeOrder

Syntax
public int getMergeOrder();
Description

Topic under construction.

MenuItem.getMergeType

Syntax
public int getMergeType();
Description

Topic under construction.

MenuItem.getParent

Syntax
public boolean getParent();
Description

Topic under construction.

Overrides

getParent() in Menu.

MenuItem.getRadioCheck

Syntax
public boolean getRadioCheck();
Description

Topic under construction.

MenuItem.getShortCut

Syntax
public int getShortCut();
Description

Topic under construction.

MenuItem.getText

Syntax
public String getText();
Description

Topic under construction.

MenuItem.getVisible

Syntax
public boolean getVisible();
Description

Topic under construction.

MenuItem.mergeMenu

Syntax 1
public MenuItem mergeMenu();
Description

Topic under construction.

Syntax 2
public void mergeMenu( MenuItem itemSrc, boolean first );
Description

Topic under construction.

MenuItem.removeOnClick

Syntax
public void removeOnClick( EventHandler value );
Description

Topic under construction.

MenuItem.removeOnInit

Syntax
public void removeOnInit( EventHandler value );
Description

Topic under construction.

MenuItem.setBarBreak

Syntax
public void setBarBreak( boolean value );
Description

Topic under construction.

MenuItem.setBreak

Syntax
public void setBreak( boolean value );
Description

Topic under construction.

MenuItem.setChecked

Syntax
public void setChecked( boolean value );
Description

Topic under construction.

MenuItem.setDefault

Syntax
public void setDefault( boolean value );
Description

Topic under construction.

MenuItem.setEnabled

Syntax
public void setEnabled( boolean value );
Description

Topic under construction.

MenuItem.setIndex

Syntax
public void setIndex( int value );
Description

Topic under construction.

MenuItem.setMDIList

Syntax
public void setMDIList( boolean value );
Description

Topic under construction.

MenuItem.setMergeOrder

Syntax
public void setMergeOrder( int value );
Description

Topic under construction.

MenuItem.setMergeType

Syntax
public void setMergeType( int value );
Description

Topic under construction.

MenuItem.setRadioCheck

Syntax
public void setRadioCheck( boolean value );
Description

Topic under construction.

MenuItem.setShortCut

Syntax
public void setShortCut( int value );
Description

Topic under construction.

MenuItem.setText

Syntax
public void setText( String value );
Description

Topic under construction.

MenuItem.setVisible

Syntax
public void setVisible( boolean value );
Description

Topic under construction.


 MenuMerge Class

MenuMerge Class

This Package | All Packages

Enum
  |
  +--MenuMerge
public class MenuMerge
extends Enum

Topic under construction.

Fields
Name | Description
ADD | Topic under construction.
MERGEITEMS | Topic under construction.
REMOVE | Topic under construction.
REPLACE | Topic under construction.

Fields

MenuMerge.ADD

Syntax
public static final int ADD;
Description
Topic under construction.

MenuMerge.MERGEITEMS

Syntax
public static final int MERGEITEMS;
Description
Topic under construction.

MenuMerge.REMOVE

Syntax
public static final int REMOVE;
Description
Topic under construction.

MenuMerge.REPLACE

Syntax
public static final int REPLACE;
Description
Topic under construction.


 MessageBox Class

MessageBox Class

This Package | All Packages

public class MessageBox

Allows you to display a message box with various buttons and icons.

Fields
Name | Description
ABORTRETRYIGNORE | Topic under construction.
DEFBUTTON1 | Topic under construction.
DEFBUTTON2 | Topic under construction.
DEFBUTTON3 | Topic under construction.
ICONASTERISK | Topic under construction.
ICONERROR | Topic under construction.
ICONEXCLAMATION | Topic under construction.
ICONHAND | Topic under construction.
ICONINFORMATION | Topic under construction.
ICONQUESTION | Topic under construction.
ICONSTOP | Topic under construction.
ICONWARNING | Topic under construction.
IDABORT | Topic under construction.
IDCANCEL | Topic under construction.
IDIGNORE | Topic under construction.
IDNO | Topic under construction.
IDOK | Topic under construction.
IDRETRY | Topic under construction.
IDYES | Topic under construction.
OK | Topic under construction.
OKCANCEL | Topic under construction.
RETRYCANCEL | Topic under construction.
YESNO | Topic under construction.
YESNOCANCEL | Topic under construction.

Methods
Name | Description
show(String text, String caption, int style) | Shows the message box with the given text, caption, and style.
show(String text, String caption) | Shows the message box with the given text and caption.
show(String text) | Shows the message box with the given text.

Fields

MessageBox.ABORTRETRYIGNORE

Syntax
public static final int ABORTRETRYIGNORE;
Description
Topic under construction.

MessageBox.DEFBUTTON1

Syntax
public static final int DEFBUTTON1;
Description
Topic under construction.

MessageBox.DEFBUTTON2

Syntax
public static final int DEFBUTTON2;
Description
Topic under construction.

MessageBox.DEFBUTTON3

Syntax
public static final int DEFBUTTON3;
Description
Topic under construction.

MessageBox.ICONASTERISK

Syntax
public static final int ICONASTERISK;
Description
Topic under construction.

MessageBox.ICONERROR

Syntax
public static final int ICONERROR;
Description
Topic under construction.

MessageBox.ICONEXCLAMATION

Syntax
public static final int ICONEXCLAMATION;
Description
Topic under construction.

MessageBox.ICONHAND

Syntax
public static final int ICONHAND;
Description
Topic under construction.

MessageBox.ICONINFORMATION

Syntax
public static final int ICONINFORMATION;
Description
Topic under construction.

MessageBox.ICONQUESTION

Syntax
public static final int ICONQUESTION;
Description
Topic under construction.

MessageBox.ICONSTOP

Syntax
public static final int ICONSTOP;
Description
Topic under construction.

MessageBox.ICONWARNING

Syntax
public static final int ICONWARNING;
Description
Topic under construction.

MessageBox.IDABORT

Syntax
public static final int IDABORT;
Description
Topic under construction.

MessageBox.IDCANCEL

Syntax
public static final int IDCANCEL;
Description
Topic under construction.

MessageBox.IDIGNORE

Syntax
public static final int IDIGNORE;
Description
Topic under construction.

MessageBox.IDNO

Syntax
public static final int IDNO;
Description
Topic under construction.

MessageBox.IDOK

Syntax
public static final int IDOK;
Description
Topic under construction.

MessageBox.IDRETRY

Syntax
public static final int IDRETRY;
Description
Topic under construction.

MessageBox.IDYES

Syntax
public static final int IDYES;
Description
Topic under construction.

MessageBox.OK

Syntax
public static final int OK;
Description
Topic under construction.

MessageBox.OKCANCEL

Syntax
public static final int OKCANCEL;
Description
Topic under construction.

MessageBox.RETRYCANCEL

Syntax
public static final int RETRYCANCEL;
Description
Topic under construction.

MessageBox.YESNO

Syntax
public static final int YESNO;
Description
Topic under construction.

MessageBox.YESNOCANCEL

Syntax
public static final int YESNOCANCEL;
Description
Topic under construction.

Methods

MessageBox.show

Syntax 1
public static int show( String text, String caption, int style );
Parameters
text
The text to show in the body of the message box.
caption
The title of the message box.
style
Controls the appearance of the message box. Specify a bitwise combination of the various values in the MessageBox class.
Return Value

Returns an integer with the value the user selected. For example, if the message box has a Yes/No/Cancel style, this method returns MessageBox.IDYES, MessageBox.IDNO, or MessageBox.IDCANCEL.

Description

Shows the message box with the given text, caption, and style.

Syntax 2
public static int show( String text, String caption );
Parameters
text
The text to show in the body of the message box.
caption
The title of the message box.
Return Value

Returns MessageBox.IDOK.

Description

Shows the message box with the given text and caption. The message box has the default style (OK button only).

Syntax 3
public static int show( String text );
Parameters
text
The text to show in the body of the message box.
Return Value

Returns MessageBox.IDOK.

Description

Shows the message box with the given text. The message box has the default style (OK button only) and no title.


 Metafile Class

Metafile Class

This Package | All Packages

Image
  |
  +--Metafile
public class Metafile
extends Image
implements IPersistable

Implements a Windows metafile as a WFC object.

Fields
Name | Description
EMR_HEADER | Topic under construction.
handle | Topic under construction.

Constructors
Name | Description
Metafile(Rectangle bounds) | Topic under construction.
Metafile(String filename) | Topic under construction.
Metafile(int hEMF, boolean fOwned) | Topic under construction.
Metafile(int hEMF) | Topic under construction.
Metafile(Class type, String resource) | Topic under construction.
Metafile(IDataStream stream) | Topic under construction.
Metafile(IStream stream) | Topic under construction.
Metafile(IPicture picture) | Topic under construction.

Methods
Name | Description
clone() | Topic under construction.
copyHandle(int h) | Retrieves a copy of the metafile.
copyHandle() | Retrieves a copy of the metafile.
dispose() | Topic under construction.
drawStretchTo(Graphics g, int x, int y, int width, int height, int rop) | Topic under construction.
drawTo(Graphics g, int x, int y, int width, int height, int rop) | Topic under construction.
finalize() | Topic under construction.
getEnhMetaFileHeader(ENHMETAHEADER emh) | Topic under construction.
getExtension() | Topic under construction.
getGraphics() | Topic under construction.
getHandle() | Topic under construction.
getPICTDESC() | Topic under construction.
getSize() | Topic under construction.
toString() | Topic under construction.

Fields

Metafile.EMR_HEADER

Syntax
public static final int EMR_HEADER;
Description
Topic under construction.

Metafile.handle

Syntax
public int handle;
Description
Topic under construction.

Constructors

Metafile.Metafile

Syntax 1
public Metafile( Rectangle bounds );
Description

Topic under construction.

Syntax 2
public Metafile( String filename );
Description

Topic under construction.

Syntax 3
public Metafile( int hEMF, boolean fOwned );
Description

Topic under construction.

Syntax 4
public Metafile( int hEMF );
Description

Topic under construction.

Syntax 5
public Metafile( Class type, String resource );
Description

Topic under construction.

Syntax 6
public Metafile( IDataStream stream );
Description

Topic under construction.

Syntax 7
public Metafile( IStream stream );
Description

Topic under construction.

Syntax 8
public Metafile( IPicture picture );
Description

Topic under construction.

Methods

Metafile.clone

Syntax
public Object clone();
Description

Topic under construction.

Metafile.copyHandle

Syntax 1
public static int copyHandle( int h );
Parameters
h
The handle to the metafile.
Description

Retrieves a copy of the metafile.

Syntax 2
public static int copyHandle();
Description

Retrieves a copy of the metafile.

Metafile.dispose

Syntax
public void dispose();
Description

Topic under construction.

Metafile.drawStretchTo

Syntax
public void drawStretchTo( Graphics g, int x, int y, int width, int height, int rop );
Description

Topic under construction.

Metafile.drawTo

Syntax
public void drawTo( Graphics g, int x, int y, int width, int height, int rop );
Description

Topic under construction.

Metafile.finalize

Syntax
public void finalize();
Description

Topic under construction.

Overrides

finalize() in Image.

Metafile.getEnhMetaFileHeader

Syntax
public ENHMETAHEADER getEnhMetaFileHeader( ENHMETAHEADER emh );
Description

Topic under construction.

Metafile.getExtension

Syntax
public String getExtension();
Description

Topic under construction.

Metafile.getGraphics

Syntax
public Graphics getGraphics();
Description

Topic under construction.

Metafile.getHandle

Syntax
public int getHandle();
Description

Topic under construction.

Metafile.getPICTDESC

Syntax
public PICTDESC getPICTDESC();
Description

Topic under construction.

Metafile.getSize

Syntax
public Point getSize();
Description

Topic under construction.

Metafile.toString

Syntax
public String toString();
Description

Topic under construction.

Overrides

toString() in Image.


 MouseEvent Class

MouseEvent Class

This Package | All Packages

Event
  |
  +--MouseEvent
public class MouseEvent
extends Event

Topic under construction.

Fields
Name | Description
button | Topic under construction.
clicks | Topic under construction.
delta | Topic under construction.
x | Topic under construction.
y | Topic under construction.

Constructors
Name | Description
MouseEvent(int button, int clicks, int x, int y, int delta) | Topic under construction.

Fields

MouseEvent.button

Syntax
public final int button;
Description
Topic under construction.

MouseEvent.clicks

Syntax
public final int clicks;
Description
Topic under construction.

MouseEvent.delta

Syntax
public final int delta;
Description
Topic under construction.

MouseEvent.x

Syntax
public final int x;
Description
Topic under construction.

MouseEvent.y

Syntax
public final int y;
Description
Topic under construction.

Constructors

MouseEvent.MouseEvent

Syntax
public MouseEvent( int button, int clicks, int x, int y, int delta );
Description

Topic under construction.


 OpenFileDialog Class

OpenFileDialog Class

This Package | All Packages

CommonDialog
  |
  +--FileDialog
    |
    +--OpenFileDialog
public class OpenFileDialog
extends FileDialog

Displays a Windows common dialog box that lets you select a file for opening. Most of the functionality for this Object is in the base class FileDialog.

The following code fragment shows a common usage of this class:

OpenFileDialog ofd = new OpenFileDialog();
// set up filters, default extensions, etc .
boolean didUserHitOK = ofd.run();
if (didUserHitOK) {
     String s = fd.getFilename();
     // or for multiple files...
     // String [] rg = fd.getFilenames();
}


 Orientation Class

Orientation Class

This Package | All Packages

Enum
  |
  +--Orientation
public class Orientation
extends Enum

Topic under construction.

Fields
Name | Description
HORIZONTAL | The control is oriented horizontally.
MAX | Topic under construction.
MIN | Topic under construction.
VERTICAL | The control is oriented vertically.

Fields

Orientation.HORIZONTAL

Syntax
public static final int HORIZONTAL;
Description
The control is oriented horizontally.

Orientation.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

Orientation.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

Orientation.VERTICAL

Syntax
public static final int VERTICAL;
Description
The control is oriented vertically.


 PaintEvent Class

PaintEvent Class

This Package | All Packages

Event
  |
  +--PaintEvent
public class PaintEvent
extends Event

Topic under construction.

Fields
Name | Description
clipRect | Topic under construction.
graphics | Topic under construction.

Constructors
Name | Description
PaintEvent(Graphics graphics, RECT rect) | Topic under construction.

Fields

PaintEvent.clipRect

Syntax
public final Rectangle clipRect;
Description
Topic under construction.

PaintEvent.graphics

Syntax
public final Graphics graphics;
Description
Topic under construction.

Constructors

PaintEvent.PaintEvent

Syntax
public PaintEvent( Graphics graphics, RECT rect );
Description

Topic under construction.


 Panel Class

Panel Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Panel
public class Panel
extends Control

Topic under construction.

Constructors
Name | Description
Panel() | Topic under construction.

Constructors

Panel.Panel

Syntax
public Panel();
Description

Topic under construction.


 Pen Class

Pen Class

This Package | All Packages

public final class Pen

This is a graphics pen. Pens are used to draw lines on graphics surfaces.

Fields
Name | Description
BLACK | Topic under construction.
NULL | Topic under construction.
STYLE_DASH | Creates a pen style that consists of a series of dashed lines: --------
STYLE_DASHDOT | Creates a pen style that consists of a dash, followed by a dot: _ .
STYLE_DASHDOTDOT | Creates a pen style that consists of a dash, followed by two dots: _ .
STYLE_DOT | Creates a pen style that consists of a dotted line: ...........
STYLE_INSIDEFRAME | Allows a pen to be drawn within a bounding rectangle.
STYLE_NULL | Creates a "null" pen, which is a pen that doesn't draw at all.
STYLE_SOLID | Creates a pen style that consists of a solid line: ___________
WHITE | Topic under construction.

Constructors
Name | Description
Pen(Color color) | Creates a new pen with the given color.
Pen(Color color, int style) | Creates a new pen with the given color and style.
Pen(Color color, int style, int width) | Creates a pen with the given style, color, and width.
Pen(int handle) | Creates a pen based on an existing Win32 HPEN handle.

Methods
Name | Description
equals(Object obj) | Checks equality of two pens.
finalize() throws Throwable | Finalizer for the pen; cleans up Win32 resources.
getColor() | Returns the color of this pen.
getHandle() | Returns the Win32 handle for this pen.
getStyle() | Returns the pen style.
getWidth() | Returns the pen width.
hashCode() | Computes the hash code for this object.

Fields

Pen.BLACK

Syntax
public static final Pen BLACK;
Description
Topic under construction.

Pen.NULL

Syntax
public static final Pen NULL;
Description
Topic under construction.

Pen.STYLE_DASH

Syntax
public static final int STYLE_DASH;
Description
Creates a pen style that consists of a series of dashed lines: --------

Pen.STYLE_DASHDOT

Syntax
public static final int STYLE_DASHDOT;
Description
Creates a pen style that consists of a dash, followed by a dot: _ . _ . _ .

Pen.STYLE_DASHDOTDOT

Syntax
public static final int STYLE_DASHDOTDOT;
Description
Creates a pen style that consists of a dash, followed by two dots: _ . . _ . . _ . .

Pen.STYLE_DOT

Syntax
public static final int STYLE_DOT;
Description
Creates a pen style that consists of a dotted line: ...........

Pen.STYLE_INSIDEFRAME

Syntax
public static final int STYLE_INSIDEFRAME;
Description
Allows a pen to be drawn within a bounding rectangle. Using this style allows you to have a wide pen that automatically conforms to the interior of a rectangle.

Pen.STYLE_NULL

Syntax
public static final int STYLE_NULL;
Description
Creates a "null" pen, which is a pen that doesn't draw at all. This is useful when you have a function that always draws a border, but you don't want the border.

Pen.STYLE_SOLID

Syntax
public static final int STYLE_SOLID;
Description
Creates a pen style that consists of a solid line: ___________

Pen.WHITE

Syntax
public static final Pen WHITE;
Description
Topic under construction.

Constructors

Pen.Pen

Syntax 1
public Pen( Color color );
Parameters
color
Color object specifying the color of the pen.
Description

Creates a new pen with the given color. The style of the pen will be solid [STYLE_SOLID]. The width of the pen is one [1] pixel.

Syntax 2
public Pen( Color color, int style );
Parameters
color
Color object with the pen's color.
style
Integer with the style of pen to create.
Description

Creates a new pen with the given color and style. The style should be one of the constants specified in the Pen class. The width of the pen is one [1] pixel.

Syntax 3
public Pen( Color color, int style, int width );
Parameters
color
Color object with the pen's color.
style
Integer with the style of the pen to create.
width
Integer with the desired width of the pen.
Description

Creates a pen with the given style, color, and width. The style should be one of the constants specified in the Pen class, and the width should be be greater than zero.

Exceptions

IllegalArgumentException thrown if there is an illegal argument.

Syntax 4
public Pen( int handle );
Parameters
handle
The Win32 HPEN to create the Pen object from.
Description

Creates a pen based on an existing Win32 HPEN handle.

Methods

Pen.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
Object to compare equality to.
Return Value

Returns true if the given object is equivalent to this object.

Description

Checks equality of two pens.

Pen.finalize

Syntax
protected void finalize() throws Throwable;
Description

Finalizer for the pen; cleans up Win32 resources.

Pen.getColor

Syntax
public Color getColor();
Return Value

Returns the pen color.

Description

Returns the color of this pen.

Pen.getHandle

Syntax
public int getHandle();
Return Value

Returns a Win32 HPEN.

Description

Returns the Win32 handle for this pen.

Pen.getStyle

Syntax
public int getStyle();
Return Value

Returns one of the Pen.STYLE_ constants.

Description

Returns the pen style.

Pen.getWidth

Syntax
public int getWidth();
Return Value

Returns the width of the pen.

Description

Returns the pen width.

Pen.hashCode

Syntax
public int hashCode();
Return Value

Returns an integer hash code value.

Description

Computes the hash code for this object.


 PictureBox Class

PictureBox Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--PictureBox
public class PictureBox
extends Control

Topic under construction.

Constructors
Name | Description
PictureBox() | Topic under construction.

Methods
Name | Description
getAutoSize() | Topic under construction.
getCenter() | Topic under construction.
getImage() | Topic under construction.
getPalette() | Topic under construction.
getStretch() | Topic under construction.
setAutoSize(boolean autoSize) | Topic under construction.
setCenter(boolean center) | Topic under construction.
setImage(Image image) | Topic under construction.
setStretch(boolean stretch) | Topic under construction.

Constructors

PictureBox.PictureBox

Syntax
public PictureBox();
Description

Topic under construction.

Methods

PictureBox.getAutoSize

Syntax
public boolean getAutoSize();
Description

Topic under construction.

PictureBox.getCenter

Syntax
public boolean getCenter();
Description

Topic under construction.

PictureBox.getImage

Syntax
public Image getImage();
Description

Topic under construction.

PictureBox.getPalette

Syntax
public Palette getPalette();
Description

Topic under construction.

Overrides

getPalette() in Control.

PictureBox.getStretch

Syntax
public boolean getStretch();
Description

Topic under construction.

PictureBox.setAutoSize

Syntax
public void setAutoSize( boolean autoSize );
Description

Topic under construction.

PictureBox.setCenter

Syntax
public void setCenter( boolean center );
Description

Topic under construction.

PictureBox.setImage

Syntax
public void setImage( Image image );
Description

Topic under construction.

PictureBox.setStretch

Syntax
public void setStretch( boolean stretch );
Description

Topic under construction.


 Point Class

Point Class

This Package | All Packages

public class Point
implements IConstructable, IPersistable

Represents a single (x,y) coordinate and various operations on such a coordinate.

Fields
Name | Description
x | The horizontal position of the coordinate.
y | The vertical position of the coordinate.

Constructors
Name | Description
Point() | Creates a new Point object at 0, 0.
Point(int x, int y) | Creates a new Point object at the given location.
Point(Point pt) | Creates a new Point object given an existing Point object.
Point(POINT pt) | Creates a new Point object given a Win32 POINT structure.
Point(SIZE size) | Creates a new Point object given a Win32 SIZE structure.
Point(int dw) | Creates a new Point object given the coordinates in a 32-bit integer.
Point(IDataStream stream) | Topic under construction.

Methods
Name | Description
equals(Object obj) | Tests to determine if the two points represent the same logical location.
getConstructorArgs() | Topic under construction.
getExtension() | Topic under construction.
hashCode() | Topic under construction.
save(IDataStream stream) | Topic under construction.
toPOINT() | Returns a Win32 POINT structure representing this object.
toSIZE() | Returns a Win32 SIZE structure representing this object.
toString() | Topic under construction.

Fields

Point.x

Syntax
public int x;
Description
The horizontal position of the coordinate.

Point.y

Syntax
public int y;
Description
The vertical position of the coordinate.

Constructors

Point.Point

Syntax 1
public Point();
Description

Creates a new Point object at 0, 0.

Syntax 2
public Point( int x, int y );
Parameters
x
The horizontal positon of the point.
y
The vertical position of the point.
Description

Creates a new Point object at the given location.

Syntax 3
public Point( Point pt );
Parameters
pt
The point object.
Description

Creates a new Point object given an existing Point object.

Syntax 4
public Point( POINT pt );
Parameters
pt
A Win32 POINT object.
Description

Creates a new Point object given a Win32 POINT structure.

Syntax 5
public Point( SIZE size );
Parameters
size
A Win32 SIZE structure.
Description

Creates a new Point object given a Win32 SIZE structure.

Syntax 6
public Point( int dw );
Parameters
dw
An integer with the two coordinate values in it.
Description

Creates a new Point object given the coordinates in a 32-bit integer. The low-order 16 bits are the horizontal [x] coordinate and the higher 16 bits are the vertical [y] coordinate.

Syntax 7
public Point( IDataStream stream );
Description

Topic under construction.

Methods

Point.equals

Syntax
public boolean equals( Object obj );
Parameters
value
Determines if this object is the same as the current one.
Return Value

Returns true if they are the same; otherwise, returns false.

Description

Tests to determine if the two points represent the same logical location. Doesn't actually test for object identity equality.

Point.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Description

Topic under construction.

Point.getExtension

Syntax
public String getExtension();
Description

Topic under construction.

Point.hashCode

Syntax
public int hashCode();
Description

Topic under construction.

Point.save

Syntax
public void save( IDataStream stream );
Description

Topic under construction.

Point.toPOINT

Syntax
public POINT toPOINT();
Return Value

Returns a Win32 POINT structure.

Description

Returns a Win32 POINT structure representing this object.

Point.toSIZE

Syntax
public SIZE toSIZE();
Return Value

Returns a Win32 SIZE structure.

Description

Returns a Win32 SIZE structure representing this object.

Point.toString

Syntax
public String toString();
Description

Topic under construction.


 ProgressBar Class

ProgressBar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ProgressBar
public class ProgressBar
extends Control

A progress bar control is a window that an application can use to indicate the progress of a lengthy operation. It consists of a rectangle that is gradually filled, from left to right, with the system highlight color as an operation progresses. A progress bar control has a range and a current position. The range represents the entire duration of the operation; the current position represents the progress the application has made toward completing the operation. The window procedure uses the range and the current position to determine the percentage of the progress bar to fill with the highlight color and to determine the text, if any, to display within the progress bar. Because the range and current position values are expressed as unsigned integers, the highest possible range or current position value is 65,535.

Constructors
Name | Description
ProgressBar() | Constructs a new ProgressBar control.

Methods
Name | Description
getMax() | Retrieves the maximum value for the progress bar.
getMin() | Retrieves the minimum value for the progress bar.
getPos() | Retrieves the current progress bar position.
getStep() | Retrieves the step increment for the progress bar control.
increment(int nHowMuch) | Advances the current position for a progress bar control by the specified step increment and redraws the bar to reflect the new position.
setMax(int nMaxNew) | Sets the maximum value for a progress bar and redraws the bar to reflect the new maximum.
setMin(int nMinNew) | Sets the minimum value for a progress bar and redraws the bar to reflect the new minimum.
setPos(int nPosNew) | Sets the current position for a progress bar and redraws the bar to reflect the new position.
setStep(int nStepNew) | Specifies the step increment for a progress bar.
step() | Advances the current position for a progress bar by the step increment and redraws the bar to reflect the new position.

Constructors

ProgressBar.ProgressBar

Syntax
public ProgressBar();
Description

Constructs a new ProgressBar control.

Methods

ProgressBar.getMax

Syntax
public synchronized int getMax();
Return Value

Returns an integer that contains the maximum progress bar value.

Description

Retrieves the maximum value for the progress bar.

ProgressBar.getMin

Syntax
public synchronized int getMin();
Return Value

Returns an integer that contains the minimum progress bar value.

Description

Retrieves the minimum value for the progress bar.

ProgressBar.getPos

Syntax
public synchronized int getPos();
Return Value

Returns an integer that identifies the current progress bar position.

Description

Retrieves the current progress bar position.

ProgressBar.getStep

Syntax
public synchronized int getStep();
Return Value

Returns an integer that identifies the current step increment.

Description

Retrieves the step increment for the progress bar control. The step increment is the amount by which a call to increment increases the progress bar's current position.

ProgressBar.increment

Syntax
public void increment( int nHowMuch );
Description

Advances the current position for a progress bar control by the specified step increment and redraws the bar to reflect the new position.

ProgressBar.setMax

Syntax
public synchronized void setMax( int nMaxNew );
Description

Sets the maximum value for a progress bar and redraws the bar to reflect the new maximum.

ProgressBar.setMin

Syntax
public synchronized void setMin( int nMinNew );
Description

Sets the minimum value for a progress bar and redraws the bar to reflect the new minimum.

ProgressBar.setPos

Syntax
public synchronized void setPos( int nPosNew );
Description

Sets the current position for a progress bar and redraws the bar to reflect the new position.

ProgressBar.setStep

Syntax
public synchronized void setStep( int nStepNew );
Description

Specifies the step increment for a progress bar. The step increment is the amount by which the progress bar increases its current position whenever the step method is called. By default, the step increment is set to 10.

ProgressBar.step

Syntax
public void step();
Description

Advances the current position for a progress bar by the step increment and redraws the bar to reflect the new position. An application sets the step increment by calling the setStep method.


 QueryContinueDragEvent Class

QueryContinueDragEvent Class

This Package | All Packages

Event
  |
  +--QueryContinueDragEvent
public class QueryContinueDragEvent
extends Event

The QueryContinueDragEvent is fired to determine if the drag operation should continue.

Fields
Name | Description
action | This will be used as the response to the query.
ACTION_CANCEL | The operation should be canceled, and no drop message sent.
ACTION_CONTINUE | The operation should continue.
ACTION_DROP | The operation should stop by performing a drop.
escapePressed | Set to true if the user has pressed the ESC key.
keyState | The current state of the SHIFT, CTRL, and ALT keys.

Constructors
Name | Description
QueryContinueDragEvent(int keyState, boolean escapePressed, int action) | Topic under construction.

Fields

QueryContinueDragEvent.action

Syntax
public int action;
Description
This will be used as the response to the query. Set to ACTION_CONTINUE to continue the drag operation.

QueryContinueDragEvent.ACTION_CANCEL

Syntax
public static final int ACTION_CANCEL;
Description
The operation should be canceled, and no drop message sent.

QueryContinueDragEvent.ACTION_CONTINUE

Syntax
public static final int ACTION_CONTINUE;
Description
The operation should continue.

QueryContinueDragEvent.ACTION_DROP

Syntax
public static final int ACTION_DROP;
Description
The operation should stop by performing a drop.

QueryContinueDragEvent.escapePressed

Syntax
public final boolean escapePressed;
Description
Set to true if the user has pressed the ESC key.

QueryContinueDragEvent.keyState

Syntax
public final int keyState;
Description
The current state of the SHIFT, CTRL, and ALT keys.

Constructors

QueryContinueDragEvent.QueryContinueDragEvent

Syntax
public QueryContinueDragEvent( int keyState, boolean escapePressed, int action );
Description

Topic under construction.


 RadioButton Class

RadioButton Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--RadioButton
public class RadioButton
extends Control

Encapsulates a radio button control. The control is a small circle that has the given text displayed next to it, typically to its right. The control highlights the circle and sends a message to its parent window when the user selects the button. The control removes the highlight and sends a message when the button is next selected.

Constructors
Name | Description
RadioButton() | Creates a RadioButton control.

Methods
Name | Description
addOnCheckedChanged(EventHandler handler) | Adds a listener to the OnCheckedChanged event.
getAlignText() | Retrieves the current text alignment for this control.
getAuto() | Retrieves a boolean value that indicates whether this button is checked, by default, where the button is a member of a group of buttons.
getChecked() | Retrieves a boolean value that indicates whether the button is checked.
getPushLike() | Retrieves a boolean value that indicates whether the button has the PushLike style set.
onCheckedChanged(Event e) | The onCheckedChanged event occurs when the value of the Checked property changes.
onClick(Event e) | The onClick event occurs when the user clicks on the RadioButton.
performClick() | Simulates a user click on the control.
removeOnCheckedChanged(EventHandler handler) | Removes an OnCheckedChanged event listener.
setAlignText(int value) | Sets the text alignment on this control.
setAuto(boolean value) | Specifies whether this button is automatically checked when it is a member of a group of buttons.
setChecked(boolean value) | Sets the checked value for the button.
setPushLike(boolean value) | Sets the PushLike style on the button.

Constructors

RadioButton.RadioButton

Syntax
public RadioButton();
Description

Creates a RadioButton control.

Methods

RadioButton.addOnCheckedChanged

Syntax
public final void addOnCheckedChanged( EventHandler handler );
Parameters
handler
Delegate to notify when the event occurs.
Description

Adds a listener to the OnCheckedChanged event.

See Also
removeOnCheckedChanged, onCheckedChanged

RadioButton.getAlignText

Syntax
public final int getAlignText();
Return Value

Returns one of the constants defined in the LeftRightAlignment class.

Description

Retrieves the current text alignment for this control.

See Also
setAlignText

RadioButton.getAuto

Syntax
public final boolean getAuto();
Return Value

Returns true if the button is to be automatically checked; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this button is checked, by default, where the button is a member of a group of buttons. Only one button in the group can be checked.

RadioButton.getChecked

Syntax
public final boolean getChecked();
Return Value

Returns true if the button is checked; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the button is checked.

RadioButton.getPushLike

Syntax
public final boolean getPushLike();
Return Value

Returns true if the button is currently configured to behave like a push button; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the button has the PushLike style set. Setting the PushLike style makes a radio button look and act like a push button. The button looks raised when it isn&#-110;t pushed or checked and sunken when it is pushed or checked.

See Also
setPushLike

RadioButton.onCheckedChanged

Syntax
protected void onCheckedChanged( Event e );
Parameters
e
Event data.
Description

The onCheckedChanged event occurs when the value of the Checked property changes.

RadioButton.onClick

Syntax
protected void onClick( Event e );
Parameters
e
Event data.
Description

The onClick event occurs when the user clicks on the RadioButton.

Overrides

onClick(Event) in Control.

RadioButton.performClick

Syntax
public final void performClick();
Description

Simulates a user click on the control.

RadioButton.removeOnCheckedChanged

Syntax
public final void removeOnCheckedChanged( EventHandler handler );
Parameters
handler
The delegate to remove from the event.
Description

Removes an OnCheckedChanged event listener.

See Also
addOnCheckedChanged, onCheckedChanged

RadioButton.setAlignText

Syntax
public final void setAlignText( int value );
Parameters
value
One of the constants defined by the LeftRightAlignment class.
Description

Sets the text alignment on this control.

See Also
getAlignText

RadioButton.setAuto

Syntax
public final void setAuto( boolean value );
Parameters
auto
If true, this button becomes the auto button for the group; otherwise, it does not.
Description

Specifies whether this button is automatically checked when it is a member of a group of buttons. Only one radio button for a given container can be the auto button for the group.

See Also
getAuto

RadioButton.setChecked

Syntax
public final void setChecked( boolean value );
Parameters
value
If true, the button is checked; otherwise, it is not.
Description

Sets the checked value for the button.

RadioButton.setPushLike

Syntax
public final void setPushLike( boolean value );
Parameters
push
If true, the button looks and behaves like a push button. Otherwise, it behaves like a standard radio button.
Description

Sets the PushLike style on the button. Setting the PushLike style makes a radio button look and act like a push button. The button looks raised when it isn&#-110;t pushed or checked,and sunken when it is pushed or checked.

See Also
getPushLike


 RasterOp Class

RasterOp Class

This Package | All Packages

public class RasterOp

The RasterOp class encapsulates a Win32 raster operation. A raster operation refers to a series of boolean operations that you can apply to bitmaps, brushes, and pens. Suppose, for example, that you have two identical images, one of which is black and white, and the other of which is in color. Suppose that you want to write the monochrome image to the colored one, but do not want the white pixels in the source image to overwrite their counterparts in the destination. Raster operations enable you to use boolean logic to express such wishes. You generally build a raster operation using a combination of a series of simple operations and boolean logic. The following raster operations represent the primitives on which you can build. BLACK The resulting pixel(s) will be black. BRUSH The resulting pixel(s) will be the color of the current brush. PEN The resulting pixel(s) will be the color of the current pen. SOURCE The resulting pixel(s) will be the color of the source bitmap image. TARGET The resulting pixel(s) will be the color of the target bitmap image. WHITE The resulting pixel(s) will be white. You can combine one or more simple raster operations using boolean logic to create more complex operations. For example, to draw a line that is always the inverse of the screen color, you would pass the return value of RasterOp.TARGET.invert() as a parameter to a drawing operation defined in the Graphics class. Much more complex effects can be created using boolean AND, OR, and XOR operators.

Fields
Name | Description
BLACK | The resulting pixels will be black.
BRUSH | The resulting pixels will be the color of the current brush.
PEN | The resulting pixels will be the color of the current pen.
SOURCE | The resulting pixels will be the color of the source image pixels.
TARGET | The resulting pixels will be the color of the target image pixels.
WHITE | The resulting pixels will be white.

Methods
Name | Description
andWith(RasterOp op) | Performs a binary AND operation that combines this RasterOp with another.
getRop() | Retrieves the ternary ROP code for this raster operation.
getRop2() | Retrieves the binary ROP2 code for this raster operation.
invert() | Retrieves an RasterOp object that represents an inversion of this one.
orWith(RasterOp op) | Performs a binary OR operation that combines this RasterOp with another.
xorWith(RasterOp op) | Performs a binary XOR operation that combines this RasterOp with another.

Fields

RasterOp.BLACK

Syntax
public static final RasterOp BLACK;
Description
The resulting pixels will be black.

RasterOp.BRUSH

Syntax
public static final RasterOp BRUSH;
Description
The resulting pixels will be the color of the current brush.

RasterOp.PEN

Syntax
public static final RasterOp PEN;
Description
The resulting pixels will be the color of the current pen.

RasterOp.SOURCE

Syntax
public static final RasterOp SOURCE;
Description
The resulting pixels will be the color of the source image pixels.

RasterOp.TARGET

Syntax
public static final RasterOp TARGET;
Description
The resulting pixels will be the color of the target image pixels.

RasterOp.WHITE

Syntax
public static final RasterOp WHITE;
Description
The resulting pixels will be white.

Methods

RasterOp.andWith

Syntax
public final RasterOp andWith( RasterOp op );
Parameters
op
The RasterOp that participates with this one in the operation.
Return Value

Returns a RasterOp object that represents the result of the binary AND operation.

Description

Performs a binary AND operation that combines this RasterOp with another.

RasterOp.getRop

Syntax
public int getRop();
Return Value

Returns the ternary ROP code for this raster operation.

Description

Retrieves the ternary ROP code for this raster operation.

RasterOp.getRop2

Syntax
public int getRop2();
Return Value

Returns the binary ROP2 code for this raster operation.

Description

Retrieves the binary ROP2 code for this raster operation.

RasterOp.invert

Syntax
public final RasterOp invert();
Return Value

Returns the inverted raster operation.

Description

Retrieves an RasterOp object that represents an inversion of this one.

RasterOp.orWith

Syntax
public final RasterOp orWith( RasterOp op );
Parameters
op
The RasterOp that participates with this one in the operation.
Return Value

Returns a RasterOp object that represents the result of the binary OR operation.

Description

Performs a binary OR operation that combines this RasterOp with another.

RasterOp.xorWith

Syntax
public final RasterOp xorWith( RasterOp op );
Parameters
op
The RasterOp that participates with this one in the operation.
Return Value

Returns a RasterOp object that represents the result of the binary XOR operation.

Description

Performs a binary XOR operation that combines this RasterOp with another.


 Rebar Class

Rebar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Rebar
public class Rebar
extends Control

Encapsulates a Rebar control. A Rebar control is a toolbar control that hosts other controls inside moveable bands. You can use these bands to resize, reposition, or hide the control.

Constructors
Name | Description
Rebar() | Creates a Rebar control.

Methods
Name | Description
add(Control control) | Adds a control to the Rebar control.
addBand(RebarBand band) | Adds a RebarBand to the Rebar control.
addOnAutoSize(AutoSizeEventHandler handler) | Adds an onAutoSize event listener.
addOnHeightChange(EventHandler handler) | Adds an onHeightChange event listener.
addOnLayoutChange(EventHandler handler) | Adds an onLayoutChange event listener.
getAutoSize() | Retrieves a boolean value that indicates whether autosizing is set for the Rebar control.
getBandBorders() | Retrieves a boolean value that indicates whether the current control has BandBorders.
getBands() | Retrieves the current bands and returns them in an array of RebarBand objects.
getBorder() | Retrieves a boolean value that indicates whether the current control has a border.
getDoubleClickToggle() | Topic under construction.
getFixedOrder() | Topic under construction.
getImageList() | Retrieves the current ImageList.
getOrientation() | Retrieves the current orientation of the control.
onAutoSize(AutoSizeEvent event) | The event handler for the autoSize event, which occurs when autosizing is applied to the bands in the Rebar control.
onHeightChange(Event event) | The heightChange event handler, which occurs whenever bands are repositioned to require the height of the control to change.
onLayoutChange(Event event) | The layoutChange event handler, which occurs whenever the bands position changes.
onResize(Event event) | The event handler for the onResize event, which is fired whenever the control's dimensions change.
remove(Control ctl) | Removes a control from the Rebar control.
removeAllBands() | Removes all bands from the Rebar.
removeBand(RebarBand band) | Removes a specified band from the Rebar.
removeOnAutoSize(AutoSizeEventHandler handler) | Removes an onAutoSize event listener.
removeOnHeightChange(EventHandler handler) | Removes an onHeightChange event listener.
removeOnLayoutChange(EventHandler handler) | Removes an onLayoutChange event listener.
setAutoSize(boolean value) | Sets the AutoSize property.
setBandBorders(boolean value) | Sets the BandBorders.
setBands(RebarBand[] bands) | Sets the bands.
setBorder(boolean value) | Sets the Border property.
setDock(int dock) | Topic under construction.
setDoubleClickToggle(boolean value) | Sets the DoubleClickToggle property.
setFixedOrder(boolean value) | Sets the FixedOrder property.
setImageList(ImageList value) | Sets the ImageList to be used with the Rebar.
setNewControls(Control[] ctls) | Sets the controls that will appear in the Rebar.
setOrientation(int value) | Sets the Orientation property.
setSite(ISite site) | Topic under construction.

Constructors

Rebar.Rebar

Syntax
public Rebar();
Description

Creates a Rebar control.

Methods

Rebar.add

Syntax
public void add( Control control );
Parameters
control
The control to add.
Description

Adds a control to the Rebar control.

Overrides

add(Control) in Control.

See Also
wfc.ui.Control.add

Rebar.addBand

Syntax
public void addBand( RebarBand band );
Parameters
band
The RebarBand to add to the Rebar control.
Description

Adds a RebarBand to the Rebar control.

Rebar.addOnAutoSize

Syntax
public void addOnAutoSize( AutoSizeEventHandler handler );
Parameters
handler
The delegate to add to the event.
Description

Adds an onAutoSize event listener.

See Also
removeOnAutoSize, onAutoSize

Rebar.addOnHeightChange

Syntax
public void addOnHeightChange( EventHandler handler );
Parameters
handler
The delegate to add to the event.
Description

Adds an onHeightChange event listener.

See Also
removeOnHeightChange, onHeightChange

Rebar.addOnLayoutChange

Syntax
public void addOnLayoutChange( EventHandler handler );
Parameters
handler
The delegate to add to the event.
Description

Adds an onLayoutChange event listener.

See Also
removeOnLayoutChange, onLayoutChange

Rebar.getAutoSize

Syntax
public boolean getAutoSize();
Return Value

Returns current AutoSize value.

Description

Retrieves a boolean value that indicates whether autosizing is set for the Rebar control.

See Also
setAutoSize

Rebar.getBandBorders

Syntax
public boolean getBandBorders();
Return Value

Returns true if the control has BandBorders; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current control has BandBorders.

See Also
setBandBorders

Rebar.getBands

Syntax
public RebarBand[] getBands();
Return Value

Returns an array of RebarBand objects that contains the current bands for this control.

Description

Retrieves the current bands and returns them in an array of RebarBand objects.

See Also
setBands

Rebar.getBorder

Syntax
public boolean getBorder();
Return Value

Returns true if the control has a border; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current control has a border.

See Also
setBorder

Rebar.getDoubleClickToggle

Syntax
public boolean getDoubleClickToggle();
Description

Topic under construction.

Rebar.getFixedOrder

Syntax
public boolean getFixedOrder();
Description

Topic under construction.

Rebar.getImageList

Syntax
public ImageList getImageList();
Return Value

Returns the current ImageList.

Description

Retrieves the current ImageList.

See Also
setImageList

Rebar.getOrientation

Syntax
public int getOrientation();
Return Value

Returns one of the enumeration constants defined in Orientation.HORIZONTAL.

Description

Retrieves the current orientation of the control.

See Also
setOrientation

Rebar.onAutoSize

Syntax
protected void onAutoSize( AutoSizeEvent event );
Parameters
event
The event data.
Description

The event handler for the autoSize event, which occurs when autosizing is applied to the bands in the Rebar control.

Rebar.onHeightChange

Syntax
protected void onHeightChange( Event event );
Parameters
event
The event data.
Description

The heightChange event handler, which occurs whenever bands are repositioned to require the height of the control to change.

Rebar.onLayoutChange

Syntax
protected void onLayoutChange( Event event );
Parameters
event
The event data.
Description

The layoutChange event handler, which occurs whenever the bands position changes.

Rebar.onResize

Syntax
protected void onResize( Event event );
Parameters
event
The event data.
Description

The event handler for the onResize event, which is fired whenever the control's dimensions change.

Overrides

onResize(Event) in Control.

See Also
wfc.ui.Control.onResize(Event)

Rebar.remove

Syntax
public void remove( Control ctl );
Parameters
ctl
The control to remove.
Description

Removes a control from the Rebar control.

Overrides

remove(Control) in Control.

See Also
wfc.ui.Control.remove(com.ms.wfc.ui.Control)

Rebar.removeAllBands

Syntax
public void removeAllBands();
Description

Removes all bands from the Rebar.

Rebar.removeBand

Syntax
public void removeBand( RebarBand band );
Parameters
band
The band to remove.
Description

Removes a specified band from the Rebar.

Rebar.removeOnAutoSize

Syntax
public void removeOnAutoSize( AutoSizeEventHandler handler );
Parameters
handler
The delegate to remove.
Description

Removes an onAutoSize event listener.

See Also
addOnAutoSize, onAutoSize

Rebar.removeOnHeightChange

Syntax
public void removeOnHeightChange( EventHandler handler );
Parameters
handler
The delegate to remove.
Description

Removes an onHeightChange event listener.

See Also
addOnHeightChange, onHeightChange

Rebar.removeOnLayoutChange

Syntax
public void removeOnLayoutChange( EventHandler handler );
Parameters
handler
The delegate to remove.
Description

Removes an onLayoutChange event listener.

See Also
addOnLayoutChange, onLayoutChange

Rebar.setAutoSize

Syntax
public void setAutoSize( boolean value );
Parameters
value
The new value for the AutoSize property.
Description

Sets the AutoSize property. When AutoSize is set to true, the Rebar automatically sizes itself to fit the contained bands.

See Also
getAutoSize

Rebar.setBandBorders

Syntax
public void setBandBorders( boolean value );
Parameters
value
The new value for BandBorders.
Description

Sets the BandBorders. When BandBorders is set to true, a small border is drawn around each band.

See Also
getBandBorders

Rebar.setBands

Syntax
public void setBands( RebarBand[] bands );
Parameters
bands
The list of bands that the Rebar will contain.
Description

Sets the bands. Each band in the Rebar contains a child control.

See Also
getBands

Rebar.setBorder

Syntax
public void setBorder( boolean value );
Parameters
value
The new value for the Border property.
Description

Sets the Border property. When Border is set to true, a small border is drawn around the Rebar.

See Also
getBorder

Rebar.setDock

Syntax
public void setDock( int dock );
Description

Topic under construction.

Overrides

setDock(int) in Control.

Rebar.setDoubleClickToggle

Syntax
public void setDoubleClickToggle( boolean value );
Parameters
value
The new DoubleClickToggle value.
Description

Sets the DoubleClickToggle property. When DoubleClickToggle is set to true, users can enlarge and shrink bands by double-clicking the band header.

See Also
getDoubleClickToggle

Rebar.setFixedOrder

Syntax
public void setFixedOrder( boolean value );
Parameters
value
The new value for the FixedOrder property.
Description

Sets the FixedOrder property. When FixedOrder is set to true, the contained bands can be sized, but the order of the bands cannot be changed.

See Also
getFixedOrder

Rebar.setImageList

Syntax
public void setImageList( ImageList value );
Parameters
value
The ImageList to be used.
Description

Sets the ImageList to be used with the Rebar.

See Also
getImageList

Rebar.setNewControls

Syntax
public void setNewControls( Control[] ctls );
Parameters
ctls
The controls to put in the Rebar.
Description

Sets the controls that will appear in the Rebar.

Overrides

setNewControls(Control[]) in Control.

See Also
wfc.ui.Control.setNewControls

Rebar.setOrientation

Syntax
public void setOrientation( int value );
Parameters
value
The new orientation value.
Description

Sets the Orientation property. This controls the direction in which the bands are drawn.

See Also
getOrientation

Rebar.setSite

Syntax
public void setSite( ISite site );
Description

Topic under construction.

Overrides

setSite(ISite) in Control.

See Also
wfc.core.Component.setSite


 RebarBand Class

RebarBand Class

This Package | All Packages

Component
  |
  +--RebarBand
public class RebarBand
extends Component

This class encapsulates a RebarBand, a child control in a Rebar object.

Constructors
Name | Description
RebarBand() | Creates a RebarBand.

Methods
Name | Description
equals(Object obj) | Retrieves a boolean value that indicates whether the specified object is equal to this one.
getAllowVariableHeight() | Retrieves a boolean value that indicates whether this RebarBand can have variable height.
getAllowVertical() | Retrieves a boolean value that indicates whether this RebarBand can be drawn vertically.
getBackColor() | Retrieve the current BackColor for this RebarBand.
getBackgroundImage() | Retrieves the background image associated with this RebarBand.
getBandBreak() | Retrieves the BandBreak value.
getBounds() | Retrieves a rectangle that defines the bounds of the RebarBand.
getChildControl() | Retrieves the child window for this RebarBand.
getChildEdge() | Retrieves the current state of the ChildEdge style for this RebarBand.
getFixedBitmap() | Retrieves the current state of the FixedBitmap style for this RebarBand.
getForeColor() | Retrieves the current ForeColor of this RebarBand.
getGrowBy() | Retrieves the current value that a variable height RebarBand can grow or shrink by during resizing.
getHeaderWidth() | Retrieves the current value for the width of the RebarBand's header.
getIdealWidth() | Retrieves the RebarBand's ideal width setting.
getImageIndex() | Retrieves the RebarBand's image index in the rebar's imagelist.
getIndex() | Retrieves the RebarBand's current index within the rebar control.
getInitialHeight() | Retrieves the RebarBand's initial display height.
getMaxInitialHeight() | Retrieves the RebarBand's maximum initial display height.
getMinChildHeight() | Retrieves the RebarBand's minimum height for its child window.
getMinChildWidth() | Retrieves the minimum width of the RebarBand's child window.
getText() | Retrieves the RebarBand's header text.
getVisible() | Retrieves a boolean value that indicates whether the RebarBand is visible.
getVisibleGripper() | Retrieves a boolean value that indicates whether the RebarBand's gripper is visible.
getWidth() | Retrieves the RebarBand's current width.
maximize() | Maximizes the current RebarBand within the Rebar control.
minimize() | Minimizes the current RebarBand within the Rebar control.
setAllowVariableHeight(boolean flag) | Sets the RebarBand's VariableHeight style.
setAllowVertical(boolean flag) | Sets the RebarBand's Vertical property.
setBackColor(Color backColor) | Sets the RebarBand's current backcolor.
setBackgroundImage(Bitmap backgroundImage) | Sets the background image of the RebarBand.
setBandBreak(boolean value) | Sets the BandBreak property.
setChildControl(Control childControl) | Sets the child window for this RebarBand.
setChildEdge(boolean flag) | Sets the RebarBand's ChildEdge property.
setFixedBitmap(boolean flag) | Sets the RebarBand's FixedBitmap property.
setForeColor(Color foreColor) | Sets the ForeColor for this RebarBand.
setGrowBy(int growby) | Sets the number of pixels this RebarBand can grow by when being resized.
setHeaderWidth(int headerWidth) | Sets the pixel width for the RebarBand's header.
setIdealWidth(int idealWidth) | Sets the ideal width for a RebarBand in the Rebar control.
setImageIndex(int imageIndex) | Sets the index of the image in the Rebar control's image list.
setIndex(int index) | Sets the index for this RebarBand.
setInitialHeight(int initHeight) | Sets the initial height of a variable-height RebarBand in the Rebar control.
setMaxInitialHeight(int maxInitHeight) | Sets the maximum initial height of a non-variable height RebarBand in the Rebar control.
setMinChildHeight(int minChildHeight) | Sets the minimum initial height of this RebarBand's child window.
setMinChildWidth(int minChildWidth) | Sets the minimum initial width of this RebarBand's child window.
setText(String text) | Sets the header text for this RebarBand.
setVisible(boolean flag) | Sets the RebarBand's Visible property.
setVisibleGripper(boolean flag) | Sets the RebarBand's VisibleGripper property.
setWidth(int width) | Sets the pixel width of the RebarBand.
toString() | Returns a string representation of this object.

Constructors

RebarBand.RebarBand

Syntax
public RebarBand();
Description

Creates a RebarBand.

Methods

RebarBand.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The object to compare to this one.
Return Value

Returns true, if the objects are equal; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified object is equal to this one.

RebarBand.getAllowVariableHeight

Syntax
public boolean getAllowVariableHeight();
Return Value

Returns true if this RebarBand's height can vary; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this RebarBand can have variable height.

RebarBand.getAllowVertical

Syntax
public boolean getAllowVertical();
Return Value

Returns true if the RebarBand can be displayed vertically; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this RebarBand can be drawn vertically.

RebarBand.getBackColor

Syntax
public Color getBackColor();
Return Value

Returns the current BackColor setting.

Description

Retrieve the current BackColor for this RebarBand.

RebarBand.getBackgroundImage

Syntax
public Bitmap getBackgroundImage();
Return Value

Returns the current background image.

Description

Retrieves the background image associated with this RebarBand.

RebarBand.getBandBreak

Syntax
public boolean getBandBreak();
Return Value

Returns the BandBreak value.

Description

Retrieves the BandBreak value.

See Also
setBandBreak

RebarBand.getBounds

Syntax
public Rectangle getBounds();
Return Value

Returns a Rectangle object that contains the bounds of the RebarBand.

Description

Retrieves a rectangle that defines the bounds of the RebarBand.

RebarBand.getChildControl

Syntax
public Control getChildControl();
Return Value

Returns the current child control.

Description

Retrieves the child window for this RebarBand.

RebarBand.getChildEdge

Syntax
public boolean getChildEdge();
Return Value

Returns the current state for the ChildEdge style.

Description

Retrieves the current state of the ChildEdge style for this RebarBand.

RebarBand.getFixedBitmap

Syntax
public boolean getFixedBitmap();
Return Value

Returns the current state for the FixedBitmap style.

Description

Retrieves the current state of the FixedBitmap style for this RebarBand.

RebarBand.getForeColor

Syntax
public Color getForeColor();
Return Value

Returns the current ForeColor color setting.

Description

Retrieves the current ForeColor of this RebarBand.

RebarBand.getGrowBy

Syntax
public int getGrowBy();
Return Value

Returns the current grow or shrink value for a variable height RebarBand.

Description

Retrieves the current value that a variable height RebarBand can grow or shrink by during resizing.

RebarBand.getHeaderWidth

Syntax
public int getHeaderWidth();
Return Value

Returns the current header width for this RebarBand.

Description

Retrieves the current value for the width of the RebarBand's header.

RebarBand.getIdealWidth

Syntax
public int getIdealWidth();
Return Value

Returns the current RebarBand's ideal width.

Description

Retrieves the RebarBand's ideal width setting.

RebarBand.getImageIndex

Syntax
public int getImageIndex();
Return Value

Returns the current RebarBand's ImageList image index.

Description

Retrieves the RebarBand's image index in the rebar's imagelist.

RebarBand.getIndex

Syntax
public int getIndex();
Return Value

Returns the current RebarBand's index in the parent rebar control.

Description

Retrieves the RebarBand's current index within the rebar control.

RebarBand.getInitialHeight

Syntax
public int getInitialHeight();
Return Value

Returns the current RebarBand's initial display height

Description

Retrieves the RebarBand's initial display height. This value is used for variable height bands.

RebarBand.getMaxInitialHeight

Syntax
public int getMaxInitialHeight();
Return Value

Returns the current RebarBand's maximum initial display height.

Description

Retrieves the RebarBand's maximum initial display height. Used for non-variable height bands.

RebarBand.getMinChildHeight

Syntax
public int getMinChildHeight();
Return Value

Returns the current RebarBand's minimum height for the child window.

Description

Retrieves the RebarBand's minimum height for its child window.

RebarBand.getMinChildWidth

Syntax
public int getMinChildWidth();
Return Value

Returns the minimum width of the RebarBand's child window.

Description

Retrieves the minimum width of the RebarBand's child window.

RebarBand.getText

Syntax
public String getText();
Return Value

Returns the RebarBand's header text.

Description

Retrieves the RebarBand's header text.

RebarBand.getVisible

Syntax
public boolean getVisible();
Return Value

Returns true if the RebarBand is visible; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the RebarBand is visible.

RebarBand.getVisibleGripper

Syntax
public boolean getVisibleGripper();
Return Value

Returns true if the gripper is visible; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the RebarBand's gripper is visible.

RebarBand.getWidth

Syntax
public int getWidth();
Return Value

Returns the current RebarBand's width.

Description

Retrieves the RebarBand's current width.

RebarBand.maximize

Syntax
public void maximize();
Description

Maximizes the current RebarBand within the Rebar control.

RebarBand.minimize

Syntax
public void minimize();
Description

Minimizes the current RebarBand within the Rebar control.

RebarBand.setAllowVariableHeight

Syntax
public void setAllowVariableHeight( boolean flag );
Parameters
flag
The VariableHeight style.
Description

Sets the RebarBand's VariableHeight style.

RebarBand.setAllowVertical

Syntax
public void setAllowVertical( boolean flag );
Parameters
flag
The Vertical property setting.
Description

Sets the RebarBand's Vertical property.

RebarBand.setBackColor

Syntax
public void setBackColor( Color backColor );
Parameters
backColor
The RebarBand's new current backcolor.
Description

Sets the RebarBand's current backcolor.

RebarBand.setBackgroundImage

Syntax
public void setBackgroundImage( Bitmap backgroundImage );
Parameters
backgroundImage
The RebarBand's new background bitmap.
Description

Sets the background image of the RebarBand.

RebarBand.setBandBreak

Syntax
public void setBandBreak( boolean value );
Parameters
value
The new value for the BandBreak property.
Description

Sets the BandBreak property. If BandBreak is set to true, this RebarBand will start on a new row.

See Also
getBandBreak

RebarBand.setChildControl

Syntax
public void setChildControl( Control childControl );
Parameters
childControl
The child control.
Description

Sets the child window for this RebarBand.

RebarBand.setChildEdge

Syntax
public void setChildEdge( boolean flag );
Parameters
flag
The new state of the ChildEdge property.
Description

Sets the RebarBand's ChildEdge property.

RebarBand.setFixedBitmap

Syntax
public void setFixedBitmap( boolean flag );
Parameters
flag
The state of the FixedBitmap property.
Description

Sets the RebarBand's FixedBitmap property.

RebarBand.setForeColor

Syntax
public void setForeColor( Color foreColor );
Parameters
foreColor
The ForeColor for this RebarBand.
Description

Sets the ForeColor for this RebarBand.

RebarBand.setGrowBy

Syntax
public void setGrowBy( int growby );
Parameters
growby
Pixels to grow by in variable-height mode.
Description

Sets the number of pixels this RebarBand can grow by when being resized. If this RebarBand is not a variable-height band, calls to this method are ignored.

RebarBand.setHeaderWidth

Syntax
public void setHeaderWidth( int headerWidth );
Parameters
headerWidth
Pixel width for the RebarBand's header text.
Description

Sets the pixel width for the RebarBand's header.

RebarBand.setIdealWidth

Syntax
public void setIdealWidth( int idealWidth );
Parameters
idealWidth
The ideal width.
Description

Sets the ideal width for a RebarBand in the Rebar control.

RebarBand.setImageIndex

Syntax
public void setImageIndex( int imageIndex );
Parameters
imageIndex
The index of this Rebar control's image.
Description

Sets the index of the image in the Rebar control's image list.

RebarBand.setIndex

Syntax
public void setIndex( int index );
Parameters
index
The index for this RebarBand.
Description

Sets the index for this RebarBand.

See Also
getIndex

RebarBand.setInitialHeight

Syntax
public void setInitialHeight( int initHeight );
Parameters
initHeight
Initial height of RebarBand in the Rebar control.
Description

Sets the initial height of a variable-height RebarBand in the Rebar control.

RebarBand.setMaxInitialHeight

Syntax
public void setMaxInitialHeight( int maxInitHeight );
Parameters
maxInitHeight
The maximum initial height of this RebarBand in the Rebar control.
Description

Sets the maximum initial height of a non-variable height RebarBand in the Rebar control.

RebarBand.setMinChildHeight

Syntax
public void setMinChildHeight( int minChildHeight );
Parameters
minChildHeight
The minimum initial height of this RebarBand's child window.
Description

Sets the minimum initial height of this RebarBand's child window.

RebarBand.setMinChildWidth

Syntax
public void setMinChildWidth( int minChildWidth );
Parameters
minChildWidth
The minimum initial width of this RebarBand's child window
Description

Sets the minimum initial width of this RebarBand's child window.

RebarBand.setText

Syntax
public void setText( String text );
Parameters
text
Text to be displayed in the header of this RebarBand.
Description

Sets the header text for this RebarBand.

RebarBand.setVisible

Syntax
public void setVisible( boolean flag );
Parameters
flag
The new state of the Visible property.
Description

Sets the RebarBand's Visible property.

RebarBand.setVisibleGripper

Syntax
public void setVisibleGripper( boolean flag );
Parameters
flag
The new state of the VisibleGripper property.
Description

Sets the RebarBand's VisibleGripper property.

RebarBand.setWidth

Syntax
public void setWidth( int width );
Parameters
width
The pixel width for this RebarBand.
Description

Sets the pixel width of the RebarBand.

RebarBand.toString

Syntax
public String toString();
Return Value

Returns a String representation of this RebarBand object.

Description

Returns a string representation of this object.


 Rectangle Class

Rectangle Class

This Package | All Packages

public class Rectangle
implements IPersistable, IConstructable

The Rectangle class is similar to a Win32 RECT structure. The Rectangle class also includes member functions to manipulate Rectangle objects and Win32 RECT structures. A Rectangle object also contains member variables that define the top, left, bottom, and right points of a rectangle.

Fields
Name | Description
height | Stores the height of the rectangle.
width | Stores the width of the rectangle.
x | Stores the x-position (or horizontal origin) of the rectangle.
y | Stores the y-position (or vertical origin) of the rectangle.

Constructors
Name | Description
Rectangle() | Constructs a Rectangle object.
Rectangle(IDataStream stream) | Constructs a Rectangle object and initializes the object from a data stream.
Rectangle(Rectangle r) | Constructs a Rectangle object and initializes it to the specified Rectangle's settings.
Rectangle(int x, int y, int width, int height) | Constructs a Rectangle object and initializes it to the settings contained in the specified Rectangle object.
Rectangle(RECT rect) | Constructs a Rectangle object and initializes it to the settings stored in a Win32 RECT.

Methods
Name | Description
contains(Point pt) | Retrieves a boolean value that indicates whether this rectangle contains the specified points.
contains(int x, int y) | Retrieves a boolean value that indicates whether this rectangle contains the specified points.
contains(Rectangle rect) | Retrieves a boolean value that indicates whether the specified rectangle is less than or equal to this one.
equals(Object obj) | Retrieves a boolean value that indicates whether the specified object is identical to this rectangle.
getBottom() | Returns the lowest point in the rectangle's y-axis.
getConstructorArgs() | Topic under construction.
getExtension() | Because the Rectangle object is not a file-based object, this method always returns null.
getRight() | Retrieves the right-most point on the rectangle's x-axis.
hashCode() | Topic under construction.
inflateRect(int x, int y) | Expands the size of the rectangle using the specified x and y values.
intersectRect(Rectangle lpRect1, Rectangle lpRect2) | Retrieves a boolean value that indicates whether two rectangles intersect.
intersectsWith(Rectangle rect) | Retrieves a boolean value that indicates whether the specified rectangle intersects with this one.
save(IDataStream stream) | Saves this object's settings to a data stream.
setBounds(int x, int y, int width, int height) | Initializes this Rectangle object.
setBounds(RECT r) | Copies the specified values to this Rectangle object.
setBounds(Rectangle r) | Copies the specified Rectangle object to this rectangle.
toRECT() | Retrieves a Win32 RECT structure that contains the settings of this Rectangle object.
toRECT(Rectangle r) | Retrieves a Win32 RECT structure that contains the settings of the specified Rectangle object.
toString() | Retrieves a String representation of this object.

Fields

Rectangle.height

Syntax
public int height;
Description
Stores the height of the rectangle.

Rectangle.width

Syntax
public int width;
Description
Stores the width of the rectangle.

Rectangle.x

Syntax
public int x;
Description
Stores the x-position (or horizontal origin) of the rectangle.

Rectangle.y

Syntax
public int y;
Description
Stores the y-position (or vertical origin) of the rectangle.

Constructors

Rectangle.Rectangle

Syntax 1
public Rectangle();
Description

Constructs a Rectangle object.

Syntax 2
public Rectangle( IDataStream stream );
Description

Constructs a Rectangle object and initializes the object from a data stream.

Syntax 3
public Rectangle( Rectangle r );
Parameters
stream
The data stream from which to initialize the Rectangle.
Description

Constructs a Rectangle object and initializes it to the specified Rectangle's settings.

Syntax 4
public Rectangle( int x, int y, int width, int height );
Parameters
A
Rectangle object.
Description

Constructs a Rectangle object and initializes it to the settings contained in the specified Rectangle object.

Syntax 5
public Rectangle( RECT rect );
Parameters
rect
A Win32 RECT structure.
Description

Constructs a Rectangle object and initializes it to the settings stored in a Win32 RECT.

Methods

Rectangle.contains

Syntax 1
public boolean contains( Point pt );
Parameters
pt
A point that contains the x and y values to be compared.
Return Value

Returns true if this rectangle contains the specified coordinates; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this rectangle contains the specified points. The x and y parameters in the pt parameter must be less than or equal to the x and y positions in the rectangle. In addition, the point's x value must be less than the rectangle's width and the point's y value must be less than the rectangle's height.

Syntax 2
public boolean contains( int x, int y );
Parameters
x
The x value to compare to the x-coordinate and width of the rectangle.
y
The y value to compare to the y-coordinate and height of the rectangle.
Return Value

Returns true, if the Rectangle contains the specified coordinates; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this rectangle contains the specified points. The specified x and y parameters must be less than or equal to the x and y coordinates in the rectangle. In addition, the x and y parameters must be less than the width and height of the rectangle, respectively.

Syntax 3
public boolean contains( Rectangle rect );
Parameters
rect
The rectangle to compare to this one.
Return Value

Returns true if this rectangle contains the coordinates stored in the specified rectangle; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified rectangle is less than or equal to this one.

Rectangle.equals

Syntax
public boolean equals( Object obj );
Parameters
obj
The object to compare.
Return Value

Returns true if the objects are equivalent; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified object is identical to this rectangle. The specified object must be a Rectangle object instance.

Rectangle.getBottom

Syntax
public final int getBottom();
Return Value

Returns the lowest point in the rectangle's y-axis. This value equates to the sum of the rectangle's y-coordinate and its height.

Description

Returns the lowest point in the rectangle's y-axis.

Rectangle.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Description

Topic under construction.

Rectangle.getExtension

Syntax
public String getExtension();
Return Value

Returns null.

Description

Because the Rectangle object is not a file-based object, this method always returns null.

Rectangle.getRight

Syntax
public final int getRight();
Return Value

Returns the right-most point on the rectangle's x-axis. This value equates to the sum of the rectangle's x-coordinate and its width.

Description

Retrieves the right-most point on the rectangle's x-axis.

Rectangle.hashCode

Syntax
public int hashCode();
Description

Topic under construction.

Rectangle.inflateRect

Syntax
public void inflateRect( int x, int y );
Parameters
x
The x value to use to formulate the rectangle's new x-coordinate and width.
y
The y value to use to formulate the rectangle's new y-coordinate and height.
Description

Expands the size of the rectangle using the specified x and y values. The inflateRect method formulates the new x and y coordinates by subtracting the value of the x and y parameters from the current value of the rectangle's x and y coordinates. The new width of the rectangle is formulated by adding the product of x and 2 to the current width. The new height is formulated by adding the product of y and 2 to the current height.

Rectangle.intersectRect

Syntax
public boolean intersectRect( Rectangle lpRect1, Rectangle lpRect2 );
Return Value

Returns true if the rectangles intersect; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether two rectangles intersect.

Rectangle.intersectsWith

Syntax
public boolean intersectsWith( Rectangle rect );
Parameters
rect
The rectangle to compare to this one.
Return Value

Returns true if the rectangles intersect; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the specified rectangle intersects with this one.

Rectangle.save

Syntax
public void save( IDataStream stream );
Parameters
stream
The data stream to which to save the settings.
Description

Saves this object's settings to a data stream.

Rectangle.setBounds

Syntax 1
public void setBounds( int x, int y, int width, int height );
Parameters
x
The x-coordinate for the rectangle.
y
The y-coordinate for the rectangle.
width
The width of the rectangle.
height
The height of the rectangle.
Description

Initializes this Rectangle object.

Syntax 2
public void setBounds( RECT r );
Parameters
r
The Win32 RECT structure that contains the values with which to initialize this rectangle.
Description

Copies the specified values to this Rectangle object.

Syntax 3
public void setBounds( Rectangle r );
Parameters
r
The Rectangle object to copy to this one.
Description

Copies the specified Rectangle object to this rectangle.

Rectangle.toRECT

Syntax 1
public final RECT toRECT();
Return Value

Returns a Win32 RECT structure that contains this rectangle's current values.

Description

Retrieves a Win32 RECT structure that contains the settings of this Rectangle object.

Syntax 2
public static final RECT toRECT( Rectangle r );
Return Value

Returns a Win32 RECT structure that contains the specified rectangle's settings.

Description

Retrieves a Win32 RECT structure that contains the settings of the specified Rectangle object.

Rectangle.toString

Syntax
public String toString();
Return Value

Returns a String representation of this Rectangle object.

Description

Retrieves a String representation of this object.


 Region Class

Region Class

This Package | All Packages

public final class Region

Topic under construction.

Fields
Name | Description
RGN_AND | Topic under construction.
RGN_COPY | Topic under construction.
RGN_DIFF | Topic under construction.
RGN_MAX | Topic under construction.
RGN_MIN | Topic under construction.
RGN_OR | Topic under construction.
RGN_XOR | Topic under construction.

Constructors
Name | Description
Region() | Topic under construction.
getPtInRegion(int x, int y) | Topic under construction.
getPtInRegion(Point point) | Topic under construction.
getRectInRegion(Rectangle lpRect) | Topic under construction.

Methods
Name | Description
combineRgn(Region pRgn1, Region pRgn2, int nCombineMode) | Topic under construction.
copyRgn(Region pRgnSrc) | Topic under construction.
createEllipticRgn(int x1, int y1, int x2, int y2) | Topic under construction.
createEllipticRgnIndirect(Rectangle lpRect) | Topic under construction.
createFromPath(Graphics g) | Topic under construction.
createPolygonRgn(POINT lpPoints[], int nMode) | Topic under construction.
createPolyPolygonRgn(POINT lpPoints[], int lpPolyCounts[], int nPolyFillMode) | Topic under construction.
createRectRgn(int x1, int y1, int x2, int y2) | Topic under construction.
createRectRgnIndirect(Rectangle lpRect) | Topic under construction.
createRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3) | Topic under construction.
equals(Object obj) | Topic under construction.
getHandle() | Topic under construction.
getRgnBox(Rectangle lpRect) | Topic under construction.
getSafeHandle(Region b) | Topic under construction.
hashCode() | Topic under construction.
offsetRgn(int x, int y) | Topic under construction.
offsetRgn(Point point) | Topic under construction.
setRectRgn(int x1, int y1, int x2, int y2) | Topic under construction.
setRectRgn(Rectangle lpRect) | Topic under construction.

Fields

Region.RGN_AND

Syntax
public static final int RGN_AND;
Description
Topic under construction.

Region.RGN_COPY

Syntax
public static final int RGN_COPY;
Description
Topic under construction.

Region.RGN_DIFF

Syntax
public static final int RGN_DIFF;
Description
Topic under construction.

Region.RGN_MAX

Syntax
public static final int RGN_MAX;
Description
Topic under construction.

Region.RGN_MIN

Syntax
public static final int RGN_MIN;
Description
Topic under construction.

Region.RGN_OR

Syntax
public static final int RGN_OR;
Description
Topic under construction.

Region.RGN_XOR

Syntax
public static final int RGN_XOR;
Description
Topic under construction.

Constructors

Region.Region

Syntax
public Region();
Description

Topic under construction.

Region.getPtInRegion

Syntax 1
public final boolean getPtInRegion( int x, int y );
Description

Topic under construction.

Syntax 2
public final boolean getPtInRegion( Point point );
Description

Topic under construction.

Region.getRectInRegion

Syntax
public final boolean getRectInRegion( Rectangle lpRect );
Description

Topic under construction.

Methods

Region.combineRgn

Syntax
public final int combineRgn( Region pRgn1, Region pRgn2, int nCombineMode );
Description

Topic under construction.

Region.copyRgn

Syntax
public final int copyRgn( Region pRgnSrc );
Description

Topic under construction.

Region.createEllipticRgn

Syntax
public final boolean createEllipticRgn( int x1, int y1, int x2, int y2 );
Description

Topic under construction.

Region.createEllipticRgnIndirect

Syntax
public final boolean createEllipticRgnIndirect( Rectangle lpRect );
Description

Topic under construction.

Region.createFromPath

Syntax
public final boolean createFromPath( Graphics g );
Description

Topic under construction.

Region.createPolygonRgn

Syntax
public final boolean createPolygonRgn( POINT lpPoints[], int nMode );
Description

Topic under construction.

Region.createPolyPolygonRgn

Syntax
public final boolean createPolyPolygonRgn( POINT lpPoints[], int lpPolyCounts[], int nPolyFillMode );
Description

Topic under construction.

Region.createRectRgn

Syntax
public final boolean createRectRgn( int x1, int y1, int x2, int y2 );
Description

Topic under construction.

Region.createRectRgnIndirect

Syntax
public final boolean createRectRgnIndirect( Rectangle lpRect );
Description

Topic under construction.

Region.createRoundRectRgn

Syntax
public final boolean createRoundRectRgn( int x1, int y1, int x2, int y2, int x3, int y3 );
Description

Topic under construction.

Region.equals

Syntax
public boolean equals( Object obj );
Description

Topic under construction.

Region.getHandle

Syntax
public final int getHandle();
Description

Topic under construction.

Region.getRgnBox

Syntax
public final int getRgnBox( Rectangle lpRect );
Description

Topic under construction.

Region.getSafeHandle

Syntax
public static final int getSafeHandle( Region b );
Description

Topic under construction.

Region.hashCode

Syntax
public int hashCode();
Description

Topic under construction.

Region.offsetRgn

Syntax 1
public final int offsetRgn( int x, int y );
Description

Topic under construction.

Syntax 2
public final int offsetRgn( Point point );
Description

Topic under construction.

Region.setRectRgn

Syntax 1
public final void setRectRgn( int x1, int y1, int x2, int y2 );
Description

Topic under construction.

Syntax 2
public final void setRectRgn( Rectangle lpRect );
Description

Topic under construction.


 ReSizeRestriction Class

ReSizeRestriction Class

This Package | All Packages

Enum
  |
  +--ReSizeRestriction
public class ReSizeRestriction
extends Enum

Topic under construction.

Fields
Name | Description
FREE | Topic under construction.
RESTRICTEDALL | Topic under construction.
RESTRICTEDX | Topic under construction.
RESTRICTEDY | Topic under construction.

Fields

ReSizeRestriction.FREE

Syntax
public static final int FREE;
Description
Topic under construction.

ReSizeRestriction.RESTRICTEDALL

Syntax
public static final int RESTRICTEDALL;
Description
Topic under construction.

ReSizeRestriction.RESTRICTEDX

Syntax
public static final int RESTRICTEDX;
Description
Topic under construction.

ReSizeRestriction.RESTRICTEDY

Syntax
public static final int RESTRICTEDY;
Description
Topic under construction.


 RichEdit Class

RichEdit Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--RichEdit
public class RichEdit
extends Control

The RichEdit class encapsulates a Win32 RichEdit control. The topics in this section are currently under construction.

Fields
Name | Description
EM_GETPARAFORMAT | Represents the message that is submitted to this control to retrieve the control's paragraph format setting.
EM_SETPARAFORMAT | Represents the message that is submitted to this control to set the paragraph format.
EM_SETTARGETDEVICE | Represents the message that is submitted to this window to set the target device and line width used for WYSIWYG (what you see is what you get) formatting in a RichEdit control.
ES_SAVESEL | Topic under construction.
ES_SELECTIONBAR | Topic under construction.
PFA_CENTER | Indicates that paragraphs are centered in the control.
PFA_LEFT | Indicates that paragraphics are aligned with the left margin.
PFA_RIGHT | Indicates that paragraphs are aligned with the right margin.
PFM_ALIGNMENT | Topic under construction.
PFM_NUMBERING | Topic under construction.
PFM_OFFSET | Topic under construction.
PFM_OFFSETINDENT | Topic under construction.
PFM_RIGHTINDENT | Topic under construction.
PFM_STARTINDENT | PARAFORMAT mask values
PFM_TABSTOPS | Topic under construction.
PFN_BULLET | Indicates that the paragraph is bulleted.

Constructors
Name | Description
RichEdit() | Constructs a RichEdit control.

Methods
Name | Description
GetParaFormat(PARAFORMAT pf) | Topic under construction.
GetParaFormatSelection() | Topic under construction.
getReadOnly() | Retrieves a boolean value that indicates whether this control is read-only.
getSelectedText() | Retrieves the currently selected text, and returns it in a String object.
getSelectionEnd() | Retrieves the zero-based index of the last character in the current selection.
getSelectionStart() | Retrieves the zero-based index of the first character in the current selection.
select(int start, int end) | Selects the text within the specified range.
selectAll() | Selects all characters in the RichEdit control.
SetParaFormat(PARAFORMAT pf) | Topic under construction.
setReadOnly(boolean value) | Specifies whether the RichEdit control is read-only.
setSelectedText(String value) | Replaces the currently selected text with the specified text.
setSelectionEnd(int value) | Specifies the zero-based index of the last character of a text selection in the RichEdit control.
setSelectionStart(int value) | Specifies the zero-based index of the first character of a text selection in the RichEdit control.
setTargetDevice(int hdc, int nLineWidth) | Sets the target device and line width used for WYSIWYG (what you see is what you get) formatting in a RichEdit control.

Fields

RichEdit.EM_GETPARAFORMAT

Syntax
public static final int EM_GETPARAFORMAT;
Description
Represents the message that is submitted to this control to retrieve the control's paragraph format setting.

RichEdit.EM_SETPARAFORMAT

Syntax
public static final int EM_SETPARAFORMAT;
Description
Represents the message that is submitted to this control to set the paragraph format.

RichEdit.EM_SETTARGETDEVICE

Syntax
public static final int EM_SETTARGETDEVICE;
Description
Represents the message that is submitted to this window to set the target device and line width used for WYSIWYG (what you see is what you get) formatting in a RichEdit control.

RichEdit.ES_SAVESEL

Syntax
public static final int ES_SAVESEL;
Description
Topic under construction.

RichEdit.ES_SELECTIONBAR

Syntax
public static final int ES_SELECTIONBAR;
Description
Topic under construction.

RichEdit.PFA_CENTER

Syntax
public static final int PFA_CENTER;
Description
Indicates that paragraphs are centered in the control.

RichEdit.PFA_LEFT

Syntax
public static final int PFA_LEFT;
Description
Indicates that paragraphics are aligned with the left margin.

RichEdit.PFA_RIGHT

Syntax
public static final int PFA_RIGHT;
Description
Indicates that paragraphs are aligned with the right margin.

RichEdit.PFM_ALIGNMENT

Syntax
public static final int PFM_ALIGNMENT;
Description
Topic under construction.

RichEdit.PFM_NUMBERING

Syntax
public static final int PFM_NUMBERING;
Description
Topic under construction.

RichEdit.PFM_OFFSET

Syntax
public static final int PFM_OFFSET;
Description
Topic under construction.

RichEdit.PFM_OFFSETINDENT

Syntax
public static final int PFM_OFFSETINDENT;
Description
Topic under construction.

RichEdit.PFM_RIGHTINDENT

Syntax
public static final int PFM_RIGHTINDENT;
Description
Topic under construction.

RichEdit.PFM_STARTINDENT

Syntax
public static final int PFM_STARTINDENT;
Description
PARAFORMAT mask values

RichEdit.PFM_TABSTOPS

Syntax
public static final int PFM_TABSTOPS;
Description
Topic under construction.

RichEdit.PFN_BULLET

Syntax
public static final int PFN_BULLET;
Description
Indicates that the paragraph is bulleted.

Constructors

RichEdit.RichEdit

Syntax
public RichEdit();
Description

Constructs a RichEdit control.

Methods

RichEdit.GetParaFormat

Syntax
public void GetParaFormat( PARAFORMAT pf );
Description

Topic under construction.

RichEdit.GetParaFormatSelection

Syntax
public PARAFORMAT GetParaFormatSelection();
Description

Topic under construction.

RichEdit.getReadOnly

Syntax
public boolean getReadOnly();
Return Value

Returns true, if the control is read-only; Otherwise, returns false.

Description

Retrieves a boolean value that indicates whether this control is read-only.

RichEdit.getSelectedText

Syntax
public String getSelectedText();
Return Value

Returns the currently selected text, if text is selected; Otherwise, returns null.

Description

Retrieves the currently selected text, and returns it in a String object.

RichEdit.getSelectionEnd

Syntax
public int getSelectionEnd();
Return Value

Returns the zero-based index of the last character in the selection

Description

Retrieves the zero-based index of the last character in the current selection.

RichEdit.getSelectionStart

Syntax
public int getSelectionStart();
Description

Retrieves the zero-based index of the first character in the current selection.

RichEdit.select

Syntax
public void select( int start, int end );
Parameters
start
The zero-based index of the character with which to begin the selection.
end
The zero-based index of the character with which to end the selection.
Description

Selects the text within the specified range.

RichEdit.selectAll

Syntax
public void selectAll();
Description

Selects all characters in the RichEdit control.

RichEdit.SetParaFormat

Syntax
public void SetParaFormat( PARAFORMAT pf );
Description

Topic under construction.

RichEdit.setReadOnly

Syntax
public void setReadOnly( boolean value );
Parameters
value
A boolean value that indicates whether the control is read-only.
Description

Specifies whether the RichEdit control is read-only.

RichEdit.setSelectedText

Syntax
public void setSelectedText( String value );
Parameters
value
The text with which to replace the selected text.
Description

Replaces the currently selected text with the specified text.

RichEdit.setSelectionEnd

Syntax
public void setSelectionEnd( int value );
Parameters
value
The zero-based index of the character at which the selection ends.
Description

Specifies the zero-based index of the last character of a text selection in the RichEdit control.

RichEdit.setSelectionStart

Syntax
public void setSelectionStart( int value );
Parameters
value
The zero-based index of the character at which the selection begins.
Description

Specifies the zero-based index of the first character of a text selection in the RichEdit control.

RichEdit.setTargetDevice

Syntax
public void setTargetDevice( int hdc, int nLineWidth );
Parameters
hdc
Handle to a device context for the target device.
nLineWidth
Line width to use for formatting.
Description

Sets the target device and line width used for WYSIWYG (what you see is what you get) formatting in a RichEdit control.


 SaveFileDialog Class

SaveFileDialog Class

This Package | All Packages

CommonDialog
  |
  +--FileDialog
    |
    +--SaveFileDialog
public class SaveFileDialog
extends FileDialog

Displays a Windows common dialog box that lets you save a file. Most of the functionality for this Object is in the FileDialog object.


 ScrollBar Class

ScrollBar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ScrollBar
public abstract class ScrollBar
extends Control

Topic under construction.

Constructors
Name | Description
ScrollBar() | Topic under construction.

Methods
Name | Description
addOnScroll(ScrollEventHandler seh) | Topic under construction.
getLargeChange() | Topic under construction.
getMaximum() | Topic under construction.
getMinimum() | Topic under construction.
getPosition() | Topic under construction.
getSmallChange() | Topic under construction.
removeOnScroll(ScrollEventHandler seh) | Topic under construction.
setLargeChange(int largeChange) | Topic under construction.
setMaximum(int max) | Topic under construction.
setMinimum(int min) | Topic under construction.
setPosition(int pos) | Topic under construction.
setSmallChange(int smallChange) | Topic under construction.
setValues(int min, int max, int smallChange, int largeChange, int pos) | Topic under construction.

Constructors

ScrollBar.ScrollBar

Syntax
public ScrollBar();
Description

Topic under construction.

Methods

ScrollBar.addOnScroll

Syntax
public void addOnScroll( ScrollEventHandler seh );
Description

Topic under construction.

ScrollBar.getLargeChange

Syntax
public int getLargeChange();
Description

Topic under construction.

ScrollBar.getMaximum

Syntax
public int getMaximum();
Description

Topic under construction.

ScrollBar.getMinimum

Syntax
public int getMinimum();
Description

Topic under construction.

ScrollBar.getPosition

Syntax
public int getPosition();
Description

Topic under construction.

ScrollBar.getSmallChange

Syntax
public int getSmallChange();
Description

Topic under construction.

ScrollBar.removeOnScroll

Syntax
public void removeOnScroll( ScrollEventHandler seh );
Description

Topic under construction.

ScrollBar.setLargeChange

Syntax
public void setLargeChange( int largeChange );
Description

Topic under construction.

ScrollBar.setMaximum

Syntax
public void setMaximum( int max );
Description

Topic under construction.

ScrollBar.setMinimum

Syntax
public void setMinimum( int min );
Description

Topic under construction.

ScrollBar.setPosition

Syntax
public void setPosition( int pos );
Description

Topic under construction.

ScrollBar.setSmallChange

Syntax
public void setSmallChange( int smallChange );
Description

Topic under construction.

ScrollBar.setValues

Syntax
public void setValues( int min, int max, int smallChange, int largeChange, int pos );
Description

Topic under construction.


 ScrollBars Class

ScrollBars Class

This Package | All Packages

Enum
  |
  +--ScrollBars
public class ScrollBars
extends Enum

Topic under construction.

Fields
Name | Description
BOTH | Topic under construction.
HORIZONTAL | Topic under construction.
MAX | Topic under construction.
MIN | Topic under construction.
NONE | Topic under construction.
VERTICAL | Topic under construction.

Fields

ScrollBars.BOTH

Syntax
public static final int BOTH;
Description
Topic under construction.

ScrollBars.HORIZONTAL

Syntax
public static final int HORIZONTAL;
Description
Topic under construction.

ScrollBars.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ScrollBars.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ScrollBars.NONE

Syntax
public static final int NONE;
Description
Topic under construction.

ScrollBars.VERTICAL

Syntax
public static final int VERTICAL;
Description
Topic under construction.


 ScrollButton Class

ScrollButton Class

This Package | All Packages

Enum
  |
  +--ScrollButton
public final class ScrollButton
extends Enum

Enum to be used with the drawScrollButton function.

Fields
Name | Description
DOWN | Draws a down-arrow scroll bar button.
LEFT | Draws a left-arrow scroll bar button.
MAX | Topic under construction.
MIN | Topic under construction.
RIGHT | Draws a right-arrow scroll bar button.
UP | Draws an up-arrow scroll bar button.

Methods
Name | Description
ensureValid(int value) | Throws an exception if the given value is not possible for this class.
valid(int value) | Determines whether the specified value is valid for this class.

Fields

ScrollButton.DOWN

Syntax
public static final int DOWN;
Description
Draws a down-arrow scroll bar button.

ScrollButton.LEFT

Syntax
public static final int LEFT;
Description
Draws a left-arrow scroll bar button.

ScrollButton.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ScrollButton.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ScrollButton.RIGHT

Syntax
public static final int RIGHT;
Description
Draws a right-arrow scroll bar button.

ScrollButton.UP

Syntax
public static final int UP;
Description
Draws an up-arrow scroll bar button.

Methods

ScrollButton.ensureValid

Syntax
public static void ensureValid( int value );
Parameters
value
Topic under construction.
Description

Throws an exception if the given value is not possible for this class.

ScrollButton.valid

Syntax
public static boolean valid( int value );
Parameters
format
The value.
Return Value

Returns true if the given value is valid; otherwise, returns false.

Description

Determines whether the specified value is valid for this class.


 ScrollEvent Class

ScrollEvent Class

This Package | All Packages

Event
  |
  +--ScrollEvent
public class ScrollEvent
extends Event

Topic under construction.

Fields
Name | Description
FIRST | Topic under construction.
LARGE_DECREMENT | Topic under construction.
LARGE_INCREMENT | Topic under construction.
LAST | Topic under construction.
newPos | Topic under construction.
SMALL_DECREMENT | Topic under construction.
SMALL_INCREMENT | Topic under construction.
THUMB_POSITION | Topic under construction.
THUMB_TRACK | Topic under construction.
type | Topic under construction.
useNewPos | Topic under construction.

Constructors
Name | Description
ScrollEvent(int type, int newPos) | Topic under construction.

Fields

ScrollEvent.FIRST

Syntax
public final static int FIRST;
Description
Topic under construction.

ScrollEvent.LARGE_DECREMENT

Syntax
public final static int LARGE_DECREMENT;
Description
Topic under construction.

ScrollEvent.LARGE_INCREMENT

Syntax
public final static int LARGE_INCREMENT;
Description
Topic under construction.

ScrollEvent.LAST

Syntax
public final static int LAST;
Description
Topic under construction.

ScrollEvent.newPos

Syntax
public final int newPos;
Description
Topic under construction.

ScrollEvent.SMALL_DECREMENT

Syntax
public final static int SMALL_DECREMENT;
Description
Topic under construction.

ScrollEvent.SMALL_INCREMENT

Syntax
public final static int SMALL_INCREMENT;
Description
Topic under construction.

ScrollEvent.THUMB_POSITION

Syntax
public final static int THUMB_POSITION;
Description
Topic under construction.

ScrollEvent.THUMB_TRACK

Syntax
public final static int THUMB_TRACK;
Description
Topic under construction.

ScrollEvent.type

Syntax
public final int type;
Description
Topic under construction.

ScrollEvent.useNewPos

Syntax
public boolean useNewPos;
Description
Topic under construction.

Constructors

ScrollEvent.ScrollEvent

Syntax
public ScrollEvent( int type, int newPos );
Description

Topic under construction.


 SelectionStyle Class

SelectionStyle Class

This Package | All Packages

Enum
  |
  +--SelectionStyle
public class SelectionStyle
extends Enum

Topic under construction.

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
MULTI_EXTENDED | Indicates that more than one item at a time can be selected, and keyboard combinations (such as SHIFT and CTRL) can be used to help in selection.
MULTI_SIMPLE | Indicates that more than one item at a time can be selected.
NONE | Indicates that no items can be selected.
ONE | Indicates that only one item at a time can be selected.

Fields

SelectionStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

SelectionStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

SelectionStyle.MULTI_EXTENDED

Syntax
public static final int MULTI_EXTENDED;
Description
Indicates that more than one item at a time can be selected, and keyboard combinations (such as SHIFT and CTRL) can be used to help in selection.

SelectionStyle.MULTI_SIMPLE

Syntax
public static final int MULTI_SIMPLE;
Description
Indicates that more than one item at a time can be selected.

SelectionStyle.NONE

Syntax
public static final int NONE;
Description
Indicates that no items can be selected.

SelectionStyle.ONE

Syntax
public static final int ONE;
Description
Indicates that only one item at a time can be selected.


 SizeMode Class

SizeMode Class

This Package | All Packages

Enum
  |
  +--SizeMode
public class SizeMode
extends Enum

An enumeration class used for tabs.

Fields
Name | Description
FillToRight | Indicates that the tabs are stretched to ensure they reach the far right of the strip, if neccessary.
Fixed | Indicates that all tabs are the same width.
Normal | Indicates that tabs are only as wide as they need to be to display their information.

Fields

SizeMode.FillToRight

Syntax
public static final int FillToRight;
Description
Indicates that the tabs are stretched to ensure they reach the far right of the strip, if neccessary. This is applicable only to tab strips with more than one row.

SizeMode.Fixed

Syntax
public static final int Fixed;
Description
Indicates that all tabs are the same width.

SizeMode.Normal

Syntax
public static final int Normal;
Description
Indicates that tabs are only as wide as they need to be to display their information. Empty space on the right is left as such.


 SortingEnum Class

SortingEnum Class

This Package | All Packages

Enum
  |
  +--SortingEnum
public class SortingEnum
extends Enum

Topic under construction.

Fields
Name | Description
ASCENDING | Topic under construction.
DESCENDING | Topic under construction.
NONE | Topic under construction.

Fields

SortingEnum.ASCENDING

Syntax
public static final int ASCENDING;
Description
Topic under construction.

SortingEnum.DESCENDING

Syntax
public static final int DESCENDING;
Description
Topic under construction.

SortingEnum.NONE

Syntax
public static final int NONE;
Description
Topic under construction.


 Splitter Class

Splitter Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--Splitter
public class Splitter
extends Control
implements IMessageFilter

Topic under construction.

Constructors
Name | Description
Splitter() | Topic under construction.

Methods
Name | Description
addOnSplitterMoved(SplitterEventHandler handler) | Topic under construction.
addOnSplitterMoving(SplitterEventHandler handler) | Topic under construction.
getMinExtra() | Topic under construction.
getMinSize() | Topic under construction.
postFilterMessage(Message m) | Topic under construction.
preFilterMessage(Message m) | Topic under construction.
removeOnSplitterMoved(SplitterEventHandler handler) | Topic under construction.
removeOnSplitterMoving(SplitterEventHandler handler) | Topic under construction.
setDock(int value) | Topic under construction.
setMinExtra(int value) | Topic under construction.
setMinSize(int value) | Topic under construction.

Constructors

Splitter.Splitter

Syntax
public Splitter();
Description

Topic under construction.

Methods

Splitter.addOnSplitterMoved

Syntax
public void addOnSplitterMoved( SplitterEventHandler handler );
Description

Topic under construction.

Splitter.addOnSplitterMoving

Syntax
public void addOnSplitterMoving( SplitterEventHandler handler );
Description

Topic under construction.

Splitter.getMinExtra

Syntax
public int getMinExtra();
Description

Topic under construction.

Splitter.getMinSize

Syntax
public int getMinSize();
Description

Topic under construction.

Splitter.postFilterMessage

Syntax
public void postFilterMessage( Message m );
Description

Topic under construction.

Splitter.preFilterMessage

Syntax
public boolean preFilterMessage( Message m );
Description

Topic under construction.

Splitter.removeOnSplitterMoved

Syntax
public void removeOnSplitterMoved( SplitterEventHandler handler );
Description

Topic under construction.

Splitter.removeOnSplitterMoving

Syntax
public void removeOnSplitterMoving( SplitterEventHandler handler );
Description

Topic under construction.

Splitter.setDock

Syntax
public void setDock( int value );
Description

Topic under construction.

Overrides

setDock(int) in Control.

Splitter.setMinExtra

Syntax
public void setMinExtra( int value );
Description

Topic under construction.

Splitter.setMinSize

Syntax
public void setMinSize( int value );
Description

Topic under construction.


 StaticImage Class

StaticImage Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--StaticImage
public class StaticImage
extends Control

Topic under construction.

Constructors
Name | Description
StaticImage() | Topic under construction.

Methods
Name | Description
setBitmap(int handle) | Topic under construction.
setBitmap(Bitmap bitmap) | Topic under construction.

Constructors

StaticImage.StaticImage

Syntax
public StaticImage();
Description

Topic under construction.

Methods

StaticImage.setBitmap

Syntax 1
public void setBitmap( int handle );
Description

Topic under construction.

Syntax 2
public void setBitmap( Bitmap bitmap );
Description

Topic under construction.


 StatusBar Class

StatusBar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--StatusBar
public class StatusBar
extends Control

This class wraps the comctl32 status bar control.

Constructors
Name | Description
StatusBar() | Creates a status bar.

Methods
Name | Description
addOnPanelClick( StatusBarPanelClickEventHandler value) | Adds an event listener for the PanelClick event.
addPanel(StatusBarPanel statusBarPanel) | Adds a panel to the status bar.
getMode() | Retrieves the state of the Mode property.
getPanels() | Retrieve an array of StatusBarPanel objects that are in the status bar.
getSimpleText() | Retrieves the SimpleText property.
getSizingGrip() | Retrieves the SizingGrip property.
getStatusBarPanel(int index) | Retrieves the specified panel in the status bar.
getText() | Overrides Control.getText().
insertPanel(int index, StatusBarPanel panel) | Inserts a panel at the specified location.
onMouseDown(MouseEvent e) | Overrides Control.onMouseDown(MouseEvent) Overrides: onMouseDown(MouseEvent) in Control.
onPanelClick(StatusBarPanelClickEvent e) | Event for when a status bar panel is clicked.
removeAllPanels() | Removes all the panels from the status bar.
removeOnPanelClick( StatusBarPanelClickEventHandler value) | Removes an event listener for the PanelClick event.
removePanel(int index) | Removes a panel from the status bar.
setFont(Font value) | Overrides Control.setFont(Font).
setMode(int mode) | Sets the state of the Mode property.
setPanel(int index, StatusBarPanel panel) | Sets a panel at a particular index.
setPanels(StatusBarPanel[] array) | Sets the panels within the status bar.
setSimpleText(String string) | Sets the SimpleText property.
setSizingGrip(boolean value) | Sets the SizingGrip property.
setText(String text) | Overrides Control.setText(String).

Constructors

StatusBar.StatusBar

Syntax
public StatusBar();
Description

Creates a status bar.

Methods

StatusBar.addOnPanelClick

Syntax
public void addOnPanelClick( StatusBarPanelClickEventHandler value );
Parameters
value
The event handler to add.
Description

Adds an event listener for the PanelClick event.

StatusBar.addPanel

Syntax
public int addPanel( StatusBarPanel statusBarPanel );
Parameters
statusBarPanel
The statusBarPanel to add.
Return Value

Returns the index of the added panel.

Description

Adds a panel to the status bar.

StatusBar.getMode

Syntax
public int getMode();
Return Value

Returns the mode of the status bar.

Description

Retrieves the state of the Mode property. The Mode property determines whether the StatusBar is simple or not.

StatusBar.getPanels

Syntax
public StatusBarPanel[] getPanels();
Return Value

Returns the array.

Description

Retrieve an array of StatusBarPanel objects that are in the status bar.

StatusBar.getSimpleText

Syntax
public String getSimpleText();
Return Value

Returns the SimpleText;

Description

Retrieves the SimpleText property. The SimpleText property is displayed when the status bar is in simple mode.

StatusBar.getSizingGrip

Syntax
public boolean getSizingGrip();
Return Value

Returns true if the status bar has a sizing grip; otherwise, returns false.

Description

Retrieves the SizingGrip property.

StatusBar.getStatusBarPanel

Syntax
public StatusBarPanel getStatusBarPanel( int index );
Parameters
index
The index of the panel requested.
Return Value

Returns a StatusBarPanel object.

Description

Retrieves the specified panel in the status bar.

StatusBar.getText

Syntax
public String getText();
Description

Overrides Control.getText().

Overrides

getText() in Control.

StatusBar.insertPanel

Syntax
public int insertPanel( int index, StatusBarPanel panel );
Parameters
index
The location at which to insert the panel.
panel
The StatusBarPanel to insert in the status bar.
Return Value

Returns the index of the added panel.

Description

Inserts a panel at the specified location.

StatusBar.onMouseDown

Syntax
protected void onMouseDown( MouseEvent e );
Description

Overrides Control.onMouseDown(MouseEvent)

Overrides

onMouseDown(MouseEvent) in Control.

StatusBar.onPanelClick

Syntax
protected void onPanelClick( StatusBarPanelClickEvent e );
Parameters
e
The event data, including the StatusBarPanel clicked.
Description

Event for when a status bar panel is clicked.

StatusBar.removeAllPanels

Syntax
public void removeAllPanels();
Description

Removes all the panels from the status bar.

StatusBar.removeOnPanelClick

Syntax
public void removeOnPanelClick( StatusBarPanelClickEventHandler value );
Parameters
value
The event handler to remove.
Description

Removes an event listener for the PanelClick event.

StatusBar.removePanel

Syntax
public void removePanel( int index );
Parameters
index
The index of the panel to remove.
Description

Removes a panel from the status bar.

Exceptions

ArrayIndexOutOfBounds thrown if the index is out of range.

StatusBar.setFont

Syntax
public void setFont( Font value );
Description

Overrides Control.setFont(Font). This method is used to update the width of any panels that have the StatusBarPAnelAutoSize.CONTENTS property set.

Overrides

setFont(Font) in Control.

StatusBar.setMode

Syntax
public void setMode( int mode );
Parameters
mode
The new mode of the status bar.
Description

Sets the state of the Mode property. The Mode property determines whether the status bar is simple or not. A simple status bar displays only one line of text.

StatusBar.setPanel

Syntax
public void setPanel( int index, StatusBarPanel panel );
Parameters
index
The index at which to change the panel.
panel
The new panel.
Description

Sets a panel at a particular index.

StatusBar.setPanels

Syntax
public void setPanels( StatusBarPanel[] array );
Parameters
array
The new panels.
Description

Sets the panels within the status bar. The previous panels will be removed.

StatusBar.setSimpleText

Syntax
public void setSimpleText( String string );
Parameters
string
The text displayed by the status bar.
Description

Sets the SimpleText property. The SimpleText property is displayed when the status bar is in simple mode.

StatusBar.setSizingGrip

Syntax
public void setSizingGrip( boolean value );
Parameters
value
Set to true if a sizing grip is desired; otherwise, set to false.
Description

Sets the SizingGrip property.

StatusBar.setText

Syntax
public void setText( String text );
Description

Overrides Control.setText(String).

Overrides

setText(String) in Control.


 StatusBarMode Class

StatusBarMode Class

This Package | All Packages

Enum
  |
  +--StatusBarMode
public class StatusBarMode
extends Enum

The status bar style.

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | The status bar panels are displayed.
SIMPLE | The status bar contains only one flat panel.

Fields

StatusBarMode.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

StatusBarMode.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

StatusBarMode.NORMAL

Syntax
public static final int NORMAL;
Description
The status bar panels are displayed.

StatusBarMode.SIMPLE

Syntax
public static final int SIMPLE;
Description
The status bar contains only one flat panel.


 StatusBarPanel Class

StatusBarPanel Class

This Package | All Packages

Object
  |
  +--StatusBarPanel
public class StatusBarPanel
extends Object
implements IConstructable

Stores the panel information.

Constructors
Name | Description
StatusBarPanel() | Topic under construction.
StatusBarPanel( String text, Icon icon, int borderStyle, int alignment, int width, int minWidth, int autoSize, Object tag, int style, String toolTipText) | Topic under construction.

Methods
Name | Description
getAlignment() | Retrieves the Alignment property.
getAutoSize() | Retrieves the AutoSize property.
getBorderStyle() | Retrieves the BorderStyle property.
getConstructorArgs() | Topic under construction.
getIcon() | Retrieves the Icon property.
getMinWidth() | Retrieves the MinWidth property.
getOnDrawItem() | Retrieves the OnDraw event handler.
getStyle() | Retrieves the style of the panel.
getTag() | Retrieves the tag data.
getText() | Retrieves the text of the panel.
getToolTipText() | Retrieves the ToolTipText property.
getWidth() | Retrieves the Width property.
onDrawItem(DrawItemEvent e) | The Draw event.
setAlignment(int align) | Sets the Alignment property.
setAutoSize(int autoSize) | Sets the AutoSize property.
setBorderStyle(int border) | Sets the BorderStyle property.
setIcon(Icon icon) | Sets the Icon propety.
setMinWidth(int width) | Sets the MinWidth property.
setOnDrawItem(DrawItemEventHandler handler) | Sets the OnDraw event handler.
setStyle(int style) | Sets the Style property.
setTag(Object obj) | Sets the tag data.
setText(String text) | Sets the Text property.
setToolTipText(String text) | Sets the ToolTipText property.
setWidth(int width) | Sets the Width property.

Constructors

StatusBarPanel.StatusBarPanel

Syntax 1
public StatusBarPanel();
Description

Topic under construction.

Syntax 2
public StatusBarPanel( String text, Icon icon, int borderStyle, int alignment, int width, int minWidth, int autoSize, Object tag, int style, String toolTipText );
Description

Topic under construction.

Methods

StatusBarPanel.getAlignment

Syntax
public int getAlignment();
Return Value

Returns the value of the Alignment property.

Description

Retrieves the Alignment property. (see SetAlignment)

StatusBarPanel.getAutoSize

Syntax
public int getAutoSize();
Return Value

Returns the value of the AutoSize property.

Description

Retrieves the AutoSize property.

StatusBarPanel.getBorderStyle

Syntax
public int getBorderStyle();
Return Value

Returns the value of the BorderStyle property.

Description

Retrieves the BorderStyle property. A panel can have a raised or sunken border or no border style.

StatusBarPanel.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Description

Topic under construction.

StatusBarPanel.getIcon

Syntax
public Icon getIcon();
Return Value

Returns the icon displayed in the panel.

Description

Retrieves the Icon property.

StatusBarPanel.getMinWidth

Syntax
public int getMinWidth();
Return Value

Returns an integer representing the minimum width of the panel.

Description

Retrieves the MinWidth property.

StatusBarPanel.getOnDrawItem

Syntax
public DrawItemEventHandler getOnDrawItem();
Return Value

Returns the event handler.

Description

Retrieves the OnDraw event handler.

StatusBarPanel.getStyle

Syntax
public int getStyle();
Return Value

Returns the style.

Description

Retrieves the style of the panel. Possible values include TEXT or OWNERDRAW.

StatusBarPanel.getTag

Syntax
public Object getTag();
Return Value

Returns s a user-specified object.

Description

Retrieves the tag data.

StatusBarPanel.getText

Syntax
public String getText();
Return Value

Returns a string containing the panel text.

Description

Retrieves the text of the panel.

StatusBarPanel.getToolTipText

Syntax
public String getToolTipText();
Return Value

Returns a string with the tooltip text.

Description

Retrieves the ToolTipText property.

StatusBarPanel.getWidth

Syntax
public int getWidth();
Return Value

Returns an integer representing the width of the panel.

Description

Retrieves the Width property.

StatusBarPanel.onDrawItem

Syntax
protected void onDrawItem( DrawItemEvent e );
Parameters
e
The event data.
Description

The Draw event.

StatusBarPanel.setAlignment

Syntax
public void setAlignment( int align );
Parameters
align
The new value of the Alignment property.
Description

Sets the Alignment property. A Panel can have LEFT, RIGHT, or CENTER text alignment.

StatusBarPanel.setAutoSize

Syntax
public void setAutoSize( int autoSize );
Parameters
autoSize
The new AutoSize value.
Description

Sets the AutoSize property.

StatusBarPanel.setBorderStyle

Syntax
public void setBorderStyle( int border );
Parameters
border
The new style to use.
Description

Sets the BorderStyle property.

StatusBarPanel.setIcon

Syntax
public void setIcon( Icon icon );
Parameters
icon
The new icon to display in the panel.
Description

Sets the Icon propety.

StatusBarPanel.setMinWidth

Syntax
public void setMinWidth( int width );
Parameters
width
The new minimum width.
Description

Sets the MinWidth property.

StatusBarPanel.setOnDrawItem

Syntax
public void setOnDrawItem( DrawItemEventHandler handler );
Parameters
handler
The new event handler.
Description

Sets the OnDraw event handler.

StatusBarPanel.setStyle

Syntax
public void setStyle( int style );
Parameters
style
The new style.
Description

Sets the Style property. Possible values include TEXT or OWNERDRAW.

StatusBarPanel.setTag

Syntax
public void setTag( Object obj );
Parameters
obj
A user-specified object.
Description

Sets the tag data.

StatusBarPanel.setText

Syntax
public void setText( String text );
Parameters
text
The new text value.
Description

Sets the Text property.

StatusBarPanel.setToolTipText

Syntax
public void setToolTipText( String text );
Parameters
text
The new text value.
Description

Sets the ToolTipText property.

StatusBarPanel.setWidth

Syntax
public void setWidth( int width );
Parameters
width
The new width.
Description

Sets the Width property.


 StatusBarPanelAutoSize Class

StatusBarPanelAutoSize Class

This Package | All Packages

Enum
  |
  +--StatusBarPanelAutoSize
public class StatusBarPanelAutoSize
extends Enum

The autosize style of a panel on a status bar.

Fields
Name | Description
CONTENTS | The panel's width is determined by its contents.
MAX | Topic under construction.
MIN | Topic under construction.
NONE | The panel size cannot be changed.
SPRING | The panel shares the remaining width of the status bar with the other SPRING panels.

Fields

StatusBarPanelAutoSize.CONTENTS

Syntax
public static final int CONTENTS;
Description
The panel's width is determined by its contents.

StatusBarPanelAutoSize.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

StatusBarPanelAutoSize.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

StatusBarPanelAutoSize.NONE

Syntax
public static final int NONE;
Description
The panel size cannot be changed.

StatusBarPanelAutoSize.SPRING

Syntax
public static final int SPRING;
Description
The panel shares the remaining width of the status bar with the other SPRING panels.


 StatusBarPanelBorderStyle Class

StatusBarPanelBorderStyle Class

This Package | All Packages

Enum
  |
  +--StatusBarPanelBorderStyle
public class StatusBarPanelBorderStyle
extends Enum

The border style of a panel on a status bar.

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
NONE | No border.
RAISED | A three-dimensional raised border.
SUNKEN | A three-dimensional sunken border.

Fields

StatusBarPanelBorderStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

StatusBarPanelBorderStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

StatusBarPanelBorderStyle.NONE

Syntax
public static final int NONE;
Description
No border.

StatusBarPanelBorderStyle.RAISED

Syntax
public static final int RAISED;
Description
A three-dimensional raised border.

StatusBarPanelBorderStyle.SUNKEN

Syntax
public static final int SUNKEN;
Description
A three-dimensional sunken border.


 StatusBarPanelClickEvent Class

StatusBarPanelClickEvent Class

This Package | All Packages

Event
  |
  +--StatusBarPanelClickEvent
public class StatusBarPanelClickEvent
extends Event

Topic under construction.

Fields
Name | Description
statusBarPanel | Topic under construction.

Constructors
Name | Description
StatusBarPanelClickEvent(StatusBarPanel statusBarPanel) | Topic under construction.

Fields

StatusBarPanelClickEvent.statusBarPanel

Syntax
public StatusBarPanel statusBarPanel;
Description
Topic under construction.

Constructors

StatusBarPanelClickEvent.StatusBarPanelClickEvent

Syntax
public StatusBarPanelClickEvent( StatusBarPanel statusBarPanel );
Description

Topic under construction.


 StatusBarPanelStyle Class

StatusBarPanelStyle Class

This Package | All Packages

Enum
  |
  +--StatusBarPanelStyle
public class StatusBarPanelStyle
extends Enum

The style of a panel on a status bar.

Fields
Name | Description
MAX | Topic under construction.
MIN | Topic under construction.
OWNERDRAW | The user draws the panel.
TEXT | A normal panel.

Fields

StatusBarPanelStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

StatusBarPanelStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

StatusBarPanelStyle.OWNERDRAW

Syntax
public static final int OWNERDRAW;
Description
The user draws the panel.

StatusBarPanelStyle.TEXT

Syntax
public static final int TEXT;
Description
A normal panel.


 TabControl Class

TabControl Class

This Package | All Packages

TabStrip
  |
  +--TabControl
public class TabControl
extends TabStrip

This control inherits the functionality of a TabStrip but manages a list of tabs for pages to be stored.

Constructors
Name | Description
TabControl() | Topic under construction.

Methods
Name | Description
add(Control control) | Topic under construction.
getControl(int index) | Topic under construction.
getControlCount() | Topic under construction.
getControls() | Topic under construction.
remove(Control control) | Topic under construction.
setNewControls(Control[] value) | Topic under construction.

Constructors

TabControl.TabControl

Syntax
public TabControl();
Description

Topic under construction.

Methods

TabControl.add

Syntax
public void add( Control control );
Description

Topic under construction.

TabControl.getControl

Syntax
public Control getControl( int index );
Description

Topic under construction.

TabControl.getControlCount

Syntax
public int getControlCount();
Description

Topic under construction.

TabControl.getControls

Syntax
public Control[] getControls();
Description

Topic under construction.

TabControl.remove

Syntax
public void remove( Control control );
Description

Topic under construction.

TabControl.setNewControls

Syntax
public void setNewControls( Control[] value );
Description

Topic under construction.


 TabDrawStyle Class

TabDrawStyle Class

This Package | All Packages

Enum
  |
  +--TabDrawStyle
public class TabDrawStyle
extends Enum

Enumeration class for tab drawing styles.

Fields
Name | Description
Normal | Indicates that the drawing style is the default, where Windows does all the painting of the controls with its default values.
OwnerDrawFixed | Indicates that all the drawing is done by the user through a delegate, which is fired whenever an item needs to be painted.

Fields

TabDrawStyle.Normal

Syntax
public static final int Normal;
Description
Indicates that the drawing style is the default, where Windows does all the painting of the controls with its default values.

TabDrawStyle.OwnerDrawFixed

Syntax
public static final int OwnerDrawFixed;
Description
Indicates that all the drawing is done by the user through a delegate, which is fired whenever an item needs to be painted.


 TabStrip Class

TabStrip Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--TabStrip
public class TabStrip
extends Control

A control for creating tabbed dialogs or tabbed toolbar/taskbar type windows. This control provides one or more rows of tabs that the user can select, one at a time. After each selection, a notification is provided that allows for the changing of the UI. Two basic UI modes that are supported are the traditional tabs seen in property page scenarios and a button-style tab, as in the taskbar found in Windows 95 and Windows NT version 4.0.

Constructors
Name | Description
TabStrip() | Creates a TabStrip control.

Methods
Name | Description
addOnDrawItem(DrawItemEventHandler value) | Adds an event handler for the OnDrawItem event notification.
addOnSelectionChange(EventHandler value) | Adds an event handler for the OnSelectionChange event notification.
addTab(Object item) | Adds a tab to the TabStrip.
createHandle() | Topic under construction.
getDisplayRect() | Returns the rectangle that represents the area of the tab control not taken up by the tabs, borders, or anything else owned by the tab.
getDrawStyle() | Indicates whether the individual tabs are painted by Windows or by the end user.
getItemSize() | Topic under construction.
getMultiline() | Indicates whether there can be more than one row of tabs.
getPadding() | Retrieves the amount of padding around the items in the individual tabs.
getRowCount() | Retrieves the number of rows currently being displayed in the TabStrip.
getSelectedIndex() | Retrieves the index of the currently selected tab in the strip, if there is one.
getSizeMode() | Retrieves the size mode.
getTabCount() | Retrieves the number of tabs in the strip.
getTabRect(int index) | Retrieves the bounding rectangle for the given tab in the TabStrip.
getTabs() | Retrieves an Object array containing all the items in the TabStrip.
getTabStyle() | Indicates whether the tabs in the TabStrip look like regular tabs as seen in property sheet applications, or if they look like butttons, as seen in the Windows 95 taskbar.
getTabText(int index) | Retrieves the text for the given tab.
insertTab(int index, Object item) | Adds a tab to the TabStrip, but in a location you specify, as opposed to the end of the list.
recreateHandle() | Ovveride this to guarantee that the tabs are re-created when appropriate.
removeAll() | Removes all tabs from the TabStrip.
removeOnDrawItem(DrawItemEventHandler value) | Removes the given handler for the OnDrawItem event.
removeOnSelectionChange(EventHandler value) | Removes the given handler for the OnSelectionChange event.
removeTab(int index) | Removes the tab at the given index of the TabStrip.
setDisplayRectSize(int width, int height) | Sets the size of the tabstrip based on a desired size for the display rectangle.
setDisplayRectSize(Point p) | Sets the size of the tabstrip based on a desired size for the display rectangle.
setDrawStyle(int value) | Indicates whether the individual tabs are painted by Windows or by the end user.
setItemSize(Point size) | Topic under construction.
setMultiline(boolean value) | Indicates whether there can be more than one row of tabs.
setPadding(Point value) | Sets the amount of padding around the items in the individual tabs.
setSelectedIndex(int index) | Sets the tab at the supplied index as being the selected tab in the strip.
setSizeMode(int value) | Sets the size mode.
setTabs(Object[] value) | Sets all the tabs in the TabStrip at once by passing in an array with all their values.
setTabStyle(int value) | Indicates whether the tabs in the TabStrip look like regular tabs as seen in property sheet applications, or if they look like butttons, as seen in the Windows 95 taskbar.
setTabText(int index, String value) | Sets the text for the given tab.

Constructors

TabStrip.TabStrip

Syntax
public TabStrip();
Description

Creates a TabStrip control.

Methods

TabStrip.addOnDrawItem

Syntax
public final void addOnDrawItem( DrawItemEventHandler value );
Parameters
value
New event handler to install for this event.
Description

Adds an event handler for the OnDrawItem event notification. This event is called for list boxes whose listStyle property is set to DrawStyle.OwnerDrawFixed and contains a Graphics object in which the item should be painted. Duplicates adds are not filtered out.

TabStrip.addOnSelectionChange

Syntax
public final void addOnSelectionChange( EventHandler value );
Parameters
value
New event handler to install for this event.
Description

Adds an event handler for the OnSelectionChange event notification. This event is sent whenever a new tab is selected. Duplicates are not filtered out.

TabStrip.addTab

Syntax
public final int addTab( Object item );
Parameters
item
The item that identifies the text to insert into the TabStrip.
Return Value

Returns the index of where the item was inserted.

Description

Adds a tab to the TabStrip. The code that adds the item calls toString() on it and inserts that value into the tab caption.

TabStrip.createHandle

Syntax
protected void createHandle();
Description

Topic under construction.

Overrides

createHandle() in Control.

TabStrip.getDisplayRect

Syntax
public final Rectangle getDisplayRect();
Return Value

Returns the rectangle with the display area of the TabStrip.

Description

Returns the rectangle that represents the area of the tab control not taken up by the tabs, borders, or anything else owned by the tab. This is typically the rectangle you want to use to place the individual children of the tab control.

TabStrip.getDrawStyle

Syntax
public final int getDrawStyle();
Return Value

Returns one of the following integer values:

  • TabDrawstyle.Normal, indicating that Windows paints the control.
  • TabDrawStyle.OwnerDrawFixed, indicating that an event is fired whenever an item needs to be drawn.
Description

Indicates whether the individual tabs are painted by Windows or by the end user. If the latter, an OnDrawItem event is fired whenever an item needs to be painted. All items must still be the same height.

TabStrip.getItemSize

Syntax
public final Point getItemSize();
Description

Topic under construction.

TabStrip.getMultiline

Syntax
public final boolean getMultiline();
Return Value

Returns a boolean value indicating whether multiple rows are allowed.

Description

Indicates whether there can be more than one row of tabs. By default (when this property is false), if there are more tabs than available display space, arrows are shown to let the user navigate between the extra tabs, but only one row is shown. If this property is set to true, then Windows spills extra tabs over onto second rows.

TabStrip.getPadding

Syntax
public final Point getPadding();
Return Value

Returns a point whose width contains the horizontal padding and whose height contains the vertical padding.

Description

Retrieves the amount of padding around the items in the individual tabs.

TabStrip.getRowCount

Syntax
public final int getRowCount();
Return Value

Returns the count of rows currently being used.

Description

Retrieves the number of rows currently being displayed in the TabStrip. This is most commonly used when the Multline property is true and you want to know how many rows are being used to display the tabs.

TabStrip.getSelectedIndex

Syntax
public final int getSelectedIndex();
Return Value

Returns the currently selected tab.

Description

Retrieves the index of the currently selected tab in the strip, if there is one. If the value is -1, there is currently no selection. If the value is 0 or greater, the value is the index of the currently selected tab.

TabStrip.getSizeMode

Syntax
public final int getSizeMode();
Return Value

Returns one of the following integer values:

  • SizeMode.Normal, indicating that tabs are only as wide as they need to be.
  • SizeMode.FillToRight, indicating that tabs at least extend to the right extent of the strip.
  • SizeMode.Fixed, indicating that all tabs are the same width.
Description

Retrieves the size mode. By default, tabs are big enough to display their text, and any space on the right of the strip is left as such. However, you can also set it so that the tabs are stretched to fill out the right extent of the strip, if necessary, or you can set it so that all tabs have the same width.

TabStrip.getTabCount

Syntax
public final int getTabCount();
Return Value

Returns the number of valid tabs.

Description

Retrieves the number of tabs in the strip.

TabStrip.getTabRect

Syntax
public final Rectangle getTabRect( int index );
Parameters
index
The index to get the bouding rectangle for.
Return Value

Returns the rectangle that identifies the bounds for the tab.

Description

Retrieves the bounding rectangle for the given tab in the TabStrip.

TabStrip.getTabs

Syntax
public final Object[] getTabs();
Return Value

Returns an array of items in the TabStrip. The first item is the 0th element, and the last item in the TabStrip is last in the array.

Description

Retrieves an Object array containing all the items in the TabStrip.

TabStrip.getTabStyle

Syntax
public final int getTabStyle();
Return Value

Returns one of the following integer values:

  • TabStyle.Tabs, indicating they are painted as normal tabs.
  • TabStyle.Buttons, indicating they are painted like taskbar buttons.
Description

Indicates whether the tabs in the TabStrip look like regular tabs as seen in property sheet applications, or if they look like butttons, as seen in the Windows 95 taskbar.

TabStrip.getTabText

Syntax
public final String getTabText( int index );
Parameters
index
The tab index.
Return Value

Returns the text of the tab.

Description

Retrieves the text for the given tab.

TabStrip.insertTab

Syntax
public final int insertTab( int index, Object item );
Parameters
index
The zero-based index of where the item should be inserted.
item
The item you want inserted.
Description

Adds a tab to the TabStrip, but in a location you specify, as opposed to the end of the list.

TabStrip.recreateHandle

Syntax
public void recreateHandle();
Description

Ovveride this to guarantee that the tabs are re-created when appropriate.

TabStrip.removeAll

Syntax
public void removeAll();
Description

Removes all tabs from the TabStrip. All values and data are discarded.

TabStrip.removeOnDrawItem

Syntax
public final void removeOnDrawItem( DrawItemEventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the given handler for the OnDrawItem event. If there are duplicate entries, all handlers are removed.

TabStrip.removeOnSelectionChange

Syntax
public final void removeOnSelectionChange( EventHandler value );
Parameters
value
The event handler to be removed.
Description

Removes the given handler for the OnSelectionChange event. If there are duplicate entries, all handlers are removed.

TabStrip.removeTab

Syntax
public void removeTab( int index );
Parameters
index
The index of the tab to remove.
Description

Removes the tab at the given index of the TabStrip. The tab and its data are discarded.

TabStrip.setDisplayRectSize

Syntax 1
public final void setDisplayRectSize( int width, int height );
Parameters
width
The new desired display width. The size of the tabstrip will be adjusted to reflect this.
height
The new desired display height. The size of the tabstrip will be adjusted to reflect this.
Description

Sets the size of the tabstrip based on a desired size for the display rectangle. Note that this is only guaranteed to be valid until tabs are added or removed. After that, the display size can change when the number of visible rows changes. [Note: zero tabs == zero rows]

Syntax 2
public final void setDisplayRectSize( Point p );
Parameters
p
The new desired display size. The size of the tabstrip will be adjusted to reflect this.
Description

Sets the size of the tabstrip based on a desired size for the display rectangle. Note that this is guaranteed to be valid only until tabs are added or removed. After that, the display size can change when the number of visible rows changes. [Note: zero tabs == zero rows]

TabStrip.setDrawStyle

Syntax
public final void setDrawStyle( int value );
Parameters
value
Set one of the following values:
  • [Tab]Drawstyle.Normal indicates that Windows paints the control.
  • [Tab]DrawStyle.OwnerDrawFixed indicates that an event is fired whenever an item needs to be drawn.
Description

Indicates whether the individual tabs are painted by Windows or by the end user. If the latter, an OnDrawItem event is fired whenever an item needs to be painted. All items must still be the same height.

TabStrip.setItemSize

Syntax
public final void setItemSize( Point size );
Description

Topic under construction.

TabStrip.setMultiline

Syntax
public final void setMultiline( boolean value );
Parameters
value
Indicates whether more than one row should be allowed.
Description

Indicates whether there can be more than one row of tabs. By default (when this property is false), if there are more tabs than available display space, arrows are shown to let the user navigate between the extra tabs, but only one row is shown. If this property is set to true, then Windows spills extra tabs over onto second rows.

TabStrip.setPadding

Syntax
public final void setPadding( Point value );
Parameters
A
Point object in which the width contains the horizontal padding and the height contains the vertical padding.
Description

Sets the amount of padding around the items in the individual tabs. You can specify both horizontal and vertical padding.

TabStrip.setSelectedIndex

Syntax
public final void setSelectedIndex( int index );
Parameters
index
The index of tab to select.
Description

Sets the tab at the supplied index as being the selected tab in the strip.

TabStrip.setSizeMode

Syntax
public final void setSizeMode( int value );
Parameters
value
Set one of the following values:
  • SizeMode.Normal indicates that tabs are only as wide as they need to be.
  • SizeMode.FillToRight indicates that tabs at least extend to the right extent of the strip.
  • SizeMode.Fixed indicates that all tabs are the same width.
Description

Sets the size mode. By default, tabs are big enough to display their text, and any space on the right of the strip is left as such. However, you can also set it so that the tabs are stretched to fill out the right extent of the strip, if necessary, or you can set it so that all tabs have the same width.

TabStrip.setTabs

Syntax
public final void setTabs( Object[] value );
Parameters
value
An array of objects that will be the new tabs in the strip.
Description

Sets all the tabs in the TabStrip at once by passing in an array with all their values. All old values in the TabStrip are discarded and lost.

TabStrip.setTabStyle

Syntax
public final void setTabStyle( int value );
Parameters
value
Set one of the following values:
  • TabStyle.Tabs indicates they are painted as normal tabs.
  • TabStyle.Buttons indicates they are painted like taskbar buttons.
Description

Indicates whether the tabs in the TabStrip look like regular tabs as seen in property sheet applications, or if they look like butttons, as seen in the Windows 95 taskbar.

TabStrip.setTabText

Syntax
public final void setTabText( int index, String value );
Parameters
index
The tab index.
value
The string to change the text to.
Description

Sets the text for the given tab.


 TabStyle Class

TabStyle Class

This Package | All Packages

Enum
  |
  +--TabStyle
public class TabStyle
extends Enum

Enumeration class for tab styles.

Fields
Name | Description
Buttons | Indicates that the tabs look like buttons as seen on the taskbar found in Windows 95 or Windows NT.
Tabs | Indicates that the tabs look like normal tabs typically seen in property pages.

Fields

TabStyle.Buttons

Syntax
public static final int Buttons;
Description
Indicates that the tabs look like buttons as seen on the taskbar found in Windows 95 or Windows NT.

TabStyle.Tabs

Syntax
public static final int Tabs;
Description
Indicates that the tabs look like normal tabs typically seen in property pages.


 TextFormat Class

TextFormat Class

This Package | All Packages

public class TextFormat

Provides different ways for text to be formatted.

Fields
Name | Description
ALL | All viable flags in the bit mask.
BOTTOM | Formats the text along the bottom of the rectangle.
EDITCONTROL | Draws the text in the same manner as a Windows Edit control does.
ENDELLIPSIS | Puts an ellipsis at the end of the text if it is too long to fit into the rectangle.
EXPANDTABS | Expands tabs in the text.
HORIZONTALCENTER | Centers the text horizontally.
LEFT | Aligns the text to the left.
NOPREFIX | Automatically breaks words at the end of the line.
PATHELLIPSIS | Puts an ellipsis in the middle of the text, properly breaking the text with appropriate backslashes.
RIGHT | Aligns the text to the right.
RIGHTTOLEFT | The text is laid from right to left, as when using Hebrew or Arabic fonts.
SINGLELINE | Automatically breaks words at the end of the line.
TOP | Aligns text to the top of the rectangle.
VERTICALCENTER | Vertically aligns text.
WORDBREAK | Automatically breaks words at the end of the line.
WORDELLIPSIS | Puts an ellipsis at the end of the text at a word break if the text is too long to fit in the rectangle.

Methods
Name | Description
ensureValid(int format) | Throws an exception if the given value is not possible for this class.
valid(int format) | Determines whether the specified format is valid for this class.

Fields

TextFormat.ALL

Syntax
public static final int ALL;
Description
All viable flags in the bit mask.

TextFormat.BOTTOM

Syntax
public static final int BOTTOM;
Description
Formats the text along the bottom of the rectangle.

TextFormat.EDITCONTROL

Syntax
public static final int EDITCONTROL;
Description
Draws the text in the same manner as a Windows Edit control does. The average character width is calculated in the same manner, and the last line of multiline text is not drawn if it would be only partially visible.

TextFormat.ENDELLIPSIS

Syntax
public static final int ENDELLIPSIS;
Description
Puts an ellipsis at the end of the text if it is too long to fit into the rectangle.

TextFormat.EXPANDTABS

Syntax
public static final int EXPANDTABS;
Description
Expands tabs in the text.

TextFormat.HORIZONTALCENTER

Syntax
public static final int HORIZONTALCENTER;
Description
Centers the text horizontally.

TextFormat.LEFT

Syntax
public static final int LEFT;
Description
Aligns the text to the left.

TextFormat.NOPREFIX

Syntax
public static final int NOPREFIX;
Description
Automatically breaks words at the end of the line.

TextFormat.PATHELLIPSIS

Syntax
public static final int PATHELLIPSIS;
Description
Puts an ellipsis in the middle of the text, properly breaking the text with appropriate backslashes.

TextFormat.RIGHT

Syntax
public static final int RIGHT;
Description
Aligns the text to the right.

TextFormat.RIGHTTOLEFT

Syntax
public static final int RIGHTTOLEFT;
Description
The text is laid from right to left, as when using Hebrew or Arabic fonts.

TextFormat.SINGLELINE

Syntax
public static final int SINGLELINE;
Description
Automatically breaks words at the end of the line.

TextFormat.TOP

Syntax
public static final int TOP;
Description
Aligns text to the top of the rectangle.

TextFormat.VERTICALCENTER

Syntax
public static final int VERTICALCENTER;
Description
Vertically aligns text.

TextFormat.WORDBREAK

Syntax
public static final int WORDBREAK;
Description
Automatically breaks words at the end of the line.

TextFormat.WORDELLIPSIS

Syntax
public static final int WORDELLIPSIS;
Description
Puts an ellipsis at the end of the text at a word break if the text is too long to fit in the rectangle.

Methods

TextFormat.ensureValid

Syntax
public static void ensureValid( int format );
Parameters
format
Topic under construction.
Description

Throws an exception if the given value is not possible for this class.

TextFormat.valid

Syntax
public static boolean valid( int format );
Parameters
format
The format.
Return Value

Returns true if the given value is a valid format; otherwise, returns false.

Description

Determines whether the specified format is valid for this class.


 TickStyle Class

TickStyle Class

This Package | All Packages

Enum
  |
  +--TickStyle
public class TickStyle
extends Enum

Enumeration class for tick styles.

Fields
Name | Description
BOTH | Tick marks appear on both sides of the control.
BOTTOMRIGHT | Tick marks appear on either the bottom or the right of the control.
MAX | Topic under construction.
MIN | Topic under construction.
NONE | The control has no tick marks.
TOPLEFT | Tick marks appear on either the top or the left of the control.

Fields

TickStyle.BOTH

Syntax
public static final int BOTH;
Description
Tick marks appear on both sides of the control.

TickStyle.BOTTOMRIGHT

Syntax
public static final int BOTTOMRIGHT;
Description
Tick marks appear on either the bottom or the right of the control.

TickStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

TickStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

TickStyle.NONE

Syntax
public static final int NONE;
Description
The control has no tick marks.

TickStyle.TOPLEFT

Syntax
public static final int TOPLEFT;
Description
Tick marks appear on either the top or the left of the control.


 ToolBar Class

ToolBar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--ToolBar
public class ToolBar
extends Control

This class wraps the comctl32 toolbar control.

Constructors
Name | Description
ToolBar() | Creates a Toolbar control.

Methods
Name | Description
addButton(ToolBarButton button) | Adds a button to the toolbar.
addOnButtonClick( ToolBarButtonClickEventHandler value) | Adds an event handler for when a toolbar button is clicked.
customize() | Brings up the customize dialog box for toolbars.
getAllowCustomize() | Retrieves the state of the AllowCustomize property.
getAppearance() | Retrieves the state of the Appearance property.
getBorderStyle() | Retrieves the state of the BorderStyle property.
getButtons() | Retrieves an array containing the toolbar buttons.
getButtonSize() | Retrieves the state of the ButtonSize property.
getDisabledImageList() | Retrieves the DisabledImageList property.
getDivider() | Retrieves the Divider property.
getDropDownArrows() | Retrieves the DropDownArrows property.
getHotImageList() | Retrieves the HotImageList property.
getImageList() | Retrieves the ImageList property.
getImageSize() | Retrieves the size of the images within the toolbar's image list.
getRightText() | Retrieves the RightText property.
getShowTips() | Retrieves the state of the ShowTips property.
getStandardImages() | Retrieves the StandardImages property.
getToolBarButton(int index) | Retrieves a ToolBarButton at a specified index.
getWrappable() | Retrieves the state of the Wrappable property.
insertButton(int index, ToolBarButton button) | Inserts a button onto the toolbar.
onButtonClick(ToolBarButtonClickEvent e) | Event fired when a toolbar button is clicked.
removeAllButtons() | Removes all the buttons in the toolbar.
removeButton(int index) | Removes a button at the specified index.
removeOnButtonClick( ToolBarButtonClickEventHandler value) | Removes an event handler for the ButtonClick event.
setAllowCustomize(boolean customize) | Sets the state of the AllowCustomize property.
setAppearance(int appear) | Sets the state of the Appearance property.
setBorderStyle(int style) | Sets the state of the BorderStyle property.
setButton(int index, ToolBarButton button) | Sets a ToolBarButton at the specified index.
setButtons(ToolBarButton[] array) | Sets all the buttons within the toolbar.
setButtonSize(Point size) | Sets the state of the ButtonSize property.
setDisabledImageList(ImageList value) | Sets the DisabledImageList property.
setDivider(boolean value) | Sets the Divider property.
setDropDownArrows(boolean value) | Sets the DropDownArrows property.
setFont(Font font) | Sets the Font property.
setHotImageList(ImageList value) | Sets the HotImageList property.
setImageList(ImageList value) | Sets the ImageList property.
setRightText(boolean value) | Sets the RightText property.
setShowTips(boolean show) | Sets the state of the ShowTips property.
setStandardImages(boolean value) | Sets the built-in button images.
setWrappable(boolean wrap) | Sets the state of the Wrappable property.

Constructors

ToolBar.ToolBar

Syntax
public ToolBar();
Description

Creates a Toolbar control.

Methods

ToolBar.addButton

Syntax
public int addButton( ToolBarButton button );
Parameters
button
The button to add to the toolbar.
Return Value

Returns the button added.

Description

Adds a button to the toolbar.

ToolBar.addOnButtonClick

Syntax
public void addOnButtonClick( ToolBarButtonClickEventHandler value );
Parameters
value
The event handler to add.
Description

Adds an event handler for when a toolbar button is clicked.

ToolBar.customize

Syntax
public void customize();
Description

Brings up the customize dialog box for toolbars.

ToolBar.getAllowCustomize

Syntax
public boolean getAllowCustomize();
Return Value

Returns the state of the AllowCustomize property.

Description

Retrieves the state of the AllowCustomize property. The AllowCustomize property enables the user to customize the toolbar.

ToolBar.getAppearance

Syntax
public int getAppearance();
Return Value

Returns the value of the Appearance property.

Description

Retrieves the state of the Appearance property. The Appearance property determines whether the toolbar appears three-dimensional, flat, or transparent.

ToolBar.getBorderStyle

Syntax
public int getBorderStyle();
Return Value

Returns the value of the BorderStyle property.

Description

Retrieves the state of the BorderStyle property. The BorderStyle property determines whether the toolbar has a border.

ToolBar.getButtons

Syntax
public ToolBarButton[] getButtons();
Return Value

Returns an array of ToolBarButton objects.

Description

Retrieves an array containing the toolbar buttons.

ToolBar.getButtonSize

Syntax
public Point getButtonSize();
Return Value

Returns the size of the buttons on the toolbar.

Description

Retrieves the state of the ButtonSize property. The ButtonSize property determines the size of the buttons on the toolbar.

ToolBar.getDisabledImageList

Syntax
public ImageList getDisabledImageList();
Return Value

Returns an imageList which represents the disabled images.

Description

Retrieves the DisabledImageList property.

ToolBar.getDivider

Syntax
public boolean getDivider();
Return Value

Returns the value of the property.

Description

Retrieves the Divider property. This will display a divider between the toolbar and the menu.

ToolBar.getDropDownArrows

Syntax
public boolean getDropDownArrows();
Return Value

Returns the boolean value.

Description

Retrieves the DropDownArrows property.

ToolBar.getHotImageList

Syntax
public ImageList getHotImageList();
Return Value

Returns an imageList which represents the hot images.

Description

Retrieves the HotImageList property.

ToolBar.getImageList

Syntax
public ImageList getImageList();
Return Value

Returns an imageList which represents the images.

Description

Retrieves the ImageList property.

ToolBar.getImageSize

Syntax
public Point getImageSize();
Return Value

Returns the size of the images in the toolbar.

Description

Retrieves the size of the images within the toolbar's image list.

ToolBar.getRightText

Syntax
public boolean getRightText();
Return Value

Returns the boolean value.

Description

Retrieves the RightText property. This property determines whether the button text is to the right of the image.

ToolBar.getShowTips

Syntax
public boolean getShowTips();
Return Value

Returns the value of the ShowTips property.

Description

Retrieves the state of the ShowTips property. The ShowTips property determines whether the tooltips show on a toolbar button.

ToolBar.getStandardImages

Syntax
public boolean getStandardImages();
Return Value

Returns the state.

Description

Retrieves the StandardImages property.

ToolBar.getToolBarButton

Syntax
public ToolBarButton getToolBarButton( int index );
Parameters
index
The index of the ToolBarButton to return.
Return Value

Returns the ToolBarButton at the specified index.

Description

Retrieves a ToolBarButton at a specified index.

Exceptions

ArrayIndexOutOfBounds thrown if the index is invalid.

ToolBar.getWrappable

Syntax
public boolean getWrappable();
Return Value

Returns the state of the Wrappable property.

Description

Retrieves the state of the Wrappable property. The Wrappable property enables buttons to be wrapped on the toolbar.

ToolBar.insertButton

Syntax
public int insertButton( int index, ToolBarButton button );
Parameters
index
The index at which to insert the button.
button
The button to add to the toolbar.
Return Value

Returns the index of the button added.

Description

Inserts a button onto the toolbar.

Exceptions

ArrayIndexOfOutBoundsException thrown if the index is invalid.

ToolBar.onButtonClick

Syntax
protected void onButtonClick( ToolBarButtonClickEvent e );
Description

Event fired when a toolbar button is clicked. param e The event data, including the ToolBarButton clicked.

ToolBar.removeAllButtons

Syntax
public void removeAllButtons();
Description

Removes all the buttons in the toolbar.

ToolBar.removeButton

Syntax
public void removeButton( int index );
Parameters
index
The index of the button to remove.
Description

Removes a button at the specified index.

Exceptions

ArrayIndexOutOfBoundsException thrown if the index is out of range.

ToolBar.removeOnButtonClick

Syntax
public void removeOnButtonClick( ToolBarButtonClickEventHandler value );
Parameters
value
The event handler to remove.
Description

Removes an event handler for the ButtonClick event.

ToolBar.setAllowCustomize

Syntax
public void setAllowCustomize( boolean customize );
Parameters
customize
The new state of the AllowCustomize property.
Description

Sets the state of the AllowCustomize property. The AllowCustomize property enables the user to customize the toolbar.

ToolBar.setAppearance

Syntax
public void setAppearance( int appear );
Parameters
appear
The new value of the Appearance property.
Description

Sets the state of the Appearance property. The Appearance property determines whether the toolbar appears three-dimensional, flat, or transparent.

ToolBar.setBorderStyle

Syntax
public void setBorderStyle( int style );
Parameters
style
The new value of the BorderStyle property.
Description

Sets the state of the BorderStyle property. The BorderStyle property determines whether the toolbar has a border.

ToolBar.setButton

Syntax
public void setButton( int index, ToolBarButton button );
Parameters
index
The index at which to set the button.
button
The button to set at the index.
Description

Sets a ToolBarButton at the specified index.

ToolBar.setButtons

Syntax
public void setButtons( ToolBarButton[] array );
Parameters
array
The new buttons to add.
Description

Sets all the buttons within the toolbar. The previous buttons will be disowned.

ToolBar.setButtonSize

Syntax
public void setButtonSize( Point size );
Parameters
size
The new size of the buttons on the toolbar.
Description

Sets the state of the ButtonSize property. The ButtonSize property determines the size of the buttons on the toolbar.

ToolBar.setDisabledImageList

Syntax
public void setDisabledImageList( ImageList value );
Parameters
value
The new ImageList.
Description

Sets the DisabledImageList property. These images are used to display images on toolbar buttons when the buttons are disabled.

ToolBar.setDivider

Syntax
public void setDivider( boolean value );
Parameters
value
The new value of the property.
Description

Sets the Divider property. This will display a divider between the toolbar and the menu.

ToolBar.setDropDownArrows

Syntax
public void setDropDownArrows( boolean value );
Parameters
value
The new boolean value of the DropDownArrows property.
Description

Sets the DropDownArrows property.

ToolBar.setFont

Syntax
public void setFont( Font font );
Parameters
font
The new font.
Description

Sets the Font property. Overrides Control.setFont so the toolbar can adjust its size if appropriate.

Overrides

setFont(Font) in Control.

ToolBar.setHotImageList

Syntax
public void setHotImageList( ImageList value );
Parameters
value
The new ImageList.
Description

Sets the HotImageList property. These images are used to display images on toolbar buttons when the mouse is over the button.

ToolBar.setImageList

Syntax
public void setImageList( ImageList value );
Parameters
value
The new ImageList.
Description

Sets the ImageList property. These images are used to display images on toolbar buttons.

ToolBar.setRightText

Syntax
public void setRightText( boolean value );
Parameters
value
The new RightText.
Description

Sets the RightText property. This property determines whether the button text is to the right of the image.

ToolBar.setShowTips

Syntax
public void setShowTips( boolean show );
Parameters
show
The new value of the ShowTips property.
Description

Sets the state of the ShowTips property. The ShowTips property determines whether the tooltips show on a toolbar button.

ToolBar.setStandardImages

Syntax
public void setStandardImages( boolean value );
Parameters
value
Set to true to use standard images; otherwise, set to false.
Description

Sets the built-in button images.

ToolBar.setWrappable

Syntax
public void setWrappable( boolean wrap );
Parameters
wrap
The state of the Wrappable property.
Description

Sets the state of the Wrappable property. The Wrappable property enables buttons to be wrapped on the toolbar.


 ToolBarAppearance Class

ToolBarAppearance Class

This Package | All Packages

Enum
  |
  +--ToolBarAppearance
public class ToolBarAppearance
extends Enum

The button appearance on a toolbar.

Fields
Name | Description
FLAT | Topic under construction.
MAX | Topic under construction.
MIN | Topic under construction.
NORMAL | Topic under construction.
TRANSPARENT | Topic under construction.

Fields

ToolBarAppearance.FLAT

Syntax
public static final int FLAT;
Description
Topic under construction.

ToolBarAppearance.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ToolBarAppearance.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ToolBarAppearance.NORMAL

Syntax
public static final int NORMAL;
Description
Topic under construction.

ToolBarAppearance.TRANSPARENT

Syntax
public static final int TRANSPARENT;
Description
Topic under construction.


 ToolBarBorderStyle Class

ToolBarBorderStyle Class

This Package | All Packages

Enum
  |
  +--ToolBarBorderStyle
public class ToolBarBorderStyle
extends Enum

The border of a toolbar.

Fields
Name | Description
FIXEDSINGLE | A single-line border.
MAX | Topic under construction.
MIN | Topic under construction.
NONE | No border.

Fields

ToolBarBorderStyle.FIXEDSINGLE

Syntax
public static final int FIXEDSINGLE;
Description
A single-line border.

ToolBarBorderStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ToolBarBorderStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ToolBarBorderStyle.NONE

Syntax
public static final int NONE;
Description
No border.


 ToolBarButton Class

ToolBarButton Class

This Package | All Packages

Object
  |
  +--ToolBarButton
public class ToolBarButton
extends Object
implements ICommandExecutor, IConstructable

Represents a button on a toolbar.

Constructors
Name | Description
ToolBarButton() | Topic under construction.
ToolBarButton(boolean enabled, int imageIndex, boolean indeterminate, Menu menu, boolean pushed, int style, Object tag, String text, String toolTipText) | Topic under construction.

Methods
Name | Description
addOnClick(EventHandler value) | Adds an listener for the Click event on this toolbar button.
dispose() | Topic under construction.
execute() | Topic under construction.
finalize() | Topic under construction.
getConstructorArgs() | Topic under construction.
getEnabled() | Retrieves the Enabled property.
getImageIndex() | Retrieves the ImageIndex property.
getIndeterminate() | Retrieves the Indeterminate property.
getMenu() | Retrieves the Menu property.
getPushed() | Retrieves the Pushed property.
getStyle() | Retrieves the Style property.
getTag() | Retrieves the Tag property.
getText() | Retrieves the Text property.
getToolTipText() | Retrieves the ToolTipText property.
onClick(Event e) | The Click event.
removeOnClick(EventHandler value) | Removes a Click event handler.
setEnabled(boolean value) | Sets the Enabled property.
setImageIndex(int index) | Sets the ImageIndex property.
setIndeterminate(boolean value) | Sets the Indeterminate property.
setMenu(Menu menu) | Sets the Menu property.
setPushed(boolean value) | Sets the Pushed property.
setStyle(int value) | Sets the Style property.
setTag(Object value) | Sets the Tag property.
setText(String text) | Sets the Text property.
setToolTipText(String value) | Sets the ToolTipText property.

Constructors

ToolBarButton.ToolBarButton

Syntax 1
public ToolBarButton();
Description

Topic under construction.

Syntax 2
public ToolBarButton( boolean enabled, int imageIndex, boolean indeterminate, Menu menu, boolean pushed, int style, Object tag, String text, String toolTipText );
Description

Topic under construction.

Methods

ToolBarButton.addOnClick

Syntax
public void addOnClick( EventHandler value );
Parameters
value
The Click event handler to add.
Description

Adds an listener for the Click event on this toolbar button.

ToolBarButton.dispose

Syntax
public void dispose();
Description

Topic under construction.

ToolBarButton.execute

Syntax
public void execute();
Description

Topic under construction.

ToolBarButton.finalize

Syntax
public void finalize();
Description

Topic under construction.

ToolBarButton.getConstructorArgs

Syntax
public ConstructorArg[] getConstructorArgs();
Description

Topic under construction.

ToolBarButton.getEnabled

Syntax
public boolean getEnabled();
Return Value

Returns the Enabled property state.

Description

Retrieves the Enabled property. This property specifies whether the button is usable.

ToolBarButton.getImageIndex

Syntax
public int getImageIndex();
Return Value

Returns the index of the image.

Description

Retrieves the ImageIndex property. This property specifies an image to use for the toolbar button.

ToolBarButton.getIndeterminate

Syntax
public boolean getIndeterminate();
Return Value

Returns the Indeterminate property state.

Description

Retrieves the Indeterminate property. This property specifies whether the button is dimmed.

ToolBarButton.getMenu

Syntax
public Menu getMenu();
Return Value

Returns a Menu object.

Description

Retrieves the Menu property. The Menu is used for drop-down toolbar buttons.

ToolBarButton.getPushed

Syntax
public boolean getPushed();
Return Value

Returns the Pushed state.

Description

Retrieves the Pushed property. This property applies to buttons of the style STYLE_CHECK.

ToolBarButton.getStyle

Syntax
public int getStyle();
Return Value

Returns the Style property.

Description

Retrieves the Style property.

ToolBarButton.getTag

Syntax
public Object getTag();
Return Value

Returns the Tag object.

Description

Retrieves the Tag property. This is user-defined data.

ToolBarButton.getText

Syntax
public String getText();
Return Value

Returns a string containing the text.

Description

Retrieves the Text property. The text is what sits next to or below the toolbar button image.

ToolBarButton.getToolTipText

Syntax
public String getToolTipText();
Return Value

Returns the string.

Description

Retrieves the ToolTipText property. This text is displayed when the user holds the mouse over the toolbar button.

ToolBarButton.onClick

Syntax
protected void onClick( Event e );
Parameters
e
The event data.
Description

The Click event.

ToolBarButton.removeOnClick

Syntax
public void removeOnClick( EventHandler value );
Parameters
value
The event handler to remove.
Description

Removes a Click event handler.

ToolBarButton.setEnabled

Syntax
public void setEnabled( boolean value );
Parameters
value
The new Enabled property state.
Description

Sets the Enabled property. This property specifies whether the button is usable.

ToolBarButton.setImageIndex

Syntax
public void setImageIndex( int index );
Parameters
index
The index of the image.
Description

Sets the ImageIndex property. This property specifies an image to use for the toolbar button.

ToolBarButton.setIndeterminate

Syntax
public void setIndeterminate( boolean value );
Parameters
value
The new Indeterminate property state.
Description

Sets the Indeterminate property. This property specifies whether the button is dimmed.

ToolBarButton.setMenu

Syntax
public void setMenu( Menu menu );
Parameters
menu
A Menu object.
Description

Sets the Menu property. The Menu is used for drop-down toolbar buttons.

ToolBarButton.setPushed

Syntax
public void setPushed( boolean value );
Parameters
value
The pushed state.
Description

Sets the Pushed property. This property applies to buttons of the style STYLE_CHECK.

ToolBarButton.setStyle

Syntax
public void setStyle( int value );
Parameters
value
The new style.
Description

Sets the Style property.

ToolBarButton.setTag

Syntax
public void setTag( Object value );
Parameters
value
The new Tag object.
Description

Sets the Tag property. This is for user-defined data.

ToolBarButton.setText

Syntax
public void setText( String text );
Parameters
text
The text value.
Description

Sets the Text property.

ToolBarButton.setToolTipText

Syntax
public void setToolTipText( String value );
Parameters
value
The string.
Description

Sets the ToolTipText property. This text is displayed when the user holds the mouse over the toolbar button.


 ToolBarButtonClickEvent Class

ToolBarButtonClickEvent Class

This Package | All Packages

Event
  |
  +--ToolBarButtonClickEvent
public class ToolBarButtonClickEvent
extends Event

Topic under construction.

Fields
Name | Description
toolBarButton | Topic under construction.

Constructors
Name | Description
ToolBarButtonClickEvent(ToolBarButton toolBarButton) | Topic under construction.

Fields

ToolBarButtonClickEvent.toolBarButton

Syntax
public ToolBarButton toolBarButton;
Description
Topic under construction.

Constructors

ToolBarButtonClickEvent.ToolBarButtonClickEvent

Syntax
public ToolBarButtonClickEvent( ToolBarButton toolBarButton );
Description

Topic under construction.


 ToolBarButtonStyle Class

ToolBarButtonStyle Class

This Package | All Packages

Enum
  |
  +--ToolBarButtonStyle
public class ToolBarButtonStyle
extends Enum

The button style within a toolbar.

Fields
Name | Description
BUTTONGROUP | Topic under construction.
CHECK | Topic under construction.
DEFAULT | Topic under construction.
DROPDOWN | Topic under construction.
MAX | Topic under construction.
MIN | Topic under construction.
SEPARATOR | Topic under construction.

Fields

ToolBarButtonStyle.BUTTONGROUP

Syntax
public static final int BUTTONGROUP;
Description
Topic under construction.

ToolBarButtonStyle.CHECK

Syntax
public static final int CHECK;
Description
Topic under construction.

ToolBarButtonStyle.DEFAULT

Syntax
public static final int DEFAULT;
Description
Topic under construction.

ToolBarButtonStyle.DROPDOWN

Syntax
public static final int DROPDOWN;
Description
Topic under construction.

ToolBarButtonStyle.MAX

Syntax
public static final int MAX;
Description
Topic under construction.

ToolBarButtonStyle.MIN

Syntax
public static final int MIN;
Description
Topic under construction.

ToolBarButtonStyle.SEPARATOR

Syntax
public static final int SEPARATOR;
Description
Topic under construction.


 ToolBarStandardImages Class

ToolBarStandardImages Class

This Package | All Packages

Object
  |
  +--ToolBarStandardImages
public class ToolBarStandardImages
extends Object

The toolbar standard images.

Fields
Name | Description
ADDTOFAVORITES | Topic under construction.
BACK | Topic under construction.
COPY | Topic under construction.
CUT | Topic under construction.
DELETE | Topic under construction.
DETAILS | Topic under construction.
FAVORITES | Topic under construction.
FILENEW | Topic under construction.
FILEOPEN | Topic under construction.
FILESAVE | Topic under construction.
FIND | Topic under construction.
FORWARD | Topic under construction.
HELP | Topic under construction.
LARGEICONS | Topic under construction.
LIST | Topic under construction.
NETCONNECT | Topic under construction.
NETDISCONNECT | Topic under construction.
NEWFOLDER | Topic under construction.
PARENTFOLDER | Topic under construction.
PASTE | Topic under construction.
PRINT | Topic under construction.
PRINTPRE | Topic under construction.
PROPERTIES | Topic under construction.
REDOW | Topic under construction.
REPLACE | Topic under construction.
SMALLICONS | Topic under construction.
SORTDATE | Topic under construction.
SORTNAME | Topic under construction.
SORTSIZE | Topic under construction.
SORTTYPE | Topic under construction.
UNDO | Topic under construction.
VIEWMENU | Topic under construction.
VIEWTREE | Topic under construction.

Fields

ToolBarStandardImages.ADDTOFAVORITES

Syntax
public static final int ADDTOFAVORITES;
Description
Topic under construction.

ToolBarStandardImages.BACK

Syntax
public static final int BACK;
Description
Topic under construction.

ToolBarStandardImages.COPY

Syntax
public static final int COPY;
Description
Topic under construction.

ToolBarStandardImages.CUT

Syntax
public static final int CUT;
Description
Topic under construction.

ToolBarStandardImages.DELETE

Syntax
public static final int DELETE;
Description
Topic under construction.

ToolBarStandardImages.DETAILS

Syntax
public static final int DETAILS;
Description
Topic under construction.

ToolBarStandardImages.FAVORITES

Syntax
public static final int FAVORITES;
Description
Topic under construction.

ToolBarStandardImages.FILENEW

Syntax
public static final int FILENEW;
Description
Topic under construction.

ToolBarStandardImages.FILEOPEN

Syntax
public static final int FILEOPEN;
Description
Topic under construction.

ToolBarStandardImages.FILESAVE

Syntax
public static final int FILESAVE;
Description
Topic under construction.

ToolBarStandardImages.FIND

Syntax
public static final int FIND;
Description
Topic under construction.

ToolBarStandardImages.FORWARD

Syntax
public static final int FORWARD;
Description
Topic under construction.

ToolBarStandardImages.HELP

Syntax
public static final int HELP;
Description
Topic under construction.

ToolBarStandardImages.LARGEICONS

Syntax
public static final int LARGEICONS;
Description
Topic under construction.

ToolBarStandardImages.LIST

Syntax
public static final int LIST;
Description
Topic under construction.

ToolBarStandardImages.NETCONNECT

Syntax
public static final int NETCONNECT;
Description
Topic under construction.

ToolBarStandardImages.NETDISCONNECT

Syntax
public static final int NETDISCONNECT;
Description
Topic under construction.

ToolBarStandardImages.NEWFOLDER

Syntax
public static final int NEWFOLDER;
Description
Topic under construction.

ToolBarStandardImages.PARENTFOLDER

Syntax
public static final int PARENTFOLDER;
Description
Topic under construction.

ToolBarStandardImages.PASTE

Syntax
public static final int PASTE;
Description
Topic under construction.

ToolBarStandardImages.PRINT

Syntax
public static final int PRINT;
Description
Topic under construction.

ToolBarStandardImages.PRINTPRE

Syntax
public static final int PRINTPRE;
Description
Topic under construction.

ToolBarStandardImages.PROPERTIES

Syntax
public static final int PROPERTIES;
Description
Topic under construction.

ToolBarStandardImages.REDOW

Syntax
public static final int REDOW;
Description
Topic under construction.

ToolBarStandardImages.REPLACE

Syntax
public static final int REPLACE;
Description
Topic under construction.

ToolBarStandardImages.SMALLICONS

Syntax
public static final int SMALLICONS;
Description
Topic under construction.

ToolBarStandardImages.SORTDATE

Syntax
public static final int SORTDATE;
Description
Topic under construction.

ToolBarStandardImages.SORTNAME

Syntax
public static final int SORTNAME;
Description
Topic under construction.

ToolBarStandardImages.SORTSIZE

Syntax
public static final int SORTSIZE;
Description
Topic under construction.

ToolBarStandardImages.SORTTYPE

Syntax
public static final int SORTTYPE;
Description
Topic under construction.

ToolBarStandardImages.UNDO

Syntax
public static final int UNDO;
Description
Topic under construction.

ToolBarStandardImages.VIEWMENU

Syntax
public static final int VIEWMENU;
Description
Topic under construction.

ToolBarStandardImages.VIEWTREE

Syntax
public static final int VIEWTREE;
Description
Topic under construction.


 ToolTip Class

ToolTip Class

This Package | All Packages

Component
  |
  +--ToolTip
public final class ToolTip
extends Component
implements IExtenderProvider

Provides tooltips for other controls.

Constructors
Name | Description
ToolTip() | Creates a ToolTip object.
getToolTip(Control control) | Retrieves the current tooltip for the specified control.
setToolTip(Control control, String caption) | Sets the tooltip for the specified control.

Methods
Name | Description
addRegion(ToolTipRegion region) | Adds a tooltip region to the control.
getAutomaticDelay() | Retrieves the current value of the AutomaticDelay property.
getAutoPopDelay() | Retrieves the current value of the AutoPopDelay property.
getInitialDelay() | Retrieves the current value of the InitialDelay property.
getRegion(Control boundControl) | Retrieves the region that is bound to the specified control.
getRegions() | Retrieves an array of all regions.
getReshowDelay() | Retrieves the current value of the ReshowDelay property.
getShowAlways() | Retrieves the current ShowAlways value.
removeAllRegions() | Removes all tooltip regions from the control.
removeRegion(ToolTipRegion region) | Removes a single tooltip region from the control.
setAutomaticDelay(int value) | Sets the AutomaticDelay property.
setAutoPopDelay(int value) | Sets the AutoPopDelay property.
setInitialDelay(int value) | Sets the InitialDelay property.
setRegions(ToolTipRegion[] regions) | Sets the regions to display.
setReshowDelay(int value) | Sets the ReshowDelay property.
setShowAlways(boolean value) | Sets the value of ShowAlways.

Constructors

ToolTip.ToolTip

Syntax
public ToolTip();
Description

Creates a ToolTip object.

ToolTip.getToolTip

Syntax
public String getToolTip( Control control );
Parameters
control
The control to get the tooltip for.
Return Value

Returns the tooltip for the specified control.

Description

Retrieves the current tooltip for the specified control.

See Also
setToolTip

ToolTip.setToolTip

Syntax
public void setToolTip( Control control, String caption );
Parameters
control
The control to set the tooltip for.
caption
The tooltip to display.
Description

Sets the tooltip for the specified control.

See Also
getToolTip

Methods

ToolTip.addRegion

Syntax
public void addRegion( ToolTipRegion region );
Parameters
region
The region to add to the control.
Description

Adds a tooltip region to the control.

See Also
removeRegion, getRegion

ToolTip.getAutomaticDelay

Syntax
public int getAutomaticDelay();
Return Value

Returns current value of the AutomaticDelay property.

Description

Retrieves the current value of the AutomaticDelay property.

See Also
setAutomaticDelay

ToolTip.getAutoPopDelay

Syntax
public int getAutoPopDelay();
Return Value

Returns current value of the AutoPopDelay property.

Description

Retrieves the current value of the AutoPopDelay property.

See Also
setAutoPopDelay

ToolTip.getInitialDelay

Syntax
public int getInitialDelay();
Return Value

Returns current value of the InitialDelay property.

Description

Retrieves the current value of the InitialDelay property.

See Also
setInitialDelay

ToolTip.getRegion

Syntax
public ToolTipRegion getRegion( Control boundControl );
Parameters
boundControl
The control to find the region for.
Return Value

Returns the region that is bound to boundControl.

Description

Retrieves the region that is bound to the specified control.

ToolTip.getRegions

Syntax
public ToolTipRegion[] getRegions();
Return Value

Returns an array of all regions.

Description

Retrieves an array of all regions.

See Also
setRegions

ToolTip.getReshowDelay

Syntax
public int getReshowDelay();
Return Value

Returns the current value of the ReshowDelay property.

Description

Retrieves the current value of the ReshowDelay property.

See Also
setReshowDelay

ToolTip.getShowAlways

Syntax
public boolean getShowAlways();
Return Value

Returns current ShowAlways value.

Description

Retrieves the current ShowAlways value.

See Also
setShowAlways

ToolTip.removeAllRegions

Syntax
public void removeAllRegions();
Description

Removes all tooltip regions from the control.

See Also
removeRegion

ToolTip.removeRegion

Syntax
public void removeRegion( ToolTipRegion region );
Parameters
region
The region to remove.
Description

Removes a single tooltip region from the control.

See Also
removeAllRegions

ToolTip.setAutomaticDelay

Syntax
public void setAutomaticDelay( int value );
Parameters
value
The new value in milliseconds.
Description

Sets the AutomaticDelay property. When the AutomaticDelay property is set, values are given to the AutoPopDelay, InitialDelay, and ReshowDelay based on the AutomaticDelay value. The AutoPopDelay is always set to 10 times the AutomaticDelay; the InitialDelay is set to 1/5 times the AutomaticDelay; and ReshowDelay is set to the same time as the AutomaticDelay.

See Also
getAutomaticDelay, setAutoPopDelay, setInitialDelay, setReshowDelay

ToolTip.setAutoPopDelay

Syntax
public void setAutoPopDelay( int value );
Parameters
value
The new value in milliseconds.
Description

Sets the AutoPopDelay property. This is the length of time the tooltip window remains visible if the pointer is stationary inside a tooltip region.

See Also
getAutomaticDelay, setAutomaticDelay, setInitialDelay, setReshowDelay

ToolTip.setInitialDelay

Syntax
public void setInitialDelay( int value );
Parameters
value
The new value in milliseconds.
Description

Sets the InitialDelay property. This is the length of time the pointer must remain stationary within a tooltip region before the tooltip window appears.

See Also
getAutomaticDelay, setAutomaticDelay, setAutoPopDelay, setReshowDelay

ToolTip.setRegions

Syntax
public void setRegions( ToolTipRegion[] regions );
Parameters
regions
The regions to display.
Description

Sets the regions to display.

See Also
getRegions

ToolTip.setReshowDelay

Syntax
public void setReshowDelay( int value );
Parameters
value
The new value in milliseconds.
Description

Sets the ReshowDelay property. This is the length of time it takes for subsequent tooltip windows to appear as the pointer moves from one tooltip region to another.

See Also
getAutomaticDelay, setAutomaticDelay, setAutoPopDelay, setInitialDelay

ToolTip.setShowAlways

Syntax
public void setShowAlways( boolean value );
Parameters
value
The new value for the ShowAlways property.
Description

Sets the value of ShowAlways. When ShowAlways is set to true, the tooltips are always displayed, even if the parent form is not active.

See Also
getShowAlways


 ToolTipRegion Class

ToolTipRegion Class

This Package | All Packages

public class ToolTipRegion
implements IConstructable

A ToolTipRegion defines an area either by a rectangle or control that displays a tooltip when the mouse hovers over it.

Constructors
Name | Description
ToolTipRegion(Control control, String caption) | Creates a ToolTipRegion object.

Methods
Name | Description
getCaption() | Retrieves the caption that will be displayed when the mouse hovers over the region.
getControl() | Retrieves the control that defines the region.
setCaption(String caption) | Sets the caption to be displayed when the mouse hovers over this region.
setControl(Control boundControl) | Sets the control that defines the region.

Constructors

ToolTipRegion.ToolTipRegion

Syntax
public ToolTipRegion( Control control, String caption );
Parameters
control
The control to make the tip for.
caption
The caption to display when the mouse hovers over the specified control.
Description

Creates a ToolTipRegion object.

Methods

ToolTipRegion.getCaption

Syntax
public String getCaption();
Return Value

Returns the caption.

Description

Retrieves the caption that will be displayed when the mouse hovers over the region.

See Also
setCaption

ToolTipRegion.getControl

Syntax
public Control getControl();
Return Value

Returns the control that defines the region.

Description

Retrieves the control that defines the region. This will be null if the region is bound to a rectangular region.

See Also
setControl

ToolTipRegion.setCaption

Syntax
public void setCaption( String caption );
Parameters
caption
The caption to display.
Description

Sets the caption to be displayed when the mouse hovers over this region.

See Also
getCaption

ToolTipRegion.setControl

Syntax
public void setControl( Control boundControl );
Parameters
boundControl
The control.
Description

Sets the control that defines the region.

See Also
getControl


 TrackBar Class

TrackBar Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--TrackBar
public class TrackBar
extends Control

Topic under construction.

Constructors
Name | Description
TrackBar() | Topic under construction.
TrackBar(IContainer container) | Topic under construction.

Methods
Name | Description
addOnScroll(EventHandler value) | Topic under construction.
getLargeChange() | Topic under construction.
getMax() | Topic under construction.
getMin() | Topic under construction.
getOrientation() | Topic under construction.
getPos() | Topic under construction.
getSmallChange() | Topic under construction.
getTickFrequency() | Topic under construction.
getTickStyle() | Topic under construction.
removeOnScroll(EventHandler value) | Topic under construction.
setLargeChange(int value) | Topic under construction.
setMax(int value) | Topic under construction.
setMin(int value) | Topic under construction.
setOrientation(int value) throws IllegalArgumentException | Topic under construction.
setPos(int value) | Topic under construction.
setRange(int minValue, int maxValue) | Topic under construction.
setSmallChange(int value) | Topic under construction.
setTickFrequency(int value) | Topic under construction.
setTickStyle(int value) throws IllegalArgumentException | Topic under construction.

Constructors

TrackBar.TrackBar

Syntax 1
public TrackBar();
Description

Topic under construction.

Syntax 2
public TrackBar( IContainer container );
Description

Topic under construction.

Methods

TrackBar.addOnScroll

Syntax
public void addOnScroll( EventHandler value );
Description

Topic under construction.

TrackBar.getLargeChange

Syntax
public int getLargeChange();
Description

Topic under construction.

TrackBar.getMax

Syntax
public int getMax();
Description

Topic under construction.

TrackBar.getMin

Syntax
public int getMin();
Description

Topic under construction.

TrackBar.getOrientation

Syntax
public int getOrientation();
Description

Topic under construction.

TrackBar.getPos

Syntax
public int getPos();
Description

Topic under construction.

TrackBar.getSmallChange

Syntax
public int getSmallChange();
Description

Topic under construction.

TrackBar.getTickFrequency

Syntax
public int getTickFrequency();
Description

Topic under construction.

TrackBar.getTickStyle

Syntax
public int getTickStyle();
Description

Topic under construction.

TrackBar.removeOnScroll

Syntax
public void removeOnScroll( EventHandler value );
Description

Topic under construction.

TrackBar.setLargeChange

Syntax
public void setLargeChange( int value );
Description

Topic under construction.

TrackBar.setMax

Syntax
public void setMax( int value );
Description

Topic under construction.

TrackBar.setMin

Syntax
public void setMin( int value );
Description

Topic under construction.

TrackBar.setOrientation

Syntax
public void setOrientation( int value ) throws IllegalArgumentException;
Description

Topic under construction.

TrackBar.setPos

Syntax
public void setPos( int value );
Description

Topic under construction.

TrackBar.setRange

Syntax
public void setRange( int minValue, int maxValue );
Description

Topic under construction.

TrackBar.setSmallChange

Syntax
public void setSmallChange( int value );
Description

Topic under construction.

TrackBar.setTickFrequency

Syntax
public void setTickFrequency( int value );
Description

Topic under construction.

TrackBar.setTickStyle

Syntax
public void setTickStyle( int value ) throws IllegalArgumentException;
Description

Topic under construction.


 TreeNode Class

TreeNode Class

This Package | All Packages

public class TreeNode

Encapsulates a node in a TreeView control.

Methods
Name | Description
addAfter(Object obj) | Inserts the specified object after the current node.
addBefore(Object obj) | Inserts the specified object above the current node.
addChild(Object obj) | Inserts the specified object as a child of the current node.
collapse(boolean recursive) | Collapses the current node.
expand(boolean recursive) | Expands the current node to display its child nodes.
getChild(int ix) | Retrieves the child node that corresponds to the specified index.
getChildCount() | Retrieves the number of the current node's children.
getChildren() | Retrieves the children of the current node in an array of TreeNode objects.
getExpanded() | Retrieves a boolean value that indicates whether the current node is expanded.
getFirstChild() | Retrieves the first child node of the current node.
getHandle() | Retrieves the HTREEITEM for this TreeView node.
getLastChild() | Retrieves the last child node of the current node.
getLevel() | Retrieves the level of the current node in the TreeView heirarchy.
getNext() | Retrieves the next node in the current node heirarchy.
getObject() | Retrieves an object for the current node.
getParent() | Retrieves the parent of the current node.
getPrev() | Retrieves the previous node in the current node heirarchy.
getSelected() | Retrieves a boolean value that indicates whether the current node is selected.
getSorted() | Retrieves a boolean value that indicates whether the children of the current node are sorted.
getTreeView() | Retrieves the TreeView control to which this node belongs.
getVisible() | Retrieves a boolean value that indicates whether the current node is visible.
remove() | Removes the current node.
select() | Selects the current node.
setObject(Object value) | Topic under construction.
setParent(TreeNode value) | Sets the current node's parent.
setSorted(boolean value) | Specifies whether the children of the current tree node should be sorted.
setVisible() | Makes the current node visible.
toString() | Topic under construction.

Methods

TreeNode.addAfter

Syntax
public TreeNode addAfter( Object obj );
Parameters
obj
The object to insert after the current node.
Return Value

Returns a TreeNode for the newly inserted node.

Description

Inserts the specified object after the current node. If the current node is null, the object is inserted as the first child.

TreeNode.addBefore

Syntax
public TreeNode addBefore( Object obj );
Parameters
obj
The object to insert before the current node.
Return Value

Returns a TreeNode object for the newly inserted node.

Description

Inserts the specified object above the current node.

TreeNode.addChild

Syntax
public TreeNode addChild( Object obj );
Parameters
obj
The object to insert as a child of the current node.
Return Value

Returns a TreeNode object for the newly inserted node.

Description

Inserts the specified object as a child of the current node.

TreeNode.collapse

Syntax
public void collapse( boolean recursive );
Parameters
recursive.
If true, all of the subtrees of the current node are collapsed. Otherwise, only the first level in the heirarchy is collapsed.
Description

Collapses the current node.

TreeNode.expand

Syntax
public void expand( boolean recursive );
Parameters
recursive
If true, the TreeNode object displays all the children of the current node, and their children, and their children, and so on. Otherwise, only the first level of the child heirarchy is displayed.
Description

Expands the current node to display its child nodes.

TreeNode.getChild

Syntax
public TreeNode getChild( int ix );
Parameters
ix
The zero-based index of the child to return.
Return Value

Returns the TreeNode at the specified index.

Description

Retrieves the child node that corresponds to the specified index.

TreeNode.getChildCount

Syntax
public int getChildCount();
Return Value

Returns an integer that identifies the number of child nodes.

Description

Retrieves the number of the current node's children.

TreeNode.getChildren

Syntax
public TreeNode[] getChildren();
Return Value

Returns an array of TreeNode objects that contains the children of the current node.

Description

Retrieves the children of the current node in an array of TreeNode objects.

TreeNode.getExpanded

Syntax
public boolean getExpanded();
Return Value

Returns true if the current node is expanded; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current node is expanded.

TreeNode.getFirstChild

Syntax
public TreeNode getFirstChild();
Return Value

Returns the TreeNode for the first child node.

Description

Retrieves the first child node of the current node.

TreeNode.getHandle

Syntax
public int getHandle();
Return Value

Returns an integer that represents the HTREEITEM.

Description

Retrieves the HTREEITEM for this TreeView node.

TreeNode.getLastChild

Syntax
public TreeNode getLastChild();
Return Value

Returns the TreeNode for the last child node.

Description

Retrieves the last child node of the current node.

TreeNode.getLevel

Syntax
public int getLevel();
Return Value

Returns an integer that identifies the current node's level.

Description

Retrieves the level of the current node in the TreeView heirarchy.

TreeNode.getNext

Syntax
public TreeNode getNext();
Return Value

Returns the next TreeNode in the heirarchy.

Description

Retrieves the next node in the current node heirarchy.

TreeNode.getObject

Syntax
public Object getObject();
Return Value

Returns the object.

Description

Retrieves an object for the current node.

TreeNode.getParent

Syntax
public TreeNode getParent();
Return Value

Returns the TreeNode for the parent of the current node.

Description

Retrieves the parent of the current node.

TreeNode.getPrev

Syntax
public TreeNode getPrev();
Return Value

Returns the previous TreeNode in the heirarchy.

Description

Retrieves the previous node in the current node heirarchy.

TreeNode.getSelected

Syntax
public boolean getSelected();
Return Value

Returns true if the current node is selected; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current node is selected.

TreeNode.getSorted

Syntax
public boolean getSorted();
Return Value

Returns true if the children are sorted; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the children of the current node are sorted.

TreeNode.getTreeView

Syntax
public TreeView getTreeView();
Return Value

Returns the TreeView control.

Description

Retrieves the TreeView control to which this node belongs.

TreeNode.getVisible

Syntax
public boolean getVisible();
Return Value

Returns true if the current node is visible; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the current node is visible.

TreeNode.remove

Syntax
public void remove();
Description

Removes the current node.

TreeNode.select

Syntax
public void select();
Description

Selects the current node.

TreeNode.setObject

Syntax
public void setObject( Object value );
Description

Topic under construction.

TreeNode.setParent

Syntax
public void setParent( TreeNode value );
Parameters
value
the TreeNode to set as the current node's parent.
Description

Sets the current node's parent.

TreeNode.setSorted

Syntax
public void setSorted( boolean value );
Parameters
value
A boolean value that indicates whether the tree node's children should be sorted.
Description

Specifies whether the children of the current tree node should be sorted.

TreeNode.setVisible

Syntax
public void setVisible();
Description

Makes the current node visible.

TreeNode.toString

Syntax
public String toString();
Description

Topic under construction.


 TreeView Class

TreeView Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--TreeView
public class TreeView
extends Control

Windows TreeView common control.

Fields
Name | Description
CUSTOM | Topic under construction.
NONE | Topic under construction.
TEXT | Topic under construction.

Constructors
Name | Description
TreeView() | Constructs a new TreeView object.

Methods
Name | Description
addChild(TreeNode parent, Object obj) | Inserts an object into the TreeView as a child of the specified parent node.
clear() | Deletes all nodes from the TreeView.
elements() | Retrieves an IEnumerator interface for this TreeView object.
getIndent() | Retrieves the offset, in pixels, of a TreeView item from its parent.
getReadOnly() | Retrieves a boolean value that indicates whether the TreeView is read-only.
getRoot() | Retrieves the root of the TreeView.
getShowButtons() | Retrieves a boolean value that indicates whether the TreeView currently displays buttons next to parent nodes that have child items.
getShowLines() | Retrieves a boolean value that indicates whether the TreeView currently displays lines linking child items to their corresponding parent items.
getShowRootLines() | Retrieves a boolean value that indicates whether the TreeView has lines linking child items to the root of the heirarchy.
getSorted() | Retrieves a boolean value that indicates whether the child items in the control are sorted.
setChildren(TreeNode parent, Object[] objs) | Inserts an array of objects into the TreeView beneath the specified parent node.
setIndent(int val) | Sets the indention level, in pixels, for child nodes.
setReadOnly(boolean val) | Specifies whether the TreeView should be read-only.
setShowButtons(boolean val) | Specifies whether the TreeView buttons should be displayed.
setShowLines(boolean val) | Specifies whether the lines between nodes in the TreeView should be displayed.
setShowRootLines(boolean val) | Specifies whether the lines linking child nodes to the TreeView's root node should be displayed.
setSorted(boolean val) | Specifies whether the nodes in the TreeView should be sorted.

Fields

TreeView.CUSTOM

Syntax
public static final int CUSTOM;
Description
Topic under construction.

TreeView.NONE

Syntax
public static final int NONE;
Description
Topic under construction.

TreeView.TEXT

Syntax
public static final int TEXT;
Description
Topic under construction.

Constructors

TreeView.TreeView

Syntax
public TreeView();
Description

Constructs a new TreeView object.

Methods

TreeView.addChild

Syntax
public TreeNode addChild( TreeNode parent, Object obj );
Parameters
parent
Identifies the parent node beneath which the object will be inserted.
Object
The object to be inserted into the TreeView.
Return Value

Returns a TreeNode for the newly inserted object.

Description

Inserts an object into the TreeView as a child of the specified parent node.

TreeView.clear

Syntax
public void clear();
Description

Deletes all nodes from the TreeView.

TreeView.elements

Syntax
public IEnumerator elements();
Return Value

Returns an IEnumerator interface, which you use to iterate through the nodes in the TreeView.

Description

Retrieves an IEnumerator interface for this TreeView object.

TreeView.getIndent

Syntax
public int getIndent();
Return Value

Returns the amount of indentation, measured in pixels.

Description

Retrieves the offset, in pixels, of a TreeView item from its parent. For example, a return value of five (5), indicates that child nodes are indented five pixels to the right of parent nodes.

TreeView.getReadOnly

Syntax
public boolean getReadOnly();
Return Value

Returns true if the labels are read-only; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the TreeView is read-only. When a TreeView is read-only, the text of nodes in the tree cannot be edited.

TreeView.getRoot

Syntax
public TreeNode getRoot();
Return Value

Returns the root node of the TreeView.

Description

Retrieves the root of the TreeView.

TreeView.getShowButtons

Syntax
public boolean getShowButtons();
Return Value

Returns true if the TreeView is configured to display buttons for TreeView nodes that have children; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the TreeView currently displays buttons next to parent nodes that have child items.

TreeView.getShowLines

Syntax
public boolean getShowLines();
Return Value

Returns true, if the lines will be displayed; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the TreeView currently displays lines linking child items to their corresponding parent items.

TreeView.getShowRootLines

Syntax
public boolean getShowRootLines();
Return Value

Returns returns true, if the lines will be displayed; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the TreeView has lines linking child items to the root of the heirarchy.

TreeView.getSorted

Syntax
public boolean getSorted();
Return Value

Returns true if the items are sorted; otherwise, returns false.

Description

Retrieves a boolean value that indicates whether the child items in the control are sorted.

TreeView.setChildren

Syntax
public void setChildren( TreeNode parent, Object[] objs );
Parameters
parent
The parent beneath which the array of objects will be inserted.
objs
The array of objects to be inserted beneath the specified parent.
Description

Inserts an array of objects into the TreeView beneath the specified parent node.

TreeView.setIndent

Syntax
public void setIndent( int val );
Parameters
val
The indention level, in pixels, for child nodes.
Description

Sets the indention level, in pixels, for child nodes.

TreeView.setReadOnly

Syntax
public void setReadOnly( boolean val );
Parameters
val
If true, the labels of TreeView items are read-only. Otherwise, these labels can be edited by users.
Description

Specifies whether the TreeView should be read-only. When a TreeView is read-only, the text of nodes in the tree cannot be edited.

TreeView.setShowButtons

Syntax
public void setShowButtons( boolean val );
Parameters
val
If true, buttons appear next to parent nodes. Otherwise, no buttons appear.
Description

Specifies whether the TreeView buttons should be displayed.

TreeView.setShowLines

Syntax
public void setShowLines( boolean val );
Parameters
val
If true, the the lines that link child and parent items are displayed. Otherwise, the lines are not displayed.
Description

Specifies whether the lines between nodes in the TreeView should be displayed.

TreeView.setShowRootLines

Syntax
public void setShowRootLines( boolean val );
Parameters
val
If true, the TreeView displays the lines. Otherwise, the lines are not displayed.
Description

Specifies whether the lines linking child nodes to the TreeView's root node should be displayed.

TreeView.setSorted

Syntax
public void setSorted( boolean val );
Parameters
val
Set to true to sort the nodes in the TreeView; otherwise, set to false.
Description

Specifies whether the nodes in the TreeView should be sorted.


 UpDown Class

UpDown Class

This Package | All Packages

Component
  |
  +--Control
    |
    +--UpDown
public class UpDown
extends Control

Implements an UpDown common control.

Fields
Name | Description
BASE_10 | Base 10 (decimal) numbering.
BASE_16 | Base 16 (hexadecimal) numbering.
LEFT | Topic under construction.
MANUAL | Topic under construction.
RIGHT | Topic under construction.

Constructors
Name | Description
UpDown() | Creates an UpDown control.

Methods
Name | Description
createHandle() | Creates a companion component.
getBase() | Indicates what base we're operating in.
getBuddy() | Retrieves the companion control.
getCreateParams() | Retrieves the information needed to create our component.
getHorizontal() | Determines if the updown control is vertical (default) or horizontal.
getInterceptArrowKeys() | Determines whether or not the control intercepts arrow keys from the companion class.
getMax() | Retrieves the current maximum value.
getMin() | Retrieves the current minimum value.
getModifyBuddy() | Determines if the control modifies the value in the companion control, or if the programmer will do it.
getPositioning() | Determines how the UpDown control is positioned relative to the companion control.
getValue() | Retrieves the current value (position) of the UpDown control.
getWrap() | Determines if the control will wrap the number it is incrementing or decrementing to the other end of the range.
setBase(int value) | Sets the base.
setBuddy(Control ctl) | Sets the companion control.
setHorizontal(boolean horz) | Determines if the UpDown control is vertical [default] or horizontal.
setInterceptArrowKeys(boolean value) | Instructions the control to start or stop intercepting arrow keys from the buddy control.
setMax(int value) | Sets the current maximum value.
setMin(int value) | Sets the current min value.
setModifyBuddy(boolean value) | Indicates if the control modifies the value in the companion control, or if the programmer will do this.
setPositioning(int value) | Sets how the UpDown control aligns itself with the companion control.
setValue(int value) | Sets the current value.
setWrap(boolean value) | Indicates if the control wraps the number it is incrementing or decrementing to the other end of the range.

Fields

UpDown.BASE_10

Syntax
public static final int BASE_10;
Description
Base 10 (decimal) numbering.

UpDown.BASE_16

Syntax
public static final int BASE_16;
Description
Base 16 (hexadecimal) numbering.

UpDown.LEFT

Syntax
public static final int LEFT;
Description
Topic under construction.

UpDown.MANUAL

Syntax
public static final int MANUAL;
Description
Topic under construction.

UpDown.RIGHT

Syntax
public static final int RIGHT;
Description
Topic under construction.

Constructors

UpDown.UpDown

Syntax
public UpDown();
Description

Creates an UpDown control.

Methods

UpDown.createHandle

Syntax
protected void createHandle();
Description

Creates a companion component. The UpDown control sends it WM_SETTEXT messages when the user selects things with the UpDown control. Override this routine to be notified when the control has finished creating things.

Overrides

createHandle() in Control.

UpDown.getBase

Syntax
public int getBase();
Return Value

Returns the base, which can be one of the BASE_ values.

Description

Indicates what base we're operating in.

UpDown.getBuddy

Syntax
public Control getBuddy();
Return Value

Returns the control object.

Description

Retrieves the companion control.

UpDown.getCreateParams

Syntax
protected CreateParams getCreateParams();
Return Value

Returns the CreateParams object.

Description

Retrieves the information needed to create our component.

Overrides

getCreateParams() in Control.

UpDown.getHorizontal

Syntax
public boolean getHorizontal();
Return Value

Returns true if vertical; otherwise, returns false.

Description

Determines if the updown control is vertical (default) or horizontal.

UpDown.getInterceptArrowKeys

Syntax
public boolean getInterceptArrowKeys();
Return Value

Returns true if intercepting arrow keys; otherwise, returns false.

Description

Determines whether or not the control intercepts arrow keys from the companion class.

UpDown.getMax

Syntax
public int getMax();
Return Value

Returns the current maximum value.

Description

Retrieves the current maximum value.

UpDown.getMin

Syntax
public int getMin();
Return Value

Returns the current minimum value.

Description

Retrieves the current minimum value.

UpDown.getModifyBuddy

Syntax
public boolean getModifyBuddy();
Return Value

Returns true if the control modifies values; otherwise, returns false.

Description

Determines if the control modifies the value in the companion control, or if the programmer will do it.

UpDown.getPositioning

Syntax
public int getPositioning();
Return Value

Returns MANUAL if positioning is done by the programmer, RIGHT if this control is positioned on the right of the companion control, or LEFT2 if positioned the left of the companion control.

Description

Determines how the UpDown control is positioned relative to the companion control.

See Also
MANUAL, RIGHT, LEFT

UpDown.getValue

Syntax
public int getValue();
Return Value

Returns the control's value.

Description

Retrieves the current value (position) of the UpDown control.

UpDown.getWrap

Syntax
public boolean getWrap();
Return Value

Returns true if wrapping is enabled; otherwise, returns false.

Description

Determines if the control will wrap the number it is incrementing or decrementing to the other end of the range.

UpDown.setBase

Syntax
public void setBase( int value );
Parameters
value
One of the BASE_ values.
Description

Sets the base.

UpDown.setBuddy

Syntax
public void setBuddy( Control ctl );
Parameters
ctl
The companion component (which must inherit from Control).
Description

Sets the companion control.

UpDown.setHorizontal

Syntax
public void setHorizontal( boolean horz );
Parameters
horz
Set to true if horizontal.
Description

Determines if the UpDown control is vertical [default] or horizontal.

UpDown.setInterceptArrowKeys

Syntax
public void setInterceptArrowKeys( boolean value );
Parameters
value
Topic under construction.
Description

Instructions the control to start or stop intercepting arrow keys from the buddy control.

UpDown.setMax

Syntax
public void setMax( int value );
Parameters
value
Topic under construction.
Description

Sets the current maximum value. This cannot be bigger than UD_MAXVAL or less than UD_MINVAL.

UpDown.setMin

Syntax
public void setMin( int value );
Parameters
value
Topic under construction.
Description

Sets the current min value.

UpDown.setModifyBuddy

Syntax
public void setModifyBuddy( boolean value );
Parameters
value
Topic under construction.
Description

Indicates if the control modifies the value in the companion control, or if the programmer will do this.

UpDown.setPositioning

Syntax
public void setPositioning( int value );
Parameters
value
Topic under construction.
Description

Sets how the UpDown control aligns itself with the companion control. Set the propget above for valid values.

UpDown.setValue

Syntax
public void setValue( int value );
Parameters
value
Topic under construction.
Description

Sets the current value.

UpDown.setWrap

Syntax
public void setWrap( boolean value );
Parameters
value
Topic under construction.
Description

Indicates if the control wraps the number it is incrementing or decrementing to the other end of the range.


 ViewEnum Class

ViewEnum Class

This Package | All Packages

Enum
  |
  +--ViewEnum
public class ViewEnum
extends Enum

Topic under construction.

Fields
Name | Description
LARGEICON | Topic under construction.
LIST | Topic under construction.
REPORT | Topic under construction.
SMALLICON | Topic under construction.

Fields

ViewEnum.LARGEICON

Syntax
public static final int LARGEICON;
Description
Topic under construction.

ViewEnum.LIST

Syntax
public static final int LIST;
Description
Topic under construction.

ViewEnum.REPORT

Syntax
public static final int REPORT;
Description
Topic under construction.

ViewEnum.SMALLICON

Syntax
public static final int SMALLICON;
Description
Topic under construction.


 VScrollBar Class

VScrollBar Class

This Package | All Packages

ScrollBar
  |
  +--VScrollBar
public class VScrollBar
extends ScrollBar

Topic under construction.

Constructors
Name | Description
VScrollBar() | Topic under construction.

Constructors

VScrollBar.VScrollBar

Syntax
public VScrollBar();
Description

Topic under construction.


 Java API

Java API Packages

  • package java.applet
  • package java.awt
  • package java.awt.datatransfer
  • package java.awt.event
  • package java.awt.image
  • package java.beans
  • package java.io
  • package java.lang
  • package java.lang.reflect
  • package java.math
  • package java.net
  • package java.security
  • package java.security.acl
  • package java.security.interfaces
  • package java.sql
  • package java.text
  • package java.util
  • package java.util.zip


 Package java.applet

Package java.applet

All Packages

Interfaces

  • AppletContext
  • AppletStub
  • AudioClip

    • Classes

  • Applet


 Class Applet

Class java.applet.Applet

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Panel
                           |
                           +----java.applet.Applet

public class Applet
extends Panel

An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application.

The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment.


 Applet Members

Applet Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Applet() |

Methods
Name | Description
destroy() | Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated.
getAppletContext() | Determines this applet's context, which allows the applet to query and affect the environment in which it runs.
getAppletInfo() | Returns information about this applet.
getAudioClip(URL) | Returns the AudioClip object specified by the URL argument.
getAudioClip(URL, String) | Returns the AudioClip object specified by the URL and name arguments.
getCodeBase() | Gets the base URL.
getDocumentBase() | Gets the document URL.
getImage(URL) | Returns an Image object that can then be painted on the screen.
getImage(URL, String) | Returns an Image object that can then be painted on the screen.
getLocale() | Gets the Locale for the applet, if it has been set.
getParameter(String) | Returns the value of the named parameter in the HTML tag.
getParameterInfo() | Returns information about the parameters than are understood by this applet.
init() | Called by the browser or applet viewer to inform this applet that it has been loaded into the system.
isActive() | Determines if this applet is active.
play(URL) | Plays the audio clip at the specified absolute URL.
play(URL, String) | Plays the audio clip given the URL and a specifier that is relative to it.
resize(Dimension) | Requests that this applet be resized.
resize(int, int) | Requests that this applet be resized.
setStub(AppletStub) | Sets this applet's stub.
showStatus(String) | Requests that the argument string be displayed in the "status window".
start() | Called by the browser or applet viewer to inform this applet that it should start its execution.
stop() | Called by the browser or applet viewer to inform this applet that it should stop its execution.


 Applet.Applet

Applet.Applet

Class Overview | Class Members | This Package | All Packages

Syntax
public Applet()


 Applet.destroy

Applet.destroy

Syntax
public void destroy()
Description
Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should destroy any resources that it has allocated. The stop method will always be called before destroy.

A subclass of Applet should override this method if it has any operation that it wants to perform before it is destroyed. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

The implementation of this method provided by the Applet class does nothing.

See Also
init, start, stop


 Applet.getAppletContext

Applet.getAppletContext

Syntax
public AppletContext getAppletContext()
Returns
the applet's context.
Description
Determines this applet's context, which allows the applet to query and affect the environment in which it runs.

This environment of an applet represents the document that contains the applet.


 Applet.getAppletInfo

Applet.getAppletInfo

Syntax
public String getAppletInfo()
Returns
a string containing information about the author, version, and copyright of the applet.
Description
Returns information about this applet. An applet should override this method to return a String containing information about the author, version, and copyright of the applet.

The implementation of this method provided by the Applet class returns null.


 Applet.getAudioClip

Applet.getAudioClip

Syntax 1
public AudioClip getAudioClip( URL url )
Parameters
url
an absolute URL giving the location of the audio clip.
Returns
the audio clip at the specified URL.
Description
Returns the AudioClip object specified by the URL argument.

This method always returns immediately, whether or not the audio clip exists. When this applet attempts to play the audio clip, the data will be loaded.

See Also
AudioClip

Syntax 2
public AudioClip getAudioClip( URL url, String name )
Parameters
url
an absolute URL giving the base location of the audio clip.
name
the location of the audio clip, relative to the url argument.
Returns
the audio clip at the specified URL.
Description
Returns the AudioClip object specified by the URL and name arguments.

This method always returns immediately, whether or not the audio clip exists. When this applet attempts to play the audio clip, the data will be loaded.

See Also
AudioClip


 Applet.getCodeBase

Applet.getCodeBase

Syntax
public URL getCodeBase()
Returns
the URL of this applet.
Description
Gets the base URL. This is the URL of the applet itself.

See Also
getDocumentBase


 Applet.getDocumentBase

Applet.getDocumentBase

Syntax
public URL getDocumentBase()
Returns
the URL of the document that contains this applet.
Description
Gets the document URL. This is the URL of the document in which the applet is embedded.

See Also
getCodeBase


 Applet.getImage

Applet.getImage

Syntax 1
public Image getImage( URL url )
Parameters
url
an absolute URL giving the location of the image.
Returns
the image at the specified URL.
Description
Returns an Image object that can then be painted on the screen. The url that is passed as an argument must specify an absolute URL.

This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.

See Also
Image

Syntax 2
public Image getImage( URL url, String name )
Parameters
url
an absolute URL giving the base location of the image.
name
the location of the image, relative to the url argument.
Returns
the image at the specified URL.
Description
Returns an Image object that can then be painted on the screen. The url argument must specify an absolute URL. The name argument is a specifier that is relative to the url argument.

This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.

See Also
Image


 Applet.getLocale

Applet.getLocale

Syntax
public Locale getLocale()
Returns
A Locale object.
Description
Gets the Locale for the applet, if it has been set. If no Locale has been set, then the default Locale is returned.

Overrides
getLocale in class Component


 Applet.getParameter

Applet.getParameter

Syntax
public String getParameter( String name )
Parameters
name
a parameter name.
Returns
the value of the named parameter.
Description
Returns the value of the named parameter in the HTML tag. For example, if this applet is specified as
    <applet code="Clock" width=50 height=50>
    <param name=Color value="blue">
    </applet>

then a call to getParameter("Color") returns the value "blue".

The name argument is case insensitive.


 Applet.getParameterInfo

Applet.getParameterInfo

Syntax
public String[][] getParameterInfo()
Returns
an array describing the parameters this applet looks for.
Description
Returns information about the parameters than are understood by this applet. An applet should override this method to return an array of Strings describing these parameters.

Each element of the array should be a set of three Strings containing the name, the type, and a description. For example:

 String pinfo[][] = {
     {"fps",    "1-10",    "frames per second"},
     {"repeat", "boolean", "repeat image loop"},
     {"imgs",   "url",     "images directory"}
 };

The implementation of this method provided by the Applet class returns null.


 Applet.init

Applet.init

Syntax
public void init()
Description
Called by the browser or applet viewer to inform this applet that it has been loaded into the system. It is always called before the first time that the start method is called.

A subclass of Applet should override this method if it has initialization to perform. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

The implementation of this method provided by the Applet class does nothing.

See Also
destroy, start, stop


 Applet.isActive

Applet.isActive

Syntax
public boolean isActive()
Returns
true if the applet is active; false otherwise.
Description
Determines if this applet is active. An applet is marked active just before its start method is called. It becomes inactive immediately after its stop method is called.

See Also
start, stop


 Applet.play

Applet.play

Syntax 1
public void play( URL url )
Parameters
url
an absolute URL giving the location of the audio clip.
Description
Plays the audio clip at the specified absolute URL. Nothing happens if the audio clip cannot be found.

Syntax 2
public void play( URL url, String name )
Parameters
url
an absolute URL giving the base location of the audio clip.
name
the location of the audio clip, relative to the url argument.
Description
Plays the audio clip given the URL and a specifier that is relative to it. Nothing happens if the audio clip cannot be found.


 Applet.resize

Applet.resize

Syntax 1
public void resize( int width, int height )
Parameters
width
the new requested width for the applet.
height
the new requested height for the applet.
Description
Requests that this applet be resized.

Overrides
resize in class Component

Syntax 2
public void resize( Dimension d )
Parameters
d
an object giving the new width and height.
Description
Requests that this applet be resized.

Overrides
resize in class Component


 Applet.setStub

Applet.setStub

Syntax
public final void setStub( AppletStub stub )
Parameters
stub
the new stub.
Description
Sets this applet's stub. This is done automatically by the system.


 Applet.showStatus

Applet.showStatus

Syntax
public void showStatus( String msg )
Parameters
msg
a string to display in the status window.
Description
Requests that the argument string be displayed in the "status window". Many browsers and applet viewers provide such a window, where the application can inform users of its current state.


 Applet.start

Applet.start

Syntax
public void start()
Description
Called by the browser or applet viewer to inform this applet that it should start its execution. It is called after the init method and each time the applet is revisited in a Web page.

A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is visited. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation.

The implementation of this method provided by the Applet class does nothing.

See Also
destroy, init, stop


 Applet.stop

Applet.stop

Syntax
public void stop()
Description
Called by the browser or applet viewer to inform this applet that it should stop its execution. It is called when the Web page that contains this applet has been replaced by another page, and also just before the applet is to be destroyed.

A subclass of Applet should override this method if it has any operation that it wants to perform each time the Web page containing it is no longer visible. For example, an applet with animation might want to use the start method to resume animation, and the stop method to suspend the animation.

The implementation of this method provided by the Applet class does nothing.

See Also
destroy, init


 Interface AppletContext

Interface java.applet.AppletContext

Interface Members | This Package | All Packages

public interface AppletContext

This interface corresponds to an applet's environment: the document containing the applet and the other applets in the same document.

The methods in this interface can be used by an applet to obtain information about its environment.


 AppletContext Members

AppletContext Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getApplet(String) | Finds and returns the applet in the document represented by this applet context with the given name.
getApplets() | Finds all the applets in the document represented by this applet context.
getAudioClip(URL) | Creates an audio clip.
getImage(URL) | Returns an Image object that can then be painted on the screen.
showDocument(URL) | Replaces the Web page currently being viewed with the given URL.
showDocument(URL, String) | Requests that the browser or applet viewer show the Web page indicated by the url argument.
showStatus(String) | Requests that the argument string be displayed in the "status window".


 AppletContext.getApplet

AppletContext.getApplet

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Applet getApplet( String name )
Parameters
name
an applet name.
Returns
the applet with the given name, or null if not found.
Description
Finds and returns the applet in the document represented by this applet context with the given name. The name can be set in the HTML tag by setting the name attribute.


 AppletContext.getApplets

AppletContext.getApplets

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Enumeration getApplets()
Returns
an enumeration of all applets in the document represented by this applet context.
Description
Finds all the applets in the document represented by this applet context.


 AppletContext.getAudioClip

AppletContext.getAudioClip

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract AudioClip getAudioClip( URL url )
Parameters
url
an absolute URL giving the location of the audio clip.
Returns
the audio clip at the specified URL.
Description
Creates an audio clip.


 AppletContext.getImage

AppletContext.getImage

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Image getImage( URL url )
Parameters
url
an absolute URL giving the location of the image.
Returns
the image at the specified URL.
Description
Returns an Image object that can then be painted on the screen. The url argument that is passed as an argument must specify an absolute URL.

This method always returns immediately, whether or not the image exists. When the applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.

See Also
Image


 AppletContext.showDocument

AppletContext.showDocument

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void showDocument( URL url )
Parameters
url
an absolute URL giving the location of the document.
Description
Replaces the Web page currently being viewed with the given URL. This method may be ignored by applet contexts that are not browsers.

Syntax 2
public abstract void showDocument( URL url, String target )
Parameters
url
an absolute URL giving the location of the document.
target
a String indicating where to display the page.
Description
Requests that the browser or applet viewer show the Web page indicated by the url argument. The target argument indicates where to display the frame. The target argument is interpreted as follows:

"_self" | show in the current frame
"_parent" | show in the parent frame
"_top" | show in the topmost frame
"_blank" | show in a new unnamed top-level window
name | show in a new top-level window named name

An applet viewer or browser is free to ignore showDocument.


 AppletContext.showStatus

AppletContext.showStatus

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void showStatus( String status )
Parameters
status
a string to display in the status window.
Description
Requests that the argument string be displayed in the "status window". Many browsers and applet viewers provide such a window, where the application can inform users of its current state.


 Interface AppletStub

Interface java.applet.AppletStub

Interface Members | This Package | All Packages

public interface AppletStub

When an applet is first created, an applet stub is attached to it using the applet's setStub method. This stub serves as the interface between the applet and the browser environment or applet viewer environment in which the application is running.

See Also:
setStub


 AppletStub Members

AppletStub Members

Interface Overview | This Package | All Packages

Methods
Name | Description
appletResize(int, int) | Called when the applet wants to be resized.
getAppletContext() | Gets a handler to the applet's context.
getCodeBase() | Gets the base URL.
getDocumentBase() | Gets the document URL.
getParameter(String) | Returns the value of the named parameter in the HTML tag.
isActive() | Determines if the applet is active.


 AppletStub.appletResize

AppletStub.appletResize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void appletResize( int width, int height )
Parameters
width
the new requested width for the applet.
height
the new requested height for the applet.
Description
Called when the applet wants to be resized.


 AppletStub.getAppletContext

AppletStub.getAppletContext

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract AppletContext getAppletContext()
Returns
the applet's context.
Description
Gets a handler to the applet's context.


 AppletStub.getCodeBase

AppletStub.getCodeBase

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract URL getCodeBase()
Returns
the URL of the applet.
Description
Gets the base URL.


 AppletStub.getDocumentBase

AppletStub.getDocumentBase

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract URL getDocumentBase()
Returns
the URL of the document containing the applet.
Description
Gets the document URL.


 AppletStub.getParameter

AppletStub.getParameter

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getParameter( String name )
Parameters
name
a parameter name.
Returns
the value of the named parameter.
Description
Returns the value of the named parameter in the HTML tag. For example, if an applet is specified as
    <applet code="Clock" width=50 height=50>
    <param name=Color value="blue">
    </applet>

then a call to getParameter("Color") returns the value "blue".


 AppletStub.isActive

AppletStub.isActive

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isActive()
Returns
true if the applet is active; false otherwise.
Description
Determines if the applet is active. An applet is active just before its start method is called. It becomes inactive immediately after its stop method is called.


 Interface AudioClip

Interface java.applet.AudioClip

Interface Members | This Package | All Packages

public interface AudioClip

The AudioClip interface is a simple abstraction for playing a sound clip. Multiple AudioClip items can be playing at the same time, and the resulting sound is mixed together to produce a composite.


 AudioClip Members

AudioClip Members

Interface Overview | This Package | All Packages

Methods
Name | Description
loop() | Starts playing this audio clip in a loop.
play() | Starts playing this audio clip.
stop() | Stops playing this audio clip.


 AudioClip.loop

AudioClip.loop

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void loop()
Description
Starts playing this audio clip in a loop.


 AudioClip.play

AudioClip.play

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void play()
Description
Starts playing this audio clip. Each time this method is called, the clip is restarted from the beginning.


 AudioClip.stop

AudioClip.stop

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void stop()
Description
Stops playing this audio clip.


 Package java.awt

Package java.awt

All Packages

Interfaces

  • Adjustable
  • ItemSelectable
  • LayoutManager
  • LayoutManager2
  • MenuContainer
  • PrintGraphics
  • Shape

    • Classes

  • AWTEvent
  • AWTEventMulticaster
  • BorderLayout
  • Button
  • Canvas
  • CardLayout
  • Checkbox
  • CheckboxGroup
  • CheckboxMenuItem
  • Choice
  • Color
  • Component
  • Container
  • Cursor
  • Dialog
  • Dimension
  • Event
  • EventQueue
  • FileDialog
  • FlowLayout
  • Font
  • FontMetrics
  • Frame
  • Graphics
  • GridBagConstraints
  • GridBagLayout
  • GridLayout
  • Image
  • Insets
  • Label
  • List
  • MediaTracker
  • Menu
  • MenuBar
  • MenuComponent
  • MenuItem
  • MenuShortcut
  • Panel
  • Point
  • Polygon
  • PopupMenu
  • PrintJob
  • Rectangle
  • ScrollPane
  • Scrollbar
  • SystemColor
  • TextArea
  • TextComponent
  • TextField
  • Toolkit
  • Window

    • Exceptions

  • AWTException
  • IllegalComponentStateException

    • Errors

  • AWTError


 Class AWTError

Class java.awt.AWTError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.awt.AWTError

public class AWTError
extends Error

Thrown when a serious Abstract Window Toolkit error has occurred.


 AWTError Members

AWTError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
AWTError(String) | Constructs an instance of AWTError with the specified detail message.


 AWTError.AWTError

AWTError.AWTError

Syntax
public AWTError( String msg )
Parameters
msg
the detail message.
Description
Constructs an instance of AWTError with the specified detail message.


 Class AWTEvent

Class java.awt.AWTEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent

public abstract class AWTEvent
extends EventObject

The root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class. Subclasses of this root AWTEvent class defined outside of the java.awt.event package should define event ID values greater than the value defined by RESERVED_ID_MAX. The event masks defined in this class are needed ONLY by component subclasses which are using Component.enableEvents() to select for event types not selected by registered listeners. If a listener is registered on a component, the appropriate event mask is already set internally by the component.

See Also:
enableEvents, ComponentEvent, FocusEvent, KeyEvent, MouseEvent, WindowEvent, ActionEvent, AdjustmentEvent, ItemEvent, TextEvent


 AWTEvent Members

AWTEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
ACTION_EVENT_MASK | The event mask for selecting action events.
ADJUSTMENT_EVENT_MASK | The event mask for selecting adjustment events.
COMPONENT_EVENT_MASK | The event mask for selecting component events.
consumed |
CONTAINER_EVENT_MASK | The event mask for selecting container events.
FOCUS_EVENT_MASK | The event mask for selecting focus events.
id |
ITEM_EVENT_MASK | The event mask for selecting item events.
KEY_EVENT_MASK | The event mask for selecting key events.
MOUSE_EVENT_MASK | The event mask for selecting mouse events.
MOUSE_MOTION_EVENT_MASK | The event mask for selecting mouse motion events.
RESERVED_ID_MAX | The maximum value for reserved AWT event IDs.
TEXT_EVENT_MASK | The event mask for selecting text events.
WINDOW_EVENT_MASK | The event mask for selecting window events.

Constructors
Name | Description
AWTEvent(Event) | Constructs an AWTEvent object from the parameters of a 1.0-style event.
AWTEvent(Object, int) | Constructs an AWTEvent object with the specified source object and type.

Methods
Name | Description
consume() |
getID() | Returns the event type.
isConsumed() |
paramString() |
toString() | Returns a string representation of the object.


 AWTEvent.ACTION_EVENT_MASK

AWTEvent.ACTION_EVENT_MASK

Syntax
public static final long ACTION_EVENT_MASK
Description
The event mask for selecting action events.


 AWTEvent.ADJUSTMENT_EVENT_MASK

AWTEvent.ADJUSTMENT_EVENT_MASK

Syntax
public static final long ADJUSTMENT_EVENT_MASK
Description
The event mask for selecting adjustment events.


 AWTEvent.COMPONENT_EVENT_MASK

AWTEvent.COMPONENT_EVENT_MASK

Syntax
public static final long COMPONENT_EVENT_MASK
Description
The event mask for selecting component events.


 AWTEvent.consumed

AWTEvent.consumed

Syntax
protected boolean consumed


 AWTEvent.CONTAINER_EVENT_MASK

AWTEvent.CONTAINER_EVENT_MASK

Syntax
public static final long CONTAINER_EVENT_MASK
Description
The event mask for selecting container events.


 AWTEvent.FOCUS_EVENT_MASK

AWTEvent.FOCUS_EVENT_MASK

Syntax
public static final long FOCUS_EVENT_MASK
Description
The event mask for selecting focus events.


 AWTEvent.id

AWTEvent.id

Syntax
protected int id


 AWTEvent.ITEM_EVENT_MASK

AWTEvent.ITEM_EVENT_MASK

Syntax
public static final long ITEM_EVENT_MASK
Description
The event mask for selecting item events.


 AWTEvent.KEY_EVENT_MASK

AWTEvent.KEY_EVENT_MASK

Syntax
public static final long KEY_EVENT_MASK
Description
The event mask for selecting key events.


 AWTEvent.MOUSE_EVENT_MASK

AWTEvent.MOUSE_EVENT_MASK

Syntax
public static final long MOUSE_EVENT_MASK
Description
The event mask for selecting mouse events.


 AWTEvent.MOUSE_MOTION_EVENT_MASK

AWTEvent.MOUSE_MOTION_EVENT_MASK

Syntax
public static final long MOUSE_MOTION_EVENT_MASK
Description
The event mask for selecting mouse motion events.


 AWTEvent.RESERVED_ID_MAX

AWTEvent.RESERVED_ID_MAX

Syntax
public static final int RESERVED_ID_MAX
Description
The maximum value for reserved AWT event IDs. Programs defining their own event IDs should use IDs greater than this value.


 AWTEvent.TEXT_EVENT_MASK

AWTEvent.TEXT_EVENT_MASK

Syntax
public static final long TEXT_EVENT_MASK
Description
The event mask for selecting text events.


 AWTEvent.WINDOW_EVENT_MASK

AWTEvent.WINDOW_EVENT_MASK

Syntax
public static final long WINDOW_EVENT_MASK
Description
The event mask for selecting window events.


 AWTEvent.AWTEvent

AWTEvent.AWTEvent

Syntax 1
public AWTEvent( Event event )
Parameters
event
the old-style event
Description
Constructs an AWTEvent object from the parameters of a 1.0-style event.

Syntax 2
public AWTEvent( Object source, int id )
Parameters
source
the object where the event originated
Description
Constructs an AWTEvent object with the specified source object and type.


 AWTEvent.consume

AWTEvent.consume

Syntax
protected void consume()


 AWTEvent.getID

AWTEvent.getID

Syntax
public int getID()
Description
Returns the event type.


 AWTEvent.isConsumed

AWTEvent.isConsumed

Syntax
protected boolean isConsumed()


 AWTEvent.paramString

AWTEvent.paramString

Syntax
public String paramString()


 AWTEvent.toString

AWTEvent.toString

Syntax
public String toString()
Description
Returns a string representation of the object.

Overrides
toString in class EventObject


 Class AWTEventMulticaster

Class java.awt.AWTEventMulticaster

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.AWTEventMulticaster

public class AWTEventMulticaster
extends Object
implements ComponentListener, ContainerListener, FocusListener, KeyListener, MouseListener, MouseMotionListener, WindowListener, ActionListener, ItemListener, AdjustmentListener, TextListener

A class which implements efficient and thread-safe multi-cast event dispatching for the AWT events defined in the java.awt.event package. This class will manage an immutable structure consisting of a chain of event listeners and will dispatch events to those listeners. Because the structure is immutable, it is safe to use this API to add/remove listeners during the process of an event dispatch operation. An example of how this class could be used to implement a new component which fires "action" events:

 public myComponent extends Component {
     ActionListener actionListener = null;
     public void addActionListener(ActionListener l) {
       actionListener = AWTEventMulticaster.add(actionListener, l);
     }
     public void removeActionListener(ActionListener l) {
         actionListener = AWTEventMulticaster.remove(actionListener, l);
     }
     public void processEvent(AWTEvent e) {
         // when event occurs which causes "action" semantic
         if (actionListener != null) {
             actionListener.actionPerformed(new ActionEvent());
         }
 }


 AWTEventMulticaster Members

AWTEventMulticaster Members

Class Overview | This Package | All Packages

Fields
Name | Description
a |
b |

Constructors
Name | Description
AWTEventMulticaster(EventListener, EventListener) | Creates an event multicaster instance which chains listener-a with listener-b.

Methods
Name | Description
actionPerformed(ActionEvent) | Handles the actionPerformed event by invoking the actionPerformed methods on listener-a and listener-b.
add(ActionListener, ActionListener) | Adds action-listener-a with action-listener-b and returns the resulting multicast listener.
add(AdjustmentListener, AdjustmentListener) | Adds adjustment-listener-a with adjustment-listener-b and returns the resulting multicast listener.
add(ComponentListener, ComponentListener) | Adds component-listener-a with component-listener-b and returns the resulting multicast listener.
add(ContainerListener, ContainerListener) | Adds container-listener-a with container-listener-b and returns the resulting multicast listener.
add(FocusListener, FocusListener) | Adds focus-listener-a with focus-listener-b and returns the resulting multicast listener.
add(ItemListener, ItemListener) | Adds item-listener-a with item-listener-b and returns the resulting multicast listener.
add(KeyListener, KeyListener) | Adds key-listener-a with key-listener-b and returns the resulting multicast listener.
add(MouseListener, MouseListener) | Adds mouse-listener-a with mouse-listener-b and returns the resulting multicast listener.
add(MouseMotionListener, MouseMotionListener) | Adds mouse-motion-listener-a with mouse-motion-listener-b and returns the resulting multicast listener.
add(TextListener, TextListener) |
add(WindowListener, WindowListener) | Adds window-listener-a with window-listener-b and returns the resulting multicast listener.
addInternal(EventListener, EventListener) | Returns the resulting multicast listener from adding listener-a and listener-b together.
adjustmentValueChanged(AdjustmentEvent) | Handles the adjustmentValueChanged event by invoking the adjustmentValueChanged methods on listener-a and listener-b.
componentAdded(ContainerEvent) | Handles the componentAdded container event by invoking the componentAdded methods on listener-a and listener-b.
componentHidden(ComponentEvent) | Handles the componentHidden event by invoking the componentHidden methods on listener-a and listener-b.
componentMoved(ComponentEvent) | Handles the componentMoved event by invoking the componentMoved methods on listener-a and listener-b.
componentRemoved(ContainerEvent) | Handles the componentRemoved container event by invoking the componentRemoved methods on listener-a and listener-b.
componentResized(ComponentEvent) | Handles the componentResized event by invoking the componentResized methods on listener-a and listener-b.
componentShown(ComponentEvent) | Handles the componentShown event by invoking the componentShown methods on listener-a and listener-b.
focusGained(FocusEvent) | Handles the focusGained event by invoking the focusGained methods on listener-a and listener-b.
focusLost(FocusEvent) | Handles the focusLost event by invoking the focusLost methods on listener-a and listener-b.
itemStateChanged(ItemEvent) | Handles the itemStateChanged event by invoking the itemStateChanged methods on listener-a and listener-b.
keyPressed(KeyEvent) | Handles the keyPressed event by invoking the keyPressed methods on listener-a and listener-b.
keyReleased(KeyEvent) | Handles the keyReleased event by invoking the keyReleased methods on listener-a and listener-b.
keyTyped(KeyEvent) | Handles the keyTyped event by invoking the keyTyped methods on listener-a and listener-b.
mouseClicked(MouseEvent) | Handles the mouseClicked event by invoking the mouseClicked methods on listener-a and listener-b.
mouseDragged(MouseEvent) | Handles the mouseDragged event by invoking the mouseDragged methods on listener-a and listener-b.
mouseEntered(MouseEvent) | Handles the mouseEntered event by invoking the mouseEntered methods on listener-a and listener-b.
mouseExited(MouseEvent) | Handles the mouseExited event by invoking the mouseExited methods on listener-a and listener-b.
mouseMoved(MouseEvent) | Handles the mouseMoved event by invoking the mouseMoved methods on listener-a and listener-b.
mousePressed(MouseEvent) | Handles the mousePressed event by invoking the mousePressed methods on listener-a and listener-b.
mouseReleased(MouseEvent) | Handles the mouseReleased event by invoking the mouseReleased methods on listener-a and listener-b.
remove(ActionListener, ActionListener) | Removes the old action-listener from action-listener-l and returns the resulting multicast listener.
remove(AdjustmentListener, AdjustmentListener) | Removes the old adjustment-listener from adjustment-listener-l and returns the resulting multicast listener.
remove(ComponentListener, ComponentListener) | Removes the old component-listener from component-listener-l and returns the resulting multicast listener.
remove(ContainerListener, ContainerListener) | Removes the old container-listener from container-listener-l and returns the resulting multicast listener.
remove(EventListener) | Removes a listener from this multicaster and returns the resulting multicast listener.
remove(FocusListener, FocusListener) | Removes the old focus-listener from focus-listener-l and returns the resulting multicast listener.
remove(ItemListener, ItemListener) | Removes the old item-listener from item-listener-l and returns the resulting multicast listener.
remove(KeyListener, KeyListener) | Removes the old key-listener from key-listener-l and returns the resulting multicast listener.
remove(MouseListener, MouseListener) | Removes the old mouse-listener from mouse-listener-l and returns the resulting multicast listener.
remove(MouseMotionListener, MouseMotionListener) | Removes the old mouse-motion-listener from mouse-motion-listener-l and returns the resulting multicast listener.
remove(TextListener, TextListener) |
remove(WindowListener, WindowListener) | Removes the old window-listener from window-listener-l and returns the resulting multicast listener.
removeInternal(EventListener, EventListener) | Returns the resulting multicast listener after removing the old listener from listener-l.
save(ObjectOutputStream, String, EventListener) |
saveInternal(ObjectOutputStream, String) |
textValueChanged(TextEvent) |
windowActivated(WindowEvent) | Handles the windowActivated event by invoking the windowActivated methods on listener-a and listener-b.
windowClosed(WindowEvent) | Handles the windowClosed event by invoking the windowClosed methods on listener-a and listener-b.
windowClosing(WindowEvent) | Handles the windowClosing event by invoking the windowClosing methods on listener-a and listener-b.
windowDeactivated(WindowEvent) | Handles the windowDeactivated event by invoking the windowDeactivated methods on listener-a and listener-b.
windowDeiconified(WindowEvent) | Handles the windowDeiconfied event by invoking the windowDeiconified methods on listener-a and listener-b.
windowIconified(WindowEvent) | Handles the windowIconified event by invoking the windowIconified methods on listener-a and listener-b.
windowOpened(WindowEvent) | Handles the windowOpened event by invoking the windowOpened methods on listener-a and listener-b.


 AWTEventMulticaster.a

AWTEventMulticaster.a

Syntax
protected final EventListener a


 AWTEventMulticaster.b

AWTEventMulticaster.b

Syntax
protected final EventListener b


 AWTEventMulticaster.AWTEventMulticaster

AWTEventMulticaster.AWTEventMulticaster

Syntax
protected AWTEventMulticaster( EventListener a, EventListener b )
Parameters
a
listener-a
b
listener-b
Description
Creates an event multicaster instance which chains listener-a with listener-b.


 AWTEventMulticaster.actionPerformed

AWTEventMulticaster.actionPerformed

Syntax
public void actionPerformed( ActionEvent e )
Parameters
e
the action event
Description
Handles the actionPerformed event by invoking the actionPerformed methods on listener-a and listener-b.


 AWTEventMulticaster.add

AWTEventMulticaster.add

Syntax 1
public static ComponentListener add( ComponentListener a, ComponentListener b )
Parameters
a
component-listener-a
b
component-listener-b
Description
Adds component-listener-a with component-listener-b and returns the resulting multicast listener.

Syntax 2
public static ContainerListener add( ContainerListener a, ContainerListener b )
Parameters
a
container-listener-a
b
container-listener-b
Description
Adds container-listener-a with container-listener-b and returns the resulting multicast listener.

Syntax 3
public static FocusListener add( FocusListener a, FocusListener b )
Parameters
a
focus-listener-a
b
focus-listener-b
Description
Adds focus-listener-a with focus-listener-b and returns the resulting multicast listener.

Syntax 4
public static KeyListener add( KeyListener a, KeyListener b )
Parameters
a
key-listener-a
b
key-listener-b
Description
Adds key-listener-a with key-listener-b and returns the resulting multicast listener.

Syntax 5
public static MouseListener add( MouseListener a, MouseListener b )
Parameters
a
mouse-listener-a
b
mouse-listener-b
Description
Adds mouse-listener-a with mouse-listener-b and returns the resulting multicast listener.

Syntax 6
public static MouseMotionListener add( MouseMotionListener a, MouseMotionListener b )
Parameters
a
mouse-motion-listener-a
b
mouse-motion-listener-b
Description
Adds mouse-motion-listener-a with mouse-motion-listener-b and returns the resulting multicast listener.

Syntax 7
public static WindowListener add( WindowListener a, WindowListener b )
Parameters
a
window-listener-a
b
window-listener-b
Description
Adds window-listener-a with window-listener-b and returns the resulting multicast listener.

Syntax 8
public static ActionListener add( ActionListener a, ActionListener b )
Parameters
a
action-listener-a
b
action-listener-b
Description
Adds action-listener-a with action-listener-b and returns the resulting multicast listener.

Syntax 9
public static ItemListener add( ItemListener a, ItemListener b )
Parameters
a
item-listener-a
b
item-listener-b
Description
Adds item-listener-a with item-listener-b and returns the resulting multicast listener.

Syntax 10
public static AdjustmentListener add( AdjustmentListener a, AdjustmentListener b )
Parameters
a
adjustment-listener-a
b
adjustment-listener-b
Description
Adds adjustment-listener-a with adjustment-listener-b and returns the resulting multicast listener.

Syntax 11
public static TextListener add( TextListener a, TextListener b )


 AWTEventMulticaster.addInternal

AWTEventMulticaster.addInternal

Syntax
protected static EventListener addInternal( EventListener a, EventListener b )
Parameters
a
event listener-a
b
event listener-b
Description
Returns the resulting multicast listener from adding listener-a and listener-b together. If listener-a is null, it returns listener-b; If listener-b is null, it returns listener-a If neither are null, then it creates and returns a new AWTEventMulticaster instance which chains a with b.


 AWTEventMulticaster.adjustmentValueChanged

AWTEventMulticaster.adjustmentValueChanged

Syntax
public void adjustmentValueChanged( AdjustmentEvent e )
Parameters
e
the adjustment event
Description
Handles the adjustmentValueChanged event by invoking the adjustmentValueChanged methods on listener-a and listener-b.


 AWTEventMulticaster.componentAdded

AWTEventMulticaster.componentAdded

Syntax
public void componentAdded( ContainerEvent e )
Parameters
e
the component event
Description
Handles the componentAdded container event by invoking the componentAdded methods on listener-a and listener-b.


 AWTEventMulticaster.componentHidden

AWTEventMulticaster.componentHidden

Syntax
public void componentHidden( ComponentEvent e )
Parameters
e
the component event
Description
Handles the componentHidden event by invoking the componentHidden methods on listener-a and listener-b.


 AWTEventMulticaster.componentMoved

AWTEventMulticaster.componentMoved

Syntax
public void componentMoved( ComponentEvent e )
Parameters
e
the component event
Description
Handles the componentMoved event by invoking the componentMoved methods on listener-a and listener-b.


 AWTEventMulticaster.componentRemoved

AWTEventMulticaster.componentRemoved

Syntax
public void componentRemoved( ContainerEvent e )
Parameters
e
the component event
Description
Handles the componentRemoved container event by invoking the componentRemoved methods on listener-a and listener-b.


 AWTEventMulticaster.componentResized

AWTEventMulticaster.componentResized

Syntax
public void componentResized( ComponentEvent e )
Parameters
e
the component event
Description
Handles the componentResized event by invoking the componentResized methods on listener-a and listener-b.


 AWTEventMulticaster.componentShown

AWTEventMulticaster.componentShown

Syntax
public void componentShown( ComponentEvent e )
Parameters
e
the component event
Description
Handles the componentShown event by invoking the componentShown methods on listener-a and listener-b.


 AWTEventMulticaster.focusGained

AWTEventMulticaster.focusGained

Syntax
public void focusGained( FocusEvent e )
Parameters
e
the focus event
Description
Handles the focusGained event by invoking the focusGained methods on listener-a and listener-b.


 AWTEventMulticaster.focusLost

AWTEventMulticaster.focusLost

Syntax
public void focusLost( FocusEvent e )
Parameters
e
the focus event
Description
Handles the focusLost event by invoking the focusLost methods on listener-a and listener-b.


 AWTEventMulticaster.itemStateChanged

AWTEventMulticaster.itemStateChanged

Syntax
public void itemStateChanged( ItemEvent e )
Parameters
e
the item event
Description
Handles the itemStateChanged event by invoking the itemStateChanged methods on listener-a and listener-b.


 AWTEventMulticaster.keyPressed

AWTEventMulticaster.keyPressed

Syntax
public void keyPressed( KeyEvent e )
Parameters
e
the key event
Description
Handles the keyPressed event by invoking the keyPressed methods on listener-a and listener-b.


 AWTEventMulticaster.keyReleased

AWTEventMulticaster.keyReleased

Syntax
public void keyReleased( KeyEvent e )
Parameters
e
the key event
Description
Handles the keyReleased event by invoking the keyReleased methods on listener-a and listener-b.


 AWTEventMulticaster.keyTyped

AWTEventMulticaster.keyTyped

Syntax
public void keyTyped( KeyEvent e )
Parameters
e
the key event
Description
Handles the keyTyped event by invoking the keyTyped methods on listener-a and listener-b.


 AWTEventMulticaster.mouseClicked

AWTEventMulticaster.mouseClicked

Syntax
public void mouseClicked( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseClicked event by invoking the mouseClicked methods on listener-a and listener-b.


 AWTEventMulticaster.mouseDragged

AWTEventMulticaster.mouseDragged

Syntax
public void mouseDragged( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseDragged event by invoking the mouseDragged methods on listener-a and listener-b.


 AWTEventMulticaster.mouseEntered

AWTEventMulticaster.mouseEntered

Syntax
public void mouseEntered( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseEntered event by invoking the mouseEntered methods on listener-a and listener-b.


 AWTEventMulticaster.mouseExited

AWTEventMulticaster.mouseExited

Syntax
public void mouseExited( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseExited event by invoking the mouseExited methods on listener-a and listener-b.


 AWTEventMulticaster.mouseMoved

AWTEventMulticaster.mouseMoved

Syntax
public void mouseMoved( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseMoved event by invoking the mouseMoved methods on listener-a and listener-b.


 AWTEventMulticaster.mousePressed

AWTEventMulticaster.mousePressed

Syntax
public void mousePressed( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mousePressed event by invoking the mousePressed methods on listener-a and listener-b.


 AWTEventMulticaster.mouseReleased

AWTEventMulticaster.mouseReleased

Syntax
public void mouseReleased( MouseEvent e )
Parameters
e
the mouse event
Description
Handles the mouseReleased event by invoking the mouseReleased methods on listener-a and listener-b.


 AWTEventMulticaster.remove

AWTEventMulticaster.remove

Syntax
protected EventListener remove( EventListener oldl )
Parameters
oldl
the listener to be removed
Description
Removes a listener from this multicaster and returns the resulting multicast listener.


 AWTEventMulticaster.remove

AWTEventMulticaster.remove

Syntax 1
public static ComponentListener remove( ComponentListener l, ComponentListener oldl )
Parameters
l
component-listener-l
oldl
the component-listener being removed
Description
Removes the old component-listener from component-listener-l and returns the resulting multicast listener.

Syntax 2
public static ContainerListener remove( ContainerListener l, ContainerListener oldl )
Parameters
l
container-listener-l
oldl
the container-listener being removed
Description
Removes the old container-listener from container-listener-l and returns the resulting multicast listener.

Syntax 3
public static FocusListener remove( FocusListener l, FocusListener oldl )
Parameters
l
focus-listener-l
oldl
the focus-listener being removed
Description
Removes the old focus-listener from focus-listener-l and returns the resulting multicast listener.

Syntax 4
public static KeyListener remove( KeyListener l, KeyListener oldl )
Parameters
l
key-listener-l
oldl
the key-listener being removed
Description
Removes the old key-listener from key-listener-l and returns the resulting multicast listener.

Syntax 5
public static MouseListener remove( MouseListener l, MouseListener oldl )
Parameters
l
mouse-listener-l
oldl
the mouse-listener being removed
Description
Removes the old mouse-listener from mouse-listener-l and returns the resulting multicast listener.

Syntax 6
public static MouseMotionListener remove( MouseMotionListener l, MouseMotionListener oldl )
Parameters
l
mouse-motion-listener-l
oldl
the mouse-motion-listener being removed
Description
Removes the old mouse-motion-listener from mouse-motion-listener-l and returns the resulting multicast listener.

Syntax 7
public static WindowListener remove( WindowListener l, WindowListener oldl )
Parameters
l
window-listener-l
oldl
the window-listener being removed
Description
Removes the old window-listener from window-listener-l and returns the resulting multicast listener.

Syntax 8
public static ActionListener remove( ActionListener l, ActionListener oldl )
Parameters
l
action-listener-l
oldl
the action-listener being removed
Description
Removes the old action-listener from action-listener-l and returns the resulting multicast listener.

Syntax 9
public static ItemListener remove( ItemListener l, ItemListener oldl )
Parameters
l
item-listener-l
oldl
the item-listener being removed
Description
Removes the old item-listener from item-listener-l and returns the resulting multicast listener.

Syntax 10
public static AdjustmentListener remove( AdjustmentListener l, AdjustmentListener oldl )
Parameters
l
adjustment-listener-l
oldl
the adjustment-listener being removed
Description
Removes the old adjustment-listener from adjustment-listener-l and returns the resulting multicast listener.

Syntax 11
public static TextListener remove( TextListener l, TextListener oldl )


 AWTEventMulticaster.removeInternal

AWTEventMulticaster.removeInternal

Syntax
protected static EventListener removeInternal( EventListener l, EventListener oldl )
Parameters
l
the listener being removed from
oldl
the listener being removed
Description
Returns the resulting multicast listener after removing the old listener from listener-l. If listener-l equals the old listener OR listener-l is null, returns null. Else if listener-l is an instance of AWTEventMulticaster, then it removes the old listener from it. Else, returns listener l.


 AWTEventMulticaster.save

AWTEventMulticaster.save

Syntax
protected static void save( ObjectOutputStream s, String k, EventListener l ) throws IOException


 AWTEventMulticaster.saveInternal

AWTEventMulticaster.saveInternal

Syntax
protected void saveInternal( ObjectOutputStream s, String k ) throws IOException


 AWTEventMulticaster.textValueChanged

AWTEventMulticaster.textValueChanged

Syntax
public void textValueChanged( TextEvent e )


 AWTEventMulticaster.windowActivated

AWTEventMulticaster.windowActivated

Syntax
public void windowActivated( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowActivated event by invoking the windowActivated methods on listener-a and listener-b.


 AWTEventMulticaster.windowClosed

AWTEventMulticaster.windowClosed

Syntax
public void windowClosed( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowClosed event by invoking the windowClosed methods on listener-a and listener-b.


 AWTEventMulticaster.windowClosing

AWTEventMulticaster.windowClosing

Syntax
public void windowClosing( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowClosing event by invoking the windowClosing methods on listener-a and listener-b.


 AWTEventMulticaster.windowDeactivated

AWTEventMulticaster.windowDeactivated

Syntax
public void windowDeactivated( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowDeactivated event by invoking the windowDeactivated methods on listener-a and listener-b.


 AWTEventMulticaster.windowDeiconified

AWTEventMulticaster.windowDeiconified

Syntax
public void windowDeiconified( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowDeiconfied event by invoking the windowDeiconified methods on listener-a and listener-b.


 AWTEventMulticaster.windowIconified

AWTEventMulticaster.windowIconified

Syntax
public void windowIconified( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowIconified event by invoking the windowIconified methods on listener-a and listener-b.


 AWTEventMulticaster.windowOpened

AWTEventMulticaster.windowOpened

Syntax
public void windowOpened( WindowEvent e )
Parameters
e
the window event
Description
Handles the windowOpened event by invoking the windowOpened methods on listener-a and listener-b.


 Class AWTException

Class java.awt.AWTException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.awt.AWTException

public class AWTException
extends Exception

Signals that an Absract Window Toolkit exception has occurred.


 AWTException Members

AWTException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
AWTException(String) | Constructs an instance of AWTException with the specified detail message.


 AWTException.AWTException

AWTException.AWTException

Syntax
public AWTException( String msg )
Parameters
msg
the detail message
Description
Constructs an instance of AWTException with the specified detail message. A detail message is an instance of String that describes this particular exception.


 Interface Adjustable

Interface java.awt.Adjustable

Interface Members | This Package | All Packages

public interface Adjustable

The interface for objects which have an adjustable numeric value contained within a bounded range of values.


 Adjustable Members

Adjustable Members

Interface Overview | This Package | All Packages

Fields
Name | Description
HORIZONTAL | The horizontal orientation.
VERTICAL | The vertical orientation.

Methods
Name | Description
addAdjustmentListener(AdjustmentListener) | Add a listener to recieve adjustment events when the value of the adjustable object changes.
getBlockIncrement() | Gets the block value increment for the adjustable object.
getMaximum() | Gets the maximum value of the adjustable object.
getMinimum() | Gets the minimum value of the adjustable object.
getOrientation() | Gets the orientation of the adjustable object.
getUnitIncrement() | Gets the unit value increment for the adjustable object.
getValue() | Gets the current value of the adjustable object.
getVisibleAmount() | Gets the length of the propertional indicator.
removeAdjustmentListener(AdjustmentListener) | Removes an adjustment listener.
setBlockIncrement(int) | Sets the block value increment for the adjustable object.
setMaximum(int) | Sets the maximum value of the adjustable object.
setMinimum(int) | Sets the minimum value of the adjustable object.
setUnitIncrement(int) | Sets the unit value increment for the adjustable object.
setValue(int) | Sets the current value of the adjustable object.
setVisibleAmount(int) | Sets the length of the proportionl indicator of the adjustable object.


 Adjustable.HORIZONTAL

Adjustable.HORIZONTAL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int HORIZONTAL
Description
The horizontal orientation.


 Adjustable.VERTICAL

Adjustable.VERTICAL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int VERTICAL
Description
The vertical orientation.


 Adjustable.addAdjustmentListener

Adjustable.addAdjustmentListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addAdjustmentListener( AdjustmentListener l )
Parameters
l
the listener to recieve events
Description
Add a listener to recieve adjustment events when the value of the adjustable object changes.

See Also
AdjustmentEvent


 Adjustable.getBlockIncrement

Adjustable.getBlockIncrement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getBlockIncrement()
Description
Gets the block value increment for the adjustable object.


 Adjustable.getMaximum

Adjustable.getMaximum

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaximum()
Description
Gets the maximum value of the adjustable object.


 Adjustable.getMinimum

Adjustable.getMinimum

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMinimum()
Description
Gets the minimum value of the adjustable object.


 Adjustable.getOrientation

Adjustable.getOrientation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getOrientation()
Description
Gets the orientation of the adjustable object.


 Adjustable.getUnitIncrement

Adjustable.getUnitIncrement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getUnitIncrement()
Description
Gets the unit value increment for the adjustable object.


 Adjustable.getValue

Adjustable.getValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getValue()
Description
Gets the current value of the adjustable object.


 Adjustable.getVisibleAmount

Adjustable.getVisibleAmount

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getVisibleAmount()
Description
Gets the length of the propertional indicator.


 Adjustable.removeAdjustmentListener

Adjustable.removeAdjustmentListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removeAdjustmentListener( AdjustmentListener l )
Parameters
l
the listener being removed
Description
Removes an adjustment listener.

See Also
AdjustmentEvent


 Adjustable.setBlockIncrement

Adjustable.setBlockIncrement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setBlockIncrement( int b )
Parameters
b
the block increment
Description
Sets the block value increment for the adjustable object.


 Adjustable.setMaximum

Adjustable.setMaximum

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setMaximum( int max )
Parameters
max
the maximum value
Description
Sets the maximum value of the adjustable object.


 Adjustable.setMinimum

Adjustable.setMinimum

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setMinimum( int min )
Parameters
min
the minimum value
Description
Sets the minimum value of the adjustable object.


 Adjustable.setUnitIncrement

Adjustable.setUnitIncrement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setUnitIncrement( int u )
Parameters
u
the unit increment
Description
Sets the unit value increment for the adjustable object.


 Adjustable.setValue

Adjustable.setValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setValue( int v )
Parameters
v
the current value
Description
Sets the current value of the adjustable object. This value must be within the range defined by the minimum and maximum values for this object.


 Adjustable.setVisibleAmount

Adjustable.setVisibleAmount

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setVisibleAmount( int v )
Parameters
v
the length of the indicator
Description
Sets the length of the proportionl indicator of the adjustable object.


 Class BorderLayout

Class java.awt.BorderLayout

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.BorderLayout

public class BorderLayout
extends Object
implements LayoutManager2, Serializable

A border layout lays out a container, arranging and resizing its components to fit in five regions: North, South, East, West, and Center. When adding a component to a container with a border layout, use one of these five names, for example:

    Panel p = new Panel();
    p.setLayout(new BorderLayout());
    p.add(new Button("Okay"), "South");
As a convenience, BorderLayout interprets the absence of a string specification the same as "Center":
    Panel p2 = new Panel();
    p2.setLayout(new BorderLayout());
    p2.add(new TextArea());  // Same as p.add(new TextArea(), "Center");

The components are laid out according to their preferred sizes and the constraints of the container's size. The North and South components may be stretched horizontally; the East and West components may be stretched vertically; the Center component may stretch both horizontally and vertically to fill any space left over.

Here is an example of five buttons in an applet laid out using the BorderLayout layout manager:

The code for this applet is as follows:

 import java.awt.*;
 import java.applet.Applet;
 public class buttonDir extends Applet {
   public void init() {
     setLayout(new BorderLayout());
     add("North",  new Button("North"));
     add("South",  new Button("South"));
     add("East",   new Button("East"));
     add("West",   new Button("West"));
     add("Center", new Button("Center"));
   }
 }

See Also:
add


 BorderLayout Members

BorderLayout Members

Class Overview | This Package | All Packages

Fields
Name | Description
CENTER | The center layout constraint (middle of container).
EAST | The east layout constraint (left side of container).
NORTH | The north layout constraint (top of container).
SOUTH | The south layout constraint (bottom of container).
WEST | The west layout constraint (right side of container).

Constructors
Name | Description
BorderLayout() | Constructs a new border layout with no gaps between components.
BorderLayout(int, int) | Constructs a border layout with the specified gaps between components.

Methods
Name | Description
addLayoutComponent(Component, Object) | Adds the specified component to the layout, using the specified constraint object.
addLayoutComponent(String, Component) | Deprecated.
getHgap() | Returns the horizontal gap between components.
getLayoutAlignmentX(Container) | Returns the alignment along the x axis.
getLayoutAlignmentY(Container) | Returns the alignment along the y axis.
getVgap() | Returns the vertical gap between components.
invalidateLayout(Container) | Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
layoutContainer(Container) | Lays out the container argument using this border layout.
maximumLayoutSize(Container) | Returns the maximum dimensions for this layout given the components in the specified target container.
minimumLayoutSize(Container) | Determines the minimum size of the target container using this layout manager.
preferredLayoutSize(Container) | Determines the preferred size of the target container using this layout manager, based on the components in the container.
removeLayoutComponent(Component) | Removes the specified component from this border layout.
setHgap(int) | Sets the horizontal gap between components.
setVgap(int) | Sets the vertical gap between components.
toString() | Returns a string representation of the state of this border layout.


 BorderLayout.CENTER

BorderLayout.CENTER

Syntax
public static final String CENTER
Description
The center layout constraint (middle of container).


 BorderLayout.EAST

BorderLayout.EAST

Syntax
public static final String EAST
Description
The east layout constraint (left side of container).


 BorderLayout.NORTH

BorderLayout.NORTH

Syntax
public static final String NORTH
Description
The north layout constraint (top of container).


 BorderLayout.SOUTH

BorderLayout.SOUTH

Syntax
public static final String SOUTH
Description
The south layout constraint (bottom of container).


 BorderLayout.WEST

BorderLayout.WEST

Syntax
public static final String WEST
Description
The west layout constraint (right side of container).


 BorderLayout.BorderLayout

BorderLayout.BorderLayout

Syntax 1
public BorderLayout()
Description
Constructs a new border layout with no gaps between components.

Syntax 2
public BorderLayout( int hgap, int vgap )
Parameters
hgap
the horizontal gap.
vgap
the vertical gap.
Description
Constructs a border layout with the specified gaps between components. The horizontal gap is specified by hgap and the vertical gap is specified by vgap.


 BorderLayout.addLayoutComponent

BorderLayout.addLayoutComponent

Syntax 1
public void addLayoutComponent( Component comp, Object constraints )
Parameters
comp
the component to be added.
constraints
an object that specifies how and where the component is added to the layout.
Description
Adds the specified component to the layout, using the specified constraint object. For border layouts, the constraint must be one of the following strings: "North", "South", "East", "West", or "Center".

Most applications do not call this method directly. This method is called when a component is added to a container using the Container.add method with the same argument types.

Exceptions
IllegalArgumentException if the constraint object is not a string, or if it not one of the five specified strings.
See Also
add

Syntax 2
public void addLayoutComponent( String name, Component comp )
Description
Note: addLayoutComponent() is deprecated. replaced by addLayoutComponent(Component, Object).


 BorderLayout.getHgap

BorderLayout.getHgap

Syntax
public int getHgap()
Description
Returns the horizontal gap between components.


 BorderLayout.getLayoutAlignmentX

BorderLayout.getLayoutAlignmentX

Syntax
public float getLayoutAlignmentX( Container parent )
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 BorderLayout.getLayoutAlignmentY

BorderLayout.getLayoutAlignmentY

Syntax
public float getLayoutAlignmentY( Container parent )
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 BorderLayout.getVgap

BorderLayout.getVgap

Syntax
public int getVgap()
Description
Returns the vertical gap between components.


 BorderLayout.invalidateLayout

BorderLayout.invalidateLayout

Syntax
public void invalidateLayout( Container target )
Description
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.


 BorderLayout.layoutContainer

BorderLayout.layoutContainer

Syntax
public void layoutContainer( Container target )
Parameters
target
the container in which to do the layout.
Description
Lays out the container argument using this border layout.

This method actually reshapes the components in the specified container in order to satisfy the constraints of this BorderLayout object. The North and Southcomponents, if any, are placed at the top and bottom of the container, respectively. The West and East components are then placed on the left and right, respectively. Finally, the Center object is placed in any remaining space in the middle.

Most applications do not call this method directly. This method is called when a container calls its doLayout method.

See Also
Container, doLayout


 BorderLayout.maximumLayoutSize

BorderLayout.maximumLayoutSize

Syntax
public Dimension maximumLayoutSize( Container target )
Parameters
target
the component which needs to be laid out
Description
Returns the maximum dimensions for this layout given the components in the specified target container.

See Also
Container, minimumLayoutSize, preferredLayoutSize


 BorderLayout.minimumLayoutSize

BorderLayout.minimumLayoutSize

Syntax
public Dimension minimumLayoutSize( Container target )
Parameters
target
the container in which to do the layout.
Returns
the minimum dimensions needed to lay out the subcomponents of the specified container.
Description
Determines the minimum size of the target container using this layout manager.

This method is called when a container calls its getMinimumSize method. Most applications do not call this method directly.

See Also
Container, preferredLayoutSize, getMinimumSize


 BorderLayout.preferredLayoutSize

BorderLayout.preferredLayoutSize

Syntax
public Dimension preferredLayoutSize( Container target )
Parameters
target
the container in which to do the layout.
Returns
the preferred dimensions to lay out the subcomponents of the specified container.
Description
Determines the preferred size of the target container using this layout manager, based on the components in the container.

Most applications do not call this method directly. This method is called when a container calls its getPreferredSize method.

See Also
Container, minimumLayoutSize, getPreferredSize


 BorderLayout.removeLayoutComponent

BorderLayout.removeLayoutComponent

Syntax
public void removeLayoutComponent( Component comp )
Parameters
comp
the component to be removed.
Description
Removes the specified component from this border layout. This method is called when a container calls its remove or removeAll methods. Most applications do not call this method directly.

See Also
remove, removeAll


 BorderLayout.setHgap

BorderLayout.setHgap

Syntax
public void setHgap( int hgap )
Parameters
hgap
the horizontal gap between components
Description
Sets the horizontal gap between components.


 BorderLayout.setVgap

BorderLayout.setVgap

Syntax
public void setVgap( int vgap )
Parameters
vgap
the vertical gap between components
Description
Sets the vertical gap between components.


 BorderLayout.toString

BorderLayout.toString

Syntax
public String toString()
Returns
a string representation of this border layout.
Description
Returns a string representation of the state of this border layout.

Overrides
toString in class Object


 Class Button

Class java.awt.Button

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Button

public class Button
extends Component

This class creates a labeled button. The application can cause some action to happen when the button is pushed. This image depicts three views of a "Quit" button as it appears under the Solaris operating system:

The first view shows the button as it appears normally. The second view shows the button when it has input focus. Its outline is darkened to let the user know that it is an active object. The third view shows the button when the user clicks the mouse over the button, and thus requests that an action be performed.

The gesture of clicking on a button with the mouse is associated with one instance of ActionEvent, which is sent out when the mouse is both pressed and released over the button. If an application is interested in knowing when the button has been pressed but not released, as a separate gesture, it can specialize processMouseEvent, or it can register itself as a listener for mouse events by calling addMouseListener. Both of these methods are defined by Component, the abstract superclass of all components.

When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button's processEvent method receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button.

If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and register the new listener to receive events from this button, by calling the button's addActionListener method. The application can make use of the button's action command as a messaging protocol.

See Also:
ActionEvent, ActionListener, processMouseEvent, addMouseListener


 Button Members

Button Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Button() | Constructs a Button with no label.
Button(String) | Constructs a Button with the specified label.

Methods
Name | Description
addActionListener(ActionListener) | Adds the specified action listener to receive action events from this button.
addNotify() | Creates the peer of the button.
getActionCommand() | Returns the command name of the action event fired by this button.
getLabel() | Gets the label of this button.
paramString() | Returns the parameter string representing the state of this button.
processActionEvent(ActionEvent) | Processes action events occurring on this button by dispatching them to any registered ActionListener objects.
processEvent(AWTEvent) | Processes events on this button.
removeActionListener(ActionListener) | Removes the specified action listener so that it no longer receives action events from this button.
setActionCommand(String) | Sets the command name for the action event fired by this button.
setLabel(String) | Sets the button's label to be the specified string.


 Button.Button

Button.Button

Syntax 1
public Button()
Description
Constructs a Button with no label.

Syntax 2
public Button( String label )
Parameters
label
A string label for the button.
Description
Constructs a Button with the specified label.


 Button.addActionListener

Button.addActionListener

Syntax
public synchronized void addActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Adds the specified action listener to receive action events from this button. Action events occur when a user presses or releases the mouse over this button.

See Also
ActionListener, removeActionListener


 Button.addNotify

Button.addNotify

Syntax
public void addNotify()
Description
Creates the peer of the button. The button's peer allows the application to change the look of the button without changing its functionality.

Overrides
addNotify in class Component
See Also
createButton, getToolkit


 Button.getActionCommand

Button.getActionCommand

Syntax
public String getActionCommand()
Description
Returns the command name of the action event fired by this button.


 Button.getLabel

Button.getLabel

Syntax
public String getLabel()
Returns
the button's label, or null if the button has no label.
Description
Gets the label of this button.

See Also
setLabel


 Button.paramString

Button.paramString

Syntax
protected String paramString()
Returns
the parameter string of this button.
Description
Returns the parameter string representing the state of this button. This string is useful for debugging.

Overrides
paramString in class Component


 Button.processActionEvent

Button.processActionEvent

Syntax
protected void processActionEvent( ActionEvent e )
Parameters
e
the action event.
Description
Processes action events occurring on this button by dispatching them to any registered ActionListener objects.

This method is not called unless action events are enabled for this button. Action events are enabled when one of the following occurs:

  • An ActionListener object is registered via addActionListener.
  • Action events are enabled via enableEvents.

See Also
ActionListener, addActionListener, enableEvents


 Button.processEvent

Button.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this button. If an event is an instance of ActionEvent, this method invokes the processActionEvent method. Otherwise, it invokes processEvent on the superclass.

Overrides
processEvent in class Component
See Also
ActionEvent, processActionEvent


 Button.removeActionListener

Button.removeActionListener

Syntax
public synchronized void removeActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Removes the specified action listener so that it no longer receives action events from this button. Action events occur when a user presses or releases the mouse over this button.

See Also
ActionListener, addActionListener


 Button.setActionCommand

Button.setActionCommand

Syntax
public void setActionCommand( String command )
Parameters
command
A string used to set the button's action command.
Description
Sets the command name for the action event fired by this button. By default this action command is set to match the label of the button.

See Also
ActionEvent


 Button.setLabel

Button.setLabel

Syntax
public synchronized void setLabel( String label )
Parameters
label
the new label, or null if the button has no label.
Description
Sets the button's label to be the specified string.

See Also
getLabel


 Class Canvas

Class java.awt.Canvas

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Canvas

public class Canvas
extends Component

A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.

An application must subclass the Canvas class in order to get useful functionality such as creating a custom component. The paint method must be overridden in order to perform custom graphics on the canvas.


 Canvas Members

Canvas Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Canvas() | Constructs a new Canvas.

Methods
Name | Description
addNotify() | Creates the peer of the canvas.
paint(Graphics) | This method is called to repaint this canvas.


 Canvas.Canvas

Canvas.Canvas

Syntax
public Canvas()
Description
Constructs a new Canvas.


 Canvas.addNotify

Canvas.addNotify

Syntax
public void addNotify()
Description
Creates the peer of the canvas. This peer allows you to change the user interface of the canvas without changing its functionality.

Overrides
addNotify in class Component
See Also
createCanvas, getToolkit


 Canvas.paint

Canvas.paint

Syntax
public void paint( Graphics g )
Parameters
g
the graphics context.
Description
This method is called to repaint this canvas. Most applications that subclass Canvas should override this method in order to perform some useful operation.

The paint method provided by Canvas redraws this canvas's rectangle in the background color.

The graphics context's origin (0, 0) is the top-left corner of this canvas. Its clipping region is the area of the context.

Overrides
paint in class Component
See Also
Graphics


 Class CardLayout

Class java.awt.CardLayout

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.CardLayout

public class CardLayout
extends Object
implements LayoutManager2, Serializable

A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards.

The ordering of cards is determined by the container's own internal ordering of its component objects. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card. The addLayoutComponent method can be used to associate a string identifier with a given card for fast random access.

See Also:
Container


 CardLayout Members

CardLayout Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CardLayout() | Creates a new card layout with gaps of size zero.
CardLayout(int, int) | Creates a new card layout with the specified horizontal and vertical gaps.

Methods
Name | Description
addLayoutComponent(Component, Object) | Adds the specified component to this card layout's internal table of names.
addLayoutComponent(String, Component) | Deprecated.
first(Container) | Flips to the first card of the container.
getHgap() | Gets the horizontal gap between components.
getLayoutAlignmentX(Container) | Returns the alignment along the x axis.
getLayoutAlignmentY(Container) | Returns the alignment along the y axis.
getVgap() | Gets the vertical gap between components.
invalidateLayout(Container) | Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
last(Container) | Flips to the last card of the container.
layoutContainer(Container) | Lays out the specified container using this card layout.
maximumLayoutSize(Container) | Returns the maximum dimensions for this layout given the components in the specified target container.
minimumLayoutSize(Container) | Calculates the minimum size for the specified panel.
next(Container) | Flips to the next card of the specified container.
preferredLayoutSize(Container) | Determines the preferred size of the container argument using this card layout.
previous(Container) | Flips to the previous card of the specified container.
removeLayoutComponent(Component) | Removes the specified component from the layout.
setHgap(int) | Sets the horizontal gap between components.
setVgap(int) | Sets the vertical gap between components.
show(Container, String) | Flips to the component that was added to this layout with the specified name, using addLayoutComponent.
toString() | Returns a string representation of the state of this card layout.


 CardLayout.CardLayout

CardLayout.CardLayout

Syntax 1
public CardLayout()
Description
Creates a new card layout with gaps of size zero.

Syntax 2
public CardLayout( int hgap, int vgap )
Parameters
hgap
the horizontal gap.
vgap
the vertical gap.
Description
Creates a new card layout with the specified horizontal and vertical gaps. The horizontal gaps are placed at the left and right edges. The vertical gaps are placed at the top and bottom edges.


 CardLayout.addLayoutComponent

CardLayout.addLayoutComponent

Syntax 1
public void addLayoutComponent( Component comp, Object constraints )
Parameters
comp
the component to be added.
constraints
a tag that identifies a particular card in the layout.
Description
Adds the specified component to this card layout's internal table of names. The object specified by constraints must be a string. The card layout stores this string as a key-value pair that can be used for random access to a particular card. By calling the show method, an application can display the component with the specified name.

Exceptions
IllegalArgumentException if the constraint is not a string.
See Also
show

Syntax 2
public void addLayoutComponent( String name, Component comp )
Description
Note: addLayoutComponent() is deprecated. replaced by addLayoutComponent(Component, Object).


 CardLayout.first

CardLayout.first

Syntax
public void first( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Description
Flips to the first card of the container.

See Also
last


 CardLayout.getHgap

CardLayout.getHgap

Syntax
public int getHgap()
Returns
the horizontal gap between components.
Description
Gets the horizontal gap between components.

See Also
setHgap, getVgap


 CardLayout.getLayoutAlignmentX

CardLayout.getLayoutAlignmentX

Syntax
public float getLayoutAlignmentX( Container parent )
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 CardLayout.getLayoutAlignmentY

CardLayout.getLayoutAlignmentY

Syntax
public float getLayoutAlignmentY( Container parent )
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 CardLayout.getVgap

CardLayout.getVgap

Syntax
public int getVgap()
Returns
the vertical gap between components.
Description
Gets the vertical gap between components.

See Also
setVgap, getHgap


 CardLayout.invalidateLayout

CardLayout.invalidateLayout

Syntax
public void invalidateLayout( Container target )
Description
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.


 CardLayout.last

CardLayout.last

Syntax
public void last( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Description
Flips to the last card of the container.

See Also
first


 CardLayout.layoutContainer

CardLayout.layoutContainer

Syntax
public void layoutContainer( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Description
Lays out the specified container using this card layout.

Each component in the parent container is reshaped to be the size of the container, minus space for surrounding insets, horizontal gaps, and vertical gaps.

See Also
doLayout


 CardLayout.maximumLayoutSize

CardLayout.maximumLayoutSize

Syntax
public Dimension maximumLayoutSize( Container target )
Parameters
target
the component which needs to be laid out
Description
Returns the maximum dimensions for this layout given the components in the specified target container.

See Also
Container, minimumLayoutSize, preferredLayoutSize


 CardLayout.minimumLayoutSize

CardLayout.minimumLayoutSize

Syntax
public Dimension minimumLayoutSize( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Returns
the minimum dimensions required to lay out the subcomponents of the specified container.
Description
Calculates the minimum size for the specified panel.

See Also
doLayout, preferredLayoutSize


 CardLayout.next

CardLayout.next

Syntax
public void next( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Description
Flips to the next card of the specified container. If the currently visible card is the last one, this method flips to the first card in the layout.

See Also
previous


 CardLayout.preferredLayoutSize

CardLayout.preferredLayoutSize

Syntax
public Dimension preferredLayoutSize( Container parent )
Parameters
parent
the name of the parent container.
Returns
the preferred dimensions to lay out the subcomponents of the specified container.
Description
Determines the preferred size of the container argument using this card layout.

See Also
getPreferredSize, minimumLayoutSize


 CardLayout.previous

CardLayout.previous

Syntax
public void previous( Container parent )
Parameters
parent
the name of the parent container in which to do the layout.
Description
Flips to the previous card of the specified container. If the currently visible card is the first one, this method flips to the last card in the layout.

See Also
next


 CardLayout.removeLayoutComponent

CardLayout.removeLayoutComponent

Syntax
public void removeLayoutComponent( Component comp )
Parameters
comp
the component to be removed.
Description
Removes the specified component from the layout.

See Also
remove, removeAll


 CardLayout.setHgap

CardLayout.setHgap

Syntax
public void setHgap( int hgap )
Parameters
hgap
the horizontal gap between components.
Description
Sets the horizontal gap between components.

See Also
getHgap, setVgap


 CardLayout.setVgap

CardLayout.setVgap

Syntax
public void setVgap( int vgap )
Parameters
vgap
the vertical gap between components.
Description
Sets the vertical gap between components.

See Also
getVgap, setHgap


 CardLayout.show

CardLayout.show

Syntax
public void show( Container parent, String name )
Parameters
parent
the name of the parent container in which to do the layout.
name
the component name.
Description
Flips to the component that was added to this layout with the specified name, using addLayoutComponent. If no such component exists, then nothing happens.

See Also
addLayoutComponent


 CardLayout.toString

CardLayout.toString

Syntax
public String toString()
Returns
a string representation of this card layout.
Description
Returns a string representation of the state of this card layout.

Overrides
toString in class Object


 Class Checkbox

Class java.awt.Checkbox

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Checkbox

public class Checkbox
extends Component
implements ItemSelectable

A check box is a graphical component that can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on."

The following code example creates a set of check boxes in a grid layout:

 setLayout(new GridLayout(3, 1));
 add(new Checkbox("one", null, true));
 add(new Checkbox("two"));
 add(new Checkbox("three"));

This image depicts the check boxes and grid layout created by this code example:

The button labeled one is in the "on" state, and the other two are in the "off" state. In this example, which uses the GridLayout class, the states of the three check boxes are set independently.

Alternatively, several check boxes can be grouped together under the control of a single object, using the CheckboxGroup class. In a check box group, at most one button can be in the "on" state at any given time. Clicking on a check box to turn it on forces any other check box in the same group that is on into the "off" state.

See Also:
GridLayout, CheckboxGroup


 Checkbox Members

Checkbox Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Checkbox() | Creates a check box with no label.
Checkbox(String) | Creates a check box with the specified label.
Checkbox(String, boolean) | Creates a check box with the specified label.
Checkbox(String, boolean, CheckboxGroup) | Creates a check box with the specified label, in the specified check box group, and set to the specified state.
Checkbox(String, CheckboxGroup, boolean) | Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.

Methods
Name | Description
addItemListener(ItemListener) | Adds the specified item listener to receive item events from this check box.
addNotify() | Creates the peer of the Checkbox.
getCheckboxGroup() | Determines this check box's group.
getLabel() | Gets the label of this check box.
getSelectedObjects() | Returns the an array (length 1) containing the checkbox label or null if the checkbox is not selected.
getState() | Determines whether this check box is in the "on" or "off" state.
paramString() | Returns the parameter string representing the state of this check box.
processEvent(AWTEvent) | Processes events on this check box.
processItemEvent(ItemEvent) | Processes item events occurring on this check box by dispatching them to any registered ItemListener objects.
removeItemListener(ItemListener) | Removes the specified item listener so that the item listener no longer receives item events from this check box.
setCheckboxGroup(CheckboxGroup) | Sets this check box's group to be the specified check box group.
setLabel(String) | Sets this check box's label to be the string argument.
setState(boolean) | Sets the state of this check box to the specified state.


 Checkbox.Checkbox

Checkbox.Checkbox

Syntax 1
public Checkbox()
Description
Creates a check box with no label. The state of this check box is set to "off," and it is not part of any check box group.

Syntax 2
public Checkbox( String label )
Parameters
label
a string label for this check box, or null for no label.
Description
Creates a check box with the specified label. The state of this check box is set to "off," and it is not part of any check box group.

Syntax 3
public Checkbox( String label, boolean state )
Parameters
label
a string label for this check box, or null for no label.
state
the initial state of this check box.
Description
Creates a check box with the specified label. The state of this check box is as specified by the state argument, and it is not part of any check box group.

Syntax 4
public Checkbox( String label, boolean state, CheckboxGroup group )
Parameters
label
a string label for this check box, or null for no label.
state
the initial state of this check box.
group
a check box group for this check box, or null for no group.
Description
Creates a check box with the specified label, in the specified check box group, and set to the specified state.

Syntax 5
public Checkbox( String label, CheckboxGroup group, boolean state )
Description
Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.


 Checkbox.addItemListener

Checkbox.addItemListener

Syntax
public synchronized void addItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Adds the specified item listener to receive item events from this check box.

See Also
ItemEvent, ItemListener, removeItemListener


 Checkbox.addNotify

Checkbox.addNotify

Syntax
public void addNotify()
Description
Creates the peer of the Checkbox. The peer allows you to change the look of the Checkbox without changing its functionality.

Overrides
addNotify in class Component
See Also
createCheckbox, getToolkit


 Checkbox.getCheckboxGroup

Checkbox.getCheckboxGroup

Syntax
public CheckboxGroup getCheckboxGroup()
Returns
this check box's group, or null if the check box is not part of a check box group.
Description
Determines this check box's group.

See Also
setCheckboxGroup


 Checkbox.getLabel

Checkbox.getLabel

Syntax
public String getLabel()
Returns
the label of this check box, or null if this check box has no label.
Description
Gets the label of this check box.

See Also
setLabel


 Checkbox.getSelectedObjects

Checkbox.getSelectedObjects

Syntax
public Object[] getSelectedObjects()
Description
Returns the an array (length 1) containing the checkbox label or null if the checkbox is not selected.

See Also
ItemSelectable


 Checkbox.getState

Checkbox.getState

Syntax
public boolean getState()
Returns
the state of this check box, as a boolean value.
Description
Determines whether this check box is in the "on" or "off" state. The boolean value true indicates the "on" state, and false indicates the "off" state.

See Also
setState


 Checkbox.paramString

Checkbox.paramString

Syntax
protected String paramString()
Returns
the parameter string of this check box.
Description
Returns the parameter string representing the state of this check box. This string is useful for debugging.

Overrides
paramString in class Component


 Checkbox.processEvent

Checkbox.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this check box. If the event is an instance of ItemEvent, this method invokes the processItemEvent method. Otherwise, it calls its superclass's processEvent method.

Overrides
processEvent in class Component
See Also
ItemEvent, processItemEvent


 Checkbox.processItemEvent

Checkbox.processItemEvent

Syntax
protected void processItemEvent( ItemEvent e )
Parameters
e
the item event.
Description
Processes item events occurring on this check box by dispatching them to any registered ItemListener objects.

This method is not called unless item events are enabled for this component. Item events are enabled when one of the following occurs:

  • An ItemListener object is registered via addItemListener.
  • Item events are enabled via enableEvents.

See Also
ItemEvent, ItemListener, addItemListener, enableEvents


 Checkbox.removeItemListener

Checkbox.removeItemListener

Syntax
public synchronized void removeItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Removes the specified item listener so that the item listener no longer receives item events from this check box.

See Also
ItemEvent, ItemListener, addItemListener


 Checkbox.setCheckboxGroup

Checkbox.setCheckboxGroup

Syntax
public void setCheckboxGroup( CheckboxGroup g )
Parameters
g
the new check box group, or null to remove this check box from any check box group.
Description
Sets this check box's group to be the specified check box group. If this check box is already in a different check box group, it is first taken out of that group.

See Also
getCheckboxGroup


 Checkbox.setLabel

Checkbox.setLabel

Syntax
public synchronized void setLabel( String label )
Parameters
label
a string to set as the new label, or null for no label.
Description
Sets this check box's label to be the string argument.

See Also
getLabel


 Checkbox.setState

Checkbox.setState

Syntax
public void setState( boolean state )
Parameters
state
the boolean state of the check box.
Description
Sets the state of this check box to the specified state. The boolean value true indicates the "on" state, and false indicates the "off" state.

See Also
getState


 Class CheckboxGroup

Class java.awt.CheckboxGroup

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.CheckboxGroup

public class CheckboxGroup
extends Object
implements Serializable

The CheckboxGroup class is used to group together a set of Checkbox buttons.

Exactly one check box button in a CheckboxGroup can be in the "on" state at any given time. Pushing any button sets its state to "on" and forces any other button that is in the "on" state into the "off" state.

The following code example produces a new check box group, with three check boxes:

 setLayout(new GridLayout(3, 1));
 CheckboxGroup cbg = new CheckboxGroup();
 add(new Checkbox("one", cbg, true));
 add(new Checkbox("two", cbg, false));
 add(new Checkbox("three", cbg, false));

This image depicts the check box group created by this example:

See Also:
Checkbox


 CheckboxGroup Members

CheckboxGroup Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CheckboxGroup() | Creates a new instance of CheckboxGroup.

Methods
Name | Description
getCurrent() | Deprecated.
getSelectedCheckbox() | Gets the current choice from this check box group.
setCurrent(Checkbox) | Deprecated.
setSelectedCheckbox(Checkbox) | Sets the currently selected check box in this group to be the specified check box.
toString() | Returns a string representation of this check box group, including the value of its current selection.


 CheckboxGroup.CheckboxGroup

CheckboxGroup.CheckboxGroup

Syntax
public CheckboxGroup()
Description
Creates a new instance of CheckboxGroup.


 CheckboxGroup.getCurrent

CheckboxGroup.getCurrent

Syntax
public Checkbox getCurrent()
Description
Note: getCurrent() is deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().


 CheckboxGroup.getSelectedCheckbox

CheckboxGroup.getSelectedCheckbox

Syntax
public Checkbox getSelectedCheckbox()
Returns
the check box that is currently in the "on" state, or null.
Description
Gets the current choice from this check box group. The current choice is the check box in this group that is currently in the "on" state, or null if all check boxes in the group are off.

See Also
Checkbox, setSelectedCheckbox


 CheckboxGroup.setCurrent

CheckboxGroup.setCurrent

Syntax
public synchronized void setCurrent( Checkbox box )
Description
Note: setCurrent() is deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).


 CheckboxGroup.setSelectedCheckbox

CheckboxGroup.setSelectedCheckbox

Syntax
public synchronized void setSelectedCheckbox( Checkbox box )
Parameters
box
the Checkbox to set as the current selection.
Description
Sets the currently selected check box in this group to be the specified check box. This method sets the state of that check box to "on" and sets all other check boxes in the group to be off.

If the check box argument is null or belongs to a different check box group, then this method does nothing.

See Also
Checkbox, getSelectedCheckbox


 CheckboxGroup.toString

CheckboxGroup.toString

Syntax
public String toString()
Returns
a string representation of this check box group.
Description
Returns a string representation of this check box group, including the value of its current selection.

Overrides
toString in class Object


 Class CheckboxMenuItem

Class java.awt.CheckboxMenuItem

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent
           |
           +----java.awt.MenuItem
                   |
                   +----java.awt.CheckboxMenuItem

public class CheckboxMenuItem
extends MenuItem
implements ItemSelectable

This class represents a check box that can be included in a menu. Clicking on the check box in the menu changes its state from "on" to "off" or from "off" to "on."

The following picture depicts a menu which contains an instance of CheckBoxMenuItem:

The item labeled Check shows a check box menu item in its "off" state.

When a check box menu item is selected, AWT sends an item event to the item. Since the event is an instance of ItemEvent, the processEvent method examines the event and passes it along to processItemEvent. The latter method redirects the event to any ItemListener objects that have registered an interest in item events generated by this menu item.

See Also:
ItemEvent, ItemListener


 CheckboxMenuItem Members

CheckboxMenuItem Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CheckboxMenuItem() | Create a check box menu item with an empty label.
CheckboxMenuItem(String) | Create a check box menu item with the specified label.
CheckboxMenuItem(String, boolean) | Create a check box menu item with the specified label and state.

Methods
Name | Description
addItemListener(ItemListener) | Adds the specified item listener to receive item events from this check box menu item.
addNotify() | Creates the peer of the checkbox item.
getSelectedObjects() | Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.
getState() | Determines whether the state of this check box menu item is "on" or "off."
paramString() | Returns the parameter string representing the state of this check box menu item.
processEvent(AWTEvent) | Processes events on this check box menu item.
processItemEvent(ItemEvent) | Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.
removeItemListener(ItemListener) | Removes the specified item listener so that it no longer receives item events from this check box menu item.
setState(boolean) | Sets this check box menu item to the specifed state.


 CheckboxMenuItem.CheckboxMenuItem

CheckboxMenuItem.CheckboxMenuItem

Syntax 1
public CheckboxMenuItem()
Description
Create a check box menu item with an empty label. The item's state is initially set to "off."

Syntax 2
public CheckboxMenuItem( String label )
Parameters
label
a string label for the check box menu item, or null for an unlabeled menu item.
Description
Create a check box menu item with the specified label. The item's state is initially set to "off."

Syntax 3
public CheckboxMenuItem( String label, boolean state )
Parameters
label
the button label.
state
the initial state of the menu item, where true indicates "on" and false indicates "off."
Description
Create a check box menu item with the specified label and state.


 CheckboxMenuItem.addItemListener

CheckboxMenuItem.addItemListener

Syntax
public synchronized void addItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Adds the specified item listener to receive item events from this check box menu item.

See Also
ItemEvent, ItemListener, removeItemListener


 CheckboxMenuItem.addNotify

CheckboxMenuItem.addNotify

Syntax
public void addNotify()
Description
Creates the peer of the checkbox item. This peer allows us to change the look of the checkbox item without changing its functionality. Most applications do not call this method directly.

Overrides
addNotify in class MenuItem
See Also
createCheckboxMenuItem, getToolkit


 CheckboxMenuItem.getSelectedObjects

CheckboxMenuItem.getSelectedObjects

Syntax
public synchronized Object[] getSelectedObjects()
Description
Returns the an array (length 1) containing the checkbox menu item label or null if the checkbox is not selected.

See Also
ItemSelectable


 CheckboxMenuItem.getState

CheckboxMenuItem.getState

Syntax
public boolean getState()
Returns
the state of this check box menu item, where true indicates "on" and false indicates "off."
Description
Determines whether the state of this check box menu item is "on" or "off."

See Also
setState


 CheckboxMenuItem.paramString

CheckboxMenuItem.paramString

Syntax
public String paramString()
Returns
the parameter string of this check box menu item.
Description
Returns the parameter string representing the state of this check box menu item. This string is useful for debugging.

Overrides
paramString in class MenuItem


 CheckboxMenuItem.processEvent

CheckboxMenuItem.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event
Description
Processes events on this check box menu item. If the event is an instance of ItemEvent, this method invokes the processItemEvent method. If the event is not an item event, it invokes processEvent on the superclass.

Check box menu items currently support only item events.

Overrides
processEvent in class MenuItem
See Also
ItemEvent, processItemEvent


 CheckboxMenuItem.processItemEvent

CheckboxMenuItem.processItemEvent

Syntax
protected void processItemEvent( ItemEvent e )
Parameters
e
the item event.
Description
Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.

This method is not called unless item events are enabled for this menu item. Item events are enabled when one of the following occurs:

  • An ItemListener object is registered via addItemListener.
  • Item events are enabled via enableEvents.

See Also
ItemEvent, ItemListener, addItemListener, enableEvents


 CheckboxMenuItem.removeItemListener

CheckboxMenuItem.removeItemListener

Syntax
public synchronized void removeItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Removes the specified item listener so that it no longer receives item events from this check box menu item.

See Also
ItemEvent, ItemListener, addItemListener


 CheckboxMenuItem.setState

CheckboxMenuItem.setState

Syntax
public synchronized void setState( boolean b )
Parameters
b
the boolean state of this check box menu item.
Description
Sets this check box menu item to the specifed state. The boolean value true indicates "on" while false indicates "off."

See Also
getState


 Class Choice

Class java.awt.Choice

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Choice

public class Choice
extends Component
implements ItemSelectable

The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of the menu.

The following code example produces a pop-up menu:

 Choice ColorChooser = new Choice();
 ColorChooser.add("Green");
 ColorChooser.add("Red");
 ColorChooser.add("Blue");

After this choice menu has been added to a panel, it appears as follows in its normal state:

In the picture, "Green" is the current choice. Pushing the mouse button down on the object causes a menu to appear with the current choice highlighted.


 Choice Members

Choice Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Choice() | Creates a new choice menu.

Methods
Name | Description
add(String) | Adds an item to this Choice menu.
addItem(String) | Adds an item to this Choice.
addItemListener(ItemListener) | Adds the specified item listener to receive item events from this Choice menu.
addNotify() | Creates the Choice's peer.
countItems() | Deprecated.
getItem(int) | Gets the string at the specified index in this Choice menu.
getItemCount() | Returns the number of items in this Choice menu.
getSelectedIndex() | Returns the index of the currently selected item.
getSelectedItem() | Gets a representation of the current choice as a string.
getSelectedObjects() | Returns an array (length 1) containing the currently selected item.
insert(String, int) | Inserts the item into this choice at the specified position.
paramString() | Returns the parameter string representing the state of this choice menu.
processEvent(AWTEvent) | Processes events on this choice.
processItemEvent(ItemEvent) | Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.
remove(int) | Removes an item from the choice menu at the specified position.
remove(String) | Remove the first occurrence of item from the Choice menu.
removeAll() | Removes all items from the choice menu.
removeItemListener(ItemListener) | Removes the specified item listener so that it no longer receives item events from this Choice menu.
select(int) | Sets the selected item in this Choice menu to be the item at the specified position.
select(String) | Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.


 Choice.Choice

Choice.Choice

Syntax
public Choice()
Description
Creates a new choice menu. The menu initially has no items in it.

By default, the first item added to the choice menu becomes the selected item, until a different selection is made by the user by calling one of the select methods.

See Also
select, select


 Choice.add

Choice.add

Syntax
public synchronized void add( String item )
Parameters
item
the item to be added
Description
Adds an item to this Choice menu.

Exceptions
NullPointerException if the item's value is null.


 Choice.addItem

Choice.addItem

Syntax
public synchronized void addItem( String item )
Parameters
item
the item to be added
Description
Adds an item to this Choice.

Exceptions
NullPointerException If the item's value is equal to null.


 Choice.addItemListener

Choice.addItemListener

Syntax
public synchronized void addItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Adds the specified item listener to receive item events from this Choice menu.

See Also
ItemEvent, ItemListener, removeItemListener


 Choice.addNotify

Choice.addNotify

Syntax
public void addNotify()
Description
Creates the Choice's peer. This peer allows us to change the look of the Choice without changing its functionality.

Overrides
addNotify in class Component
See Also
createChoice, getToolkit


 Choice.countItems

Choice.countItems

Syntax
public int countItems()
Description
Note: countItems() is deprecated. As of JDK version 1.1, replaced by getItemCount().


 Choice.getItem

Choice.getItem

Syntax
public String getItem( int index )
Parameters
index
the index at which to begin.
Description
Gets the string at the specified index in this Choice menu.

See Also
getItemCount


 Choice.getItemCount

Choice.getItemCount

Syntax
public int getItemCount()
Description
Returns the number of items in this Choice menu.

See Also
getItem


 Choice.getSelectedIndex

Choice.getSelectedIndex

Syntax
public int getSelectedIndex()
Description
Returns the index of the currently selected item.

See Also
getSelectedItem


 Choice.getSelectedItem

Choice.getSelectedItem

Syntax
public synchronized String getSelectedItem()
Returns
a string representation of the currently selected item in this choice menu.
Description
Gets a representation of the current choice as a string.

See Also
getSelectedIndex


 Choice.getSelectedObjects

Choice.getSelectedObjects

Syntax
public synchronized Object[] getSelectedObjects()
Description
Returns an array (length 1) containing the currently selected item. If this choice has no items, returns null.

See Also
ItemSelectable


 Choice.insert

Choice.insert

Syntax
public synchronized void insert( String item, int index )
Parameters
item
the item to be inserted
index
the position at which the item should be inserted
Description
Inserts the item into this choice at the specified position.

Exceptions
IllegalArgumentException if index is less than 0.


 Choice.paramString

Choice.paramString

Syntax
protected String paramString()
Returns
the parameter string of this Choice menu.
Description
Returns the parameter string representing the state of this choice menu. This string is useful for debugging.

Overrides
paramString in class Component


 Choice.processEvent

Choice.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this choice. If the event is an instance of ItemEvent, it invokes the processItemEvent method. Otherwise, it calls its superclass's processEvent method.

Overrides
processEvent in class Component
See Also
ItemEvent, processItemEvent


 Choice.processItemEvent

Choice.processItemEvent

Syntax
protected void processItemEvent( ItemEvent e )
Parameters
e
the item event.
Description
Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.

This method is not called unless item events are enabled for this component. Item events are enabled when one of the following occurs:

  • An ItemListener object is registered via addItemListener.
  • Item events are enabled via enableEvents.

See Also
ItemEvent, ItemListener, addItemListener, enableEvents


 Choice.remove

Choice.remove

Syntax 1
public synchronized void remove( String item )
Parameters
item
the item to remove from this Choice menu.
Description
Remove the first occurrence of item from the Choice menu.

Exceptions
IllegalArgumentException if the item doesn't exist in the choice menu.

Syntax 2
public synchronized void remove( int position )
Parameters
position
the position of the item.
Description
Removes an item from the choice menu at the specified position.


 Choice.removeAll

Choice.removeAll

Syntax
public synchronized void removeAll()
Description
Removes all items from the choice menu.

See Also
remove


 Choice.removeItemListener

Choice.removeItemListener

Syntax
public synchronized void removeItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Removes the specified item listener so that it no longer receives item events from this Choice menu.

See Also
ItemEvent, ItemListener, addItemListener


 Choice.select

Choice.select

Syntax 1
public synchronized void select( int pos )
Parameters
pos
the positon of the selected item.
Description
Sets the selected item in this Choice menu to be the item at the specified position.

Exceptions
IllegalArgumentException if the specified position is invalid.
See Also
getSelectedItem, getSelectedIndex

Syntax 2
public synchronized void select( String str )
Parameters
str
the specified string
Description
Sets the selected item in this Choice menu to be the item whose name is equal to the specified string. If more than one item matches (is equal to) the specified string, the one with the smallest index is selected.

See Also
getSelectedItem, getSelectedIndex


 Class Color

Class java.awt.Color

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Color

public class Color
extends Object
implements Serializable

This class encapsulates colors using the RGB format. In RGB format, the red, blue, and green components of a color are each represented by an integer in the range 0-255. The value 0 indicates no contribution from this primary color. The value 255 indicates the maximum intensity of this color component.

Although the Color class is based on the three-component RGB model, the class provides a set of convenience methods for converting between RGB and HSB colors. For a definition of the RGB and HSB color models, see Foley, van Dam, Feiner, and Hughes, Computer Graphics: Principles and Practice.


 Color Members

Color Members

Class Overview | This Package | All Packages

Fields
Name | Description
black | The color black.
blue | The color blue.
cyan | The color cyan.
darkGray | The color dark gray.
gray | The color gray.
green | The color green.
lightGray | The color light gray.
magenta | The color magneta.
orange | The color orange.
pink | The color pink.
red | The color red.
white | The color white.
yellow | The color yellow.

Constructors
Name | Description
Color(float, float, float) | Creates a color with the specified red, green, and blue values, where each of the values is in the range 0.0-1.0.
Color(int) | Creates a color with the specified RGB value, where the red component is in bits 16-23 of the argument, the green component is in bits 8-15 of the argument, and the blue component is in bits 0-7.
Color(int, int, int) | Creates a color with the specified red, green, and blue components.

Methods
Name | Description
brighter() | Creates a brighter version of this color.
darker() | Creates a darker version of this color.
decode(String) | Converts a string to an integer and returns the specified color.
equals(Object) | Determines whether another object is equal to this color.
getBlue() | Gets the blue component of this color.
getColor(String) | Finds a color in the system properties.
getColor(String, Color) | Finds a color in the system properties.
getColor(String, int) | Finds a color in the system properties.
getGreen() | Gets the green component of this color.
getHSBColor(float, float, float) | Creates a Color object based on values supplied for the HSB color model.
getRed() | Gets the red component of this color.
getRGB() | Gets the RGB value representing the color in the default RGB ColorModel.
hashCode() | Computes the hash code for this color.
HSBtoRGB(float, float, float) | Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the RGB model.
RGBtoHSB(int, int, int, float[]) | Converts the components of a color, as specified by the RGB model, to an equivalent set of values for hue, saturation, and brightness, the three components of the HSB model.
toString() | Creates a string that represents this color and indicates the values of its RGB components.


 Color.black

Color.black

Syntax
public static final Color black
Description
The color black.


 Color.blue

Color.blue

Syntax
public static final Color blue
Description
The color blue.


 Color.cyan

Color.cyan

Syntax
public static final Color cyan
Description
The color cyan.


 Color.darkGray

Color.darkGray

Syntax
public static final Color darkGray
Description
The color dark gray.


 Color.gray

Color.gray

Syntax
public static final Color gray
Description
The color gray.


 Color.green

Color.green

Syntax
public static final Color green
Description
The color green.


 Color.lightGray

Color.lightGray

Syntax
public static final Color lightGray
Description
The color light gray.


 Color.magenta

Color.magenta

Syntax
public static final Color magenta
Description
The color magneta.


 Color.orange

Color.orange

Syntax
public static final Color orange
Description
The color orange.


 Color.pink

Color.pink

Syntax
public static final Color pink
Description
The color pink.


 Color.red

Color.red

Syntax
public static final Color red
Description
The color red.


 Color.white

Color.white

Syntax
public static final Color white
Description
The color white.


 Color.yellow

Color.yellow

Syntax
public static final Color yellow
Description
The color yellow.


 Color.Color

Color.Color

Syntax 1
public Color( int r, int g, int b )
Parameters
r
the red component.
g
the green component.
b
the blue component.
Description
Creates a color with the specified red, green, and blue components. The three arguments must each be in the range 0-255.

The actual color used in rendering depends on finding the best match given the color space available for a given output device.

See Also
getRed, getGreen, getBlue, getRGB

Syntax 2
public Color( int rgb )
Parameters
rgb
an integer giving the red, green, and blue components.
Description
Creates a color with the specified RGB value, where the red component is in bits 16-23 of the argument, the green component is in bits 8-15 of the argument, and the blue component is in bits 0-7. The value zero indicates no contribution from the primary color component.

The actual color used in rendering depends on finding the best match given the color space available for a given output device.

See Also
getRGBdefault, getRed, getGreen, getBlue, getRGB

Syntax 3
public Color( float r, float g, float b )
Parameters
r
the red component
g
the red component
b
the red component
Description
Creates a color with the specified red, green, and blue values, where each of the values is in the range 0.0-1.0. The value 0.0 indicates no contribution from the primary color component. The value 1.0 indicates the maximum intensity of the primary color component.

The actual color used in rendering depends on finding the best match given the color space available for a given output device.

See Also
getRed, getGreen, getBlue, getRGB


 Color.brighter

Color.brighter

Syntax
public Color brighter()
Returns
a new Color object, a brighter version of this color.
Description
Creates a brighter version of this color.

This method applies an arbitrary scale factor to each of the three RGB components of the color to create a brighter version of the same color. Although brighter and darker are inverse operations, the results of a series of invocations of these two methods may be inconsistent because of rounding errors.

See Also
darker


 Color.darker

Color.darker

Syntax
public Color darker()
Returns
a new Color object, a darker version of this color.
Description
Creates a darker version of this color.

This method applies an arbitrary scale factor to each of the three RGB components of the color to create a darker version of the same color. Although brighter and darker are inverse operations, the results of a series of invocations of these two methods may be inconsistent because of rounding errors.

See Also
brighter


 Color.decode

Color.decode

Syntax
public static Color decode( String nm ) throws NumberFormatException
Parameters
nm
a string that represents a color as a 24-bit integer.
Returns
the new color
Description
Converts a string to an integer and returns the specified color. This method handles string formats that are used to represent octal and hexidecimal numbers.

Exceptions
NumberFormatException if the specified string cannot be interpreted as a decimal, octal, or hexidecimal integer.
See Also
decode


 Color.equals

Color.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Determines whether another object is equal to this color.

The result is true if and only if the argument is not null and is a Color object that has the same red, green, and blue values as this object.

Overrides
equals in class Object


 Color.getBlue

Color.getBlue

Syntax
public int getBlue()
Returns
the blue component of this color.
Description
Gets the blue component of this color. The result is an integer in the range 0 to 255.

See Also
getRGB


 Color.getColor

Color.getColor

Syntax 1
public static Color getColor( String nm )
Parameters
nm
the name of the color property
Returns
the color value of the property.
Description
Finds a color in the system properties.

The argument is treated as the name of a system property to be obtained. The string value of this property is then interpreted as an integer which is then converted to a color.

If the specified property is not found, or could not be parsed as an integer, then null is returned.

See Also
getProperty, getInteger, Color

Syntax 2
public static Color getColor( String nm, Color v )
Parameters
nm
the name of the color property
v
the default color value.
Returns
the color value of the property.
Description
Finds a color in the system properties.

The first argument is treated as the name of a system property to be obtained. The string value of this property is then interpreted as an integer which is then converted to a color.

If the specified property is not found, or cannot be parsed as an integer, then the color specified by the second argument is returned instead.

See Also
getProperty, getInteger, Color

Syntax 3
public static Color getColor( String nm, int v )
Parameters
nm
the name of the color property.
v
the default color value, as an integer.
Returns
the color value of the property.
Description
Finds a color in the system properties.

The first argument is treated as the name of a system property to be obtained. The string value of this property is then interpreted as an integer which is then converted to a color.

If the specified property is not found, or could not be parsed as an integer, then the integer value v is used instead, and is converted to a color.

See Also
getProperty, getInteger, Color


 Color.getGreen

Color.getGreen

Syntax
public int getGreen()
Returns
the green component of this color.
Description
Gets the green component of this color. The result is an integer in the range 0 to 255.

See Also
getRGB


 Color.getHSBColor

Color.getHSBColor

Syntax
public static Color getHSBColor( float h, float s, float b )
Parameters
h
the hue component.
s
the saturation of the color.
b
the brightness of the color.
Returns
a Color object with the specified hue, saturation, and brightness.
Description
Creates a Color object based on values supplied for the HSB color model.

Each of the three components should be a floating-point value between zero and one (a number in the range 0.0 ≤ h, s, b ≤ 1.0).


 Color.getRed

Color.getRed

Syntax
public int getRed()
Returns
the red component of this color.
Description
Gets the red component of this color. The result is an integer in the range 0 to 255.

See Also
getRGB


 Color.getRGB

Color.getRGB

Syntax
public int getRGB()
Description
Gets the RGB value representing the color in the default RGB ColorModel. The red, green, and blue components of the color are each scaled to be a value between 0 (abscence of the color) and 255 (complete saturation). Bits 24-31 of the returned integer are 0xff, bits 16-23 are the red value, bit 8-15 are the green value, and bits 0-7 are the blue value.

See Also
getRGBdefault, getRed, getGreen, getBlue


 Color.hashCode

Color.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Computes the hash code for this color.

Overrides
hashCode in class Object


 Color.HSBtoRGB

Color.HSBtoRGB

Syntax
public static int HSBtoRGB( float hue, float saturation, float brightness )
Parameters
hue
the hue component of the color.
saturation
the saturation of the color.
brightness
the brightness of the color.
Returns
the RGB value of the color with the indicated hue, saturation, and brightness.
Description
Converts the components of a color, as specified by the HSB model, to an equivalent set of values for the RGB model.

The integer that is returned by HSBtoRGB encodes the value of a color in bits 0&endash;23 of an integer value, the same format used by the method getRGB. This integer can be supplied as an argument to the Color constructor that takes a single integer argument.

See Also
getRGB, Color


 Color.RGBtoHSB

Color.RGBtoHSB

Syntax
public static float[] RGBtoHSB( int r, int g, int b, float hsbvals[] )
Parameters
r
the red component of the color.
g
the green component of the color.
b
the blue component of the color.
hsbvals
the array to be used to return the three HSB values, or null.
Returns
an array of three elements containing the hue, saturation, and brightness (in that order), of the color with the indicated red, green, and blue components.
Description
Converts the components of a color, as specified by the RGB model, to an equivalent set of values for hue, saturation, and brightness, the three components of the HSB model.

If the hsbvals argument is null, then a new array is allocated to return the result. Otherwise, the method returns the array hsbvals, with the values put into that array.

See Also
getRGB, Color


 Color.toString

Color.toString

Syntax
public String toString()
Returns
a representation of this color as a String object.
Description
Creates a string that represents this color and indicates the values of its RGB components.

Overrides
toString in class Object


 Class Component

Class java.awt.Component

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component

public abstract class Component
extends Object
implements ImageObserver, MenuContainer, Serializable

A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.

The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window.


 Component Members

Component Members

Class Overview | This Package | All Packages

Fields
Name | Description
BOTTOM_ALIGNMENT | Ease-of-use constant for getAlignmentY.
CENTER_ALIGNMENT | Ease-of-use constant for getAlignmentY and getAlignmentX().
LEFT_ALIGNMENT | Ease-of-use constant for getAlignmentX.
RIGHT_ALIGNMENT | Ease-of-use constant for getAlignmentX.
TOP_ALIGNMENT | Ease-of-use constant for getAlignmentY.

Constructors
Name | Description
Component() | Constructs a new component.

Methods
Name | Description
action(Event, Object) | Deprecated.
add(PopupMenu) | Adds the specified popup menu to the component.
addComponentListener(ComponentListener) | Adds the specified component listener to receive component events from this component.
addFocusListener(FocusListener) | Adds the specified focus listener to receive focus events from this component.
addKeyListener(KeyListener) | Adds the specified key listener to receive key events from this component.
addMouseListener(MouseListener) | Adds the specified mouse listener to receive mouse events from this component.
addMouseMotionListener(MouseMotionListener) | Adds the specified mouse motion listener to receive mouse motion events from this component.
addNotify() | Notifies this component that it has been added to a container and if a peer is required, it should be created.
bounds() | Deprecated.
checkImage(Image, ImageObserver) | Returns the status of the construction of a screen representation of the specified image.
checkImage(Image, int, int, ImageObserver) | Returns the status of the construction of a screen representation of the specified image.
contains(int, int) | Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component.
contains(Point) | Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component.
createImage(ImageProducer) | Creates an image from the specified image producer.
createImage(int, int) | Creates an off-screen drawable image to be used for double buffering.
deliverEvent(Event) | Deprecated.
disable() | Deprecated.
disableEvents(long) | Disables the events defined by the specified event mask parameter from being delivered to this component.
dispatchEvent(AWTEvent) | Dispatches an event to this component or one of its sub components.
doLayout() | Prompts the layout manager to lay out this component.
enable() | Deprecated.
enable(boolean) | Deprecated.
enableEvents(long) | Enables the events defined by the specified event mask parameter to be delivered to this component.
getAlignmentX() | Returns the alignment along the x axis.
getAlignmentY() | Returns the alignment along the y axis.
getBackground() | Gets the background color of this component.
getBounds() | Gets the bounds of this component in the form of a Rectangle object.
getColorModel() | Gets the instance of ColorModel used to display the component on the output device.
getComponentAt(int, int) | Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component.
getComponentAt(Point) | Returns the component or subcomponent that contains the specified point.
getCursor() | Gets the cursor set on this component.
getFont() | Gets the font of this component.
getFontMetrics(Font) | Gets the font metrics for the specified font.
getForeground() | Gets the foreground color of this component.
getGraphics() | Creates a graphics context for this component.
getLocale() | Gets the locale of this component.
getLocation() | Gets the location of this component in the form of a point specifying the component's top-left corner.
getLocationOnScreen() | Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space.
getMaximumSize() | Gets the maximum size of this component.
getMinimumSize() | Gets the mininimum size of this component.
getName() | Gets the name of the component.
getParent() | Gets the parent of this component.
getPeer() | Deprecated.
getPreferredSize() | Gets the preferred size of this component.
getSize() | Returns the size of this component in the form of a Dimension object.
getToolkit() | Gets the toolkit of this component.
getTreeLock() | Gets this component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.
gotFocus(Event, Object) | Deprecated.
handleEvent(Event) | Deprecated.
hide() | Deprecated.
imageUpdate(Image, int, int, int, int, int) | Repaints the component when the image has changed.
inside(int, int) | Deprecated.
invalidate() | Invalidates this component.
isEnabled() | Determines whether this component is enabled.
isFocusTraversable() | Returns the value of a flag that indicates whether this component can be traversed using Tab or Shift-Tab keyboard focus traversal.
isShowing() | Determines whether this component is showing on screen.
isValid() | Determines whether this component is valid.
isVisible() | Determines whether this component is visible.
keyDown(Event, int) | Deprecated.
keyUp(Event, int) | Deprecated.
layout() | Deprecated.
list() | Prints a listing of this component to the standard system output stream System.out.
list(PrintStream) | Prints a listing of this component to the specified output stream.
list(PrintStream, int) | Prints out a list, starting at the specified indention, to the specified print stream.
list(PrintWriter) | Prints a listing to the specified print writer.
list(PrintWriter, int) | Prints out a list, starting at the specified indention, to the specified print writer.
locate(int, int) | Deprecated.
location() | Deprecated.
lostFocus(Event, Object) | Deprecated.
minimumSize() | Deprecated.
mouseDown(Event, int, int) | Deprecated.
mouseDrag(Event, int, int) | Deprecated.
mouseEnter(Event, int, int) | Deprecated.
mouseExit(Event, int, int) | Deprecated.
mouseMove(Event, int, int) | Deprecated.
mouseUp(Event, int, int) | Deprecated.
move(int, int) | Deprecated.
nextFocus() | Deprecated.
paint(Graphics) | Paints this component.
paintAll(Graphics) | Paints this component and all of its subcomponents.
paramString() | Returns the parameter string representing the state of this component.
postEvent(Event) | Deprecated.
preferredSize() | Deprecated.
prepareImage(Image, ImageObserver) | Prepares an image for rendering on this component.
prepareImage(Image, int, int, ImageObserver) | Prepares an image for rendering on this component at the specified width and height.
print(Graphics) | Prints this component.
printAll(Graphics) | Prints this component and all of its subcomponents.
processComponentEvent(ComponentEvent) | Processes component events occurring on this component by dispatching them to any registered ComponentListener objects.
processEvent(AWTEvent) | Processes events occurring on this component.
processFocusEvent(FocusEvent) | Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
processKeyEvent(KeyEvent) | Processes key events occurring on this component by dispatching them to any registered KeyListener objects.
processMouseEvent(MouseEvent) | Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects.
processMouseMotionEvent(MouseEvent) | Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects.
remove(MenuComponent) | Removes the specified popup menu from the component.
removeComponentListener(ComponentListener) | Removes the specified component listener so that it no longer receives component events from this component.
removeFocusListener(FocusListener) | Removes the specified focus listener so that it no longer receives focus events from this component.
removeKeyListener(KeyListener) | Removes the specified key listener so that it no longer receives key events from this component.
removeMouseListener(MouseListener) | Removes the specified mouse listener so that it no longer receives mouse events from this component.
removeMouseMotionListener(MouseMotionListener) | Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component.
removeNotify() | Notifies this component that it has been removed from its container and if a peers exists, it destroys it.
repaint() | Repaints this component.
repaint(int, int, int, int) | Repaints the specified rectangle of this component.
repaint(long) | Repaints the component.
repaint(long, int, int, int, int) | Repaints the specified rectangle of this component within tm milliseconds.
requestFocus() | Requests that this component get the input focus.
reshape(int, int, int, int) | Deprecated.
resize(Dimension) | Deprecated.
resize(int, int) | Deprecated.
setBackground(Color) | Sets the background color of this component.
setBounds(int, int, int, int) | Moves and resizes this component.
setBounds(Rectangle) | Moves and resizes this component to conform to the new bounding rectangle r.
setCursor(Cursor) | Set the cursor image to a predefined cursor.
setEnabled(boolean) | Enables or disables this component, depending on the value of the parameter b.
setFont(Font) | Sets the font of this component.
setForeground(Color) | Sets the foreground color of this component.
setLocale(Locale) | Sets the locale of this component.
setLocation(int, int) | Moves this component to a new location.
setLocation(Point) | Moves this component to a new location.
setName(String) | Sets the name of the component to the specified string.
setSize(Dimension) | Resizes this component so that it has width d.width and height d.height.
setSize(int, int) | Resizes this component so that it has width width and height.
setVisible(boolean) | Shows or hides this component depending on the value of parameter b.
show() | Deprecated.
show(boolean) | Deprecated.
size() | Deprecated.
toString() | Returns a string representation of this component and its values.
transferFocus() | Transfers the focus to the next component.
update(Graphics) | Updates this component.
validate() | Ensures that this component has a valid layout.


 Component.BOTTOM_ALIGNMENT

Component.BOTTOM_ALIGNMENT

Syntax
public static final float BOTTOM_ALIGNMENT
Description
Ease-of-use constant for getAlignmentY. Specifies an alignment to the bottom of the component.

See Also
getAlignmentY


 Component.CENTER_ALIGNMENT

Component.CENTER_ALIGNMENT

Syntax
public static final float CENTER_ALIGNMENT
Description
Ease-of-use constant for getAlignmentY and getAlignmentX. Specifies an alignment to the center of the component

See Also
getAlignmentX, getAlignmentY


 Component.LEFT_ALIGNMENT

Component.LEFT_ALIGNMENT

Syntax
public static final float LEFT_ALIGNMENT
Description
Ease-of-use constant for getAlignmentX. Specifies an alignment to the left side of the component.

See Also
getAlignmentX


 Component.RIGHT_ALIGNMENT

Component.RIGHT_ALIGNMENT

Syntax
public static final float RIGHT_ALIGNMENT
Description
Ease-of-use constant for getAlignmentX. Specifies an alignment to the right side of the component.

See Also
getAlignmentX


 Component.TOP_ALIGNMENT

Component.TOP_ALIGNMENT

Syntax
public static final float TOP_ALIGNMENT
Description
Ease-of-use constant for getAlignmentY(). Specifies an alignment to the top of the component.

See Also
getAlignmentY


 Component.Component

Component.Component

Syntax
protected Component()
Description
Constructs a new component. Class Component can be extended directly to create a lightweight component that does not utilize an opaque native window. A lightweight component must be hosted by a native container somewhere higher up in the component tree (for example, by a Frame object).


 Component.action

Component.action

Syntax
public boolean action( Event evt, Object what )
Description
Note: action() is deprecated. As of JDK version 1.1, should register this component as ActionListener on component which fires action events.


 Component.add

Component.add

Syntax
public synchronized void add( PopupMenu popup )
Parameters
popup
the popup menu to be added to the component.
Description
Adds the specified popup menu to the component.

See Also
remove


 Component.addComponentListener

Component.addComponentListener

Syntax
public synchronized void addComponentListener( ComponentListener l )
Parameters
l
the component listener.
Description
Adds the specified component listener to receive component events from this component.

See Also
ComponentEvent, ComponentListener, removeComponentListener


 Component.addFocusListener

Component.addFocusListener

Syntax
public synchronized void addFocusListener( FocusListener l )
Parameters
l
the focus listener.
Description
Adds the specified focus listener to receive focus events from this component.

See Also
FocusEvent, FocusListener, removeFocusListener


 Component.addKeyListener

Component.addKeyListener

Syntax
public synchronized void addKeyListener( KeyListener l )
Parameters
l
the key listener.
Description
Adds the specified key listener to receive key events from this component.

See Also
KeyEvent, KeyListener, removeKeyListener


 Component.addMouseListener

Component.addMouseListener

Syntax
public synchronized void addMouseListener( MouseListener l )
Parameters
l
the mouse listener.
Description
Adds the specified mouse listener to receive mouse events from this component.

See Also
MouseEvent, MouseListener, removeMouseListener


 Component.addMouseMotionListener

Component.addMouseMotionListener

Syntax
public synchronized void addMouseMotionListener( MouseMotionListener l )
Parameters
l
the mouse motion listener.
Description
Adds the specified mouse motion listener to receive mouse motion events from this component.

See Also
MouseMotionEvent, MouseMotionListener, removeMouseMotionListener


 Component.addNotify

Component.addNotify

Syntax
public void addNotify()
Description
Notifies this component that it has been added to a container and if a peer is required, it should be created. This method should be called by Container.add, and not by user code directly.

See Also
removeNotify


 Component.bounds

Component.bounds

Syntax
public Rectangle bounds()
Description
Note: bounds() is deprecated. As of JDK version 1.1, replaced by getBounds().


 Component.checkImage

Component.checkImage

Syntax 1
public int checkImage( Image image, ImageObserver observer )
Parameters
image
the Image object whose status is being checked.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
the bitwise inclusive OR of ImageObserver flags indicating what information about the image is currently available.
Description
Returns the status of the construction of a screen representation of the specified image.

This method does not cause the image to begin loading. An application must use the prepareImage method to force the loading of an image.

Information on the flags returned by this method can be found with the discussion of the ImageObserver interface.

See Also
prepareImage, checkImage, ImageObserver

Syntax 2
public int checkImage( Image image, int width, int height, ImageObserver observer )
Parameters
image
the Image object whose status is being checked.
width
the width of the scaled version whose status is to be checked.
height
the height of the scaled version whose status is to be checked.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
the bitwise inclusive OR of ImageObserver flags indicating what information about the image is currently available.
Description
Returns the status of the construction of a screen representation of the specified image.

This method does not cause the image to begin loading. An application must use the prepareImage method to force the loading of an image.

The checkImage method of Component calls its peer's checkImage method to calculate the flags. If this component does not yet have a peer, the component's toolkit's checkImage method is called instead.

Information on the flags returned by this method can be found with the discussion of the ImageObserver interface.

See Also
prepareImage, checkImage, _top_


 Component.contains

Component.contains

Syntax 1
public boolean contains( int x, int y )
Parameters
x
the x coordinate of the point.
y
the y coordinate of the point.
Description
Checks whether this component "contains" the specified point, where x and y are defined to be relative to the coordinate system of this component.

See Also
getComponentAt

Syntax 2
public boolean contains( Point p )
Parameters
p
the point.
Description
Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component.

See Also
getComponentAt


 Component.createImage

Component.createImage

Syntax 1
public Image createImage( ImageProducer producer )
Parameters
producer
the image producer
Returns
the image produced.
Description
Creates an image from the specified image producer.

Syntax 2
public Image createImage( int width, int height )
Parameters
width
the specified width.
height
the specified height.
Returns
an off-screen drawable image, which can be used for double buffering.
Description
Creates an off-screen drawable image to be used for double buffering.


 Component.deliverEvent

Component.deliverEvent

Syntax
public void deliverEvent( Event e )
Description
Note: deliverEvent() is deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e).


 Component.disable

Component.disable

Syntax
public void disable()
Description
Note: disable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).


 Component.disableEvents

Component.disableEvents

Syntax
protected final void disableEvents( long eventsToDisable )
Parameters
eventsToDisable
the event mask defining the event types
Description
Disables the events defined by the specified event mask parameter from being delivered to this component.

See Also
enableEvents


 Component.dispatchEvent

Component.dispatchEvent

Syntax
public final void dispatchEvent( AWTEvent e )
Parameters
e
the event
Description
Dispatches an event to this component or one of its sub components.


 Component.doLayout

Component.doLayout

Syntax
public void doLayout()
Description
Prompts the layout manager to lay out this component. This is usually called when the component (more specifically, container) is validated.

See Also
validate, LayoutManager


 Component.enable

Component.enable

Syntax 1
public void enable()
Description
Note: enable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).

Syntax 2
public void enable( boolean b )
Description
Note: enable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).


 Component.enableEvents

Component.enableEvents

Syntax
protected final void enableEvents( long eventsToEnable )
Parameters
eventsToEnable
the event mask defining the event types.
Description
Enables the events defined by the specified event mask parameter to be delivered to this component.

Event types are automatically enabled when a listener for that event type is added to the component.

This method only needs to be invoked by subclasses of Component which desire to have the specified event types delivered to processEvent regardless of whether or not a listener is registered.

See Also
processEvent, disableEvents


 Component.getAlignmentX

Component.getAlignmentX

Syntax
public float getAlignmentX()
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 Component.getAlignmentY

Component.getAlignmentY

Syntax
public float getAlignmentY()
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 Component.getBackground

Component.getBackground

Syntax
public Color getBackground()
Returns
This component's background color. If this component does not have a background color, the background color of its parent is returned.
Description
Gets the background color of this component.

See Also
setBackground


 Component.getBounds

Component.getBounds

Syntax
public Rectangle getBounds()
Returns
A rectangle indicating this component's bounds.
Description
Gets the bounds of this component in the form of a Rectangle object. The bounds specify this component's width, height, and location relative to its parent.

See Also
setBounds, getLocation, getSize


 Component.getColorModel

Component.getColorModel

Syntax
public ColorModel getColorModel()
Returns
The color model used by this component.
Description
Gets the instance of ColorModel used to display the component on the output device.

See Also
ColorModel, getColorModel, getColorModel


 Component.getComponentAt

Component.getComponentAt

Syntax 1
public Component getComponentAt( int x, int y )
Parameters
x
the x coordinate.
y
the y coordinate.
Returns
the component or subcomponent that contains the (x, y) location; null if the location is outside this component.
Description
Determines if this component or one of its immediate subcomponents contains the (x, y) location, and if so, returns the containing component. This method only looks one level deep. If the point (x, y) is inside a subcomponent that itself has subcomponents, it does not go looking down the subcomponent tree.

The locate method of Component simply returns the component itself if the (x, y) coordinate location is inside its bounding box, and null otherwise.

See Also
contains

Syntax 2
public Component getComponentAt( Point p )
Parameters
p
the point.
Description
Returns the component or subcomponent that contains the specified point.

See Also
contains


 Component.getCursor

Component.getCursor

Syntax
public Cursor getCursor()
Returns
The cursor for this component.
Description
Gets the cursor set on this component.

See Also
setCursor, Cursor


 Component.getFont

Component.getFont

Syntax
public Font getFont()
Returns
This component's font. If a font has not been set for this component, the font of its parent is returned.
Description
Gets the font of this component.

See Also
setFont


 Component.getFontMetrics

Component.getFontMetrics

Syntax
public FontMetrics getFontMetrics( Font font )
Parameters
font
The font for which font metrics is to be obtained.
font
the font.
Returns
The font metrics for font.
Description
Gets the font metrics for the specified font.

See Also
getFont, getPeer, getFontMetrics, getFontMetrics


 Component.getForeground

Component.getForeground

Syntax
public Color getForeground()
Returns
This component's foreground color. If this component does not have a foreground color, the foreground color of its parent is returned.
Description
Gets the foreground color of this component.

See Also
java.awt.Component#setForeground


 Component.getGraphics

Component.getGraphics

Syntax
public Graphics getGraphics()
Returns
A graphics context for this component, or null if it has none.
Description
Creates a graphics context for this component. This method will return null if this component is currently not on the screen.

See Also
paint


 Component.getLocale

Component.getLocale

Syntax
public Locale getLocale()
Returns
This component's locale. If this component does not have a locale, the locale of its parent is returned.
Description
Gets the locale of this component.

Exceptions
IllegalComponentStateException If the Component does not have its own locale and has not yet been added to a containment hierarchy such that the locale can be determined from the containing parent.
See Also
setLocale


 Component.getLocation

Component.getLocation

Syntax
public Point getLocation()
Returns
An instance of Point representing the top-left corner of the component's bounds in the coordinate space of the component's parent.
Description
Gets the location of this component in the form of a point specifying the component's top-left corner. The location will be relative to the parent's coordinate space.

See Also
setLocation, getLocationOnScreen


 Component.getLocationOnScreen

Component.getLocationOnScreen

Syntax
public Point getLocationOnScreen()
Returns
An instance of Point representing the top-left corner of the component's bounds in the coordinate space of the screen.
Description
Gets the location of this component in the form of a point specifying the component's top-left corner in the screen's coordinate space.

See Also
setLocation, getLocation


 Component.getMaximumSize

Component.getMaximumSize

Syntax
public Dimension getMaximumSize()
Returns
A dimension object indicating this component's maximum size.
Description
Gets the maximum size of this component.

See Also
getMinimumSize, getPreferredSize, LayoutManager


 Component.getMinimumSize

Component.getMinimumSize

Syntax
public Dimension getMinimumSize()
Returns
A dimension object indicating this component's minimum size.
Description
Gets the mininimum size of this component.

See Also
getPreferredSize, awtLayoutManager


 Component.getName

Component.getName

Syntax
public String getName()
Returns
This component's name.
Description
Gets the name of the component.

See Also
setName


 Component.getParent

Component.getParent

Syntax
public Container getParent()
Returns
The parent container of this component.
Description
Gets the parent of this component.


 Component.getPeer

Component.getPeer

Syntax
public ComponentPeer getPeer()
Description
Note: getPeer() is deprecated. As of JDK version 1.1, programs should not directly manipulate peers.


 Component.getPreferredSize

Component.getPreferredSize

Syntax
public Dimension getPreferredSize()
Returns
A dimension object indicating this component's preferred size.
Description
Gets the preferred size of this component.

See Also
getMinimumSize, LayoutManager


 Component.getSize

Component.getSize

Syntax
public Dimension getSize()
Returns
A Dimension object that indicates the size of this component.
Description
Returns the size of this component in the form of a Dimension object. The height field of the Dimension object contains this component's height, and the width field of the Dimension object contains this component's width.

See Also
setSize


 Component.getToolkit

Component.getToolkit

Syntax
public Toolkit getToolkit()
Returns
The toolkit of this component.
Description
Gets the toolkit of this component. Note that the frame that contains a component controls which toolkit is used by that component. Therefore if the component is moved from one frame to another, the toolkit it uses may change.


 Component.getTreeLock

Component.getTreeLock

Syntax
public final Object getTreeLock()
Returns
This component's locking object.
Description
Gets this component's locking object (the object that owns the thread sychronization monitor) for AWT component-tree and layout operations.


 Component.gotFocus

Component.gotFocus

Syntax
public boolean gotFocus( Event evt, Object what )
Description
Note: gotFocus() is deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).


 Component.handleEvent

Component.handleEvent

Syntax
public boolean handleEvent( Event evt )
Description
Note: handleEvent() is deprecated. As of JDK version 1.1 replaced by processEvent(AWTEvent).


 Component.hide

Component.hide

Syntax
public void hide()
Description
Note: hide() is deprecated. As of JDK version 1.1, replaced by setVisible(boolean).


 Component.imageUpdate

Component.imageUpdate

Syntax
public boolean imageUpdate( Image img, int flags, int x, int y, int w, int h )
Parameters
img
the image being observed.
infoflags
see imageUpdate for more information.
x
the x coordinate.
y
the y coordinate.
width
the width.
height
the height.
Returns
true if the flags indicate that the image is completely loaded; false otherwise.
Description
Repaints the component when the image has changed. This imageUpdate method of an ImageObserver is called when more information about an image which had been previously requested using an asynchronous routine such as the drawImage method of Graphics becomes available. See the definition of imageUpdate for more information on this method and its arguments.

The imageUpdate method of Component incrementally draws an image on the component as more of the bits of the image are available.

If the system property awt.image.incrementalDraw is missing or has the value true, the image is incrementally drawn, If the system property has any other value, then the image is not drawn until it has been completely loaded.

Also, if incremental drawing is in effect, the value of the system property awt.image.redrawrate is interpreted as an integer to give the maximum redraw rate, in milliseconds. If the system property is missing or cannot be interpreted as an integer, the redraw rate is once every 100ms.

The interpretation of the x, y, width, and height arguments depends on the value of the infoflags argument.

See Also
ImageObserver, drawImage, drawImage, drawImage, drawImage, imageUpdate


 Component.inside

Component.inside

Syntax
public boolean inside( int x, int y )
Description
Note: inside() is deprecated. As of JDK version 1.1, replaced by contains(int, int).


 Component.invalidate

Component.invalidate

Syntax
public void invalidate()
Description
Invalidates this component. This component and all parents above it are marked as needing to be laid out. This method can be called often, so it needs to execute quickly.

See Also
validate, doLayout, LayoutManager


 Component.isEnabled

Component.isEnabled

Syntax
public boolean isEnabled()
Returns
true if the component is enabled; false otherwise.
Description
Determines whether this component is enabled. An enabled component can respond to user input and generate events. Components are enabled initially by default. A component may be enabled or disabled by calling its setEnabled method.

See Also
setEnabled


 Component.isFocusTraversable

Component.isFocusTraversable

Syntax
public boolean isFocusTraversable()
Returns
true if this component is focus-traverable; false otherwise.
Description
Returns the value of a flag that indicates whether this component can be traversed using Tab or Shift-Tab keyboard focus traversal. If this method returns "false", this component may still request the keyboard focus using requestFocus(), but it will not automatically be assigned focus during tab traversal.


 Component.isShowing

Component.isShowing

Syntax
public boolean isShowing()
Returns
true if the component is showing; false otherwise.
Description
Determines whether this component is showing on screen. This means that the component must be visible, and it must be in a container that is visible and showing.

See Also
setVisible


 Component.isValid

Component.isValid

Syntax
public boolean isValid()
Returns
true if the component is valid; false otherwise.
Description
Determines whether this component is valid. Components are invalidated when they are first shown on the screen.

See Also
validate, invalidate


 Component.isVisible

Component.isVisible

Syntax
public boolean isVisible()
Returns
true if the component is visible; false otherwise.
Description
Determines whether this component is visible. Components are initially visible, with the exception of top level components such as Frame objects.

See Also
setVisible


 Component.keyDown

Component.keyDown

Syntax
public boolean keyDown( Event evt, int key )
Description
Note: keyDown() is deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).


 Component.keyUp

Component.keyUp

Syntax
public boolean keyUp( Event evt, int key )
Description
Note: keyUp() is deprecated. As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).


 Component.layout

Component.layout

Syntax
public void layout()
Description
Note: layout() is deprecated. As of JDK version 1.1, replaced by doLayout().


 Component.list

Component.list

Syntax 1
public void list()
Description
Prints a listing of this component to the standard system output stream System.out.

See Also
out

Syntax 2
public void list( PrintStream out )
Parameters
out
a print stream.
Description
Prints a listing of this component to the specified output stream.

Syntax 3
public void list( PrintStream out, int indent )
Parameters
out
a print stream.
indent
number of spaces to indent.
Description
Prints out a list, starting at the specified indention, to the specified print stream.

See Also
println

Syntax 4
public void list( PrintWriter out )
Parameters
out
The print writer to print to.
Description
Prints a listing to the specified print writer.

Syntax 5
public void list( PrintWriter out, int indent )
Parameters
out
The print writer to print to.
indent
The number of spaces to indent.
Description
Prints out a list, starting at the specified indention, to the specified print writer.

See Also
println


 Component.locate

Component.locate

Syntax
public Component locate( int x, int y )
Description
Note: locate() is deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).


 Component.location

Component.location

Syntax
public Point location()
Description
Note: location() is deprecated. As of JDK version 1.1, replaced by getLocation().


 Component.lostFocus

Component.lostFocus

Syntax
public boolean lostFocus( Event evt, Object what )
Description
Note: lostFocus() is deprecated. As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).


 Component.minimumSize

Component.minimumSize

Syntax
public Dimension minimumSize()
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize().


 Component.mouseDown

Component.mouseDown

Syntax
public boolean mouseDown( Event evt, int x, int y )
Description
Note: mouseDown() is deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).


 Component.mouseDrag

Component.mouseDrag

Syntax
public boolean mouseDrag( Event evt, int x, int y )
Description
Note: mouseDrag() is deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).


 Component.mouseEnter

Component.mouseEnter

Syntax
public boolean mouseEnter( Event evt, int x, int y )
Description
Note: mouseEnter() is deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).


 Component.mouseExit

Component.mouseExit

Syntax
public boolean mouseExit( Event evt, int x, int y )
Description
Note: mouseExit() is deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).


 Component.mouseMove

Component.mouseMove

Syntax
public boolean mouseMove( Event evt, int x, int y )
Description
Note: mouseMove() is deprecated. As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).


 Component.mouseUp

Component.mouseUp

Syntax
public boolean mouseUp( Event evt, int x, int y )
Description
Note: mouseUp() is deprecated. As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).


 Component.move

Component.move

Syntax
public void move( int x, int y )
Description
Note: move() is deprecated. As of JDK version 1.1, replaced by setLocation(int, int).


 Component.nextFocus

Component.nextFocus

Syntax
public void nextFocus()
Description
Note: nextFocus() is deprecated. As of JDK version 1.1, replaced by transferFocus().


 Component.paint

Component.paint

Syntax
public void paint( Graphics g )
Parameters
g
The graphics context to use for painting.
Description
Paints this component. This method is called when the contents of the component should be painted in response to the component first being shown or damage needing repair. The clip rectangle in the Graphics parameter will be set to the area which needs to be painted.

See Also
update


 Component.paintAll

Component.paintAll

Syntax
public void paintAll( Graphics g )
Parameters
g
the graphics context to use for painting.
Description
Paints this component and all of its subcomponents.

The origin of the graphics context, its (0, 0) coordinate point, is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component.

See Also
paint


 Component.paramString

Component.paramString

Syntax
protected String paramString()
Returns
the parameter string of this component.
Description
Returns the parameter string representing the state of this component. This string is useful for debugging.


 Component.postEvent

Component.postEvent

Syntax
public boolean postEvent( Event e )
Description
Note: postEvent() is deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).


 Component.preferredSize

Component.preferredSize

Syntax
public Dimension preferredSize()
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize().


 Component.prepareImage

Component.prepareImage

Syntax 1
public boolean prepareImage( Image image, ImageObserver observer )
Parameters
image
the Image for which to prepare a screen representation.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
true if the image has already been fully prepared; false otherwise.
Description
Prepares an image for rendering on this component. The image data is downloaded asynchronously in another thread and the appropriate screen representation of the image is generated.

Syntax 2
public boolean prepareImage( Image image, int width, int height, ImageObserver observer )
Parameters
image
the instance of Image for which to prepare a screen representation.
width
the width of the desired screen representation.
height
the height of the desired screen representation.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
true if the image has already been fully prepared; false otherwise.
Description
Prepares an image for rendering on this component at the specified width and height.

The image data is downloaded asynchronously in another thread, and an appropriately scaled screen representation of the image is generated.

See Also
ImageObserver


 Component.print

Component.print

Syntax
public void print( Graphics g )
Parameters
g
the graphics context to use for printing.
Description
Prints this component. Applications should override this method for components that must do special processing before being printed or should be printed differently than they are painted.

The default implementation of this method calls the paint method.

The origin of the graphics context, its (0, 0) coordinate point, is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component.

See Also
paint


 Component.printAll

Component.printAll

Syntax
public void printAll( Graphics g )
Parameters
g
the graphics context to use for printing.
Description
Prints this component and all of its subcomponents.

The origin of the graphics context, its (0, 0) coordinate point, is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component.

See Also
print


 Component.processComponentEvent

Component.processComponentEvent

Syntax
protected void processComponentEvent( ComponentEvent e )
Parameters
e
the component event.
Description
Processes component events occurring on this component by dispatching them to any registered ComponentListener objects.

This method is not called unless component events are enabled for this component. Component events are enabled when one of the following occurs:

  • A ComponentListener object is registered via addComponentListener.
  • Component events are enabled via enableEvents.

See Also
ComponentEvent, ComponentListener, addComponentListener, enableEvents


 Component.processEvent

Component.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events occurring on this component. By default this method calls the appropriate process<event type>Event method for the given class of event.

See Also
processComponentEvent, processFocusEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent


 Component.processFocusEvent

Component.processFocusEvent

Syntax
protected void processFocusEvent( FocusEvent e )
Parameters
e
the focus event.
Description
Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.

This method is not called unless focus events are enabled for this component. Focus events are enabled when one of the following occurs:

  • A FocusListener object is registered via addFocusListener.
  • Focus events are enabled via enableEvents.

See Also
FocusEvent, FocusListener, addFocusListener, enableEvents


 Component.processKeyEvent

Component.processKeyEvent

Syntax
protected void processKeyEvent( KeyEvent e )
Parameters
e
the key event.
Description
Processes key events occurring on this component by dispatching them to any registered KeyListener objects.

This method is not called unless key events are enabled for this component. Key events are enabled when one of the following occurs:

  • A KeyListener object is registered via addKeyListener.
  • Key events are enabled via enableEvents.

See Also
KeyEvent, KeyListener, addKeyListener, enableEvents


 Component.processMouseEvent

Component.processMouseEvent

Syntax
protected void processMouseEvent( MouseEvent e )
Parameters
e
the mouse event.
Description
Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects.

This method is not called unless mouse events are enabled for this component. Mouse events are enabled when one of the following occurs:

  • A MouseListener object is registered via addMouseListener.
  • Mouse events are enabled via enableEvents.

See Also
MouseEvent, MouseListener, addMouseListener, enableEvents


 Component.processMouseMotionEvent

Component.processMouseMotionEvent

Syntax
protected void processMouseMotionEvent( MouseEvent e )
Parameters
e
the mouse motion event.
Description
Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects.

This method is not called unless mouse motion events are enabled for this component. Mouse motion events are enabled when one of the following occurs:

  • A MouseMotionListener object is registered via addMouseMotionListener.
  • Mouse motion events are enabled via enableEvents.

See Also
MouseMotionEvent, MouseMotionListener, addMouseMotionListener, enableEvents


 Component.remove

Component.remove

Syntax
public synchronized void remove( MenuComponent popup )
Parameters
popup
the popup menu to be removed.
Description
Removes the specified popup menu from the component.

See Also
add


 Component.removeComponentListener

Component.removeComponentListener

Syntax
public synchronized void removeComponentListener( ComponentListener l )
Parameters
l
the component listener.
Description
Removes the specified component listener so that it no longer receives component events from this component.

See Also
ComponentEvent, ComponentListener, addComponentListener


 Component.removeFocusListener

Component.removeFocusListener

Syntax
public synchronized void removeFocusListener( FocusListener l )
Parameters
l
the focus listener.
Description
Removes the specified focus listener so that it no longer receives focus events from this component.

See Also
FocusEvent, FocusListener, addFocusListener


 Component.removeKeyListener

Component.removeKeyListener

Syntax
public synchronized void removeKeyListener( KeyListener l )
Parameters
l
the key listener.
Description
Removes the specified key listener so that it no longer receives key events from this component.

See Also
KeyEvent, KeyListener, addKeyListener


 Component.removeMouseListener

Component.removeMouseListener

Syntax
public synchronized void removeMouseListener( MouseListener l )
Parameters
l
the mouse listener.
Description
Removes the specified mouse listener so that it no longer receives mouse events from this component.

See Also
MouseEvent, MouseListener, addMouseListener


 Component.removeMouseMotionListener

Component.removeMouseMotionListener

Syntax
public synchronized void removeMouseMotionListener( MouseMotionListener l )
Parameters
l
the mouse motion listener.
Description
Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component.

See Also
MouseMotionEvent, MouseMotionListener, addMouseMotionListener


 Component.removeNotify

Component.removeNotify

Syntax
public void removeNotify()
Description
Notifies this component that it has been removed from its container and if a peers exists, it destroys it. This method should be called by Container.remove, and not by user code directly.

See Also
addNotify


 Component.repaint

Component.repaint

Syntax 1
public void repaint()
Description
Repaints this component.

This method causes a call to this component's update method as soon as possible.

See Also
update

Syntax 2
public void repaint( long tm )
Parameters
tm
maximum time in milliseconds before update
Description
Repaints the component. This will result in a call to update within tm milliseconds.

See Also
paint, update

Syntax 3
public void repaint( int x, int y, int width, int height )
Parameters
x
the x coordinate.
y
the y coordinate.
width
the width.
height
the height.
Description
Repaints the specified rectangle of this component.

This method causes a call to this component's update method as soon as possible.

See Also
update

Syntax 4
public void repaint( long tm, int x, int y, int width, int height )
Parameters
tm
maximum time in milliseconds before update.
x
the x coordinate.
y
the y coordinate.
width
the width.
height
the height.
Description
Repaints the specified rectangle of this component within tm milliseconds.

This method causes a call to this component's update method.

See Also
update


 Component.requestFocus

Component.requestFocus

Syntax
public void requestFocus()
Description
Requests that this component get the input focus.

This component's gotFocus method is called when this method is successful. The component must be visible on the screen for this request to be granted

See Also
FocusEvent, addFocusListener, processFocusEvent, isFocusTraversable


 Component.reshape

Component.reshape

Syntax
public void reshape( int x, int y, int width, int height )
Description
Note: reshape() is deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).


 Component.resize

Component.resize

Syntax 1
public void resize( int width, int height )
Description
Note: resize() is deprecated. As of JDK version 1.1, replaced by setSize(int, int).

Syntax 2
public void resize( Dimension d )
Description
Note: resize() is deprecated. As of JDK version 1.1, replaced by setSize(Dimension).


 Component.setBackground

Component.setBackground

Syntax
public void setBackground( Color c )
Parameters
c
The color to become this component's background color.
Description
Sets the background color of this component.

See Also
getBackground


 Component.setBounds

Component.setBounds

Syntax 1
public void setBounds( int x, int y, int width, int height )
Parameters
x
The new x-coordinate of this component.
y
The new y-coordinate of this component.
width
The new width of this component.
height
The new height of this component.
Description
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height.

See Also
getBounds, setLocation, setLocation, setSize, setSize

Syntax 2
public void setBounds( Rectangle r )
Parameters
r
The new bounding rectangle for this component.
Description
Moves and resizes this component to conform to the new bounding rectangle r. This component's new position is specified by r.x and r.y, and its new size is specified by r.width and r.height.

See Also
getBounds, setLocation, setLocation, setSize, setSize


 Component.setCursor

Component.setCursor

Syntax
public synchronized void setCursor( Cursor cursor )
Parameters
cursor
One of the constants defined by the Cursor class.
Description
Set the cursor image to a predefined cursor.

See Also
getCursor, Cursor


 Component.setEnabled

Component.setEnabled

Syntax
public void setEnabled( boolean b )
Parameters
b
If true, this component is enabled; otherwise this component is disabled.
Description
Enables or disables this component, depending on the value of the parameter b. An enabled component can respond to user input and generate events. Components are enabled initially by default.

See Also
isEnabled


 Component.setFont

Component.setFont

Syntax
public synchronized void setFont( Font f )
Parameters
f
The font to become this component's font.
Description
Sets the font of this component.

See Also
getFont


 Component.setForeground

Component.setForeground

Syntax
public void setForeground( Color c )
Parameters
c
The color to become this component's foreground color.
Description
Sets the foreground color of this component.

See Also
getForeground


 Component.setLocale

Component.setLocale

Syntax
public void setLocale( Locale l )
Parameters
l
The locale to become this component's locale.
Description
Sets the locale of this component.

See Also
getLocale


 Component.setLocation

Component.setLocation

Syntax 1
public void setLocation( int x, int y )
Parameters
x
The x-coordinate of the new location's top-left corner in the parent's coordinate space.
y
The y-coordinate of the new location's top-left corner in the parent's coordinate space.
Description
Moves this component to a new location. The top-left corner of the new location is specified by the x and y parameters in the coordinate space of this component's parent.

See Also
getLocation, setBounds

Syntax 2
public void setLocation( Point p )
Parameters
p
The point defining the top-left corner of the new location, given in the coordinate space of this component's parent.
Description
Moves this component to a new location. The top-left corner of the new location is specified by point p. Point p is given in the parent's coordinate space.

See Also
getLocation, setBounds


 Component.setName

Component.setName

Syntax
public void setName( String name )
Parameters
name
The string that is to be this component's name.
Description
Sets the name of the component to the specified string.

See Also
getName


 Component.setSize

Component.setSize

Syntax 1
public void setSize( int width, int height )
Parameters
width
The new width of this component in pixels.
height
The new height of this component in pixels.
Description
Resizes this component so that it has width width and height.

See Also
getSize, setBounds

Syntax 2
public void setSize( Dimension d )
Parameters
d
The dimension specifying the new size of this component.
Description
Resizes this component so that it has width d.width and height d.height.

See Also
setSize, setBounds


 Component.setVisible

Component.setVisible

Syntax
public void setVisible( boolean b )
Parameters
b
If true, shows this component; otherwise, hides this component.
Description
Shows or hides this component depending on the value of parameter b.

See Also
isVisible


 Component.show

Component.show

Syntax 1
public void show()
Description
Note: show() is deprecated. As of JDK version 1.1, replaced by setVisible(boolean).

Syntax 2
public void show( boolean b )
Description
Note: show() is deprecated. As of JDK version 1.1, replaced by setVisible(boolean).


 Component.size

Component.size

Syntax
public Dimension size()
Description
Note: size() is deprecated. As of JDK version 1.1, replaced by getSize().


 Component.toString

Component.toString

Syntax
public String toString()
Returns
a string representation of this component.
Description
Returns a string representation of this component and its values.

Overrides
toString in class Object


 Component.transferFocus

Component.transferFocus

Syntax
public void transferFocus()
Description
Transfers the focus to the next component.

See Also
requestFocus, gotFocus


 Component.update

Component.update

Syntax
public void update( Graphics g )
Parameters
g
the specified context to use for updating.
Description
Updates this component.

The AWT calls the update method in response to a call to repaint. The appearance of the component on the screen has not changed since the last call to update or paint. You can assume that the background is not cleared.

The updatemethod of Component does the following:

  • Clears this component by filling it with the background color.
  • Sets the color of the graphics context to be the foreground color of this component.
  • Calls this component's paint method to completely redraw this component.

The origin of the graphics context, its (0, 0) coordinate point, is the top-left corner of this component. The clipping region of the graphics context is the bounding rectangle of this component.

See Also
paint, repaint


 Component.validate

Component.validate

Syntax
public void validate()
Description
Ensures that this component has a valid layout. This method is primarily intended to operate on instances of Container.

See Also
invalidate, doLayout, LayoutManager, validate


 Class Container

Class java.awt.Container

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container

public abstract class Container
extends Component

A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.

Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).

See Also:
add, getComponent, LayoutManager


 Container Members

Container Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Container() | Constructs a new Container.

Methods
Name | Description
add(Component) | Adds the specified component to the end of this container.
add(Component, int) | Adds the specified component to this container at the given position.
add(Component, Object) | Adds the specified component to the end of this container.
add(Component, Object, int) | Adds the specified component to this container with the specified constraints at the specified index.
add(String, Component) | Adds the specified component to this container.
addContainerListener(ContainerListener) | Adds the specified container listener to receive container events from this container.
addImpl(Component, Object, int) | Adds the specified component to this container at the specified index.
addNotify() | Notifies the container to create a peer.
countComponents() | Deprecated.
deliverEvent(Event) | Deprecated.
doLayout() | Causes this container to lay out its components.
getAlignmentX() | Returns the alignment along the x axis.
getAlignmentY() | Returns the alignment along the y axis.
getComponent(int) | Gets the nth component in this container.
getComponentAt(int, int) | Locates the component that contains the x,y position.
getComponentAt(Point) | Gets the component that contains the specified point.
getComponentCount() | Gets the number of components in this panel.
getComponents() | Gets all the components in this container.
getInsets() | Determines the insets of this container, which indicate the size of the container's border.
getLayout() | Gets the layout manager for this container.
getMaximumSize() | Returns the maximum size of this container.
getMinimumSize() | Returns the minimum size of this container.
getPreferredSize() | Returns the preferred size of this container.
insets() | Deprecated.
invalidate() | Invalidates the container.
isAncestorOf(Component) | Checks if the component is contained in the component hierarchy of this container.
layout() | Deprecated.
list(PrintStream, int) | Prints a listing of this container to the specified output stream.
list(PrintWriter, int) | Prints out a list, starting at the specified indention, to the specified print writer.
locate(int, int) | Deprecated.
minimumSize() | Deprecated.
paint(Graphics) | Paints the container.
paintComponents(Graphics) | Paints each of the components in this container.
paramString() | Returns the parameter string representing the state of this container.
preferredSize() | Deprecated.
print(Graphics) | Prints the container.
printComponents(Graphics) | Prints each of the components in this container.
processContainerEvent(ContainerEvent) | Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.
processEvent(AWTEvent) | Processes events on this container.
remove(Component) | Removes the specified component from this container.
remove(int) | Removes the component, specified by index, from this container.
removeAll() | Removes all the components from this container.
removeContainerListener(ContainerListener) | Removes the specified container listener so it no longer receives container events from this container.
removeNotify() | Notifies this container and all of its subcomponents to remove their peers.
setLayout(LayoutManager) | Sets the layout manager for this container.
validate() | Validates this container and all of its subcomponents.
validateTree() | Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).


 Container.Container

Container.Container

Syntax
protected Container()
Description
Constructs a new Container. Containers can be extended directly, but are lightweight in this case and must be contained by a parent somewhere higher up in the component tree that is native. (such as Frame for example).


 Container.add

Container.add

Syntax 1
public Component add( Component comp )
Parameters
comp
the component to be added.
Returns
the component argument.
Description
Adds the specified component to the end of this container.

Syntax 2
public Component add( String name, Component comp )
Description
Adds the specified component to this container. It is strongly advised to use the 1.1 method, add(Component, Object), in place of this method.

Syntax 3
public Component add( Component comp, int index )
Parameters
comp
the component to be added.
index
the position at which to insert the component, or -1 to insert the component at the end.
Returns
the component comp
Description
Adds the specified component to this container at the given position.

See Also
remove

Syntax 4
public void add( Component comp, Object constraints )
Parameters
comp
the component to be added
constraints
an object expressing layout contraints for this component
Description
Adds the specified component to the end of this container. Also notifies the layout manager to add the component to this container's layout using the specified constraints object.

See Also
LayoutManager

Syntax 5
public void add( Component comp, Object constraints, int index )
Parameters
comp
the component to be added
constraints
an object expressing layout contraints for this
index
the position in the container's list at which to insert the component. -1 means insert at the end. component
Description
Adds the specified component to this container with the specified constraints at the specified index. Also notifies the layout manager to add the component to the this container's layout using the specified constraints object.

See Also
remove, LayoutManager


 Container.addContainerListener

Container.addContainerListener

Syntax
public synchronized void addContainerListener( ContainerListener l )
Parameters
l
the container listener
Description
Adds the specified container listener to receive container events from this container.


 Container.addImpl

Container.addImpl

Syntax
protected void addImpl( Component comp, Object constraints, int index )
Parameters
comp
the component to be added.
constraints
an object expressing layout contraints for this component.
index
the position in the container's list at which to insert the component, where -1 means insert at the end.
Description
Adds the specified component to this container at the specified index. This method also notifies the layout manager to add the component to this container's layout using the specified constraints object.

This is the method to override if a program needs to track every add request to a container. An overriding method should usually include a call to the superclass's version of the method:

super.addImpl(comp, constraints, index)

See Also
add, add, add, LayoutManager


 Container.addNotify

Container.addNotify

Syntax
public void addNotify()
Description
Notifies the container to create a peer. It will also notify the components contained in this container. This method should be called by Container.add, and not by user code directly.

Overrides
addNotify in class Component
See Also
removeNotify


 Container.countComponents

Container.countComponents

Syntax
public int countComponents()
Description
Note: countComponents() is deprecated. As of JDK version 1.1, replaced by getComponentCount().


 Container.deliverEvent

Container.deliverEvent

Syntax
public void deliverEvent( Event e )
Description
Note: deliverEvent() is deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)

Overrides
deliverEvent in class Component


 Container.doLayout

Container.doLayout

Syntax
public void doLayout()
Description
Causes this container to lay out its components. Most programs should not call this method directly, but should invoke the validate method instead.

Overrides
doLayout in class Component
See Also
layoutContainer, setLayout, validate


 Container.getAlignmentX

Container.getAlignmentX

Syntax
public float getAlignmentX()
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.

Overrides
getAlignmentX in class Component


 Container.getAlignmentY

Container.getAlignmentY

Syntax
public float getAlignmentY()
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.

Overrides
getAlignmentY in class Component


 Container.getComponent

Container.getComponent

Syntax
public Component getComponent( int n )
Parameters
n
the index of the component to get.
Returns
the nth component in this container.
Description
Gets the nth component in this container.

Exceptions
ArrayIndexOutOfBoundsException if the nth value does not exist.


 Container.getComponentAt

Container.getComponentAt

Syntax
public Component getComponentAt( int x, int y )
Parameters
x
the x coordinate
y
the y coordinate
Returns
null if the component does not contain the position. If there is no child component at the requested point and the point is within the bounds of the container the container itself is returned; otherwise the top-most child is returned.
Description
Locates the component that contains the x,y position. The top-most child component is returned in the case where there is overlap in the components. This is determined by finding the component closest to the index 0 that claims to contain the given point via Component.contains().

Overrides
getComponentAt in class Component
See Also
contains


 Container.getComponentAt

Container.getComponentAt

Syntax
public Component getComponentAt( Point p )
Parameters
p
the point.
Returns
returns the component that contains the point, or null if the component does not contain the point.
Description
Gets the component that contains the specified point.

Overrides
getComponentAt in class Component
See Also
contains


 Container.getComponentCount

Container.getComponentCount

Syntax
public int getComponentCount()
Returns
the number of components in this panel.
Description
Gets the number of components in this panel.

See Also
getComponent


 Container.getComponents

Container.getComponents

Syntax
public Component[] getComponents()
Returns
an array of all the components in this container.
Description
Gets all the components in this container.


 Container.getInsets

Container.getInsets

Syntax
public Insets getInsets()
Returns
the insets of this container.
Description
Determines the insets of this container, which indicate the size of the container's border.

A Frame object, for example, has a top inset that corresponds to the height of the frame's title bar.

See Also
Insets, LayoutManager


 Container.getLayout

Container.getLayout

Syntax
public LayoutManager getLayout()
Description
Gets the layout manager for this container.

See Also
doLayout, setLayout


 Container.getMaximumSize

Container.getMaximumSize

Syntax
public Dimension getMaximumSize()
Description
Returns the maximum size of this container.

Overrides
getMaximumSize in class Component
See Also
getPreferredSize


 Container.getMinimumSize

Container.getMinimumSize

Syntax
public Dimension getMinimumSize()
Returns
an instance of Dimension that represents the minimum size of this container.
Description
Returns the minimum size of this container.

Overrides
getMinimumSize in class Component
See Also
getPreferredSize, getLayout, minimumLayoutSize, getMinimumSize


 Container.getPreferredSize

Container.getPreferredSize

Syntax
public Dimension getPreferredSize()
Returns
an instance of Dimension that represents the preferred size of this container.
Description
Returns the preferred size of this container.

Overrides
getPreferredSize in class Component
See Also
getMinimumSize, getLayout, preferredLayoutSize, getPreferredSize


 Container.insets

Container.insets

Syntax
public Insets insets()
Description
Note: insets() is deprecated. As of JDK version 1.1, replaced by getInsets().


 Container.invalidate

Container.invalidate

Syntax
public void invalidate()
Description
Invalidates the container. The container and all parents above it are marked as needing to be laid out. This method can be called often, so it needs to execute quickly.

Overrides
invalidate in class Component
See Also
validate, layout, LayoutManager


 Container.isAncestorOf

Container.isAncestorOf

Syntax
public boolean isAncestorOf( Component c )
Parameters
c
the component
Returns
true if it is an ancestor; true otherwise.
Description
Checks if the component is contained in the component hierarchy of this container.


 Container.layout

Container.layout

Syntax
public void layout()
Description
Note: layout() is deprecated. As of JDK version 1.1, replaced by doLayout().

Overrides
layout in class Component


 Container.list

Container.list

Syntax 1
public void list( PrintStream out, int indent )
Parameters
out
a print stream.
indent
the number of spaces to indent.
Description
Prints a listing of this container to the specified output stream. The listing starts at the specified indentation.

Overrides
list in class Component
See Also
list

Syntax 2
public void list( PrintWriter out, int indent )
Description
Prints out a list, starting at the specified indention, to the specified print writer.

Overrides
list in class Component


 Container.locate

Container.locate

Syntax
public Component locate( int x, int y )
Description
Note: locate() is deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).

Overrides
locate in class Component


 Container.minimumSize

Container.minimumSize

Syntax
public Dimension minimumSize()
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Overrides
minimumSize in class Component


 Container.paint

Container.paint

Syntax
public void paint( Graphics g )
Parameters
g
the specified Graphics window
Description
Paints the container. This forwards the paint to any lightweight components that are children of this container. If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, paint() will not be forwarded to that child.

Overrides
paint in class Component
See Also
update


 Container.paintComponents

Container.paintComponents

Syntax
public void paintComponents( Graphics g )
Parameters
g
the graphics context.
Description
Paints each of the components in this container.

See Also
paint, paintAll


 Container.paramString

Container.paramString

Syntax
protected String paramString()
Returns
the parameter string of this container.
Description
Returns the parameter string representing the state of this container. This string is useful for debugging.

Overrides
paramString in class Component


 Container.preferredSize

Container.preferredSize

Syntax
public Dimension preferredSize()
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Overrides
preferredSize in class Component


 Container.print

Container.print

Syntax
public void print( Graphics g )
Parameters
g
the specified Graphics window
Description
Prints the container. This forwards the print to any lightweight components that are children of this container. If this method is reimplemented, super.print(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, print() will not be forwarded to that child.

Overrides
print in class Component
See Also
update


 Container.printComponents

Container.printComponents

Syntax
public void printComponents( Graphics g )
Parameters
g
the graphics context.
Description
Prints each of the components in this container.

See Also
print, printAll


 Container.processContainerEvent

Container.processContainerEvent

Syntax
protected void processContainerEvent( ContainerEvent e )
Parameters
e
the container event
Description
Processes container events occurring on this container by dispatching them to any registered ContainerListener objects. NOTE: This method will not be called unless container events are enabled for this component; this happens when one of the following occurs: a) A ContainerListener object is registered via addContainerListener() b) Container events are enabled via enableEvents()

See Also
enableEvents


 Container.processEvent

Container.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event
Description
Processes events on this container. If the event is a ContainerEvent, it invokes the processContainerEvent method, else it invokes its superclass's processEvent.

Overrides
processEvent in class Component


 Container.remove

Container.remove

Syntax 1
public void remove( int index )
Parameters
index
the index of the component to be removed.
Description
Removes the component, specified by index, from this container.

See Also
add

Syntax 2
public void remove( Component comp )
Parameters
comp
the component to be removed
Description
Removes the specified component from this container.

See Also
add


 Container.removeAll

Container.removeAll

Syntax
public void removeAll()
Description
Removes all the components from this container.

See Also
add, remove


 Container.removeContainerListener

Container.removeContainerListener

Syntax
public void removeContainerListener( ContainerListener l )
Parameters
l
the container listener
Description
Removes the specified container listener so it no longer receives container events from this container.


 Container.removeNotify

Container.removeNotify

Syntax
public void removeNotify()
Description
Notifies this container and all of its subcomponents to remove their peers. This method should be invoked by the container's remove method, and not directly by user code.

Overrides
removeNotify in class Component
See Also
remove, remove


 Container.setLayout

Container.setLayout

Syntax
public void setLayout( LayoutManager mgr )
Parameters
mgr
the specified layout manager
Description
Sets the layout manager for this container.

See Also
doLayout, getLayout


 Container.validate

Container.validate

Syntax
public void validate()
Description
Validates this container and all of its subcomponents.

AWT uses validate to cause a container to lay out its subcomponents again after the components it contains have been added to or modified.

Overrides
validate in class Component
See Also
validate, invalidate


 Container.validateTree

Container.validateTree

Syntax
protected void validateTree()
Description
Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid). Synchronization should be provided by the method that calls this one: validate.


 Class Cursor

Class java.awt.Cursor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Cursor

public class Cursor
extends Object
implements Serializable

A class to encapsulate the bitmap representation of the mouse cursor.

See Also:
setCursor


 Cursor Members

Cursor Members

Class Overview | This Package | All Packages

Fields
Name | Description
CROSSHAIR_CURSOR | The crosshair cursor type.
DEFAULT_CURSOR | The default cursor type (gets set if no cursor is defined).
E_RESIZE_CURSOR | The east-resize cursor type.
HAND_CURSOR | The hand cursor type.
MOVE_CURSOR | The move cursor type.
N_RESIZE_CURSOR | The north-resize cursor type.
NE_RESIZE_CURSOR | The north-east-resize cursor type.
NW_RESIZE_CURSOR | The north-west-resize cursor type.
predefined |
S_RESIZE_CURSOR | The south-resize cursor type.
SE_RESIZE_CURSOR | The south-east-resize cursor type.
SW_RESIZE_CURSOR | The south-west-resize cursor type.
TEXT_CURSOR | The text cursor type.
W_RESIZE_CURSOR | The west-resize cursor type.
WAIT_CURSOR | The wait cursor type.

Constructors
Name | Description
Cursor(int) | Creates a new cursor object with the specified type.

Methods
Name | Description
getDefaultCursor() | Return the system default cursor.
getPredefinedCursor(int) | Returns a cursor object with the specified predefined type.
getType() | Returns the type for this cursor.


 Cursor.CROSSHAIR_CURSOR

Cursor.CROSSHAIR_CURSOR

Syntax
public static final int CROSSHAIR_CURSOR
Description
The crosshair cursor type.


 Cursor.DEFAULT_CURSOR

Cursor.DEFAULT_CURSOR

Syntax
public static final int DEFAULT_CURSOR
Description
The default cursor type (gets set if no cursor is defined).


 Cursor.E_RESIZE_CURSOR

Cursor.E_RESIZE_CURSOR

Syntax
public static final int E_RESIZE_CURSOR
Description
The east-resize cursor type.


 Cursor.HAND_CURSOR

Cursor.HAND_CURSOR

Syntax
public static final int HAND_CURSOR
Description
The hand cursor type.


 Cursor.MOVE_CURSOR

Cursor.MOVE_CURSOR

Syntax
public static final int MOVE_CURSOR
Description
The move cursor type.


 Cursor.N_RESIZE_CURSOR

Cursor.N_RESIZE_CURSOR

Syntax
public static final int N_RESIZE_CURSOR
Description
The north-resize cursor type.


 Cursor.NE_RESIZE_CURSOR

Cursor.NE_RESIZE_CURSOR

Syntax
public static final int NE_RESIZE_CURSOR
Description
The north-east-resize cursor type.


 Cursor.NW_RESIZE_CURSOR

Cursor.NW_RESIZE_CURSOR

Syntax
public static final int NW_RESIZE_CURSOR
Description
The north-west-resize cursor type.


 Cursor.predefined

Cursor.predefined

Syntax
protected static Cursor predefined[]


 Cursor.S_RESIZE_CURSOR

Cursor.S_RESIZE_CURSOR

Syntax
public static final int S_RESIZE_CURSOR
Description
The south-resize cursor type.


 Cursor.SE_RESIZE_CURSOR

Cursor.SE_RESIZE_CURSOR

Syntax
public static final int SE_RESIZE_CURSOR
Description
The south-east-resize cursor type.


 Cursor.SW_RESIZE_CURSOR

Cursor.SW_RESIZE_CURSOR

Syntax
public static final int SW_RESIZE_CURSOR
Description
The south-west-resize cursor type.


 Cursor.TEXT_CURSOR

Cursor.TEXT_CURSOR

Syntax
public static final int TEXT_CURSOR
Description
The text cursor type.


 Cursor.W_RESIZE_CURSOR

Cursor.W_RESIZE_CURSOR

Syntax
public static final int W_RESIZE_CURSOR
Description
The west-resize cursor type.


 Cursor.WAIT_CURSOR

Cursor.WAIT_CURSOR

Syntax
public static final int WAIT_CURSOR
Description
The wait cursor type.


 Cursor.Cursor

Cursor.Cursor

Syntax
public Cursor( int type )
Parameters
type
the type of cursor
Description
Creates a new cursor object with the specified type.


 Cursor.getDefaultCursor

Cursor.getDefaultCursor

Syntax
public static Cursor getDefaultCursor()
Description
Return the system default cursor.


 Cursor.getPredefinedCursor

Cursor.getPredefinedCursor

Syntax
public static Cursor getPredefinedCursor( int type )
Parameters
type
the type of predefined cursor
Description
Returns a cursor object with the specified predefined type.


 Cursor.getType

Cursor.getType

Syntax
public int getType()
Description
Returns the type for this cursor.


 Class Dialog

Class java.awt.Dialog

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Window
                           |
                           +----java.awt.Dialog

public class Dialog
extends Window

A class that produces a dialog - a window that takes input from the user. The default layout for a dialog is BorderLayout.

Dialogs are capable of generating the following window events: WindowOpened, WindowClosing, WindowClosed, WindowActivated, WindowDeactivated.

See Also:
WindowEvent, addWindowListener


 Dialog Members

Dialog Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Dialog(Frame) | Constructs an initially invisible Dialog with an empty title.
Dialog(Frame, boolean) | Constructs an initially invisible Dialog with an empty title.
Dialog(Frame, String) | Constructs an initially invisible Dialog with a title.
Dialog(Frame, String, boolean) | Constructs an initially invisible Dialog with a title.

Methods
Name | Description
addNotify() | Creates the dialog's peer.
getTitle() | Gets the title of the dialog.
isModal() | Indicates whether the dialog is modal.
isResizable() | Indicates whether this dialog window is resizable.
paramString() | Returns the parameter string representing the state of this dialog window.
setModal(boolean) | Specifies whether this dialog is modal.
setResizable(boolean) | Sets the resizable flag.
setTitle(String) | Sets the title of the Dialog.
show() | Shows the dialog.


 Dialog.Dialog

Dialog.Dialog

Syntax 1
public Dialog( Frame parent )
Parameters
parent
the owner of the dialog
Description
Constructs an initially invisible Dialog with an empty title.

See Also
setSize, setVisible

Syntax 2
public Dialog( Frame parent, boolean modal )
Parameters
parent
the owner of the dialog
modal
if true, dialog blocks input to the parent window when shown
Description
Constructs an initially invisible Dialog with an empty title. A modal Dialog grabs all the input to the parent frame from the user.

Syntax 3
public Dialog( Frame parent, String title )
Parameters
parent
the owner of the dialog
title
the title of the dialog
Description
Constructs an initially invisible Dialog with a title.

See Also
setSize, setVisible

Syntax 4
public Dialog( Frame parent, String title, boolean modal )
Parameters
parent
the owner of the dialog
title
the title of the dialog
modal
if true, dialog blocks input to the parent window when shown
Description
Constructs an initially invisible Dialog with a title. A modal Dialog grabs all the input to the parent frame from the user.

See Also
setSize, setVisible


 Dialog.addNotify

Dialog.addNotify

Syntax
public void addNotify()
Description
Creates the dialog's peer. The peer allows us to change the appearance of the frame without changing its functionality.

Overrides
addNotify in class Window


 Dialog.getTitle

Dialog.getTitle

Syntax
public String getTitle()
Returns
the title of this dialog window.
Description
Gets the title of the dialog.

See Also
setTitle


 Dialog.isModal

Dialog.isModal

Syntax
public boolean isModal()
Returns
true if this dialog window is modal; false otherwise.
Description
Indicates whether the dialog is modal. A modal dialog grabs all input from the user.

See Also
setModal


 Dialog.isResizable

Dialog.isResizable

Syntax
public boolean isResizable()
Returns
true if the user can resize the dialog; false otherwise.
Description
Indicates whether this dialog window is resizable.

See Also
setResizable


 Dialog.paramString

Dialog.paramString

Syntax
protected String paramString()
Returns
the parameter string of this dialog window.
Description
Returns the parameter string representing the state of this dialog window. This string is useful for debugging.

Overrides
paramString in class Container


 Dialog.setModal

Dialog.setModal

Syntax
public void setModal( boolean b )
Description
Specifies whether this dialog is modal. A modal Dialog grabs all the input to the parent frame from the user.

See Also
isModal


 Dialog.setResizable

Dialog.setResizable

Syntax
public synchronized void setResizable( boolean resizable )
Parameters
resizable
true if the user can resize this dialog; false otherwise.
Description
Sets the resizable flag.

See Also
isResizable


 Dialog.setTitle

Dialog.setTitle

Syntax
public synchronized void setTitle( String title )
Parameters
title
the new title being given to the dialog
Description
Sets the title of the Dialog.

See Also
getTitle


 Dialog.show

Dialog.show

Syntax
public void show()
Description
Shows the dialog. This will bring the dialog to the front if the dialog is already visible. If the dialog is modal, this call will block input to the parent window until the dialog is taken down by calling hide or dispose. It is permissible to show modal dialogs from the event dispatching thread because the toolkit will ensure that another dispatching thread will run while the one which invoked show is blocked.

Overrides
show in class Window
See Also
hide


 Class Dimension

Class java.awt.Dimension

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Dimension

public class Dimension
extends Object
implements Serializable

The Dimension class encapsulates the width and height of a component in a single object. The class is associated with certain properties of components. Several methods defined by the Component class and the LayoutManager interface return a Dimension object.

Normally the values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

See Also:
Component, LayoutManager


 Dimension Members

Dimension Members

Class Overview | This Package | All Packages

Fields
Name | Description
height | The height dimension.
width | The width dimension.

Constructors
Name | Description
Dimension() | Creates an instance of Dimension with a width of zero and a height of zero.
Dimension(Dimension) | Creates an instance of Dimension whose width and height are the same as for the specified dimension.
Dimension(int, int) | Constructs a Dimension and initializes it to the specified width and specified height.

Methods
Name | Description
equals(Object) | Checks whether two dimension objects have equal values.
getSize() | Gets the size of this Dimension object.
setSize(Dimension) | Set the size of this Dimension object to the specified size.
setSize(int, int) | Set the size of this Dimension object to the specified width and height.
toString() | Returns a string that represents this Dimension object's values.


 Dimension.height

Dimension.height

Syntax
public int height
Description
The height dimension.


 Dimension.width

Dimension.width

Syntax
public int width
Description
The width dimension.


 Dimension.Dimension

Dimension.Dimension

Syntax 1
public Dimension()
Description
Creates an instance of Dimension with a width of zero and a height of zero.

Syntax 2
public Dimension( Dimension d )
Parameters
d
the specified dimension for the width and height values.
Description
Creates an instance of Dimension whose width and height are the same as for the specified dimension.

Syntax 3
public Dimension( int width, int height )
Parameters
width
the specified width dimension
height
the specified height dimension
Description
Constructs a Dimension and initializes it to the specified width and specified height.


 Dimension.equals

Dimension.equals

Syntax
public boolean equals( Object obj )
Description
Checks whether two dimension objects have equal values.

Overrides
equals in class Object


 Dimension.getSize

Dimension.getSize

Syntax
public Dimension getSize()
Returns
the size of this dimension, a new instance of Dimension with the same width and height.
Description
Gets the size of this Dimension object. This method is included for completeness, to parallel the getSize method defined by Component.

See Also
setSize, getSize


 Dimension.setSize

Dimension.setSize

Syntax 1
public void setSize( Dimension d )
Parameters
d
the new size for this Dimension object.
Description
Set the size of this Dimension object to the specified size. This method is included for completeness, to parallel the setSize method defined by Component.

See Also
getSize, setSize

Syntax 2
public void setSize( int width, int height )
Parameters
width
the new width for this Dimension object.
height
the new height for this Dimension object.
Description
Set the size of this Dimension object to the specified width and height. This method is included for completeness, to parallel the setSize method defined by Component.

See Also
getSize, setSize


 Dimension.toString

Dimension.toString

Syntax
public String toString()
Returns
a string representation of this dimension, including the values of width and height.
Description
Returns a string that represents this Dimension object's values.

Overrides
toString in class Object


 Class Event

Class java.awt.Event

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Event

public class Event
extends Object
implements Serializable

Event is a platform-independent class that encapsulates events from the platform's Graphical User Interface in the Java 1.0 event model. In Java 1.1 and later versions, the Event class is maintained only for backwards compatibilty. The information in this class description is provided to assist programmers in converting Java 1.0 programs to the new event model.

In the Java 1.0 event model, an event contains an id field that indicates what type of event it is and which other Event variables are relevant for the event.

For keyboard events, key contains a value indicating which key was activated, and modifiers contains the modifiers for that event. For the KEY_PRESS and KEY_RELEASE event ids, the value of key is the unicode character code for the key. For KEY_ACTION and KEY_ACTION_RELEASE, the value of key is one of the defined action-key identifiers in the Event class (PGUP, PGDN, F1, F2, etc).


 Event Members

Event Members

Class Overview | This Package | All Packages

Fields
Name | Description
ACTION_EVENT | This event indicates that the user wants some action to occur.
ALT_MASK | This flag indicates that the Alt key was down when the event occurred.
arg | An arbitrary argument of the event.
BACK_SPACE | The BackSpace key.
CAPS_LOCK | The Caps Lock key, a non-ASCII action key.
clickCount | For MOUSE_DOWN events, this field indicates the number of consecutive clicks.
CTRL_MASK | This flag indicates that the Control key was down when the event occurred.
DELETE | The Delete key.
DOWN | The Down Arrow key, a non-ASCII action key.
END | The End key, a non-ASCII action key.
ENTER | The Enter key.
ESCAPE | The Escape key.
evt | The next event.
F1 | The F1 function key, a non-ASCII action key.
F10 | The F10 function key, a non-ASCII action key.
F11 | The F11 function key, a non-ASCII action key.
F12 | The F12 function key, a non-ASCII action key.
F2 | The F2 function key, a non-ASCII action key.
F3 | The F3 function key, a non-ASCII action key.
F4 | The F4 function key, a non-ASCII action key.
F5 | The F5 function key, a non-ASCII action key.
F6 | The F6 function key, a non-ASCII action key.
F7 | The F7 function key, a non-ASCII action key.
F8 | The F8 function key, a non-ASCII action key.
F9 | The F9 function key, a non-ASCII action key.
GOT_FOCUS | A component gained the focus.
HOME | The Home key, a non-ASCII action key.
id | Indicates which type of event the event is, and which other Event variables are relevant for the event.
INSERT | The Insert key, a non-ASCII action key.
key | The key code of the key that was pressed in a keyboard event.
KEY_ACTION | The user has pressed a non-ASCII action key.
KEY_ACTION_RELEASE | The user has released a non-ASCII action key.
KEY_PRESS | The user has pressed a normal key.
KEY_RELEASE | The user has released a normal key.
LEFT | The Left Arrow key, a non-ASCII action key.
LIST_DESELECT | An item in a list has been deselected.
LIST_SELECT | An item in a list has been selected.
LOAD_FILE | A file loading event.
LOST_FOCUS | A component lost the focus.
META_MASK | This flag indicates that the Meta key was down when the event occurred.
modifiers | The state of the modifier keys.
MOUSE_DOWN | The user has pressed the mouse button.
MOUSE_DRAG | The user has moved the mouse with a button pressed.
MOUSE_ENTER | The mouse has entered a component.
MOUSE_EXIT | The mouse has exited a component.
MOUSE_MOVE | The mouse has moved with no button pressed.
MOUSE_UP | The user has released the mouse button.
NUM_LOCK | The Num Lock key, a non-ASCII action key.
PAUSE | The Pause key, a non-ASCII action key.
PGDN | The Page Down key, a non-ASCII action key.
PGUP | The Page Up key, a non-ASCII action key.
PRINT_SCREEN | The Print Screen key, a non-ASCII action key.
RIGHT | The Right Arrow key, a non-ASCII action key.
SAVE_FILE | A file saving event.
SCROLL_ABSOLUTE | The user has moved the bubble (thumb) in a scroll bar, moving to an "absolute" position, rather than to an offset from the last postion.
SCROLL_BEGIN | The scroll begin event.
SCROLL_END | The scroll end event.
SCROLL_LINE_DOWN | The user has activated the line down area of a scroll bar.
SCROLL_LINE_UP | The user has activated the line up area of a scroll bar.
SCROLL_LOCK | The Scroll Lock key, a non-ASCII action key.
SCROLL_PAGE_DOWN | The user has activated the page down area of a scroll bar.
SCROLL_PAGE_UP | The user has activated the page up area of a scroll bar.
SHIFT_MASK | This flag indicates that the Shift key was down when the event occurred.
TAB | The Tab key.
target | The target component.
UP | The Up Arrow key, a non-ASCII action key.
when | The time stamp.
WINDOW_DEICONIFY | The user has asked the window manager to de-iconify the window.
WINDOW_DESTROY | The user has asked the window manager to kill the window.
WINDOW_EXPOSE | The user has asked the window manager to expose the window.
WINDOW_ICONIFY | The user has asked the window manager to iconify the window.
WINDOW_MOVED | The user has asked the window manager to move the window.
x | The x coordinate of the event.
y | The y coordinate of the event.

Constructors
Name | Description
Event(Object, int, Object) | Creates an instance of Event with the specified target component, event type, and argument.
Event(Object, long, int, int, int, int, int) | Creates an instance of Event, with the specified target component, time stamp, event type, x and y coordinates, keyboard key, state of the modifier keys, and an argument set to null.
Event(Object, long, int, int, int, int, int, Object) | Creates an instance of Event with the specified target component, time stamp, event type, x and y coordinates, keyboard key, state of the modifier keys, and argument.

Methods
Name | Description
controlDown() | Checks if the Control key is down.
metaDown() | Checks if the Meta key is down.
paramString() | Returns the parameter string representing this event.
shiftDown() | Checks if the Shift key is down.
toString() | Returns a representation of this event's values as a string.
translate(int, int) | Translates this event so that its x and y coordinates are increased by dx and dy, respectively.


 Event.ACTION_EVENT

Event.ACTION_EVENT

Syntax
public static final int ACTION_EVENT
Description
This event indicates that the user wants some action to occur.


 Event.ALT_MASK

Event.ALT_MASK

Syntax
public static final int ALT_MASK
Description
This flag indicates that the Alt key was down when the event occurred. For mouse events, this flag indicates that the middle mouse button was pressed or released.


 Event.arg

Event.arg

Syntax
public Object arg
Description
An arbitrary argument of the event. The value of this field depends on the type of event.


 Event.BACK_SPACE

Event.BACK_SPACE

Syntax
public static final int BACK_SPACE
Description
The BackSpace key.


 Event.CAPS_LOCK

Event.CAPS_LOCK

Syntax
public static final int CAPS_LOCK
Description
The Caps Lock key, a non-ASCII action key.


 Event.clickCount

Event.clickCount

Syntax
public int clickCount
Description
For MOUSE_DOWN events, this field indicates the number of consecutive clicks. For other events, its value is 0.


 Event.CTRL_MASK

Event.CTRL_MASK

Syntax
public static final int CTRL_MASK
Description
This flag indicates that the Control key was down when the event occurred.


 Event.DELETE

Event.DELETE

Syntax
public static final int DELETE
Description
The Delete key.


 Event.DOWN

Event.DOWN

Syntax
public static final int DOWN
Description
The Down Arrow key, a non-ASCII action key.


 Event.END

Event.END

Syntax
public static final int END
Description
The End key, a non-ASCII action key.


 Event.ENTER

Event.ENTER

Syntax
public static final int ENTER
Description
The Enter key.


 Event.ESCAPE

Event.ESCAPE

Syntax
public static final int ESCAPE
Description
The Escape key.


 Event.evt

Event.evt

Syntax
public Event evt
Description
The next event. This field is set when putting events into a linked list.


 Event.F1

Event.F1

Syntax
public static final int F1
Description
The F1 function key, a non-ASCII action key.


 Event.F10

Event.F10

Syntax
public static final int F10
Description
The F10 function key, a non-ASCII action key.


 Event.F11

Event.F11

Syntax
public static final int F11
Description
The F11 function key, a non-ASCII action key.


 Event.F12

Event.F12

Syntax
public static final int F12
Description
The F12 function key, a non-ASCII action key.


 Event.F2

Event.F2

Syntax
public static final int F2
Description
The F2 function key, a non-ASCII action key.


 Event.F3

Event.F3

Syntax
public static final int F3
Description
The F3 function key, a non-ASCII action key.


 Event.F4

Event.F4

Syntax
public static final int F4
Description
The F4 function key, a non-ASCII action key.


 Event.F5

Event.F5

Syntax
public static final int F5
Description
The F5 function key, a non-ASCII action key.


 Event.F6

Event.F6

Syntax
public static final int F6
Description
The F6 function key, a non-ASCII action key.


 Event.F7

Event.F7

Syntax
public static final int F7
Description
The F7 function key, a non-ASCII action key.


 Event.F8

Event.F8

Syntax
public static final int F8
Description
The F8 function key, a non-ASCII action key.


 Event.F9

Event.F9

Syntax
public static final int F9
Description
The F9 function key, a non-ASCII action key.


 Event.GOT_FOCUS

Event.GOT_FOCUS

Syntax
public static final int GOT_FOCUS
Description
A component gained the focus.


 Event.HOME

Event.HOME

Syntax
public static final int HOME
Description
The Home key, a non-ASCII action key.


 Event.id

Event.id

Syntax
public int id
Description
Indicates which type of event the event is, and which other Event variables are relevant for the event.


 Event.INSERT

Event.INSERT

Syntax
public static final int INSERT
Description
The Insert key, a non-ASCII action key.


 Event.key

Event.key

Syntax
public int key
Description
The key code of the key that was pressed in a keyboard event.


 Event.KEY_ACTION

Event.KEY_ACTION

Syntax
public static final int KEY_ACTION
Description
The user has pressed a non-ASCII action key. The key field contains a value that indicates that the event occurred on one of the action keys, which comprise the 12 function keys, the arrow (cursor) keys, Page Up, Page Down, Home, End, Print Screen, Scroll Lock, Caps Lock, Num Lock, Pause, and Insert.


 Event.KEY_ACTION_RELEASE

Event.KEY_ACTION_RELEASE

Syntax
public static final int KEY_ACTION_RELEASE
Description
The user has released a non-ASCII action key. The key field contains a value that indicates that the event occurred on one of the action keys, which comprise the 12 function keys, the arrow (cursor) keys, Page Up, Page Down, Home, End, Print Screen, Scroll Lock, Caps Lock, Num Lock, Pause, and Insert.


 Event.KEY_PRESS

Event.KEY_PRESS

Syntax
public static final int KEY_PRESS
Description
The user has pressed a normal key.


 Event.KEY_RELEASE

Event.KEY_RELEASE

Syntax
public static final int KEY_RELEASE
Description
The user has released a normal key.


 Event.LEFT

Event.LEFT

Syntax
public static final int LEFT
Description
The Left Arrow key, a non-ASCII action key.


 Event.LIST_DESELECT

Event.LIST_DESELECT

Syntax
public static final int LIST_DESELECT
Description
An item in a list has been deselected.


 Event.LIST_SELECT

Event.LIST_SELECT

Syntax
public static final int LIST_SELECT
Description
An item in a list has been selected.


 Event.LOAD_FILE

Event.LOAD_FILE

Syntax
public static final int LOAD_FILE
Description
A file loading event.


 Event.LOST_FOCUS

Event.LOST_FOCUS

Syntax
public static final int LOST_FOCUS
Description
A component lost the focus.


 Event.META_MASK

Event.META_MASK

Syntax
public static final int META_MASK
Description
This flag indicates that the Meta key was down when the event occurred. For mouse events, this flag indicates that the right button was pressed or released.


 Event.modifiers

Event.modifiers

Syntax
public int modifiers
Description
The state of the modifier keys.


 Event.MOUSE_DOWN

Event.MOUSE_DOWN

Syntax
public static final int MOUSE_DOWN
Description
The user has pressed the mouse button. The ALT_MASK flag indicates that the middle button has been pressed. The META_MASKflag indicates that the right button has been pressed.

See Also
ALT_MASK, META_MASK


 Event.MOUSE_DRAG

Event.MOUSE_DRAG

Syntax
public static final int MOUSE_DRAG
Description
The user has moved the mouse with a button pressed. The ALT_MASK flag indicates that the middle button is being pressed. The META_MASK flag indicates that the right button is being pressed.

See Also
ALT_MASK, META_MASK


 Event.MOUSE_ENTER

Event.MOUSE_ENTER

Syntax
public static final int MOUSE_ENTER
Description
The mouse has entered a component.


 Event.MOUSE_EXIT

Event.MOUSE_EXIT

Syntax
public static final int MOUSE_EXIT
Description
The mouse has exited a component.


 Event.MOUSE_MOVE

Event.MOUSE_MOVE

Syntax
public static final int MOUSE_MOVE
Description
The mouse has moved with no button pressed.


 Event.MOUSE_UP

Event.MOUSE_UP

Syntax
public static final int MOUSE_UP
Description
The user has released the mouse button. The ALT_MASK flag indicates that the middle button has been released. The META_MASKflag indicates that the right button has been released.

See Also
ALT_MASK, META_MASK


 Event.NUM_LOCK

Event.NUM_LOCK

Syntax
public static final int NUM_LOCK
Description
The Num Lock key, a non-ASCII action key.


 Event.PAUSE

Event.PAUSE

Syntax
public static final int PAUSE
Description
The Pause key, a non-ASCII action key.


 Event.PGDN

Event.PGDN

Syntax
public static final int PGDN
Description
The Page Down key, a non-ASCII action key.


 Event.PGUP

Event.PGUP

Syntax
public static final int PGUP
Description
The Page Up key, a non-ASCII action key.


 Event.PRINT_SCREEN

Event.PRINT_SCREEN

Syntax
public static final int PRINT_SCREEN
Description
The Print Screen key, a non-ASCII action key.


 Event.RIGHT

Event.RIGHT

Syntax
public static final int RIGHT
Description
The Right Arrow key, a non-ASCII action key.


 Event.SAVE_FILE

Event.SAVE_FILE

Syntax
public static final int SAVE_FILE
Description
A file saving event.


 Event.SCROLL_ABSOLUTE

Event.SCROLL_ABSOLUTE

Syntax
public static final int SCROLL_ABSOLUTE
Description
The user has moved the bubble (thumb) in a scroll bar, moving to an "absolute" position, rather than to an offset from the last postion.


 Event.SCROLL_BEGIN

Event.SCROLL_BEGIN

Syntax
public static final int SCROLL_BEGIN
Description
The scroll begin event.


 Event.SCROLL_END

Event.SCROLL_END

Syntax
public static final int SCROLL_END
Description
The scroll end event.


 Event.SCROLL_LINE_DOWN

Event.SCROLL_LINE_DOWN

Syntax
public static final int SCROLL_LINE_DOWN
Description
The user has activated the line down area of a scroll bar.


 Event.SCROLL_LINE_UP

Event.SCROLL_LINE_UP

Syntax
public static final int SCROLL_LINE_UP
Description
The user has activated the line up area of a scroll bar.


 Event.SCROLL_LOCK

Event.SCROLL_LOCK

Syntax
public static final int SCROLL_LOCK
Description
The Scroll Lock key, a non-ASCII action key.


 Event.SCROLL_PAGE_DOWN

Event.SCROLL_PAGE_DOWN

Syntax
public static final int SCROLL_PAGE_DOWN
Description
The user has activated the page down area of a scroll bar.


 Event.SCROLL_PAGE_UP

Event.SCROLL_PAGE_UP

Syntax
public static final int SCROLL_PAGE_UP
Description
The user has activated the page up area of a scroll bar.


 Event.SHIFT_MASK

Event.SHIFT_MASK

Syntax
public static final int SHIFT_MASK
Description
This flag indicates that the Shift key was down when the event occurred.


 Event.TAB

Event.TAB

Syntax
public static final int TAB
Description
The Tab key.


 Event.target

Event.target

Syntax
public Object target
Description
The target component. This indicates the component over which the event occurred or with which the event is associated.


 Event.UP

Event.UP

Syntax
public static final int UP
Description
The Up Arrow key, a non-ASCII action key.


 Event.when

Event.when

Syntax
public long when
Description
The time stamp.


 Event.WINDOW_DEICONIFY

Event.WINDOW_DEICONIFY

Syntax
public static final int WINDOW_DEICONIFY
Description
The user has asked the window manager to de-iconify the window.


 Event.WINDOW_DESTROY

Event.WINDOW_DESTROY

Syntax
public static final int WINDOW_DESTROY
Description
The user has asked the window manager to kill the window.


 Event.WINDOW_EXPOSE

Event.WINDOW_EXPOSE

Syntax
public static final int WINDOW_EXPOSE
Description
The user has asked the window manager to expose the window.


 Event.WINDOW_ICONIFY

Event.WINDOW_ICONIFY

Syntax
public static final int WINDOW_ICONIFY
Description
The user has asked the window manager to iconify the window.


 Event.WINDOW_MOVED

Event.WINDOW_MOVED

Syntax
public static final int WINDOW_MOVED
Description
The user has asked the window manager to move the window.


 Event.x

Event.x

Syntax
public int x
Description
The x coordinate of the event.


 Event.y

Event.y

Syntax
public int y
Description
The y coordinate of the event.


 Event.Event

Event.Event

Syntax 1
public Event( Object target, long when, int id, int x, int y, int key, int modifiers, Object arg )
Parameters
target
the target component.
when
the time stamp.
id
the event type.
x
the x coordinate.
y
the y coordinate.
key
the key pressed in a keyboard event.
modifiers
the state of the modifier keys.
arg
the specified argument.
Description
Creates an instance of Event with the specified target component, time stamp, event type, x and y coordinates, keyboard key, state of the modifier keys, and argument.

Syntax 2
public Event( Object target, long when, int id, int x, int y, int key, int modifiers )
Parameters
target
the target component.
when
the time stamp.
id
the event type.
x
the x coordinate.
y
the y coordinate.
key
the key pressed in a keyboard event.
modifiers
the state of the modifier keys.
Description
Creates an instance of Event, with the specified target component, time stamp, event type, x and y coordinates, keyboard key, state of the modifier keys, and an argument set to null.

Syntax 3
public Event( Object target, int id, Object arg )
Parameters
target
the target component.
id
the event type.
arg
the specified argument.
Description
Creates an instance of Event with the specified target component, event type, and argument.


 Event.controlDown

Event.controlDown

Syntax
public boolean controlDown()
Returns
true if the key is down; false otherwise.
Description
Checks if the Control key is down.

See Also
modifiers, shiftDown, metaDown


 Event.metaDown

Event.metaDown

Syntax
public boolean metaDown()
Returns
true if the key is down; false otherwise.
Description
Checks if the Meta key is down.

See Also
modifiers, shiftDown, controlDown


 Event.paramString

Event.paramString

Syntax
protected String paramString()
Returns
the parameter string of this event.
Description
Returns the parameter string representing this event. This string is useful for debugging.


 Event.shiftDown

Event.shiftDown

Syntax
public boolean shiftDown()
Returns
true if the key is down; false otherwise.
Description
Checks if the Shift key is down.

See Also
modifiers, controlDown, metaDown


 Event.toString

Event.toString

Syntax
public String toString()
Returns
a string that represents the event and the values of its member fields.
Description
Returns a representation of this event's values as a string.

Overrides
toString in class Object
See Also
paramString


 Event.translate

Event.translate

Syntax
public void translate( int x, int y )
Parameters
dx
the distance to translate the x coordinate.
dy
the distance to translate the y coordinate.
Description
Translates this event so that its x and y coordinates are increased by dx and dy, respectively.

This method translates an event relative to the given component. This involves, at a minimum, translating the coordinates into the local coordinate system of the given component. It may also involve translating a region in the case of an expose event.


 Class EventQueue

Class java.awt.EventQueue

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.EventQueue

public class EventQueue
extends Object

EventQueue is a platform-independent class that queues events, both from the underlying peer classes and from trusted application classes. There is only one EventQueue for the system.


 EventQueue Members

EventQueue Members

Class Overview | This Package | All Packages

Constructors
Name | Description
EventQueue() |

Methods
Name | Description
getNextEvent() | Remove an event from the queue and return it.
peekEvent() | Return the first event without removing it.
peekEvent(int) |
postEvent(AWTEvent) | Post a 1.1-style event to the EventQueue.


 EventQueue.EventQueue

EventQueue.EventQueue

Syntax
public EventQueue()


 EventQueue.getNextEvent

EventQueue.getNextEvent

Syntax
public synchronized AWTEvent getNextEvent() throws InterruptedException
Returns
the next AWTEvent
Description
Remove an event from the queue and return it. This method will block until an event has been posted by another thread.

Exceptions
InterruptedException if another thread has interrupted this thread.


 EventQueue.peekEvent

EventQueue.peekEvent

Syntax 1
public synchronized AWTEvent peekEvent()
Returns
the first event, which is either an instance of java.awt.Event or java.awt.AWTEvent.
Description
Return the first event without removing it.

Syntax 2
public synchronized AWTEvent peekEvent( int id )


 EventQueue.postEvent

EventQueue.postEvent

Syntax
public synchronized void postEvent( AWTEvent theEvent )
Parameters
theEvent
an instance of java.awt.AWTEvent, or a subclass of it.
Description
Post a 1.1-style event to the EventQueue.


 Class FileDialog

Class java.awt.FileDialog

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Window
                           |
                           +----java.awt.Dialog
                                   |
                                   +----java.awt.FileDialog

public class FileDialog
extends Dialog

The FileDialog class displays a dialog window from which the user can select a file.

Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file.

See Also:
show


 FileDialog Members

FileDialog Members

Class Overview | This Package | All Packages

Fields
Name | Description
LOAD | This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
SAVE | This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

Constructors
Name | Description
FileDialog(Frame) | Creates a file dialog for loading a file.
FileDialog(Frame, String) | Creates a file dialog window with the specified title for loading a file.
FileDialog(Frame, String, int) | Creates a file dialog window with the specified title for loading or saving a file.

Methods
Name | Description
addNotify() | Creates the file dialog's peer.
getDirectory() | Gets the directory of this file dialog.
getFile() | Gets the selected file of this file dialog.
getFilenameFilter() | Determines this file dialog's filename filter.
getMode() | Indicates whether this file dialog box is for loading from a file or for saving to a file.
paramString() | Returns the parameter string representing the state of this file dialog window.
setDirectory(String) | Sets the directory of this file dialog window to be the specified directory.
setFile(String) | Sets the selected file for this file dialog window to be the specified file.
setFilenameFilter(FilenameFilter) | Sets the filename filter for this file dialog window to the specified filter.
setMode(int) | Sets the mode of the file dialog.


 FileDialog.LOAD

FileDialog.LOAD

Syntax
public static final int LOAD
Description
This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.


 FileDialog.SAVE

FileDialog.SAVE

Syntax
public static final int SAVE
Description
This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.


 FileDialog.FileDialog

FileDialog.FileDialog

Syntax 1
public FileDialog( Frame parent )
Parameters
parent
the owner of the dialog
Description
Creates a file dialog for loading a file. The title of the file dialog is initially empty.

Syntax 2
public FileDialog( Frame parent, String title )
Parameters
parent
the owner of the dialog.
title
the title of the dialog.
Description
Creates a file dialog window with the specified title for loading a file. The files shown are those in the current directory.

Syntax 3
public FileDialog( Frame parent, String title, int mode )
Parameters
parent
the owner of the dialog.
title
the title of the dialog.
mode
the mode of the dialog.
Description
Creates a file dialog window with the specified title for loading or saving a file.

If the value of mode is LOAD, then the file dialog is finding a file to read. If the value of mode is SAVE, the file dialog is finding a place to write a file.

See Also
LOAD, SAVE


 FileDialog.addNotify

FileDialog.addNotify

Syntax
public void addNotify()
Description
Creates the file dialog's peer. The peer allows us to change the look of the file dialog without changing its functionality.

Overrides
addNotify in class Dialog


 FileDialog.getDirectory

FileDialog.getDirectory

Syntax
public String getDirectory()
Returns
the directory of this file dialog.
Description
Gets the directory of this file dialog.

See Also
setDirectory


 FileDialog.getFile

FileDialog.getFile

Syntax
public String getFile()
Returns
the currently selected file of this file dialog window, or null if none is selected.
Description
Gets the selected file of this file dialog.

See Also
setFile


 FileDialog.getFilenameFilter

FileDialog.getFilenameFilter

Syntax
public FilenameFilter getFilenameFilter()
Returns
this file dialog's filename filter.
Description
Determines this file dialog's filename filter. A filename filter allows the user to specify which files appear in the file dialog window.

See Also
FilenameFilter, setFilenameFilter


 FileDialog.getMode

FileDialog.getMode

Syntax
public int getMode()
Returns
the mode of this file dialog window, either FileDialog.LOAD or FileDialog.SAVE.
Description
Indicates whether this file dialog box is for loading from a file or for saving to a file.

See Also
LOAD, SAVE, setMode


 FileDialog.paramString

FileDialog.paramString

Syntax
protected String paramString()
Returns
the parameter string of this file dialog window.
Description
Returns the parameter string representing the state of this file dialog window. This string is useful for debugging.

Overrides
paramString in class Dialog


 FileDialog.setDirectory

FileDialog.setDirectory

Syntax
public synchronized void setDirectory( String dir )
Parameters
dir
the specific directory.
Description
Sets the directory of this file dialog window to be the specified directory.

See Also
getDirectory


 FileDialog.setFile

FileDialog.setFile

Syntax
public synchronized void setFile( String file )
Parameters
file
the file being set.
Description
Sets the selected file for this file dialog window to be the specified file. This file becomes the default file if it is set before the file dialog window is first shown.

See Also
getFile


 FileDialog.setFilenameFilter

FileDialog.setFilenameFilter

Syntax
public synchronized void setFilenameFilter( FilenameFilter filter )
Parameters
filter
the specified filter.
Description
Sets the filename filter for this file dialog window to the specified filter.

See Also
FilenameFilter, getFilenameFilter


 FileDialog.setMode

FileDialog.setMode

Syntax
public void setMode( int mode )
Parameters
mode
the mode for this file dialog, either FileDialog.LOAD or FileDialog.SAVE.
Description
Sets the mode of the file dialog.

Exceptions
IllegalArgumentException if an illegal file dialog mode is used.
See Also
LOAD, SAVE, getMode


 Class FlowLayout

Class java.awt.FlowLayout

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.FlowLayout

public class FlowLayout
extends Object
implements LayoutManager, Serializable

A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered.

For example, the following picture shows an applet using the flow layout manager (its default layout manager) to position three buttons:

Graphic of Layout for Three Buttons

Here is the code for this applet:

 import java.awt.*;
 import java.applet.Applet;
 public class myButtons extends Applet {
     Button button1, button2, button3;
     public void init() {
         button1 = new Button("Ok");
         button2 = new Button("Open");
         button3 = new Button("Close");
         add(button1);
         add(button2);
         add(button3);
     }
 }

A flow layout lets each component assume its natural (preferred) size.


 FlowLayout Members

FlowLayout Members

Class Overview | This Package | All Packages

Fields
Name | Description
CENTER | This value indicates that each row of components should be centered.
LEFT | This value indicates that each row of components should be left-justified.
RIGHT | This value indicates that each row of components should be right-justified.

Constructors
Name | Description
FlowLayout() | Constructs a new Flow Layout with a centered alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int) | Constructs a new Flow Layout with the specified alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int, int, int) | Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Methods
Name | Description
addLayoutComponent(String, Component) | Adds the specified component to the layout.
getAlignment() | Gets the alignment for this layout.
getHgap() | Gets the horizontal gap between components.
getVgap() | Gets the vertical gap between components.
layoutContainer(Container) | Lays out the container.
minimumLayoutSize(Container) | Returns the minimum dimensions needed to layout the components contained in the specified target container.
preferredLayoutSize(Container) | Returns the preferred dimensions for this layout given the components in the specified target container.
removeLayoutComponent(Component) | Removes the specified component from the layout.
setAlignment(int) | Sets the alignment for this layout.
setHgap(int) | Sets the horizontal gap between components.
setVgap(int) | Sets the vertical gap between components.
toString() | Returns a string representation of this FlowLayout object and its values.


 FlowLayout.CENTER

FlowLayout.CENTER

Syntax
public static final int CENTER
Description
This value indicates that each row of components should be centered.


 FlowLayout.LEFT

FlowLayout.LEFT

Syntax
public static final int LEFT
Description
This value indicates that each row of components should be left-justified.


 FlowLayout.RIGHT

FlowLayout.RIGHT

Syntax
public static final int RIGHT
Description
This value indicates that each row of components should be right-justified.


 FlowLayout.FlowLayout

FlowLayout.FlowLayout

Syntax 1
public FlowLayout()
Description
Constructs a new Flow Layout with a centered alignment and a default 5-unit horizontal and vertical gap.

Syntax 2
public FlowLayout( int align )
Parameters
align
the alignment value
Description
Constructs a new Flow Layout with the specified alignment and a default 5-unit horizontal and vertical gap. The value of the alignment argument must be one of FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.

Syntax 3
public FlowLayout( int align, int hgap, int vgap )
Parameters
align
the alignment value.
hgap
the horizontal gap between components.
vgap
the vertical gap between components.
Description
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

The value of the alignment argument must be one of FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.


 FlowLayout.addLayoutComponent

FlowLayout.addLayoutComponent

Syntax
public void addLayoutComponent( String name, Component comp )
Parameters
name
the name of the component
comp
the component to be added
Description
Adds the specified component to the layout. Not used by this class.


 FlowLayout.getAlignment

FlowLayout.getAlignment

Syntax
public int getAlignment()
Returns
the alignment value for this layout.
Description
Gets the alignment for this layout. Possible values are FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.

See Also
setAlignment


 FlowLayout.getHgap

FlowLayout.getHgap

Syntax
public int getHgap()
Returns
the horizontal gap between components.
Description
Gets the horizontal gap between components.

See Also
setHgap


 FlowLayout.getVgap

FlowLayout.getVgap

Syntax
public int getVgap()
Returns
the vertical gap between components.
Description
Gets the vertical gap between components.

See Also
setVgap


 FlowLayout.layoutContainer

FlowLayout.layoutContainer

Syntax
public void layoutContainer( Container target )
Parameters
target
the specified component being laid out.
Description
Lays out the container. This method lets each component take its preferred size by reshaping the components in the target container in order to satisfy the constraints of this FlowLayout object.

See Also
Container, doLayout


 FlowLayout.minimumLayoutSize

FlowLayout.minimumLayoutSize

Syntax
public Dimension minimumLayoutSize( Container target )
Parameters
target
the component which needs to be laid out
Returns
the minimum dimensions to lay out the subcomponents of the specified container.
Description
Returns the minimum dimensions needed to layout the components contained in the specified target container.

See Also
preferredLayoutSize, Container, doLayout


 FlowLayout.preferredLayoutSize

FlowLayout.preferredLayoutSize

Syntax
public Dimension preferredLayoutSize( Container target )
Parameters
target
the component which needs to be laid out
Returns
the preferred dimensions to lay out the subcomponents of the specified container.
Description
Returns the preferred dimensions for this layout given the components in the specified target container.

See Also
Container, minimumLayoutSize, getPreferredSize


 FlowLayout.removeLayoutComponent

FlowLayout.removeLayoutComponent

Syntax
public void removeLayoutComponent( Component comp )
Parameters
comp
the component to remove
Description
Removes the specified component from the layout. Not used by this class.

See Also
removeAll


 FlowLayout.setAlignment

FlowLayout.setAlignment

Syntax
public void setAlignment( int align )
Parameters
align
the alignment value.
Description
Sets the alignment for this layout. Possible values are FlowLayout.LEFT, FlowLayout.RIGHT, and FlowLayout.CENTER.

See Also
getAlignment


 FlowLayout.setHgap

FlowLayout.setHgap

Syntax
public void setHgap( int hgap )
Parameters
hgap
the horizontal gap between components
Description
Sets the horizontal gap between components.

See Also
getHgap


 FlowLayout.setVgap

FlowLayout.setVgap

Syntax
public void setVgap( int vgap )
Parameters
vgap
the vertical gap between components
Description
Sets the vertical gap between components.

See Also
getVgap


 FlowLayout.toString

FlowLayout.toString

Syntax
public String toString()
Returns
a string representation of this layout.
Description
Returns a string representation of this FlowLayout object and its values.

Overrides
toString in class Object


 Class Font

Class java.awt.Font

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Font

public class Font
extends Object
implements Serializable

A class that produces font objects.


 Font Members

Font Members

Class Overview | This Package | All Packages

Fields
Name | Description
BOLD | The bold style constant.
ITALIC | The italicized style constant.
name | The logical name of this font.
PLAIN | The plain style constant.
size | The point size of this font.
style | The style of the font.

Constructors
Name | Description
Font(String, int, int) | Creates a new font with the specified name, style and point size.

Methods
Name | Description
decode(String) | Gets the specified font using the name passed in.
equals(Object) | Compares this object to the specifed object.
getFamily() | Gets the platform specific family name of the font.
getFont(String) | Gets a font from the system properties list.
getFont(String, Font) | Gets the specified font from the system properties list.
getName() | Gets the logical name of the font.
getPeer() | Gets the peer of the font.
getSize() | Gets the point size of the font.
getStyle() | Gets the style of the font.
hashCode() | Returns a hashcode for this font.
isBold() | Indicates whether the font's style is bold.
isItalic() | Indicates whether the font's style is italic.
isPlain() | Indicates whether the font's style is plain.
toString() | Converts this object to a String representation.


 Font.BOLD

Font.BOLD

Syntax
public static final int BOLD
Description
The bold style constant. This style can be combined with the other style constants for mixed styles.


 Font.ITALIC

Font.ITALIC

Syntax
public static final int ITALIC
Description
The italicized style constant. This style can be combined with the other style constants for mixed styles.


 Font.name

Font.name

Syntax
protected String name
Description
The logical name of this font.


 Font.PLAIN

Font.PLAIN

Syntax
public static final int PLAIN
Description
The plain style constant. This style can be combined with the other style constants for mixed styles.


 Font.size

Font.size

Syntax
protected int size
Description
The point size of this font.


 Font.style

Font.style

Syntax
protected int style
Description
The style of the font. This is the sum of the constants PLAIN, BOLD, or ITALIC.


 Font.Font

Font.Font

Syntax
public Font( String name, int style, int size )
Parameters
name
the font name
style
the constant style used
size
the point size of the font
Description
Creates a new font with the specified name, style and point size.

See Also
getFontList


 Font.decode

Font.decode

Syntax
public static Font decode( String str )
Parameters
str
the name
Description
Gets the specified font using the name passed in.


 Font.equals

Font.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare this font with.
Returns
true if the objects are equal; false otherwise.
Description
Compares this object to the specifed object. The result is true if and only if the argument is not null and is a Font object with the same name, style, and point size as this font.

Overrides
equals in class Object


 Font.getFamily

Font.getFamily

Syntax
public String getFamily()
Returns
a string, the platform specific family name.
Description
Gets the platform specific family name of the font. Use the getName method to get the logical name of the font.

See Also
getName


 Font.getFont

Font.getFont

Syntax
public static Font getFont( String nm )
Parameters
nm
the property name
Description
Gets a font from the system properties list.

See Also
getFont


 Font.getFont

Font.getFont

Syntax
public static Font getFont( String nm, Font font )
Parameters
nm
the property name
font
a default font to return if property nm is not defined
Returns
the Font value of the property.
Description
Gets the specified font from the system properties list. The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty. The string value of this property is then interpreted as a font.

The property value should be one of the following forms:

  • fontname-style-pointsize
  • fontname-pointsize
  • fontname-style
  • fontname
where style is one of the three strings "BOLD", "BOLDITALIC", or "ITALIC", and point size is a decimal representation of the point size.

The default style is PLAIN. The default point size is 12.

If the specified property is not found, the font argument is returned instead.


 Font.getName

Font.getName

Syntax
public String getName()
Returns
a string, the logical name of the font.
Description
Gets the logical name of the font.

See Also
getFamily


 Font.getPeer

Font.getPeer

Syntax
public FontPeer getPeer()
Returns
the peer of the font.
Description
Gets the peer of the font.


 Font.getSize

Font.getSize

Syntax
public int getSize()
Returns
the point size of this font.
Description
Gets the point size of the font.


 Font.getStyle

Font.getStyle

Syntax
public int getStyle()
Returns
the style of this font.
Description
Gets the style of the font.

See Also
isPlain, isBold, isItalic


 Font.hashCode

Font.hashCode

Syntax
public int hashCode()
Returns
a hashcode value for this font.
Description
Returns a hashcode for this font.

Overrides
hashCode in class Object


 Font.isBold

Font.isBold

Syntax
public boolean isBold()
Returns
true if the font is bold; false otherwise.
Description
Indicates whether the font's style is bold.

See Also
getStyle


 Font.isItalic

Font.isItalic

Syntax
public boolean isItalic()
Returns
true if the font is italic; false otherwise.
Description
Indicates whether the font's style is italic.

See Also
getStyle


 Font.isPlain

Font.isPlain

Syntax
public boolean isPlain()
Returns
true if the font is neither bold nor italic; false otherwise.
Description
Indicates whether the font's style is plain.

See Also
getStyle


 Font.toString

Font.toString

Syntax
public String toString()
Returns
a string representation of this object
Description
Converts this object to a String representation.

Overrides
toString in class Object


 Class FontMetrics

Class java.awt.FontMetrics

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.FontMetrics

public abstract class FontMetrics
extends Object
implements Serializable

A font metrics object, which gives information about the rendering of a particular font on a particular screen. Note that the implementations of these methods are inefficient, they are usually overridden with more efficient toolkit-specific implementations.

Note to subclassers: Since many of these methods form closed mutually recursive loops, you must take care that you implement at least one of the methods in each such loop in order to prevent infinite recursion when your subclass is used. In particular, the following is the minimal suggested set of methods to override in order to ensure correctness and prevent infinite recursion (though other subsets are equally feasible):

  • getAscent()
  • getDescent()
  • getLeading()
  • getMaxAdvance()
  • charWidth(char ch)
  • charsWidth(char data[], int off, int len)

When an application asks AWT to place a character at the position (x, y), the character is placed so that its reference point (shown as the dot in the accompanying image) is put at that position. The reference point specifies a horizontal line called the baseline of the character. In normal printing, the baselines of characters should align.

In addition, every character in a font has an ascent, a descent, and an advance width. The ascent is the amount by which the character ascends above the baseline. The descent is the amount by which the character descends below the baseline. The advance width indicates the position at which AWT should place the next character.

If the current character is placed with its reference point at the position (x, y), and the character's advance width is w, then the following character is placed with its reference point at the position (x + w, y). The advance width is often the same as the width of character's bounding box, but need not be so. In particular, oblique and italic fonts often have characters whose top-right corner extends slightly beyond the advance width.

An array of characters or a string can also have an ascent, a descent, and an advance width. The ascent of the array is the maximum ascent of any character in the array. The descent is the maximum descent of any character in the array. The advance width is the sum of the advance widths of each of the characters in the array.

See Also:
Font


 FontMetrics Members

FontMetrics Members

Class Overview | This Package | All Packages

Fields
Name | Description
font | The actual font.

Constructors
Name | Description
FontMetrics(Font) | Creates a new FontMetrics object for finding out height and width information about the specified font and specific character glyphs in that font.

Methods
Name | Description
bytesWidth(byte[], int, int) | Returns the total advance width for showing the specified array of bytes in this Font.
charsWidth(char[], int, int) | Returns the total advance width for showing the specified array of characters in this Font.
charWidth(char) | Returns the advance width of the specified character in this Font.
charWidth(int) | Returns the advance width of the specified character in this Font.
getAscent() | Determines the font ascent of the font described by this font metric.
getDescent() | Determines the font descent of the font described by this font metric.
getFont() | Gets the font described by this font metric.
getHeight() | Gets the standard height of a line of text in this font.
getLeading() | Determines the standard leading of the font described by this font metric.
getMaxAdvance() | Gets the maximum advance width of any character in this Font.
getMaxAscent() | Determines the maximum ascent of the font described by this font metric.
getMaxDecent() | For backward compatibility only. Deprecated.
getMaxDescent() | Determines the maximum descent of the font described by this font metric.
getWidths() | Gets the advance widths of the first 256 characters in the Font.
stringWidth(String) | Returns the total advance width for showing the specified String in this Font.
toString() | Returns a representation of this FontMetric object's values as a string.


 FontMetrics.font

FontMetrics.font

Syntax
protected Font font
Description
The actual font.

See Also
getFont


 FontMetrics.FontMetrics

FontMetrics.FontMetrics

Syntax
protected FontMetrics( Font font )
Parameters
font
the font
Description
Creates a new FontMetrics object for finding out height and width information about the specified font and specific character glyphs in that font.

See Also
Font


 FontMetrics.bytesWidth

FontMetrics.bytesWidth

Syntax
public int bytesWidth( byte data[], int off, int len )
Parameters
data
the array of bytes to be measured
off
the start offset of the bytes in the array
len
the number of bytes to be measured from the array
Returns
the advance width of the subarray of the specified byte array in the font described by this font metric.
Description
Returns the total advance width for showing the specified array of bytes in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.

See Also
charsWidth, stringWidth


 FontMetrics.charsWidth

FontMetrics.charsWidth

Syntax
public int charsWidth( char data[], int off, int len )
Parameters
data
the array of characters to be measured
off
the start offset of the characters in the array
len
the number of characters to be measured from the array
Returns
the advance width of the subarray of the specified char array in the font described by this font metric.
Description
Returns the total advance width for showing the specified array of characters in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.

See Also
charWidth, charWidth, bytesWidth, stringWidth


 FontMetrics.charWidth

FontMetrics.charWidth

Syntax 1
public int charWidth( int ch )
Parameters
ch
the character to be measured
Returns
the advance width of the specified char in the font described by this font metric.
Description
Returns the advance width of the specified character in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.

See Also
charsWidth, stringWidth

Syntax 2
public int charWidth( char ch )
Parameters
ch
the character to be measured
Returns
the advance width of the specified char > in the font described by this font metric.
Description
Returns the advance width of the specified character in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.

See Also
charsWidth, stringWidth


 FontMetrics.getAscent

FontMetrics.getAscent

Syntax
public int getAscent()
Returns
the font ascent of the font.
Description
Determines the font ascent of the font described by this font metric. The font ascent is the distance from the font's baseline to the top of most alphanumeric characters. Some characters in the font may extend above the font ascent line.

See Also
getMaxAscent


 FontMetrics.getDescent

FontMetrics.getDescent

Syntax
public int getDescent()
Returns
the font descent of the font.
Description
Determines the font descent of the font described by this font metric. The font descent is the distance from the font's baseline to the bottom of most alphanumeric characters with descenders. Some characters in the font may extend below the font descent line.

See Also
getMaxDescent


 FontMetrics.getFont

FontMetrics.getFont

Syntax
public Font getFont()
Returns
the font described by this font metric.
Description
Gets the font described by this font metric.


 FontMetrics.getHeight

FontMetrics.getHeight

Syntax
public int getHeight()
Returns
the standard height of the font.
Description
Gets the standard height of a line of text in this font. This is the distance between the baseline of adjacent lines of text. It is the sum of the leading + ascent + descent. There is no guarantee that lines of text spaced at this distance will be disjoint; such lines may overlap if some characters overshoot either the standard ascent or the standard descent metric.

See Also
getLeading, getAscent, getDescent


 FontMetrics.getLeading

FontMetrics.getLeading

Syntax
public int getLeading()
Returns
the standard leading of the font.
Description
Determines the standard leading of the font described by this font metric. The standard leading (interline spacing) is the logical amount of space to be reserved between the descent of one line of text and the ascent of the next line. The height metric is calculated to include this extra space.

See Also
getHeight, getAscent, getDescent


 FontMetrics.getMaxAdvance

FontMetrics.getMaxAdvance

Syntax
public int getMaxAdvance()
Returns
the maximum advance width of any character in the font, or -1 if the maximum advance width is not known.
Description
Gets the maximum advance width of any character in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.


 FontMetrics.getMaxAscent

FontMetrics.getMaxAscent

Syntax
public int getMaxAscent()
Returns
the maximum ascent of any character in the font.
Description
Determines the maximum ascent of the font described by this font metric. No character extends further above the font's baseline than this height.

See Also
getAscent


 FontMetrics.getMaxDecent

FontMetrics.getMaxDecent

Syntax
public int getMaxDecent()
Description
Note: getMaxDecent() is deprecated. As of JDK version 1.1.1, replaced by getMaxDescent().

For backward compatibility only.

See Also
getMaxDescent


 FontMetrics.getMaxDescent

FontMetrics.getMaxDescent

Syntax
public int getMaxDescent()
Returns
the maximum descent of any character in the font.
Description
Determines the maximum descent of the font described by this font metric. No character extends further below the font's baseline than this height.

See Also
getDescent


 FontMetrics.getWidths

FontMetrics.getWidths

Syntax
public int[] getWidths()
Returns
an array giving the advance widths of the characters in the font described by this font metric.
Description
Gets the advance widths of the first 256 characters in the Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.


 FontMetrics.stringWidth

FontMetrics.stringWidth

Syntax
public int stringWidth( String str )
Parameters
str
the String to be measured
Returns
the advance width of the specified string in the font described by this font metric.
Description
Returns the total advance width for showing the specified String in this Font. The advance width is the amount by which the current point is moved from one character to the next in a line of text.

See Also
bytesWidth, charsWidth


 FontMetrics.toString

FontMetrics.toString

Syntax
public String toString()
Returns
a string representation of this font metric.
Description
Returns a representation of this FontMetric object's values as a string.

Overrides
toString in class Object


 Class Frame

Class java.awt.Frame

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Window
                           |
                           +----java.awt.Frame

public class Frame
extends Window
implements MenuContainer

A Frame is a top-level window with a title and a border. The default layout for a frame is BorderLayout. Frames are capable of generating the following types of window events: WindowOpened, WindowClosing, WindowClosed, WindowIconified, WindowDeiconified, WindowActivated, WindowDeactivated.

See Also:
WindowEvent, addWindowListener


 Frame Members

Frame Members

Class Overview | This Package | All Packages

Fields
Name | Description
CROSSHAIR_CURSOR | Deprecated.
DEFAULT_CURSOR | Deprecated.
E_RESIZE_CURSOR | Deprecated.
HAND_CURSOR | Deprecated.
MOVE_CURSOR | Deprecated.
N_RESIZE_CURSOR | Deprecated.
NE_RESIZE_CURSOR | Deprecated.
NW_RESIZE_CURSOR | Deprecated.
S_RESIZE_CURSOR | Deprecated.
SE_RESIZE_CURSOR | Deprecated.
SW_RESIZE_CURSOR | Deprecated.
TEXT_CURSOR | Deprecated.
W_RESIZE_CURSOR | Deprecated.
WAIT_CURSOR | Deprecated.

Constructors
Name | Description
Frame() | Constructs a new instance of Frame that is initially invisible.
Frame(String) | Constructs a new, initially invisible Frame object with the specified title.

Methods
Name | Description
addNotify() | Creates the Frame's peer.
dispose() | Disposes of the Frame.
getCursorType() | Deprecated.
getIconImage() | Gets the icon image for this frame.
getMenuBar() | Gets the menu bar for this frame.
getTitle() | Gets the title of the frame.
isResizable() | Indicates whether this frame is resizable.
paramString() | Returns the parameter String of this Frame.
remove(MenuComponent) | Removes the specified menu bar from this frame.
setCursor(int) | Deprecated.
setIconImage(Image) | Sets the image to display when this frame is iconized.
setMenuBar(MenuBar) | Sets the menu bar for this frame to the specified menu bar.
setResizable(boolean) | Sets the resizable flag, which determines whether this frame is resizable.
setTitle(String) | Sets the title for this frame to the specified title.


 Frame.CROSSHAIR_CURSOR

Frame.CROSSHAIR_CURSOR

Syntax
public static final int CROSSHAIR_CURSOR
Description
Note: CROSSHAIR_CURSOR is deprecated. replaced by Cursor.CROSSHAIR_CURSOR.


 Frame.DEFAULT_CURSOR

Frame.DEFAULT_CURSOR

Syntax
public static final int DEFAULT_CURSOR
Description
Note: DEFAULT_CURSOR is deprecated. replaced by Cursor.DEFAULT_CURSOR.


 Frame.E_RESIZE_CURSOR

Frame.E_RESIZE_CURSOR

Syntax
public static final int E_RESIZE_CURSOR
Description
Note: E_RESIZE_CURSOR is deprecated. replaced by Cursor.E_RESIZE_CURSOR.


 Frame.HAND_CURSOR

Frame.HAND_CURSOR

Syntax
public static final int HAND_CURSOR
Description
Note: HAND_CURSOR is deprecated. replaced by Cursor.HAND_CURSOR.


 Frame.MOVE_CURSOR

Frame.MOVE_CURSOR

Syntax
public static final int MOVE_CURSOR
Description
Note: MOVE_CURSOR is deprecated. replaced by Cursor.MOVE_CURSOR.


 Frame.N_RESIZE_CURSOR

Frame.N_RESIZE_CURSOR

Syntax
public static final int N_RESIZE_CURSOR
Description
Note: N_RESIZE_CURSOR is deprecated. replaced by Cursor.N_RESIZE_CURSOR.


 Frame.NE_RESIZE_CURSOR

Frame.NE_RESIZE_CURSOR

Syntax
public static final int NE_RESIZE_CURSOR
Description
Note: NE_RESIZE_CURSOR is deprecated. replaced by Cursor.NE_RESIZE_CURSOR.


 Frame.NW_RESIZE_CURSOR

Frame.NW_RESIZE_CURSOR

Syntax
public static final int NW_RESIZE_CURSOR
Description
Note: NW_RESIZE_CURSOR is deprecated. replaced by Cursor.NW_RESIZE_CURSOR.


 Frame.S_RESIZE_CURSOR

Frame.S_RESIZE_CURSOR

Syntax
public static final int S_RESIZE_CURSOR
Description
Note: S_RESIZE_CURSOR is deprecated. replaced by Cursor.S_RESIZE_CURSOR.


 Frame.SE_RESIZE_CURSOR

Frame.SE_RESIZE_CURSOR

Syntax
public static final int SE_RESIZE_CURSOR
Description
Note: SE_RESIZE_CURSOR is deprecated. replaced by Cursor.SE_RESIZE_CURSOR.


 Frame.SW_RESIZE_CURSOR

Frame.SW_RESIZE_CURSOR

Syntax
public static final int SW_RESIZE_CURSOR
Description
Note: SW_RESIZE_CURSOR is deprecated. replaced by Cursor.SW_RESIZE_CURSOR.


 Frame.TEXT_CURSOR

Frame.TEXT_CURSOR

Syntax
public static final int TEXT_CURSOR
Description
Note: TEXT_CURSOR is deprecated. replaced by Cursor.TEXT_CURSOR.


 Frame.W_RESIZE_CURSOR

Frame.W_RESIZE_CURSOR

Syntax
public static final int W_RESIZE_CURSOR
Description
Note: W_RESIZE_CURSOR is deprecated. replaced by Cursor.W_RESIZE_CURSOR.


 Frame.WAIT_CURSOR

Frame.WAIT_CURSOR

Syntax
public static final int WAIT_CURSOR
Description
Note: WAIT_CURSOR is deprecated. replaced by Cursor.WAIT_CURSOR.


 Frame.Frame

Frame.Frame

Syntax 1
public Frame()
Description
Constructs a new instance of Frame that is initially invisible.

See Also
setSize, setVisible

Syntax 2
public Frame( String title )
Parameters
title
the title for the frame
Description
Constructs a new, initially invisible Frame object with the specified title.

See Also
setSize, setVisible


 Frame.addNotify

Frame.addNotify

Syntax
public void addNotify()
Description
Creates the Frame's peer. The peer allows us to change the look of the Frame without changing its functionality.

Overrides
addNotify in class Window


 Frame.dispose

Frame.dispose

Syntax
public synchronized void dispose()
Description
Disposes of the Frame. This method must be called to release the resources that are used for the frame. All components contained by the frame and all windows owned by the frame will also be destroyed.

Overrides
dispose in class Window


 Frame.getCursorType

Frame.getCursorType

Syntax
public int getCursorType()
Description
Note: getCursorType() is deprecated. As of JDK version 1.1, replaced by Component.getCursor().


 Frame.getIconImage

Frame.getIconImage

Syntax
public Image getIconImage()
Returns
the icon image for this frame, or null if this frame doesn't have an icon image.
Description
Gets the icon image for this frame.

See Also
setIconImage


 Frame.getMenuBar

Frame.getMenuBar

Syntax
public MenuBar getMenuBar()
Returns
the menu bar for this frame, or null if this frame doesn't have a menu bar.
Description
Gets the menu bar for this frame.

See Also
setMenuBar


 Frame.getTitle

Frame.getTitle

Syntax
public String getTitle()
Returns
the title of this frame, or null if this frame doesn't have a title.
Description
Gets the title of the frame.

See Also
setTitle


 Frame.isResizable

Frame.isResizable

Syntax
public boolean isResizable()
Returns
true if the user can resize this frame; false otherwise.
Description
Indicates whether this frame is resizable. By default, all frames are initially resizable.

See Also
setResizable


 Frame.paramString

Frame.paramString

Syntax
protected String paramString()
Description
Returns the parameter String of this Frame.

Overrides
paramString in class Container


 Frame.remove

Frame.remove

Syntax
public synchronized void remove( MenuComponent m )
Parameters
m
the menu component to remove.
Description
Removes the specified menu bar from this frame.

Overrides
remove in class Component


 Frame.setCursor

Frame.setCursor

Syntax
public synchronized void setCursor( int cursorType )
Description
Note: setCursor() is deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor).


 Frame.setIconImage

Frame.setIconImage

Syntax
public synchronized void setIconImage( Image image )
Parameters
image
the icon image to be displayed
Description
Sets the image to display when this frame is iconized. Not all platforms support the concept of iconizing a window.

See Also
getIconImage


 Frame.setMenuBar

Frame.setMenuBar

Syntax
public synchronized void setMenuBar( MenuBar mb )
Parameters
mb
the menu bar being set
Description
Sets the menu bar for this frame to the specified menu bar.

See Also
getMenuBar


 Frame.setResizable

Frame.setResizable

Syntax
public synchronized void setResizable( boolean resizable )
Parameters
resizable
true if this frame is resizable; false otherwise.
Description
Sets the resizable flag, which determines whether this frame is resizable. By default, all frames are initially resizable.

See Also
isResizable


 Frame.setTitle

Frame.setTitle

Syntax
public synchronized void setTitle( String title )
Parameters
title
the specified title of this frame.
Description
Sets the title for this frame to the specified title.

See Also
getTitle


 Class Graphics

Class java.awt.Graphics

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Graphics

public abstract class Graphics
extends Object

The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices, as well as onto off-screen images.

A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties:

  • The Component object on which to draw.
  • A translation origin for rendering and clipping coordinates.
  • The current clip.
  • The current color.
  • The current font.
  • The current logical pixel operation function (XOR or Paint).
  • The current XOR alternation color (see setXORMode).

Coordinates are infinitely thin and lie between the pixels of the output device. Operations which draw the outline of a figure operate by traversing an infinitely thin path between pixels with a pixel-sized pen that hangs down and to the right of the anchor point on the path. Operations which fill a figure operate by filling the interior of that infinitely thin path. Operations which render horizontal text render the ascending portion of character glyphs entirely above the baseline coordinate.

The graphics pen hangs down and to the right from the path it traverses. This has the following implications:

  • If you draw a figure that covers a given rectangle, that figure occupies one extra row of pixels on the right and bottom edges as compared to filling a figure that is bounded by that same rectangle.
  • If you draw a horizontal line along the same y coordinate as the baseline of a line of text, that line is drawn entirely below the text, except for any descenders.

All coordinates which appear as arguments to the methods of this Graphics object are considered relative to the translation origin of this Graphics object prior to the invocation of the method. All rendering operations modify only pixels which lie within the area bounded by both the current clip of the graphics context and the extents of the component used to create the Graphics object. All drawing or writing is done in the current color, using the current paint mode, and in the current font.

See Also:
Component, clipRect, setColor, setPaintMode, setXORMode, setFont


 Graphics Members

Graphics Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Graphics() | Constructs a new Graphics object.

Methods
Name | Description
clearRect(int, int, int, int) | Clears the specified rectangle by filling it with the background color of the current drawing surface.
clipRect(int, int, int, int) | Intersects the current clip with the specified rectangle.
copyArea(int, int, int, int, int, int) | Copies an area of the component by a distance specified by dx and dy.
create() | Creates a new Graphics object that is a copy of this Graphics object.
create(int, int, int, int) | Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.
dispose() | Disposes of this graphics context and releases any system resources that it is using.
draw3DRect(int, int, int, int, boolean) | Draws a 3-D highlighted outline of the specified rectangle.
drawArc(int, int, int, int, int, int) | Draws the outline of a circular or elliptical arc covering the specified rectangle.
drawBytes(byte[], int, int, int, int) | Draws the text given by the specified byte array, using this graphics context's current font and color.
drawChars(char[], int, int, int, int) | Draws the text given by the specified character array, using this graphics context's current font and color.
drawImage(Image, int, int, Color, ImageObserver) | Draws as much of the specified image as is currently available.
drawImage(Image, int, int, ImageObserver) | Draws as much of the specified image as is currently available.
drawImage(Image, int, int, int, int, Color, ImageObserver) | Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image, int, int, int, int, ImageObserver) | Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image, int, int, int, int, int, int, int, int, Color, ImageObserver) | Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
drawImage(Image, int, int, int, int, int, int, int, int, ImageObserver) | Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
drawLine(int, int, int, int) | Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
drawOval(int, int, int, int) | Draws the outline of an oval.
drawPolygon(int[], int[], int) | Draws a closed polygon defined by arrays of x and y coordinates.
drawPolygon(Polygon) | Draws the outline of a polygon defined by the specified Polygon object.
drawPolyline(int[], int[], int) | Draws a sequence of connected lines defined by arrays of x and y coordinates.
drawRect(int, int, int, int) | Draws the outline of the specified rectangle.
drawRoundRect(int, int, int, int, int, int) | Draws an outlined round-cornered rectangle using this graphics context's current color.
drawString(String, int, int) | Draws the text given by the specified string, using this graphics context's current font and color.
fill3DRect(int, int, int, int, boolean) | Paints a 3-D highlighted rectangle filled with the current color.
fillArc(int, int, int, int, int, int) | Fills a circular or elliptical arc covering the specified rectangle.
fillOval(int, int, int, int) | Fills an oval bounded by the specified rectangle with the current color.
fillPolygon(int[], int[], int) | Fills a closed polygon defined by arrays of x and y coordinates.
fillPolygon(Polygon) | Fills the polygon defined by the specified Polygon object with the graphics context's current color.
fillRect(int, int, int, int) | Fills the specified rectangle.
fillRoundRect(int, int, int, int, int, int) | Fills the specified rounded corner rectangle with the current color.
finalize() | Disposes of this graphics context once it is no longer referenced.
getClip() | Gets the current clipping area.
getClipBounds() | Returns the bounding rectangle of the current clipping area.
getClipRect() | Deprecated.
getColor() | Gets this graphics context's current color.
getFont() | Gets the current font.
getFontMetrics() | Gets the font metrics of the current font.
getFontMetrics(Font) | Gets the font metrics for the specified font.
setClip(int, int, int, int) | Sets the current clip to the rectangle specified by the given coordinates.
setClip(Shape) | Sets the current clipping area to an arbitrary clip shape.
setColor(Color) | Sets this graphics context's current color to the specified color.
setFont(Font) | Sets this graphics context's font to the specified font.
setPaintMode() | Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color.
setXORMode(Color) | Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color.
toString() | Returns a String object representing this Graphics object's value.
translate(int, int) | Translates the origin of the graphics context to the point (x, y) in the current coordinate system.


 Graphics.Graphics

Graphics.Graphics

Syntax
protected Graphics()
Description
Constructs a new Graphics object. This constructor is the default contructor for a graphics context.

Since Graphics is an abstract class, applications cannot call this constructor directly. Graphics contexts are obtained from other graphics contexts or are created by calling getGraphics on a component.

See Also
create, getGraphics


 Graphics.clearRect

Graphics.clearRect

Syntax
public abstract void clearRect( int x, int y, int width, int height )
Parameters
x
the x coordinate of the rectangle to clear.
y
the y coordinate of the rectangle to clear.
width
the width of the rectangle to clear.
height
the height of the rectangle to clear.
Description
Clears the specified rectangle by filling it with the background color of the current drawing surface. This operation does not use the current paint mode.

Beginning with Java 1.1, the background color of offscreen images may be system dependent. Applications should use setColor followed by fillRect to ensure that an offscreen image is cleared to a specific color.

See Also
fillRect, drawRect, setColor, setPaintMode, setXORMode


 Graphics.clipRect

Graphics.clipRect

Syntax
public abstract void clipRect( int x, int y, int width, int height )
Parameters
x
the x coordinate of the rectangle to intersect the clip with
y
the y coordinate of the rectangle to intersect the clip with
width
the width of the rectangle to intersect the clip with
height
the height of the rectangle to intersect the clip with
Description
Intersects the current clip with the specified rectangle. The resulting clipping area is the intersection of the current clipping area and the specified rectangle. This method can only be used to make the current clip smaller. To set the current clip larger, use any of the setClip methods. Rendering operations have no effect outside of the clipping area.

See Also
setClip, setClip


 Graphics.copyArea

Graphics.copyArea

Syntax
public abstract void copyArea( int x, int y, int width, int height, int dx, int dy )
Parameters
x
the x coordinate of the source rectangle.
y
the y coordinate of the source rectangle.
width
the width of the source rectangle.
height
the height of the source rectangle.
dx
the horizontal distance to copy the pixels.
dy
the vertical distance to copy the pixels.
Description
Copies an area of the component by a distance specified by dx and dy. From the point specified by x and y, this method copies downwards and to the right. To copy an area of the component to the left or upwards, specify a negative value for dx or dy. If a portion of the source rectangle lies outside the bounds of the component, or is obscured by another window or component, copyArea will be unable to copy the associated pixels. The area that is omitted can be refreshed by calling the component's paint method.


 Graphics.create

Graphics.create

Syntax 1
public abstract Graphics create()
Returns
a new graphics context that is a copy of this graphics context.
Description
Creates a new Graphics object that is a copy of this Graphics object.

Syntax 2
public Graphics create( int x, int y, int width, int height )
Parameters
x
the x coordinate.
y
the y coordinate.
width
the width of the clipping rectangle.
height
the height of the clipping rectangle.
Returns
a new graphics context.
Description
Creates a new Graphics object based on this Graphics object, but with a new translation and clip area. The new Graphics object has its origin translated to the specified point (x, y). Its clip area is determined by the intersection of the original clip area with the specified rectangle. The arguments are all interpreted in the coordinate system of the original Graphics object. The new graphics context is identical to the original, except in two respects:

  • The new graphics context is translated by (x, y). That is to say, the point (0, 0) in the new graphics context is the same as (x, y) in the original graphics context.
  • The new graphics context has an additional clipping rectangle, in addition to whatever (translated) clipping rectangle it inherited from the original graphics context. The origin of the new clipping rectangle is at (0, 0), and its size is specified by the width and height arguments.

See Also
translate, clipRect


 Graphics.dispose

Graphics.dispose

Syntax
public abstract void dispose()
Description
Disposes of this graphics context and releases any system resources that it is using. A Graphics object cannot be used after disposehas been called.

When a Java program runs, a large number of Graphics objects can be created within a short time frame. Although the finalization process of the garbage collector also disposes of the same system resources, it is preferable to manually free the associated resources by calling this method rather than to rely on a finalization process which may not run to completion for a long period of time.

Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return. For efficiency, programmers should call dispose when finished using a Graphics object only if it was created directly from a component or another Graphics object.

See Also
finalize, paint, update, getGraphics, create


 Graphics.draw3DRect

Graphics.draw3DRect

Syntax
public void draw3DRect( int x, int y, int width, int height, boolean raised )
Parameters
x
the x coordinate of the rectangle to be drawn.
y
the y coordinate of the rectangle to be drawn.
width
the width of the rectangle to be drawn.
height
the height of the rectangle to be drawn.
raised
a boolean that determines whether the rectangle appears to be raised above the surface or sunk into the surface.
Description
Draws a 3-D highlighted outline of the specified rectangle. The edges of the rectangle are highlighted so that they appear to be beveled and lit from the upper left corner.

The colors used for the highlighting effect are determined based on the current color. The resulting rectangle covers an area that is width + 1 pixels wide by height + 1 pixels tall.

See Also
fill3DRect


 Graphics.drawArc

Graphics.drawArc

Syntax
public abstract void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle )
Parameters
x
the x coordinate of the upper-left corner of the arc to be drawn.
y
the y coordinate of the upper-left corner of the arc to be drawn.
width
the width of the arc to be drawn.
height
the height of the arc to be drawn.
startAngle
the beginning angle.
arcAngle
the angular extent of the arc, relative to the start angle.
Description
Draws the outline of a circular or elliptical arc covering the specified rectangle.

The resulting arc begins at startAngle and extends for arcAngle degrees, using the current color. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.

The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments.

The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.

See Also
fillArc


 Graphics.drawBytes

Graphics.drawBytes

Syntax
public void drawBytes( byte data[], int offset, int length, int x, int y )
Parameters
data
the data to be drawn
offset
the start offset in the data
length
the number of bytes that are drawn
x
the x coordinate of the baseline of the text
y
the y coordinate of the baseline of the text
Description
Draws the text given by the specified byte array, using this graphics context's current font and color. The baseline of the first character is at position (x, y) in this graphics context's coordinate system.

See Also
drawChars, drawString


 Graphics.drawChars

Graphics.drawChars

Syntax
public void drawChars( char data[], int offset, int length, int x, int y )
Parameters
data
the array of characters to be drawn
offset
the start offset in the data
length
the number of characters to be drawn
x
the x coordinate of the baseline of the text
y
the y coordinate of the baseline of the text
Description
Draws the text given by the specified character array, using this graphics context's current font and color. The baseline of the first character is at position (x, y) in this graphics context's coordinate system.

See Also
drawBytes, drawString


 Graphics.drawImage

Graphics.drawImage

Syntax 1
public abstract boolean drawImage( Image img, int x, int y, ImageObserver observer )
Parameters
img
the specified image to be drawn.
x
the x coordinate.
y
the y coordinate.
observer
object to be notified as more of the image is converted.
Description
Draws as much of the specified image as is currently available. The image is drawn with its top-left corner at (x, y) in this graphics context's coordinate space. Transparent pixels in the image do not affect whatever pixels are already there.

This method returns immediately in all cases, even if the complete image has not yet been loaded, and it has not been dithered and converted for the current output device.

If the image has not yet been completely loaded, then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

See Also
Image, ImageObserver, imageUpdate

Syntax 2
public abstract boolean drawImage( Image img, int x, int y, int width, int height, ImageObserver observer )
Parameters
img
the specified image to be drawn.
x
the x coordinate.
y
the y coordinate.
width
the width of the rectangle.
height
the height of the rectangle.
observer
object to be notified as more of the image is converted.
Description
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

The image is drawn inside the specified rectangle of this graphics context's coordinate space, and is scaled if necessary. Transparent pixels do not affect whatever pixels are already there.

This method returns immediately in all cases, even if the entire image has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete, then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the image observer by calling its imageUpdate method.

A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence.

See Also
Image, ImageObserver, imageUpdate

Syntax 3
public abstract boolean drawImage( Image img, int x, int y, Color bgcolor, ImageObserver observer )
Parameters
img
the specified image to be drawn.
x
the x coordinate.
y
the y coordinate.
bgcolor
the background color to paint under the non-opaque portions of the image.
observer
object to be notified as more of the image is converted.
Description
Draws as much of the specified image as is currently available. The image is drawn with its top-left corner at (x, y) in this graphics context's coordinate space. Transparent pixels are drawn in the specified background color.

This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.

This method returns immediately in all cases, even if the complete image has not yet been loaded, and it has not been dithered and converted for the current output device.

If the image has not yet been completely loaded, then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

See Also
Image, ImageObserver, imageUpdate

Syntax 4
public abstract boolean drawImage( Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer )
Parameters
img
the specified image to be drawn.
x
the x coordinate.
y
the y coordinate.
width
the width of the rectangle.
height
the height of the rectangle.
bgcolor
the background color to paint under the non-opaque portions of the image.
observer
object to be notified as more of the image is converted.
Description
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

The image is drawn inside the specified rectangle of this graphics context's coordinate space, and is scaled if necessary. Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.

This method returns immediately in all cases, even if the entire image has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence.

See Also
Image, ImageObserver, imageUpdate

Syntax 5
public abstract boolean drawImage( Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer )
Parameters
img
the specified image to be drawn
dx1
the x coordinate of the first corner of the destination rectangle.
dy1
the y coordinate of the first corner of the destination rectangle.
dx2
the x coordinate of the second corner of the destination rectangle.
dy2
the y coordinate of the second corner of the destination rectangle.
sx1
the x coordinate of the first corner of the source rectangle.
sy1
the y coordinate of the first corner of the source rectangle.
sx2
the x coordinate of the second corner of the source rectangle.
sy2
the y coordinate of the second corner of the source rectangle.
observer
object to be notified as more of the image is scaled and converted.
Description
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. Transparent pixels do not affect whatever pixels are already there.

This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.

See Also
Image, ImageObserver, imageUpdate

Syntax 6
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 )
Parameters
img
the specified image to be drawn
dx1
the x coordinate of the first corner of the destination rectangle.
dy1
the y coordinate of the first corner of the destination rectangle.
dx2
the x coordinate of the second corner of the destination rectangle.
dy2
the y coordinate of the second corner of the destination rectangle.
sx1
the x coordinate of the first corner of the source rectangle.
sy1
the y coordinate of the first corner of the source rectangle.
sx2
the x coordinate of the second corner of the source rectangle.
sy2
the y coordinate of the second corner of the source rectangle.
bgcolor
the background color to paint under the non-opaque portions of the image.
observer
object to be notified as more of the image is scaled and converted.
Description
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.

Transparent pixels are drawn in the specified background color. This operation is equivalent to filling a rectangle of the width and height of the specified image with the given color and then drawing the image on top of it, but possibly more efficient.

This method returns immediately in all cases, even if the image area to be drawn has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

This method always uses the unscaled version of the image to render the scaled rectangle and performs the required scaling on the fly. It does not use a cached, scaled version of the image for this operation. Scaling of the image from source to destination is performed such that the first coordinate of the source rectangle is mapped to the first coordinate of the destination rectangle, and the second source coordinate is mapped to the second destination coordinate. The subimage is scaled and flipped as needed to preserve those mappings.

See Also
Image, ImageObserver, imageUpdate


 Graphics.drawLine

Graphics.drawLine

Syntax
public abstract void drawLine( int x1, int y1, int x2, int y2 )
Parameters
x1
the first point's x coordinate.
y1
the first point's y coordinate.
x2
the second point's x coordinate.
y2
the second point's y coordinate.
Description
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.


 Graphics.drawOval

Graphics.drawOval

Syntax
public abstract void drawOval( int x, int y, int width, int height )
Parameters
x
the x coordinate of the upper left corner of the oval to be drawn.
y
the y coordinate of the upper left corner of the oval to be drawn.
width
the width of the oval to be drawn.
height
the height of the oval to be drawn.
Description
Draws the outline of an oval. The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments.

The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.

See Also
fillOval


 Graphics.drawPolygon

Graphics.drawPolygon

Syntax 1
public abstract void drawPolygon( int xPoints[], int yPoints[], int nPoints )
Parameters
xPoints
a an array of x coordinates.
yPoints
a an array of y coordinates.
nPoints
a the total number of points.
Description
Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point.

This method draws the polygon defined by nPoint line segments, where the first nPoint - 1 line segments are line segments from (xPoints[i - 1], yPoints[i - 1]) to (xPoints[i], yPoints[i]), for 1 ≤ i ≤ nPoints. The figure is automatically closed by drawing a line connecting the final point to the first point, if those points are different.

See Also
fillPolygon, drawPolyline

Syntax 2
public void drawPolygon( Polygon p )
Parameters
p
the polygon to draw.
Description
Draws the outline of a polygon defined by the specified Polygon object.

See Also
fillPolygon, drawPolyline


 Graphics.drawPolyline

Graphics.drawPolyline

Syntax
public abstract void drawPolyline( int xPoints[], int yPoints[], int nPoints )
Parameters
xPoints
an array of x points
yPoints
an array of y points
nPoints
the total number of points
Description
Draws a sequence of connected lines defined by arrays of x and y coordinates. Each pair of (x, y) coordinates defines a point. The figure is not closed if the first point differs from the last point.

See Also
drawPolygon


 Graphics.drawRect

Graphics.drawRect

Syntax
public void drawRect( int x, int y, int width, int height )
Parameters
x
the x coordinate of the rectangle to be drawn.
y
the y coordinate of the rectangle to be drawn.
width
the width of the rectangle to be drawn.
height
the height of the rectangle to be drawn.
Description
Draws the outline of the specified rectangle. The left and right edges of the rectangle are at x and x + width. The top and bottom edges are at y and y + height. The rectangle is drawn using the graphics context's current color.

See Also
fillRect, clearRect


 Graphics.drawRoundRect

Graphics.drawRoundRect

Syntax
public abstract void drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )
Parameters
x
the x coordinate of the rectangle to be drawn.
y
the y coordinate of the rectangle to be drawn.
width
the width of the rectangle to be drawn.
height
the height of the rectangle to be drawn.
arcWidth
the horizontal diameter of the arc at the four corners.
arcHeight
the vertical diameter of the arc at the four corners.
Description
Draws an outlined round-cornered rectangle using this graphics context's current color. The left and right edges of the rectangle are at x and x + width, respectively. The top and bottom edges of the rectangle are at y and y + height.

See Also
fillRoundRect


 Graphics.drawString

Graphics.drawString

Syntax
public abstract void drawString( String str, int x, int y )
Parameters
str
the string to be drawn.
x
the x coordinate.
y
the y coordinate.
Description
Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the first character is at position (x, y) in this graphics context's coordinate system.

See Also
drawBytes, drawChars


 Graphics.fill3DRect

Graphics.fill3DRect

Syntax
public void fill3DRect( int x, int y, int width, int height, boolean raised )
Parameters
x
the x coordinate of the rectangle to be filled.
y
the y coordinate of the rectangle to be filled.
width
the width of the rectangle to be filled.
height
the height of the rectangle to be filled.
raised
a boolean value that determines whether the rectangle appears to be raised above the surface or etched into the surface.
Description
Paints a 3-D highlighted rectangle filled with the current color. The edges of the rectangle will be highlighted so that it appears as if the edges were beveled and lit from the upper left corner. The colors used for the highlighting effect will be determined from the current color.

See Also
draw3DRect


 Graphics.fillArc

Graphics.fillArc

Syntax
public abstract void fillArc( int x, int y, int width, int height, int startAngle, int arcAngle )
Parameters
x
the x coordinate of the upper-left corner of the arc to be filled.
y
the y coordinate of the upper-left corner of the arc to be filled.
width
the width of the arc to be filled.
height
the height of the arc to be filled.
startAngle
the beginning angle.
arcAngle
the angular extent of the arc, relative to the start angle.
Description
Fills a circular or elliptical arc covering the specified rectangle.

The resulting arc begins at startAngle and extends for arcAngle degrees. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a counter-clockwise rotation while a negative value indicates a clockwise rotation.

The center of the arc is the center of the rectangle whose origin is (x, y) and whose size is specified by the width and height arguments.

The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.

See Also
drawArc


 Graphics.fillOval

Graphics.fillOval

Syntax
public abstract void fillOval( int x, int y, int width, int height )
Parameters
x
the x coordinate of the upper left corner of the oval to be filled.
y
the y coordinate of the upper left corner of the oval to be filled.
width
the width of the oval to be filled.
height
the height of the oval to be filled.
Description
Fills an oval bounded by the specified rectangle with the current color.

See Also
drawOval


 Graphics.fillPolygon

Graphics.fillPolygon

Syntax 1
public abstract void fillPolygon( int xPoints[], int yPoints[], int nPoints )
Parameters
xPoints
a an array of x coordinates.
yPoints
a an array of y coordinates.
nPoints
a the total number of points.
Description
Fills a closed polygon defined by arrays of x and y coordinates.

This method draws the polygon defined by nPoint line segments, where the first nPoint - 1 line segments are line segments from (xPoints[i - 1], yPoints[i - 1]) to (xPoints[i], yPoints[i]), for 1 ≤ i ≤ nPoints. The figure is automatically closed by drawing a line connecting the final point to the first point, if those points are different.

The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.

See Also
drawPolygon

Syntax 2
public void fillPolygon( Polygon p )
Parameters
p
the polygon to fill.
Description
Fills the polygon defined by the specified Polygon object with the graphics context's current color.

The area inside the polygon is defined using an even-odd fill rule, also known as the alternating rule.

See Also
drawPolygon


 Graphics.fillRect

Graphics.fillRect

Syntax
public abstract void fillRect( int x, int y, int width, int height )
Parameters
x
the x coordinate of the rectangle to be filled.
y
the y coordinate of the rectangle to be filled.
width
the width of the rectangle to be filled.
height
the height of the rectangle to be filled.
Description
Fills the specified rectangle. The left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1. The resulting rectangle covers an area width pixels wide by height pixels tall. The rectangle is filled using the graphics context's current color.

See Also
fillRect, clearRect


 Graphics.fillRoundRect

Graphics.fillRoundRect

Syntax
public abstract void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )
Parameters
x
the x coordinate of the rectangle to be filled.
y
the y coordinate of the rectangle to be filled.
width
the width of the rectangle to be filled.
height
the height of the rectangle to be filled.
arcWidth
the horizontal diameter of the arc at the four corners.
arcHeight
the vertical diameter of the arc at the four corners.
Description
Fills the specified rounded corner rectangle with the current color. The left and right edges of the rectangle are at x and x + width - 1, respectively. The top and bottom edges of the rectangle are at y and y + height - 1.

See Also
drawRoundRect


 Graphics.finalize

Graphics.finalize

Syntax
public void finalize()
Description
Disposes of this graphics context once it is no longer referenced.

Overrides
finalize in class Object
See Also
dispose


 Graphics.getClip

Graphics.getClip

Syntax
public abstract Shape getClip()
Returns
a Shape object representing the current clipping area.
Description
Gets the current clipping area.

See Also
getClipBounds, clipRect, setClip, setClip


 Graphics.getClipBounds

Graphics.getClipBounds

Syntax
public abstract Rectangle getClipBounds()
Returns
the bounding rectangle of the current clipping area.
Description
Returns the bounding rectangle of the current clipping area. The coordinates in the rectangle are relative to the coordinate system origin of this graphics context.

See Also
getClip, clipRect, setClip, setClip


 Graphics.getClipRect

Graphics.getClipRect

Syntax
public Rectangle getClipRect()
Description
Note: getClipRect() is deprecated. As of JDK version 1.1, replaced by getClipBounds().


 Graphics.getColor

Graphics.getColor

Syntax
public abstract Color getColor()
Returns
this graphics context's current color.
Description
Gets this graphics context's current color.

See Also
Color, setColor


 Graphics.getFont

Graphics.getFont

Syntax
public abstract Font getFont()
Returns
this graphics context's current font.
Description
Gets the current font.

See Also
Font, setFont


 Graphics.getFontMetrics

Graphics.getFontMetrics

Syntax 1
public FontMetrics getFontMetrics()
Returns
the font metrics of this graphics context's current font.
Description
Gets the font metrics of the current font.

See Also
getFont, FontMetrics, getFontMetrics

Syntax 2
public abstract FontMetrics getFontMetrics( Font f )
Parameters
f
the specified font
Returns
the font metrics for the specified font.
Description
Gets the font metrics for the specified font.

See Also
getFont, FontMetrics, getFontMetrics


 Graphics.setClip

Graphics.setClip

Syntax
public abstract void setClip( int x, int y, int width, int height )
Parameters
x
the x coordinate of the new clip rectangle.
y
the y coordinate of the new clip rectangle.
width
the width of the new clip rectangle.
height
the height of the new clip rectangle.
Description
Sets the current clip to the rectangle specified by the given coordinates. Rendering operations have no effect outside of the clipping area.

See Also
clipRect, setClip


 Graphics.setClip

Graphics.setClip

Syntax
public abstract void setClip( Shape clip )
Description
Sets the current clipping area to an arbitrary clip shape. Not all objects which implement the Shape interface can be used to set the clip. The only Shape objects which are guaranteed to be supported are Shape objects which are obtained via the getClip method and via Rectangle objects.

See Also
getClip, clipRect, setClip


 Graphics.setColor

Graphics.setColor

Syntax
public abstract void setColor( Color c )
Parameters
c
the new rendering color.
Description
Sets this graphics context's current color to the specified color. All subsequent graphics operations using this graphics context use this specified color.

See Also
Color, getColor


 Graphics.setFont

Graphics.setFont

Syntax
public abstract void setFont( Font font )
Parameters
font
the font.
Description
Sets this graphics context's font to the specified font. All subsequent text operations using this graphics context use this font.

See Also
getFont, drawChars, drawString, drawBytes


 Graphics.setPaintMode

Graphics.setPaintMode

Syntax
public abstract void setPaintMode()
Description
Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color. This sets the logical pixel operation function to the paint or overwrite mode. All subsequent rendering operations will overwrite the destination with the current color.


 Graphics.setXORMode

Graphics.setXORMode

Syntax
public abstract void setXORMode( Color c1 )
Parameters
c1
the XOR alternation color
Description
Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color. This specifies that logical pixel operations are performed in the XOR mode, which alternates pixels between the current color and a specified XOR color.

When drawing operations are performed, pixels which are the current color are changed to the specified color, and vice versa.

Pixels that are of colors other than those two colors are changed in an unpredictable but reversible manner; if the same figure is drawn twice, then all pixels are restored to their original values.


 Graphics.toString

Graphics.toString

Syntax
public String toString()
Returns
a string representation of this graphics context.
Description
Returns a String object representing this Graphics object's value.

Overrides
toString in class Object


 Graphics.translate

Graphics.translate

Syntax
public abstract void translate( int x, int y )
Parameters
x
the x coordinate.
y
the y coordinate.
Description
Translates the origin of the graphics context to the point (x, y) in the current coordinate system. Modifies this graphics context so that its new origin corresponds to the point (x, y) in this graphics context's original coordinate system. All coordinates used in subsequent rendering operations on this graphics context will be relative to this new origin.


 Class GridBagConstraints

Class java.awt.GridBagConstraints

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.GridBagConstraints

public class GridBagConstraints
extends Object
implements Cloneable, Serializable

The GridBagConstraints class specifies constraints for components that are laid out using the GridBagLayout class.

See Also:
GridBagLayout


 GridBagConstraints Members

GridBagConstraints Members

Class Overview | This Package | All Packages

Fields
Name | Description
anchor | This field is used when the component is smaller than its display area.
BOTH | Resize the component both horizontally and vertically.
CENTER | Put the component in the center of its display area.
EAST | Put the component on the left side of its display area, centered vertically.
fill | This field is used when the component's display area is larger than the component's requested size.
gridheight | Specifies the number of cells in a column for the component's display area.
gridwidth | Specifies the number of cells in a row for the component's display area.
gridx | Specifies the cell at the left of the component's display area, where the leftmost cell has gridx = 0.
gridy | Specifies the cell at the top of the component's display area, where the topmost cell has gridy = 0.
HORIZONTAL | Resize the component horizontally but not vertically.
insets | This field specifies the external padding of the component, the minimum amount of space between the component and the edges of its display area.
ipadx | This field specifies the internal padding of the component, how much space to add to the minimum width of the component.
ipady | This field specifies the internal padding, that is, how much space to add to the minimum height of the component.
NONE | Do not resize the component.
NORTH | Put the component at the top of its display area, centered horizontally.
NORTHEAST | Put the component at the top-right corner of its display area.
NORTHWEST | Put the component at the top-left corner of its display area.
RELATIVE | Specify that this component is the next-to-last component in its column or row (gridwidth, gridheight), or that this component be placed next to the previously added component (gridx, gridy).
REMAINDER | Specify that this component is the last component in its column or row.
SOUTH | Put the component at the bottom of its display area, centered horizontally.
SOUTHEAST | Put the component at the bottom-right corner of its display area.
SOUTHWEST | Put the component at the bottom-left corner of its display area.
VERTICAL | Resize the component vertically but not horizontally.
weightx | Specifies how to distribute extra horizontal space.
weighty | Specifies how to distribute extra vertical space.
WEST | Put the component on the left side of its display area, centered vertically.

Constructors
Name | Description
GridBagConstraints() | Creates a GridBagConstraint object with all of its fields set to their default value.

Methods
Name | Description
clone() | Creates a copy of this grid bag constraint.


 GridBagConstraints.anchor

GridBagConstraints.anchor

Syntax
public int anchor
Description
This field is used when the component is smaller than its display area. It determines where, within the display area, to place the component. Possible values are CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, and NORTHWEST. The default value is CENTER.


 GridBagConstraints.BOTH

GridBagConstraints.BOTH

Syntax
public static final int BOTH
Description
Resize the component both horizontally and vertically.


 GridBagConstraints.CENTER

GridBagConstraints.CENTER

Syntax
public static final int CENTER
Description
Put the component in the center of its display area.


 GridBagConstraints.EAST

GridBagConstraints.EAST

Syntax
public static final int EAST
Description
Put the component on the left side of its display area, centered vertically.


 GridBagConstraints.fill

GridBagConstraints.fill

Syntax
public int fill
Description
This field is used when the component's display area is larger than the component's requested size. It determines whether to resize the component, and if so, how.

The following values are valid for fill:

  • NONE: Do not resize the component.
  • HORIZONTAL: Make the component wide enough to fill its display area horizontally, but do not change its height.
  • VERTICAL: Make the component tall enough to fill its display area vertically, but do not change its width.
  • BOTH: Make the component fill its display area entirely.

The default value is NONE.


 GridBagConstraints.gridheight

GridBagConstraints.gridheight

Syntax
public int gridheight
Description
Specifies the number of cells in a column for the component's display area.

Use REMAINDER to specify that the component be the last one in its column. Use RELATIVE to specify that the component be the next-to-last one in its column.

The default value is 1.

See Also
gridwidth


 GridBagConstraints.gridwidth

GridBagConstraints.gridwidth

Syntax
public int gridwidth
Description
Specifies the number of cells in a row for the component's display area.

Use REMAINDER to specify that the component be the last one in its row. Use RELATIVE to specify that the component be the next-to-last one in its row.

The default value is 1.

See Also
gridheight


 GridBagConstraints.gridx

GridBagConstraints.gridx

Syntax
public int gridx
Description
Specifies the cell at the left of the component's display area, where the leftmost cell has gridx = 0. The value RELATIVE specifies that the component be placed just to the right of the component that was added to the container just before this component was added.

The default value is RELATIVE.

See Also
gridy


 GridBagConstraints.gridy

GridBagConstraints.gridy

Syntax
public int gridy
Description
Specifies the cell at the top of the component's display area, where the topmost cell has gridy = 0. The value RELATIVE specifies that the component be placed just below the component that was added to the container just before this component was added.

The default value is RELATIVE.

See Also
gridx


 GridBagConstraints.HORIZONTAL

GridBagConstraints.HORIZONTAL

Syntax
public static final int HORIZONTAL
Description
Resize the component horizontally but not vertically.


 GridBagConstraints.insets

GridBagConstraints.insets

Syntax
public Insets insets
Description
This field specifies the external padding of the component, the minimum amount of space between the component and the edges of its display area.

The default value is new Insets(0, 0, 0, 0).


 GridBagConstraints.ipadx

GridBagConstraints.ipadx

Syntax
public int ipadx
Description
This field specifies the internal padding of the component, how much space to add to the minimum width of the component. The width of the component is at least its minimum width plus (ipadx * 2) pixels.

The default value is 0.

See Also
ipady


 GridBagConstraints.ipady

GridBagConstraints.ipady

Syntax
public int ipady
Description
This field specifies the internal padding, that is, how much space to add to the minimum height of the component. The height of the component is at least its minimum height plus (ipady * 2) pixels.

The default value is 0.

See Also
ipadx


 GridBagConstraints.NONE

GridBagConstraints.NONE

Syntax
public static final int NONE
Description
Do not resize the component.


 GridBagConstraints.NORTH

GridBagConstraints.NORTH

Syntax
public static final int NORTH
Description
Put the component at the top of its display area, centered horizontally.


 GridBagConstraints.NORTHEAST

GridBagConstraints.NORTHEAST

Syntax
public static final int NORTHEAST
Description
Put the component at the top-right corner of its display area.


 GridBagConstraints.NORTHWEST

GridBagConstraints.NORTHWEST

Syntax
public static final int NORTHWEST
Description
Put the component at the top-left corner of its display area.


 GridBagConstraints.RELATIVE

GridBagConstraints.RELATIVE

Syntax
public static final int RELATIVE
Description
Specify that this component is the next-to-last component in its column or row (gridwidth, gridheight), or that this component be placed next to the previously added component (gridx, gridy).

See Also
gridwidth, gridheight, gridx, gridy


 GridBagConstraints.REMAINDER

GridBagConstraints.REMAINDER

Syntax
public static final int REMAINDER
Description
Specify that this component is the last component in its column or row.


 GridBagConstraints.SOUTH

GridBagConstraints.SOUTH

Syntax
public static final int SOUTH
Description
Put the component at the bottom of its display area, centered horizontally.


 GridBagConstraints.SOUTHEAST

GridBagConstraints.SOUTHEAST

Syntax
public static final int SOUTHEAST
Description
Put the component at the bottom-right corner of its display area.


 GridBagConstraints.SOUTHWEST

GridBagConstraints.SOUTHWEST

Syntax
public static final int SOUTHWEST
Description
Put the component at the bottom-left corner of its display area.


 GridBagConstraints.VERTICAL

GridBagConstraints.VERTICAL

Syntax
public static final int VERTICAL
Description
Resize the component vertically but not horizontally.


 GridBagConstraints.weightx

GridBagConstraints.weightx

Syntax
public double weightx
Description
Specifies how to distribute extra horizontal space.

The grid bag layout manager calculates the weight of a column to be the maximum weighty of all the components in a row. If the resulting layout is smaller horizontally than the area it needs to fill, the extra space is distributed to each column in proportion to its weight. A column that has a weight zero receives no extra space.

If all the weights are zero, all the extra space appears between the grids of the cell and the left and right edges.

The default value of this field is 0.

See Also
weighty


 GridBagConstraints.weighty

GridBagConstraints.weighty

Syntax
public double weighty
Description
Specifies how to distribute extra vertical space.

The grid bag layout manager calculates the weight of a row to be the maximum weightx of all the components in a row. If the resulting layout is smaller vertically than the area it needs to fill, the extra space is distributed to each row in proportion to its weight. A row that has a weight of zero receives no extra space.

If all the weights are zero, all the extra space appears between the grids of the cell and the top and bottom edges.

The default value of this field is 0.

See Also
weightx


 GridBagConstraints.WEST

GridBagConstraints.WEST

Syntax
public static final int WEST
Description
Put the component on the left side of its display area, centered vertically.


 GridBagConstraints.GridBagConstraints

GridBagConstraints.GridBagConstraints

Syntax
public GridBagConstraints()
Description
Creates a GridBagConstraint object with all of its fields set to their default value.


 GridBagConstraints.clone

GridBagConstraints.clone

Syntax
public Object clone()
Returns
a copy of this grid bag constraint
Description
Creates a copy of this grid bag constraint.

Overrides
clone in class Object


 Class GridBagLayout

Class java.awt.GridBagLayout

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.GridBagLayout

public class GridBagLayout
extends Object
implements LayoutManager2, Serializable

The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic rectangular grid of cells, with each component occupying one or more cells, called its display area.

Each component managed by a grid bag layout is associated with an instance of GridBagConstraints that specifies how the component is laid out within its display area.

How a GridBagLayout object places a set of components depends on the GridBagConstraints object associated with each component, and on the minimum size and the preferred size of the components' containers.

To use a grid bag layout effectively, you must customize one or more of the GridBagConstraints objects that are associated with its components. You customize a GridBagConstraints object by setting one or more of its instance variables:

gridx, gridy
Specifies the cell at the upper left of the component's display area, where the upper-left-most cell has address gridx = 0, gridy = 0. Use GridBagConstraints.RELATIVE (the default value) to specify that the component be just placed just to the right of (for gridx) or just below (for gridy) the component that was added to the container just before this component was added.
gridwidth, gridheight
Specifies the number of cells in a row (for gridwidth) or column (for gridheight) in the component's display area. The default value is 1. Use GridBagConstraints.REMAINDER to specify that the component be the last one in its row (for gridwidth) or column (for gridheight). Use GridBagConstraints.RELATIVE to specify that the component be the next to last one in its row (for gridwidth) or column (for gridheight).
fill
Used when the component's display area is larger than the component's requested size to determine whether (and how) to resize the component. Possible values are GridBagConstraints.NONE (the default), GridBagConstraints.HORIZONTAL (make the component wide enough to fill its display area horizontally, but don't change its height), GridBagConstraints.VERTICAL (make the component tall enough to fill its display area vertically, but don't change its width), and GridBagConstraints.BOTH (make the component fill its display area entirely).
ipadx, ipady
Specifies the component's internal padding within the layout, how much to add to the minimum size of the component. The width of the component will be at least its minimum width plus (ipadx * 2) pixels (since the padding applies to both sides of the component). Similarly, the height of the component will be at least the minimum height plus (ipady * 2) pixels.
insets
Specifies the component's external padding, the minimum amount of space between the component and the edges of its display area.
anchor
Used when the component is smaller than its display area to determine where (within the display area) to place the component. Valid values are GridBagConstraints.CENTER (the default), GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagConstraints.EAST, GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHWEST, GridBagConstraints.WEST, and GridBagConstraints.NORTHWEST.
weightx, weighty
Used to determine how to distribute space, which is important for specifying resizing behavior. Unless you specify a weight for at least one component in a row (weightx) and column (weighty), all the components clump together in the center of their container. This is because when the weight is zero (the default), the GridBagLayout object puts any extra space between its grid of cells and the edges of the container.

The following figure shows ten components (all buttons) managed by a grid bag layout:

Each of the ten components has the fill field of its associated GridBagConstraints object set to GridBagConstraints.BOTH. In addition, the components have the following non-default constraints:

  • Button1, Button2, Button3: weightx = 1.0
  • Button4: weightx = 1.0, gridwidth = GridBagConstraints.REMAINDER
  • Button5: gridwidth = GridBagConstraints.REMAINDER
  • Button6: gridwidth = GridBagConstraints.RELATIVE
  • Button7: gridwidth = GridBagConstraints.REMAINDER
  • Button8: gridheight = 2, weighty = 1.0
  • Button9, Button 10: gridwidth = GridBagConstraints.REMAINDER

Here is the code that implements the example shown above:

 import java.awt.*;
 import java.util.*;
 import java.applet.Applet;
 public class GridBagEx1 extends Applet {
     protected void makebutton(String name,
                               GridBagLayout gridbag,
                               GridBagConstraints c) {
         Button button = new Button(name);
         gridbag.setConstraints(button, c);
         add(button);
     }
     public void init() {
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
         setFont(new Font("Helvetica", Font.PLAIN, 14));
         setLayout(gridbag);
         c.fill = GridBagConstraints.BOTH;
         c.weightx = 1.0;
         makebutton("Button1", gridbag, c);
         makebutton("Button2", gridbag, c);
         makebutton("Button3", gridbag, c);
            c.gridwidth = GridBagConstraints.REMAINDER; //end row
         makebutton("Button4", gridbag, c);
         c.weightx = 0.0;		   //reset to the default
         makebutton("Button5", gridbag, c); //another row
        c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in row
         makebutton("Button6", gridbag, c);
        c.gridwidth = GridBagConstraints.REMAINDER; //end row
         makebutton("Button7", gridbag, c);
        c.gridwidth = 1;	   	   //reset to the default
        c.gridheight = 2;
         c.weighty = 1.0;
         makebutton("Button8", gridbag, c);
         c.weighty = 0.0;		   //reset to the default
        c.gridwidth = GridBagConstraints.REMAINDER; //end row
        c.gridheight = 1;		   //reset to the default
         makebutton("Button9", gridbag, c);
         makebutton("Button10", gridbag, c);
         setSize(300, 100);
     }
     public static void main(String args[]) {
        Frame f = new Frame("GridBag Layout Example");
        GridBagEx1 ex1 = new GridBagEx1();
        ex1.init();
        f.add("Center", ex1);
        f.pack();
        f.setSize(f.getPreferredSize());
        f.show();
     }
 }

See Also:
GridBagConstraints


 GridBagLayout Members

GridBagLayout Members

Class Overview | This Package | All Packages

Fields
Name | Description
columnWeights |
columnWidths |
comptable |
defaultConstraints |
layoutInfo |
MAXGRIDSIZE | The maximum number of grid positions (both horizontally and vertically) that can be laid out by the grid bag layout.
MINSIZE | The smallest grid that can be laid out by the grid bag layout.
PREFERREDSIZE |
rowHeights |
rowWeights |

Constructors
Name | Description
GridBagLayout() | Creates a grid bag layout manager.

Methods
Name | Description
addLayoutComponent(Component, Object) | Adds the specified component to the layout, using the specified constraint object.
addLayoutComponent(String, Component) | Adds the specified component with the specified name to the layout.
AdjustForGravity(GridBagConstraints, Rectangle) |
ArrangeGrid(Container) |
getConstraints(Component) | Gets the constraints for the specified component.
getLayoutAlignmentX(Container) | Returns the alignment along the x axis.
getLayoutAlignmentY(Container) | Returns the alignment along the y axis.
getLayoutDimensions() | Determines column widths and row heights for the layout grid.
GetLayoutInfo(Container, int) | Print the layout constraints.
getLayoutOrigin() | Determines the origin of the layout grid.
getLayoutWeights() | Determines the weights of the layout grid's columns and rows.
GetMinSize(Container, GridBagLayoutInfo) |
invalidateLayout(Container) | Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
layoutContainer(Container) | Lays out the specified container using this grid bag layout.
location(int, int) | Determines which cell in the layout grid contains the point specified by (x, y).
lookupConstraints(Component) | Retrieves the constraints for the specified component.
maximumLayoutSize(Container) | Returns the maximum dimensions for this layout given the components in the specified target container.
minimumLayoutSize(Container) | Determines the minimum size of the target container using this grid bag layout.
preferredLayoutSize(Container) | Determines the preferred size of the target container using this grid bag layout.
removeLayoutComponent(Component) | Removes the specified component from this layout.
setConstraints(Component, GridBagConstraints) | Sets the constraints for the specified component in this layout.
toString() | Returns a string representation of this grid bag layout's values.


 GridBagLayout.columnWeights

GridBagLayout.columnWeights

Syntax
public double columnWeights[]


 GridBagLayout.columnWidths

GridBagLayout.columnWidths

Syntax
public int columnWidths[]


 GridBagLayout.comptable

GridBagLayout.comptable

Syntax
protected Hashtable comptable


 GridBagLayout.defaultConstraints

GridBagLayout.defaultConstraints

Syntax
protected GridBagConstraints defaultConstraints


 GridBagLayout.layoutInfo

GridBagLayout.layoutInfo

Syntax
protected GridBagLayoutInfo layoutInfo


 GridBagLayout.MAXGRIDSIZE

GridBagLayout.MAXGRIDSIZE

Syntax
protected static final int MAXGRIDSIZE
Description
The maximum number of grid positions (both horizontally and vertically) that can be laid out by the grid bag layout.


 GridBagLayout.MINSIZE

GridBagLayout.MINSIZE

Syntax
protected static final int MINSIZE
Description
The smallest grid that can be laid out by the grid bag layout.


 GridBagLayout.PREFERREDSIZE

GridBagLayout.PREFERREDSIZE

Syntax
protected static final int PREFERREDSIZE


 GridBagLayout.rowHeights

GridBagLayout.rowHeights

Syntax
public int rowHeights[]


 GridBagLayout.rowWeights

GridBagLayout.rowWeights

Syntax
public double rowWeights[]


 GridBagLayout.GridBagLayout

GridBagLayout.GridBagLayout

Syntax
public GridBagLayout()
Description
Creates a grid bag layout manager.


 GridBagLayout.addLayoutComponent

GridBagLayout.addLayoutComponent

Syntax 1
public void addLayoutComponent( String name, Component comp )
Parameters
name
the name of the component.
comp
the component to be added.
Description
Adds the specified component with the specified name to the layout.

Syntax 2
public void addLayoutComponent( Component comp, Object constraints )
Parameters
comp
the component to be added.
constraints
an object that determines how the component is added to the layout.
Description
Adds the specified component to the layout, using the specified constraint object.


 GridBagLayout.AdjustForGravity

GridBagLayout.AdjustForGravity

Syntax
protected void AdjustForGravity( GridBagConstraints constraints, Rectangle r )


 GridBagLayout.ArrangeGrid

GridBagLayout.ArrangeGrid

Syntax
protected void ArrangeGrid( Container parent )


 GridBagLayout.getConstraints

GridBagLayout.getConstraints

Syntax
public GridBagConstraints getConstraints( Component comp )
Parameters
comp
the component to be queried.
Returns
the constraint for the specified component in this grid bag layout; a copy of the actual constraint object is returned.
Description
Gets the constraints for the specified component. A copy of the actual GridBagConstraints object is returned.


 GridBagLayout.getLayoutAlignmentX

GridBagLayout.getLayoutAlignmentX

Syntax
public float getLayoutAlignmentX( Container parent )
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 GridBagLayout.getLayoutAlignmentY

GridBagLayout.getLayoutAlignmentY

Syntax
public float getLayoutAlignmentY( Container parent )
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 GridBagLayout.getLayoutDimensions

GridBagLayout.getLayoutDimensions

Syntax
public int[][] getLayoutDimensions()
Returns
an array of two arrays, containing the widths of the layout columns and the heights of the layout rows.
Description
Determines column widths and row heights for the layout grid.

Most applications do not call this method directly.


 GridBagLayout.GetLayoutInfo

GridBagLayout.GetLayoutInfo

Syntax
protected GridBagLayoutInfo GetLayoutInfo( Container parent, int sizeflag )
Description
Print the layout constraints. Useful for debugging.


 GridBagLayout.getLayoutOrigin

GridBagLayout.getLayoutOrigin

Syntax
public Point getLayoutOrigin()
Returns
the origin of the cell in the top-left corner of the layout grid.
Description
Determines the origin of the layout grid. Most applications do not call this method directly.


 GridBagLayout.getLayoutWeights

GridBagLayout.getLayoutWeights

Syntax
public double[][] getLayoutWeights()
Returns
an array of two arrays, representing the horizontal weights of the layout columns and the vertical weights of the layout rows.
Description
Determines the weights of the layout grid's columns and rows. Weights are used to calculate how much a given column or row stretches beyond its preferred size, if the layout has extra room to fill.

Most applications do not call this method directly.


 GridBagLayout.GetMinSize

GridBagLayout.GetMinSize

Syntax
protected Dimension GetMinSize( Container parent, GridBagLayoutInfo info )


 GridBagLayout.invalidateLayout

GridBagLayout.invalidateLayout

Syntax
public void invalidateLayout( Container target )
Description
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.


 GridBagLayout.layoutContainer

GridBagLayout.layoutContainer

Syntax
public void layoutContainer( Container parent )
Parameters
parent
the container in which to do the layout.
Description
Lays out the specified container using this grid bag layout. This method reshapes components in the specified container in order to satisfy the contraints of this GridBagLayout object.

Most applications do not call this method directly.

See Also
Container, doLayout


 GridBagLayout.location

GridBagLayout.location

Syntax
public Point location( int x, int y )
Parameters
x
the x coordinate of a point.
y
the y coordinate of a point.
Returns
an ordered pair of indexes that indicate which cell in the layout grid contains the point (x, y).
Description
Determines which cell in the layout grid contains the point specified by (x, y). Each cell is identified by its column index (ranging from 0 to the number of columns minus 1) and its row index (ranging from 0 to the number of rows minus 1).

If the (x, y) point lies outside the grid, the following rules are used. The column index is returned as zero if x lies to the left of the layout, and as the number of columns if x lies to the right of the layout. The row index is returned as zero if y lies above the layout, and as the number of rows if y lies below the layout.


 GridBagLayout.lookupConstraints

GridBagLayout.lookupConstraints

Syntax
protected GridBagConstraints lookupConstraints( Component comp )
Parameters
comp
the component to be queried
Returns
the contraints for the specified component.
Description
Retrieves the constraints for the specified component. The return value is not a copy, but is the actual GridBagConstraints object used by the layout mechanism.


 GridBagLayout.maximumLayoutSize

GridBagLayout.maximumLayoutSize

Syntax
public Dimension maximumLayoutSize( Container target )
Parameters
target
the component which needs to be laid out
Description
Returns the maximum dimensions for this layout given the components in the specified target container.

See Also
Container, minimumLayoutSize, preferredLayoutSize


 GridBagLayout.minimumLayoutSize

GridBagLayout.minimumLayoutSize

Syntax
public Dimension minimumLayoutSize( Container parent )
Parameters
target
the container in which to do the layout.
Description
Determines the minimum size of the target container using this grid bag layout.

Most applications do not call this method directly.

See Also
doLayout


 GridBagLayout.preferredLayoutSize

GridBagLayout.preferredLayoutSize

Syntax
public Dimension preferredLayoutSize( Container parent )
Parameters
target
the container in which to do the layout.
Description
Determines the preferred size of the target container using this grid bag layout.

Most applications do not call this method directly.

See Also
getPreferredSize


 GridBagLayout.removeLayoutComponent

GridBagLayout.removeLayoutComponent

Syntax
public void removeLayoutComponent( Component comp )
Parameters
comp
the component to be removed.
Description
Removes the specified component from this layout.

Most applications do not call this method directly.

See Also
remove, removeAll


 GridBagLayout.setConstraints

GridBagLayout.setConstraints

Syntax
public void setConstraints( Component comp, GridBagConstraints constraints )
Parameters
comp
the component to be modified.
constraints
the constraints to be applied.
Description
Sets the constraints for the specified component in this layout.


 GridBagLayout.toString

GridBagLayout.toString

Syntax
public String toString()
Returns
a string representation of this grid bag layout.
Description
Returns a string representation of this grid bag layout's values.

Overrides
toString in class Object


 Class GridLayout

Class java.awt.GridLayout

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.GridLayout

public class GridLayout
extends Object
implements LayoutManager, Serializable

The GridLayout class is a layout manager that lays out a container's components in a rectangular grid.

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

For example, the following is an applet that lays out six buttons into three rows and two columns:

 import java.awt.*;
 import java.applet.Applet;
 public class ButtonGrid extends Applet {
     public void init() {
         setLayout(new GridLayout(3,2));
         add(new Button("1"));
         add(new Button("2"));
         add(new Button("3"));
         add(new Button("4"));
         add(new Button("5"));
         add(new Button("6"));
     }
 }

It produces the following output:


 GridLayout Members

GridLayout Members

Class Overview | This Package | All Packages

Constructors
Name | Description
GridLayout() | Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int, int) | Creates a grid layout with the specified number of rows and columns.
GridLayout(int, int, int, int) | Creates a grid layout with the specified number of rows and columns.

Methods
Name | Description
addLayoutComponent(String, Component) | Adds the specified component with the specified name to the layout.
getColumns() | Gets the number of columns in this layout.
getHgap() | Gets the horizontal gap between components.
getRows() | Gets the number of rows in this layout.
getVgap() | Gets the vertical gap between components.
layoutContainer(Container) | Lays out the specified container using this layout.
minimumLayoutSize(Container) | Determines the minimum size of the container argument using this grid layout.
preferredLayoutSize(Container) | Determines the preferred size of the container argument using this grid layout.
removeLayoutComponent(Component) | Removes the specified component from the layout.
setColumns(int) | Sets the number of columns in this layout to the specified value.
setHgap(int) | Sets the horizontal gap between components to the specified value.
setRows(int) | Sets the number of rows in this layout to the specified value.
setVgap(int) | Sets the vertical gap between components to the specified value.
toString() | Returns the string representation of this grid layout's values.


 GridLayout.GridLayout

GridLayout.GridLayout

Syntax 1
public GridLayout()
Description
Creates a grid layout with a default of one column per component, in a single row.

Syntax 2
public GridLayout( int rows, int cols )
Parameters
rows
the rows, with the value zero meaning any number of rows.
cols
the columns, with the value zero meaning any number of columns.
Description
Creates a grid layout with the specified number of rows and columns. All components in the layout are given equal size.

One, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column.

Syntax 3
public GridLayout( int rows, int cols, int hgap, int vgap )
Parameters
rows
the rows, with the value zero meaning any number of rows.
cols
the columns, with the value zero meaning any number of columns.
hgap
the horizontal gap.
vgap
the vertical gap.
Description
Creates a grid layout with the specified number of rows and columns. All components in the layout are given equal size.

In addition, the horizontal and vertical gaps are set to the specified values. Horizontal gaps are placed at the left and right edges, and between each of the columns. Vertical gaps are placed at the top and bottom edges, and between each of the rows.

One, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column.

Exceptions
IllegalArgumentException if the of rows or cols is invalid.


 GridLayout.addLayoutComponent

GridLayout.addLayoutComponent

Syntax
public void addLayoutComponent( String name, Component comp )
Parameters
name
the name of the component.
comp
the component to be added.
Description
Adds the specified component with the specified name to the layout.


 GridLayout.getColumns

GridLayout.getColumns

Syntax
public int getColumns()
Returns
the number of columns in this layout.
Description
Gets the number of columns in this layout.


 GridLayout.getHgap

GridLayout.getHgap

Syntax
public int getHgap()
Returns
the horizontal gap between components.
Description
Gets the horizontal gap between components.


 GridLayout.getRows

GridLayout.getRows

Syntax
public int getRows()
Returns
the number of rows in this layout.
Description
Gets the number of rows in this layout.


 GridLayout.getVgap

GridLayout.getVgap

Syntax
public int getVgap()
Returns
the vertical gap between components.
Description
Gets the vertical gap between components.


 GridLayout.layoutContainer

GridLayout.layoutContainer

Syntax
public void layoutContainer( Container parent )
Parameters
target
the container in which to do the layout.
Description
Lays out the specified container using this layout.

This method reshapes the components in the specified target container in order to satisfy the constraints of the GridLayout object.

The grid layout manager determines the size of individual components by dividing the free space in the container into equal-sized portions according to the number of rows and columns in the layout. The container's free space equals the container's size minus any insets and any specified horizontal or vertical gap. All components in a grid layout are given the same size.

See Also
Container, doLayout


 GridLayout.minimumLayoutSize

GridLayout.minimumLayoutSize

Syntax
public Dimension minimumLayoutSize( Container parent )
Parameters
target
the container in which to do the layout.
Returns
the minimum dimensions needed to lay out the subcomponents of the specified container.
Description
Determines the minimum size of the container argument using this grid layout.

The minimum width of a grid layout is the largest minimum width of any of the widths in the container times the number of columns, plus the horizontal padding times the number of columns plus one, plus the left and right insets of the target container.

The minimum height of a grid layout is the largest minimum height of any of the widths in the container times the number of rows, plus the vertical padding times the number of rows plus one, plus the top and left insets of the target container.

See Also
preferredLayoutSize, doLayout


 GridLayout.preferredLayoutSize

GridLayout.preferredLayoutSize

Syntax
public Dimension preferredLayoutSize( Container parent )
Parameters
target
the container in which to do the layout.
Returns
the preferred dimensions to lay out the subcomponents of the specified container.
Description
Determines the preferred size of the container argument using this grid layout.

The preferred width of a grid layout is the largest preferred width of any of the widths in the container times the number of columns, plus the horizontal padding times the number of columns plus one, plus the left and right insets of the target container.

The preferred height of a grid layout is the largest preferred height of any of the widths in the container times the number of rows, plus the vertical padding times the number of rows plus one, plus the top and left insets of the target container.

See Also
minimumLayoutSize, getPreferredSize


 GridLayout.removeLayoutComponent

GridLayout.removeLayoutComponent

Syntax
public void removeLayoutComponent( Component comp )
Parameters
comp
the component to be removed.
Description
Removes the specified component from the layout.


 GridLayout.setColumns

GridLayout.setColumns

Syntax
public void setColumns( int cols )
Parameters
cols
the number of columns in this layout.
Description
Sets the number of columns in this layout to the specified value.

Exceptions
IllegalArgumentException if the value of both rows and cols is set to zero.


 GridLayout.setHgap

GridLayout.setHgap

Syntax
public void setHgap( int hgap )
Parameters
hgap
the horizontal gap between components.
Description
Sets the horizontal gap between components to the specified value.


 GridLayout.setRows

GridLayout.setRows

Syntax
public void setRows( int rows )
Parameters
rows
the number of rows in this layout.
Description
Sets the number of rows in this layout to the specified value.

Exceptions
IllegalArgumentException if the value of both rows and cols is set to zero.


 GridLayout.setVgap

GridLayout.setVgap

Syntax
public void setVgap( int vgap )
Parameters
vgap
the vertical gap between components.
Description
Sets the vertical gap between components to the specified value.


 GridLayout.toString

GridLayout.toString

Syntax
public String toString()
Returns
a string representation of this grid layout.
Description
Returns the string representation of this grid layout's values.

Overrides
toString in class Object


 Class IllegalComponentStateException

Class java.awt.IllegalComponentStateException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalStateException
                                   |
                                   +----java.awt.IllegalComponentStateException

public class IllegalComponentStateException
extends IllegalStateException

Signals that an AWT component is not in an appropriate state for the requested operation.


 IllegalComponentStateException Members

IllegalComponentStateException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalComponentStateException() | Constructs an IllegalComponentStateException with no detail message.
IllegalComponentStateException(String) | Constructs an IllegalComponentStateException with the specified detail message.


 IllegalComponentStateException.IllegalComponentStateException

IllegalComponentStateException.IllegalComponentStateException

Class Overview | Class Members | This Package | All Packages

Syntax 1
public IllegalComponentStateException()
Description
Constructs an IllegalComponentStateException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public IllegalComponentStateException( String s )
Parameters
s
the String that contains a detailed message
Description
Constructs an IllegalComponentStateException with the specified detail message. A detail message is a String that describes this particular exception.


 Class Image

Class java.awt.Image

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Image

public abstract class Image
extends Object

The abstract class Image is the superclass of all classes that represent graphical images. The image must be obtained in a platform-specific manner.


 Image Members

Image Members

Class Overview | This Package | All Packages

Fields
Name | Description
SCALE_AREA_AVERAGING | Use the Area Averaging image scaling algorithm.
SCALE_DEFAULT | Use the default image-scaling algorithm.
SCALE_FAST | Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
SCALE_REPLICATE | Use the image scaling algorithm embodied in the ReplicateScaleFilter class.
SCALE_SMOOTH | Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
UndefinedProperty | The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.

Constructors
Name | Description
Image() |

Methods
Name | Description
flush() | Flushes all resources being used by this Image object.
getGraphics() | Creates a graphics context for drawing to an off-screen image.
getHeight(ImageObserver) | Determines the height of the image.
getProperty(String, ImageObserver) | Gets a property of this image by name.
getScaledInstance(int, int, int) | Creates a scaled version of this image.
getSource() | Gets the object that produces the pixels for the image.
getWidth(ImageObserver) | Determines the width of the image.


 Image.SCALE_AREA_AVERAGING

Image.SCALE_AREA_AVERAGING

Syntax
public static final int SCALE_AREA_AVERAGING
Description
Use the Area Averaging image scaling algorithm. The image object is free to substitute a different filter that performs the same algorithm yet integrates more efficiently into the image infrastructure supplied by the toolkit.

See Also
AreaAveragingScaleFilter


 Image.SCALE_DEFAULT

Image.SCALE_DEFAULT

Syntax
public static final int SCALE_DEFAULT
Description
Use the default image-scaling algorithm.


 Image.SCALE_FAST

Image.SCALE_FAST

Syntax
public static final int SCALE_FAST
Description
Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.


 Image.SCALE_REPLICATE

Image.SCALE_REPLICATE

Syntax
public static final int SCALE_REPLICATE
Description
Use the image scaling algorithm embodied in the ReplicateScaleFilter class. The Image object is free to substitute a different filter that performs the same algorithm yet integrates more efficiently into the imaging infrastructure supplied by the toolkit.

See Also
ReplicateScaleFilter


 Image.SCALE_SMOOTH

Image.SCALE_SMOOTH

Syntax
public static final int SCALE_SMOOTH
Description
Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.


 Image.UndefinedProperty

Image.UndefinedProperty

Syntax
public static final Object UndefinedProperty
Description
The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.


 Image.Image

Image.Image

Syntax
public Image()


 Image.flush

Image.flush

Syntax
public abstract void flush()
Description
Flushes all resources being used by this Image object. This includes any pixel data that is being cached for rendering to the screen as well as any system resources that are being used to store data or pixels for the image. The image is reset to a state similar to when it was first created so that if it is again rendered, the image data will have to be recreated or fetched again from its source.


 Image.getGraphics

Image.getGraphics

Syntax
public abstract Graphics getGraphics()
Returns
a graphics context to draw to the off-screen image.
Description
Creates a graphics context for drawing to an off-screen image. This method can only be called for off-screen images.

See Also
Graphics, createImage


 Image.getHeight

Image.getHeight

Syntax
public abstract int getHeight( ImageObserver observer )
Parameters
observer
an object waiting for the image to be loaded.
Returns
the height of this image, or -1 if the height is not yet known.
Description
Determines the height of the image. If the height is not yet known, this method returns -1 and the specified ImageObserver object is notified later.

See Also
getWidth, ImageObserver


 Image.getProperty

Image.getProperty

Syntax
public abstract Object getProperty( String name, ImageObserver observer )
Parameters
name
a property name.
observer
an object waiting for this image to be loaded.
Returns
the value of the named property.
Description
Gets a property of this image by name.

Individual property names are defined by the various image formats. If a property is not defined for a particular image, this method returns the UndefinedProperty object.

If the properties for this image are not yet known, this method returns null, and the ImageObserver object is notified later.

The property name "comment" should be used to store an optional comment which can be presented to the application as a description of the image, its source, or its author.

See Also
ImageObserver, UndefinedProperty


 Image.getScaledInstance

Image.getScaledInstance

Syntax
public Image getScaledInstance( int width, int height, int hints )
Parameters
width
the width to which to scale the image.
height
the height to which to scale the image.
hints
flags to indicate the type of algorithm to use for image resampling.
Returns
a scaled version of the image.
Description
Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely. If either the width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions.

See Also
SCALE_DEFAULT, SCALE_FAST, SCALE_SMOOTH, SCALE_REPLICATE, SCALE_AREA_AVERAGING


 Image.getSource

Image.getSource

Syntax
public abstract ImageProducer getSource()
Returns
the image producer that produces the pixels for this image.
Description
Gets the object that produces the pixels for the image. This method is called by the image filtering classes and by methods that perform image conversion and scaling.

See Also
ImageProducer


 Image.getWidth

Image.getWidth

Syntax
public abstract int getWidth( ImageObserver observer )
Parameters
observer
an object waiting for the image to be loaded.
Returns
the width of this image, or -1 if the width is not yet known.
Description
Determines the width of the image. If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later.

See Also
getHeight, ImageObserver


 Class Insets

Class java.awt.Insets

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Insets

public class Insets
extends Object
implements Cloneable, Serializable

An Insets object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title.

See Also:
LayoutManager, Container


 Insets Members

Insets Members

Class Overview | This Package | All Packages

Fields
Name | Description
bottom | The inset from the bottom.
left | The inset from the left.
right | The inset from the right.
top | The inset from the top.

Constructors
Name | Description
Insets(int, int, int, int) | Creates and initializes a new Insets object with the specified top, left, bottom, and right insets.

Methods
Name | Description
clone() | Create a copy of this object.
equals(Object) | Checks whether two insets objects are equal.
toString() | Returns a String object representing this Insets object's values.


 Insets.bottom

Insets.bottom

Syntax
public int bottom
Description
The inset from the bottom.


 Insets.left

Insets.left

Syntax
public int left
Description
The inset from the left.


 Insets.right

Insets.right

Syntax
public int right
Description
The inset from the right.


 Insets.top

Insets.top

Syntax
public int top
Description
The inset from the top.


 Insets.Insets

Insets.Insets

Syntax
public Insets( int top, int left, int bottom, int right )
Parameters
top
the inset from the top.
left
the inset from the left.
bottom
the inset from the bottom.
right
the inset from the right.
Description
Creates and initializes a new Insets object with the specified top, left, bottom, and right insets.


 Insets.clone

Insets.clone

Syntax
public Object clone()
Returns
a copy of this Insets object.
Description
Create a copy of this object.

Overrides
clone in class Object


 Insets.equals

Insets.equals

Syntax
public boolean equals( Object obj )
Returns
true if the two insets are equal; otherwise false.
Description
Checks whether two insets objects are equal. Two instances of Insets are equal if the four integer values of the fields top, left, bottom, and right are all equal.

Overrides
equals in class Object


 Insets.toString

Insets.toString

Syntax
public String toString()
Returns
a string representation of this Insets object, including the values of its member fields.
Description
Returns a String object representing this Insets object's values.

Overrides
toString in class Object


 Interface ItemSelectable

Interface java.awt.ItemSelectable

Interface Members | This Package | All Packages

public interface ItemSelectable

The interface for objects which contain a set of items for which zero or more can be selected.


 ItemSelectable Members

ItemSelectable Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addItemListener(ItemListener) | Add a listener to recieve item events when the state of an item changes.
getSelectedObjects() | Returns the selected items or null if no items are selected.
removeItemListener(ItemListener) | Removes an item listener.


 ItemSelectable.addItemListener

ItemSelectable.addItemListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addItemListener( ItemListener l )
Parameters
l
the listener to recieve events
Description
Add a listener to recieve item events when the state of an item changes.

See Also
ItemEvent


 ItemSelectable.getSelectedObjects

ItemSelectable.getSelectedObjects

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object[] getSelectedObjects()
Description
Returns the selected items or null if no items are selected.


 ItemSelectable.removeItemListener

ItemSelectable.removeItemListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removeItemListener( ItemListener l )
Parameters
l
the listener being removed
Description
Removes an item listener.

See Also
ItemEvent


 Class Label

Class java.awt.Label

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Label

public class Label
extends Component

A Label object is a component for placing text in a container. A label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly.

For example, the code . . .

 setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
 add(new Label("Hi There!"));
 add(new Label("Another Label"));

produces the following label:


 Label Members

Label Members

Class Overview | This Package | All Packages

Fields
Name | Description
CENTER | Indicates that the label should be centered.
LEFT | Indicates that the label should be left justified.
RIGHT | Indicates that the label should be right justified.

Constructors
Name | Description
Label() | Constructs an empty label.
Label(String) | Constructs a new label with the specified string of text, left justified.
Label(String, int) | Constructs a new label that presents the specified string of text with the specified alignment.

Methods
Name | Description
addNotify() | Creates the peer for this label.
getAlignment() | Gets the current alignment of this label.
getText() | Gets the text of this label.
paramString() | Returns the parameter string representing the state of this label.
setAlignment(int) | Sets the alignment for this label to the specified alignment.
setText(String) | Sets the text for this label to the specified text.


 Label.CENTER

Label.CENTER

Syntax
public static final int CENTER
Description
Indicates that the label should be centered.


 Label.LEFT

Label.LEFT

Syntax
public static final int LEFT
Description
Indicates that the label should be left justified.


 Label.RIGHT

Label.RIGHT

Syntax
public static final int RIGHT
Description
Indicates that the label should be right justified.


 Label.Label

Label.Label

Syntax 1
public Label()
Description
Constructs an empty label.

Syntax 2
public Label( String text )
Parameters
text
the string that the label presents.
Description
Constructs a new label with the specified string of text, left justified.

Syntax 3
public Label( String text, int alignment )
Parameters
text
the string that the label presents.
alignment
the alignment value.
Description
Constructs a new label that presents the specified string of text with the specified alignment.

Possible values for alignment are Label.LEFT, Label.RIGHT, and Label.CENTER.


 Label.addNotify

Label.addNotify

Syntax
public void addNotify()
Description
Creates the peer for this label. The peer allows us to modify the appearance of the label without changing its functionality.

Overrides
addNotify in class Component


 Label.getAlignment

Label.getAlignment

Syntax
public int getAlignment()
Description
Gets the current alignment of this label. Possible values are Label.LEFT, Label.RIGHT, and Label.CENTER.

See Also
setAlignment


 Label.getText

Label.getText

Syntax
public String getText()
Returns
the text of this label.
Description
Gets the text of this label.

See Also
setText


 Label.paramString

Label.paramString

Syntax
protected String paramString()
Returns
the parameter string of this label.
Description
Returns the parameter string representing the state of this label. This string is useful for debugging.

Overrides
paramString in class Component


 Label.setAlignment

Label.setAlignment

Syntax
public synchronized void setAlignment( int alignment )
Parameters
alignment
the alignment to be set.
Description
Sets the alignment for this label to the specified alignment. Possible values are Label.LEFT, Label.RIGHT, and Label.CENTER.

Exceptions
IllegalArgumentException if an improper value for alignment is given.
See Also
getAlignment


 Label.setText

Label.setText

Syntax
public synchronized void setText( String text )
Parameters
text
the text that this label presents.
Description
Sets the text for this label to the specified text.

See Also
getText


 Interface LayoutManager

Interface java.awt.LayoutManager

Interface Members | This Package | All Packages

public interface LayoutManager

Defines the interface for classes that know how to layout Containers.

See Also:
Container


 LayoutManager Members

LayoutManager Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addLayoutComponent(String, Component) | Adds the specified component with the specified name to the layout.
layoutContainer(Container) | Lays out the container in the specified panel.
minimumLayoutSize(Container) | Calculates the minimum size dimensions for the specified panel given the components in the specified parent container.
preferredLayoutSize(Container) | Calculates the preferred size dimensions for the specified panel given the components in the specified parent container.
removeLayoutComponent(Component) | Removes the specified component from the layout.


 LayoutManager.addLayoutComponent

LayoutManager.addLayoutComponent

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addLayoutComponent( String name, Component comp )
Parameters
name
the component name
comp
the component to be added
Description
Adds the specified component with the specified name to the layout.


 LayoutManager.layoutContainer

LayoutManager.layoutContainer

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void layoutContainer( Container parent )
Parameters
parent
the component which needs to be laid out
Description
Lays out the container in the specified panel.


 LayoutManager.minimumLayoutSize

LayoutManager.minimumLayoutSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Dimension minimumLayoutSize( Container parent )
Parameters
parent
the component to be laid out
Description
Calculates the minimum size dimensions for the specified panel given the components in the specified parent container.

See Also
preferredLayoutSize


 LayoutManager.preferredLayoutSize

LayoutManager.preferredLayoutSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Dimension preferredLayoutSize( Container parent )
Parameters
parent
the component to be laid out
Description
Calculates the preferred size dimensions for the specified panel given the components in the specified parent container.

See Also
minimumLayoutSize


 LayoutManager.removeLayoutComponent

LayoutManager.removeLayoutComponent

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removeLayoutComponent( Component comp )
Parameters
comp
the component ot be removed
Description
Removes the specified component from the layout.


 Interface LayoutManager2

Interface java.awt.LayoutManager2

Interface Members | This Package | All Packages

public interface LayoutManager2
extends LayoutManager

Defines an interface for classes that know how to layout Containers based on a layout constraints object. This interface extends the LayoutManager interface to deal with layouts explicitly in terms of constraint objects that specify how and where components should be added to the layout.

This minimal extension to LayoutManager is intended for tool providers who wish to the creation of constraint-based layouts. It does not yet provide full, general support for custom constraint-based layout managers.

See Also:
LayoutManager, Container


 LayoutManager2 Members

LayoutManager2 Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addLayoutComponent(Component, Object) | Adds the specified component to the layout, using the specified constraint object.
getLayoutAlignmentX(Container) | Returns the alignment along the x axis.
getLayoutAlignmentY(Container) | Returns the alignment along the y axis.
invalidateLayout(Container) | Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
maximumLayoutSize(Container) | Returns the maximum size of this component.


 LayoutManager2.addLayoutComponent

LayoutManager2.addLayoutComponent

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addLayoutComponent( Component comp, Object constraints )
Parameters
comp
the component to be added
constraints
where/how the component is added to the layout.
Description
Adds the specified component to the layout, using the specified constraint object.


 LayoutManager2.getLayoutAlignmentX

LayoutManager2.getLayoutAlignmentX

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float getLayoutAlignmentX( Container target )
Description
Returns the alignment along the x axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 LayoutManager2.getLayoutAlignmentY

LayoutManager2.getLayoutAlignmentY

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float getLayoutAlignmentY( Container target )
Description
Returns the alignment along the y axis. This specifies how the component would like to be aligned relative to other components. The value should be a number between 0 and 1 where 0 represents alignment along the origin, 1 is aligned the furthest away from the origin, 0.5 is centered, etc.


 LayoutManager2.invalidateLayout

LayoutManager2.invalidateLayout

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void invalidateLayout( Container target )
Description
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.


 LayoutManager2.maximumLayoutSize

LayoutManager2.maximumLayoutSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Dimension maximumLayoutSize( Container target )
Description
Returns the maximum size of this component.

See Also
getMinimumSize, getPreferredSize, LayoutManager


 Class List

Class java.awt.List

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.List

public class List
extends Component
implements ItemSelectable

The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items.

For example, the code . . .

 List lst = new List(4, false);
 lst.add("Mercury");
 lst.add("Venus");
 lst.add("Earth");
 lst.add("JavaSoft");
 lst.add("Mars");
 lst.add("Jupiter");
 lst.add("Saturn");
 lst.add("Uranus");
 lst.add("Neptune");
 lst.add("Pluto");
 cnt.add(lst);

where cnt is a container, produces the following scrolling list:

Clicking on an item that isn't selected selects it. Clicking on an item that is already selected deselects it. In the preceding example, only one item from the scrolling list can be selected at a time, since the second argument when creating the new scrolling list is false. Selecting an item causes any other selected item to be automatically deselected.

Beginning with Java 1.1, the Abstract Window Toolkit sends the List object all mouse, keyboard, and focus events that occur over it. (The old AWT event model is being maintained only for backwards compatibility, and its use is discouraged.)

When an item is selected or deselected, AWT sends an instance of ItemEvent to the list. When the user double-clicks on an item in a scrolling list, AWT sends an instance of ActionEvent to the list following the item event. AWT also generates an action event when the user presses the return key while an item in the list is selected.

If an application wants to perform some action based on an item in this list being selected or activated, it should implement ItemListener or ActionListener as appropriate and register the new listener to receive events from this list.

For multiple-selection scrolling lists, it is considered a better user interface to use an external gesture (such as clicking on a button) to trigger the action.

See Also:
ItemEvent, ItemListener, ActionEvent, ActionListener


 List Members

List Members

Class Overview | This Package | All Packages

Constructors
Name | Description
List() | Creates a new scrolling list.
List(int) | Creates a new scrolling list initialized with the specified number of visible lines.
List(int, boolean) | Creates a new scrolling list initialized to display the specified number of rows.

Methods
Name | Description
add(String) | Adds the specified item to the end of scrolling list.
add(String, int) | Adds the specified item to the end of the scrolling list.
addActionListener(ActionListener) | Adds the specified action listener to receive action events from this list.
addItem(String) | Deprecated.
addItem(String, int) | Deprecated.
addItemListener(ItemListener) | Adds the specified item listener to receive item events from this list.
addNotify() | Creates the peer for the list.
allowsMultipleSelections() | Deprecated.
clear() | Deprecated.
countItems() | Deprecated.
delItem(int) | Deprecated.
delItems(int, int) | Deprecated.
deselect(int) | Deselects the item at the specified index.
getItem(int) | Gets the item associated with the specified index.
getItemCount() | Gets the number of items in the list.
getItems() | Gets the items in the list.
getMinimumSize() | Determines the minimum size of this scrolling list.
getMinimumSize(int) | Gets the minumum dimensions for a list with the specified number of rows.
getPreferredSize() | Gets the preferred size of this scrolling list.
getPreferredSize(int) | Gets the preferred dimensions for a list with the specified number of rows.
getRows() | Get the number of visible lines in this list.
getSelectedIndex() | Gets the index of the selected item on the list,
getSelectedIndexes() | Gets the selected indexes on the list.
getSelectedItem() | Get the selected item on this scrolling list.
getSelectedItems() | Get the selected items on this scrolling list.
getSelectedObjects() | Returns the selected items on the list in an array of Objects.
getVisibleIndex() | Gets the index of the item that was last made visible by the method makeVisible.
isIndexSelected(int) | Determines if the specified item in this scrolling list is selected.
isMultipleMode() | Determines whether this list allows multiple selections.
isSelected(int) | Deprecated.
makeVisible(int) | Makes the item at the specified index visible.
minimumSize() | Deprecated.
minimumSize(int) | Deprecated.
paramString() | Returns the parameter string representing the state of this scrolling list.
preferredSize() | Deprecated.
preferredSize(int) | Deprecated.
processActionEvent(ActionEvent) | Processes action events occurring on this component by dispatching them to any registered ActionListener objects.
processEvent(AWTEvent) | Processes events on this scrolling list.
processItemEvent(ItemEvent) | Processes item events occurring on this list by dispatching them to any registered ItemListener objects.
remove(int) | Remove the item at the specified position from this scrolling list.
remove(String) | Removes the first occurrence of an item from the list.
removeActionListener(ActionListener) | Removes the specified action listener so that it no longer receives action events from this list.
removeAll() | Removes all items from this list.
removeItemListener(ItemListener) | Removes the specified item listener so that it no longer receives item events from this list.
removeNotify() | Removes the peer for this list.
replaceItem(String, int) | Replaces the item at the specified index in the scrolling list with the new string.
select(int) | Selects the item at the specified index in the scrolling list.
setMultipleMode(boolean) | Sets the flag that determines whether this list allows multiple selections.
setMultipleSelections(boolean) | Deprecated.


 List.List

List.List

Syntax 1
public List()
Description
Creates a new scrolling list. Initially there are no visible lines, and only one item can be selected from the list.

Syntax 2
public List( int rows )
Parameters
rows
the number of items to show.
Description
Creates a new scrolling list initialized with the specified number of visible lines. By default, multiple selections are not allowed.

Syntax 3
public List( int rows, boolean multipleMode )
Parameters
rows
the number of items to show.
multipleMode
if true, then multiple selections are allowed; otherwise, only one item can be selected at a time.
Description
Creates a new scrolling list initialized to display the specified number of rows. If the value of multipleMode is true, then the user can select multiple items from the list. If it is false, only one item at a time can be selected.


 List.add

List.add

Syntax 1
public void add( String item )
Parameters
item
the item to be added.
Description
Adds the specified item to the end of scrolling list.

Syntax 2
public synchronized void add( String item, int index )
Parameters
item
the item to be added.
index
the position at which to add the item.
Description
Adds the specified item to the end of the scrolling list. The index is zero-based. If value of the index is -1 then the item is added to the end. If value of the index is greater than the number of items in the list, the item is added at the end.


 List.addActionListener

List.addActionListener

Syntax
public synchronized void addActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Adds the specified action listener to receive action events from this list. Action events occur when a user double-clicks on a list item.

See Also
ActionEvent, ActionListener, removeActionListener


 List.addItem

List.addItem

Syntax 1
public void addItem( String item )
Description
Note: addItem() is deprecated. replaced by add(String).

Syntax 2
public synchronized void addItem( String item, int index )
Description
Note: addItem() is deprecated. replaced by add(String, int).


 List.addItemListener

List.addItemListener

Syntax
public synchronized void addItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Adds the specified item listener to receive item events from this list.

See Also
ItemEvent, ItemListener, removeItemListener


 List.addNotify

List.addNotify

Syntax
public void addNotify()
Description
Creates the peer for the list. The peer allows us to modify the list's appearance without changing its functionality.

Overrides
addNotify in class Component


 List.allowsMultipleSelections

List.allowsMultipleSelections

Syntax
public boolean allowsMultipleSelections()
Description
Note: allowsMultipleSelections() is deprecated. As of JDK version 1.1, replaced by isMultipleMode().


 List.clear

List.clear

Syntax
public synchronized void clear()
Description
Note: clear() is deprecated. As of JDK version 1.1, replaced by removeAll().


 List.countItems

List.countItems

Syntax
public int countItems()
Description
Note: countItems() is deprecated. As of JDK version 1.1, replaced by getItemCount().


 List.delItem

List.delItem

Syntax
public synchronized void delItem( int position )
Description
Note: delItem() is deprecated. replaced by remove(String) and remove(int).


 List.delItems

List.delItems

Syntax
public synchronized void delItems( int start, int end )
Description
Note: delItems() is deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method.


 List.deselect

List.deselect

Syntax
public synchronized void deselect( int index )
Parameters
index
the position of the item to deselect.
Description
Deselects the item at the specified index.

If the item at the specified index is not selected, or if the index is out of range, then the operation is ignored.

See Also
select, getSelectedItem, isIndexSelected


 List.getItem

List.getItem

Syntax
public String getItem( int index )
Parameters
index
the position of the item.
Returns
an item that is associated with the specified index.
Description
Gets the item associated with the specified index.

See Also
getItemCount


 List.getItemCount

List.getItemCount

Syntax
public int getItemCount()
Returns
the number of items in the list.
Description
Gets the number of items in the list.

See Also
getItem


 List.getItems

List.getItems

Syntax
public synchronized String[] getItems()
Returns
a string array containing items of the list.
Description
Gets the items in the list.

See Also
select, deselect, isIndexSelected


 List.getMinimumSize

List.getMinimumSize

Syntax 1
public Dimension getMinimumSize( int rows )
Parameters
rows
number of rows in the list.
Returns
the minimum dimensions for displaying this scrolling list.
Description
Gets the minumum dimensions for a list with the specified number of rows.

See Also
getMinimumSize

Syntax 2
public Dimension getMinimumSize()
Returns
the minimum dimensions needed to display this scrolling list.
Description
Determines the minimum size of this scrolling list.

Overrides
getMinimumSize in class Component
See Also
getMinimumSize


 List.getPreferredSize

List.getPreferredSize

Syntax 1
public Dimension getPreferredSize( int rows )
Parameters
rows
number of rows in the list.
Returns
the preferred dimensions for displaying this scrolling list.
Description
Gets the preferred dimensions for a list with the specified number of rows.

See Also
getPreferredSize

Syntax 2
public Dimension getPreferredSize()
Returns
the preferred dimensions for displaying this scrolling list.
Description
Gets the preferred size of this scrolling list.

Overrides
getPreferredSize in class Component
See Also
getPreferredSize


 List.getRows

List.getRows

Syntax
public int getRows()
Returns
the number of visible lines in this scrolling list.
Description
Get the number of visible lines in this list.


 List.getSelectedIndex

List.getSelectedIndex

Syntax
public synchronized int getSelectedIndex()
Returns
the index of the selected item, or -1 if no item is selected, or if more that one item is selected.
Description
Gets the index of the selected item on the list,

See Also
select, deselect, isIndexSelected


 List.getSelectedIndexes

List.getSelectedIndexes

Syntax
public synchronized int[] getSelectedIndexes()
Returns
an array of the selected indexes of this scrolling list.
Description
Gets the selected indexes on the list.

See Also
select, deselect, isIndexSelected


 List.getSelectedItem

List.getSelectedItem

Syntax
public synchronized String getSelectedItem()
Returns
the selected item on the list, or null if no item is selected.
Description
Get the selected item on this scrolling list.

See Also
select, deselect, isIndexSelected


 List.getSelectedItems

List.getSelectedItems

Syntax
public synchronized String[] getSelectedItems()
Returns
an array of the selected items on this scrolling list.
Description
Get the selected items on this scrolling list.

See Also
select, deselect, isIndexSelected


 List.getSelectedObjects

List.getSelectedObjects

Syntax
public Object[] getSelectedObjects()
Description
Returns the selected items on the list in an array of Objects.

See Also
ItemSelectable


 List.getVisibleIndex

List.getVisibleIndex

Syntax
public int getVisibleIndex()
Returns
the index of the item that was last made visible.
Description
Gets the index of the item that was last made visible by the method makeVisible.

See Also
makeVisible


 List.isIndexSelected

List.isIndexSelected

Syntax
public boolean isIndexSelected( int index )
Parameters
index
the item to be checked.
Returns
true if the specified item has been selected; false otherwise.
Description
Determines if the specified item in this scrolling list is selected.

See Also
select, deselect


 List.isMultipleMode

List.isMultipleMode

Syntax
public boolean isMultipleMode()
Returns
true if this list allows multiple selections; otherwise, false.
Description
Determines whether this list allows multiple selections.

See Also
setMultipleMode


 List.isSelected

List.isSelected

Syntax
public boolean isSelected( int index )
Description
Note: isSelected() is deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).


 List.makeVisible

List.makeVisible

Syntax
public synchronized void makeVisible( int index )
Parameters
index
the position of the item.
Description
Makes the item at the specified index visible.

See Also
getVisibleIndex


 List.minimumSize

List.minimumSize

Syntax 1
public Dimension minimumSize( int rows )
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).

Syntax 2
public Dimension minimumSize()
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Overrides
minimumSize in class Component


 List.paramString

List.paramString

Syntax
protected String paramString()
Returns
the parameter string of this scrolling list.
Description
Returns the parameter string representing the state of this scrolling list. This string is useful for debugging.

Overrides
paramString in class Component


 List.preferredSize

List.preferredSize

Syntax 1
public Dimension preferredSize( int rows )
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).

Syntax 2
public Dimension preferredSize()
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Overrides
preferredSize in class Component


 List.processActionEvent

List.processActionEvent

Syntax
protected void processActionEvent( ActionEvent e )
Parameters
e
the action event.
Description
Processes action events occurring on this component by dispatching them to any registered ActionListener objects.

This method is not called unless action events are enabled for this component. Action events are enabled when one of the following occurs:

  • An ActionListener object is registered via addActionListener.
  • Action events are enabled via enableEvents.

See Also
ActionEvent, ActionListener, addActionListener, enableEvents


 List.processEvent

List.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this scrolling list. If an event is an instance of ItemEvent, it invokes the processItemEvent method. Else, if the event is an instance of ActionEvent, it invokes processActionEvent. If the event is not an item event or an action event, it invokes processEvent on the superclass.

Overrides
processEvent in class Component
See Also
ActionEvent, ItemEvent, processActionEvent, processItemEvent


 List.processItemEvent

List.processItemEvent

Syntax
protected void processItemEvent( ItemEvent e )
Parameters
e
the item event.
Description
Processes item events occurring on this list by dispatching them to any registered ItemListener objects.

This method is not called unless item events are enabled for this component. Item events are enabled when one of the following occurs:

  • An ItemListener object is registered via addItemListener.
  • Item events are enabled via enableEvents.

See Also
ItemEvent, ItemListener, addItemListener, enableEvents


 List.remove

List.remove

Syntax 1
public synchronized void remove( String item )
Parameters
item
the item to remove from the list.
Description
Removes the first occurrence of an item from the list.

Exceptions
IllegalArgumentException if the item doesn't exist in the list.

Syntax 2
public synchronized void remove( int position )
Parameters
position
the index of the item to delete.
Description
Remove the item at the specified position from this scrolling list.

See Also
add


 List.removeActionListener

List.removeActionListener

Syntax
public synchronized void removeActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Removes the specified action listener so that it no longer receives action events from this list. Action events occur when a user double-clicks on a list item.

See Also
ActionEvent, ActionListener, addActionListener


 List.removeAll

List.removeAll

Syntax
public synchronized void removeAll()
Description
Removes all items from this list.

See Also
remove, delItems


 List.removeItemListener

List.removeItemListener

Syntax
public synchronized void removeItemListener( ItemListener l )
Parameters
l
the item listener.
Description
Removes the specified item listener so that it no longer receives item events from this list.

See Also
ItemEvent, ItemListener, addItemListener


 List.removeNotify

List.removeNotify

Syntax
public void removeNotify()
Description
Removes the peer for this list. The peer allows us to modify the list's appearance without changing its functionality.

Overrides
removeNotify in class Component


 List.replaceItem

List.replaceItem

Syntax
public synchronized void replaceItem( String newValue, int index )
Parameters
newValue
a new string to replace an existing item.
index
the position of the item to replace.
Description
Replaces the item at the specified index in the scrolling list with the new string.


 List.select

List.select

Syntax
public synchronized void select( int index )
Parameters
index
the position of the item to select.
Description
Selects the item at the specified index in the scrolling list.

See Also
getSelectedItem, deselect, isIndexSelected


 List.setMultipleMode

List.setMultipleMode

Syntax
public synchronized void setMultipleMode( boolean b )
Parameters
b
if true then multiple selections are allowed; otherwise, only one item from the list can be selected at once.
Description
Sets the flag that determines whether this list allows multiple selections.

See Also
isMultipleMode


 List.setMultipleSelections

List.setMultipleSelections

Syntax
public synchronized void setMultipleSelections( boolean b )
Description
Note: setMultipleSelections() is deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean).


 Class MediaTracker

Class java.awt.MediaTracker

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MediaTracker

public class MediaTracker
extends Object
implements Serializable

The MediaTracker class is a utility class to track the status of a number of media objects. Media objects could include audio clips as well as images, though currently only images are supported.

To use a media tracker, create an instance of MediaTracker and call its addImage method for each image to be tracked. In addition, each image can be assigned a unique identifier. This identifier controls the priority order in which the images are fetched. It can also be used to identify unique subsets of the images that can be waited on independently. Images with a lower ID are loaded in preference to those with a higher ID number.

Here is an example:

 import java.applet.Applet;
 import java.awt.Color;
 import java.awt.Image;
 import java.awt.Graphics;
 import java.awt.MediaTracker;
 public class ImageBlaster extends Applet implements Runnable {
    MediaTracker tracker;
    Image bg;
    Image anim[] = new Image[5];
    int index;
    Thread animator;
    // Get the images for the background (id == 0)
    // and the animation frames (id == 1)
      // and add them to the MediaTracker
    public void init() {
        tracker = new MediaTracker(this);
        bg = getImage(getDocumentBase(),
                  "images/background.gif");
        tracker.addImage(bg, 0);
        for (int i = 0; i < 5; i++) {
        anim[i] = getImage(getDocumentBase(),
                      "images/anim"+i+".gif");
        tracker.addImage(anim[i], 1);
        }
    }
    // Start the animation thread.
    public void start() {
        animator = new Thread(this);
        animator.start();
    }
    // Stop the animation thread.
    public void stop() {
        animator.stop();
        animator = null;
    }
    // Run the animation thread.
    // First wait for the background image to fully load
      // and paint.  Then wait for all of the animation
    // frames to finish loading. Finally, loop and
    // increment the animation frame index.
    public void run() {
        try {
        tracker.waitForID(0);
        tracker.waitForID(1);
        } catch (InterruptedException e) {
        return;
        }
        Thread me = Thread.currentThread();
        while (animator == me) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            break;
        }
        synchronized (this) {
            index++;
            if (index >= anim.length) {
            index = 0;
            }
        }
        repaint();
        }
    }
    // The background image fills the frame so we
    // don't need to clear the applet on repaints.
      // Just call the paint method.
    public void update(Graphics g) {
        paint(g);
    }
    // Paint a large red rectangle if there are any errors
    // loading the images.  Otherwise always paint the
    // background so that it appears incrementally as it
      // is loading.  Finally, only paint the current animation
    // frame if all of the frames (id == 1) are done loading,
    // so that we don't get partial animations.
    public void paint(Graphics g) {
        if ((tracker.statusAll(false) & MediaTracker.ERRORED) != 0) {
        g.setColor(Color.red);
        g.fillRect(0, 0, size().width, size().height);
        return;
        }
        g.drawImage(bg, 0, 0, this);
        if (tracker.statusID(1, false) == MediaTracker.COMPLETE) {
        g.drawImage(anim[index], 10, 10, this);
        }
    }
 }


 MediaTracker Members

MediaTracker Members

Class Overview | This Package | All Packages

Fields
Name | Description
ABORTED | Flag indicating that the downloading of some media was aborted.
COMPLETE | Flag indicating that the downloading of media was completed successfully.
ERRORED | Flag indicating that the downloading of some media encountered an error.
LOADING | Flag indicating some media is currently being loaded.

Constructors
Name | Description
MediaTracker(Component) | Creates a media tracker to track images for a given component.

Methods
Name | Description
addImage(Image, int) | Adds an image to the list of images being tracked by this media tracker.
addImage(Image, int, int, int) | Adds a scaled image to the list of images being tracked by this media tracker.
checkAll() | Checks to see if all images being tracked by this media tracker have finished loading.
checkAll(boolean) | Checks to see if all images being tracked by this media tracker have finished loading.
checkID(int) | Checks to see if all images tracked by this media tracker that are tagged with the specified identifier have finished loading.
checkID(int, boolean) | Checks to see if all images tracked by this media tracker that are tagged with the specified identifier have finished loading.
getErrorsAny() | Returns a list of all media that have encountered an error.
getErrorsID(int) | Returns a list of media with the specified ID that have encountered an error.
isErrorAny() | Checks the error status of all of the images.
isErrorID(int) | Checks the error status of all of the images tracked by this media tracker with the specified identifier.
removeImage(Image) | Remove the specified image from this media tracker.
removeImage(Image, int) | Remove the specified image from the specified tracking ID of this media tracker.
removeImage(Image, int, int, int) | Remove the specified image with the specified width, height, and ID from this media tracker.
statusAll(boolean) | Calculates and returns the bitwise inclusive OR of the status of all media that are tracked by this media tracker.
statusID(int, boolean) | Calculates and returns the bitwise inclusive OR of the status of all media with the specified identifier that are tracked by this media tracker.
waitForAll() | Starts loading all images tracked by this media tracker.
waitForAll(long) | Starts loading all images tracked by this media tracker.
waitForID(int) | Starts loading all images tracked by this media tracker with the specified identifier.
waitForID(int, long) | Starts loading all images tracked by this media tracker with the specified identifier.


 MediaTracker.ABORTED

MediaTracker.ABORTED

Syntax
public static final int ABORTED
Description
Flag indicating that the downloading of some media was aborted.

See Also
statusAll, statusID


 MediaTracker.COMPLETE

MediaTracker.COMPLETE

Syntax
public static final int COMPLETE
Description
Flag indicating that the downloading of media was completed successfully.

See Also
statusAll, statusID


 MediaTracker.ERRORED

MediaTracker.ERRORED

Syntax
public static final int ERRORED
Description
Flag indicating that the downloading of some media encountered an error.

See Also
statusAll, statusID


 MediaTracker.LOADING

MediaTracker.LOADING

Syntax
public static final int LOADING
Description
Flag indicating some media is currently being loaded.

See Also
statusAll, statusID


 MediaTracker.MediaTracker

MediaTracker.MediaTracker

Syntax
public MediaTracker( Component comp )
Parameters
comp
the component on which the images will eventually be drawn.
Description
Creates a media tracker to track images for a given component.


 MediaTracker.addImage

MediaTracker.addImage

Syntax 1
public void addImage( Image image, int id )
Parameters
image
the image to be tracked.
id
an identifier used to track this image.
Description
Adds an image to the list of images being tracked by this media tracker. The image will eventually be rendered at its default (unscaled) size.

Syntax 2
public synchronized void addImage( Image image, int id, int w, int h )
Parameters
image
the image to be tracked.
id
an identifier that can be used to track this image.
w
the width at which the image is rendered.
h
the height at which the image is rendered.
Description
Adds a scaled image to the list of images being tracked by this media tracker. The image will eventually be rendered at the indicated width and height.


 MediaTracker.checkAll

MediaTracker.checkAll

Syntax 1
public boolean checkAll()
Returns
true if all images have finished loading, have been aborted, or have encountered an error; false otherwise.
Description
Checks to see if all images being tracked by this media tracker have finished loading.

This method does not start loading the images if they are not already loading.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny or isErrorID methods to check for errors.

See Also
checkAll, checkID, isErrorAny, isErrorID

Syntax 2
public boolean checkAll( boolean load )
Parameters
load
if true, start loading any images that are not yet being loaded.
Returns
true if all images have finished loading, have been aborted, or have encountered an error; false otherwise.
Description
Checks to see if all images being tracked by this media tracker have finished loading.

If the value of the load flag is true, then this method starts loading any images that are not yet being loaded.

If there is an error while loading or scaling an image, that image is considered to have finished loading. Use the isErrorAny and isErrorID methods to check for errors.

See Also
checkID, checkAll, isErrorAny, isErrorID


 MediaTracker.checkID

MediaTracker.checkID

Syntax 1
public boolean checkID( int id )
Parameters
id
the identifier of the images to check.
Returns
true if all images have finished loading, have been aborted, or have encountered an error; false otherwise.
Description
Checks to see if all images tracked by this media tracker that are tagged with the specified identifier have finished loading.

This method does not start loading the images if they are not already loading.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny or isErrorID methods to check for errors.

See Also
checkID, checkAll, isErrorAny, isErrorID

Syntax 2
public boolean checkID( int id, boolean load )
Parameters
id
the identifier of the images to check.
load
if true, start loading any images that are not yet being loaded.
Returns
true if all images have finished loading, have been aborted, or have encountered an error; false otherwise.
Description
Checks to see if all images tracked by this media tracker that are tagged with the specified identifier have finished loading.

If the value of the load flag is true, then this method starts loading any images that are not yet being loaded.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny or isErrorID methods to check for errors.

See Also
checkID, checkAll, isErrorAny, isErrorID


 MediaTracker.getErrorsAny

MediaTracker.getErrorsAny

Syntax
public synchronized Object[] getErrorsAny()
Returns
an array of media objects tracked by this media tracker that have encountered an error, or null if there are none with errors.
Description
Returns a list of all media that have encountered an error.

See Also
isErrorAny, getErrorsID


 MediaTracker.getErrorsID

MediaTracker.getErrorsID

Syntax
public synchronized Object[] getErrorsID( int id )
Parameters
id
the identifier of the images to check.
Returns
an array of media objects tracked by this media tracker with the specified identifier that have encountered an error, or null if there are none with errors.
Description
Returns a list of media with the specified ID that have encountered an error.

See Also
isErrorID, isErrorAny, getErrorsAny


 MediaTracker.isErrorAny

MediaTracker.isErrorAny

Syntax
public synchronized boolean isErrorAny()
Returns
true if any of the images tracked by this media tracker had an error during loading; false otherwise.
Description
Checks the error status of all of the images.

See Also
isErrorID, getErrorsAny


 MediaTracker.isErrorID

MediaTracker.isErrorID

Syntax
public synchronized boolean isErrorID( int id )
Parameters
id
the identifier of the images to check.
Returns
true if any of the images with the specified identifier had an error during loading; false otherwise.
Description
Checks the error status of all of the images tracked by this media tracker with the specified identifier.

See Also
isErrorAny, getErrorsID


 MediaTracker.removeImage

MediaTracker.removeImage

Syntax 1
public synchronized void removeImage( Image image )
Parameters
image
the image to be removed
Description
Remove the specified image from this media tracker. All instances of the specified image are removed, regardless of scale or ID.

See Also
removeImage, removeImage

Syntax 2
public synchronized void removeImage( Image image, int id )
Parameters
image
the image to be removed.
id
the tracking ID frrom which to remove the image.
Description
Remove the specified image from the specified tracking ID of this media tracker. All instances of Image being tracked under the specified ID are removed regardless of scale.

See Also
removeImage, removeImage

Syntax 3
public synchronized void removeImage( Image image, int id, int width, int height )
Parameters
image
the image to be removed
id
the tracking ID from which to remove the image.
width
the width to remove (-1 for unscaled).
height
the height to remove (-1 for unscaled).
Description
Remove the specified image with the specified width, height, and ID from this media tracker. Only the specified instance (with any duplicates) is removed.

See Also
removeImage, removeImage


 MediaTracker.statusAll

MediaTracker.statusAll

Syntax
public int statusAll( boolean load )
Parameters
load
if true, start loading any images that are not yet being loaded.
Returns
the bitwise inclusive OR of the status of all of the media being tracked.
Description
Calculates and returns the bitwise inclusive OR of the status of all media that are tracked by this media tracker.

Possible flags defined by the MediaTracker class are LOADING, ABORTED, ERRORED, and COMPLETE. An image that hasn't started loading has zero as its status.

If the value of load is true, then this method starts loading any images that are not yet being loaded.

See Also
statusID, LOADING, ABORTED, ERRORED, COMPLETE


 MediaTracker.statusID

MediaTracker.statusID

Syntax
public int statusID( int id, boolean load )
Parameters
id
the identifier of the images to check.
load
if true, start loading any images that are not yet being loaded.
Returns
the bitwise inclusive OR of the status of all of the media with the specified identifier that are being tracked.
Description
Calculates and returns the bitwise inclusive OR of the status of all media with the specified identifier that are tracked by this media tracker.

Possible flags defined by the MediaTracker class are LOADING, ABORTED, ERRORED, and COMPLETE. An image that hasn't started loading has zero as its status.

If the value of load is true, then this method starts loading any images that are not yet being loaded.

See Also
statusAll, LOADING, ABORTED, ERRORED, COMPLETE


 MediaTracker.waitForAll

MediaTracker.waitForAll

Syntax 1
public void waitForAll() throws InterruptedException
Description
Starts loading all images tracked by this media tracker. This method waits until all the images being tracked have finished loading.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny or isErrorID methods to check for errors.

Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
waitForID, waitForAll, isErrorAny, isErrorID

Syntax 2
public synchronized boolean waitForAll( long ms ) throws InterruptedException
Parameters
ms
the number of milliseconds to wait for the loading to complete.
Returns
true if all images were successfully loaded; false otherwise.
Description
Starts loading all images tracked by this media tracker. This method waits until all the images being tracked have finished loading, or until the length of time specified in milliseconds by the ms argument has passed.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny or isErrorID methods to check for errors.

Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
waitForID, waitForAll, isErrorAny, isErrorID


 MediaTracker.waitForID

MediaTracker.waitForID

Syntax 1
public void waitForID( int id ) throws InterruptedException
Parameters
id
the identifier of the images to check.
Description
Starts loading all images tracked by this media tracker with the specified identifier. This method waits until all the images with the specified identifier have finished loading.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the isErrorAny and isErrorID methods to check for errors.

Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
waitForAll, isErrorAny, isErrorID

Syntax 2
public synchronized boolean waitForID( int id, long ms ) throws InterruptedException
Parameters
id
the identifier of the images to check.
ms
the length of time, in milliseconds, to wait for the loading to complete.
Description
Starts loading all images tracked by this media tracker with the specified identifier. This method waits until all the images with the specified identifier have finished loading, or until the length of time specified in milliseconds by the ms argument has passed.

If there is an error while loading or scaling an image, then that image is considered to have finished loading. Use the statusID, isErrorID, and isErrorAny methods to check for errors.

Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
waitForAll, waitForID, statusID, isErrorAny, isErrorID


 Class Menu

Class java.awt.Menu

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent
           |
           +----java.awt.MenuItem
                   |
                   +----java.awt.Menu

public class Menu
extends MenuItem
implements MenuContainer

A Menu object is a pull-down menu component that is deployed from a menu bar.

A menu can optionally be a tear-off menu. A tear-off menu can be opened and dragged away from its parent menu bar or menu. It remains on the screen after the mouse button has been released. The mechanism for tearing off a menu is platform dependent, since the look and feel of the tear-off menu is determined by its peer. On platforms that do not support tear-off menus, the tear-off property is ignored.

Each item in a menu must belong to the MenuItem class. It can be an instance of MenuItem, a submenu (an instance of Menu), or a check box (an instance of CheckboxMenuItem).

See Also:
MenuItem, CheckboxMenuItem


 Menu Members

Menu Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Menu() | Constructs a new menu with an empty label.
Menu(String) | Constructs a new menu with the specified label.
Menu(String, boolean) | Constructs a new menu with the specified label.

Methods
Name | Description
add(MenuItem) | Adds the specified menu item to this menu.
add(String) | Adds an item with the specified label to this menu.
addNotify() | Creates the menu's peer.
addSeparator() | Adds a separator line, or a hypen, to the menu at the current position.
countItems() | Deprecated.
getItem(int) | Gets the item located at the specified index of this menu.
getItemCount() | Get the number of items in this menu.
insert(MenuItem, int) | Inserts a menu item into this menu at the specified position.
insert(String, int) | Inserts a menu item with the specified label into this menu at the specified position.
insertSeparator(int) | Inserts a separator at the specified position.
isTearOff() | Indicates whether this menu is a tear-off menu.
paramString() | Gets the parameter string representing the state of this menu.
remove(int) | Removes the menu item at the specified index from this menu.
remove(MenuComponent) | Removes the specified menu item from this menu.
removeAll() | Removes all items from this menu.
removeNotify() | Removes the menu's peer.


 Menu.Menu

Menu.Menu

Syntax 1
public Menu()
Description
Constructs a new menu with an empty label. This menu is not a tear-off menu.

Syntax 2
public Menu( String label )
Parameters
label
the menu's label in the menu bar, or in another menu of which this menu is a submenu.
Description
Constructs a new menu with the specified label. This menu is not a tear-off menu.

Syntax 3
public Menu( String label, boolean tearOff )
Parameters
label
the menu's label in the menu bar, or in another menu of which this menu is a submenu.
tearOff
if true, the menu is a tear-off menu.
Description
Constructs a new menu with the specified label. If the value of tearOff is true, the menu can be torn off.

Tear-off functionality may not be supported by all implementations of AWT. If a particular implementation doesn't support tear-off menus, this value is silently ignored.


 Menu.add

Menu.add

Syntax 1
public synchronized MenuItem add( MenuItem mi )
Parameters
mi
the menu item to be added.
Returns
the menu item added.
Description
Adds the specified menu item to this menu. If the menu item has been part of another menu, remove it from that menu.

See Also
insert, insert

Syntax 2
public void add( String label )
Parameters
label
the text on the item.
Description
Adds an item with the specified label to this menu.

See Also
insert, insert


 Menu.addNotify

Menu.addNotify

Syntax
public void addNotify()
Description
Creates the menu's peer. The peer allows us to modify the appearance of the menu without changing its functionality.

Overrides
addNotify in class MenuItem


 Menu.addSeparator

Menu.addSeparator

Syntax
public void addSeparator()
Description
Adds a separator line, or a hypen, to the menu at the current position.

See Also
insertSeparator


 Menu.countItems

Menu.countItems

Syntax
public int countItems()
Description
Note: countItems() is deprecated. As of JDK version 1.1, replaced by getItemCount().


 Menu.getItem

Menu.getItem

Syntax
public MenuItem getItem( int index )
Parameters
index
the position of the item to be returned.
Returns
the item located at the specified index.
Description
Gets the item located at the specified index of this menu.


 Menu.getItemCount

Menu.getItemCount

Syntax
public int getItemCount()
Returns
the number of items in this menu.
Description
Get the number of items in this menu.


 Menu.insert

Menu.insert

Syntax 1
public synchronized void insert( MenuItem menuitem, int index )
Parameters
menuitem
the menu item to be inserted.
index
the position at which the menu item should be inserted.
Description
Inserts a menu item into this menu at the specified position.

Exceptions
IllegalArgumentException if the value of index is less than zero.
See Also
add, add

Syntax 2
public void insert( String label, int index )
Parameters
label
the text on the item.
index
the position at which the menu item should be inserted.
Description
Inserts a menu item with the specified label into this menu at the specified position.

See Also
add, add


 Menu.insertSeparator

Menu.insertSeparator

Syntax
public void insertSeparator( int index )
Parameters
index
the position at which the menu separator should be inserted.
Description
Inserts a separator at the specified position.

Exceptions
IllegalArgumentException if the value of index is less than 0.
See Also
addSeparator


 Menu.isTearOff

Menu.isTearOff

Syntax
public boolean isTearOff()
Returns
true if this is a tear-off menu; false otherwise.
Description
Indicates whether this menu is a tear-off menu.

Tear-off functionality may not be supported by all implementations of AWT. If a particular implementation doesn't support tear-off menus, this value is silently ignored.


 Menu.paramString

Menu.paramString

Syntax
public String paramString()
Description
Gets the parameter string representing the state of this menu. This string is useful for debugging.

Overrides
paramString in class MenuItem


 Menu.remove

Menu.remove

Syntax 1
public synchronized void remove( int index )
Parameters
index
the position of the item to be removed.
Description
Removes the menu item at the specified index from this menu.

Syntax 2
public synchronized void remove( MenuComponent item )
Parameters
item
the item to be removed from the menu
Description
Removes the specified menu item from this menu.


 Menu.removeAll

Menu.removeAll

Syntax
public synchronized void removeAll()
Description
Removes all items from this menu.


 Menu.removeNotify

Menu.removeNotify

Syntax
public void removeNotify()
Description
Removes the menu's peer. The peer allows us to modify the appearance of the menu without changing its functionality.

Overrides
removeNotify in class MenuComponent


 Class MenuBar

Class java.awt.MenuBar

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent
           |
           +----java.awt.MenuBar

public class MenuBar
extends MenuComponent
implements MenuContainer

The MenuBar class encapsulates the platform's concept of a menu bar bound to a frame. In order to associate the menu bar with a Frame object, call the frame's setMenuBar method.

This is what a menu bar might look like:

A menu bar handles keyboard shortcuts for menu items, passing them along to its child menus. (Keyboard shortcuts, which are optional, provide the user with an alternative to the mouse for invoking a menu item and the action that is associated with it.) Each menu item can maintain an instance of MenuShortcut. The MenuBar class defines several methods, shortCuts and getShortcutMenuItem that retrieve information about the shortcuts a given menu bar is managing.

See Also:
Frame, setMenuBar, Menu, MenuItem, MenuShortcut


 MenuBar Members

MenuBar Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MenuBar() | Creates a new menu bar.

Methods
Name | Description
add(Menu) | Adds the specified menu to the menu bar.
addNotify() | Creates the menu bar's peer.
countMenus() | Deprecated.
deleteShortcut(MenuShortcut) | Deletes the specified menu shortcut.
getHelpMenu() | Gets the help menu on the menu bar.
getMenu(int) | Gets the specified menu.
getMenuCount() | Gets the number of menus on the menu bar.
getShortcutMenuItem(MenuShortcut) | Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none has been specified.
remove(int) | Removes the menu located at the specified index from this menu bar.
remove(MenuComponent) | Removes the specified menu component from this menu bar.
removeNotify() | Removes the menu bar's peer.
setHelpMenu(Menu) | Sets the help menu on this menu bar to be the specified menu.
shortcuts() | Gets an enumeration of all menu shortcuts this menu bar is managing.


 MenuBar.MenuBar

MenuBar.MenuBar

Syntax
public MenuBar()
Description
Creates a new menu bar.


 MenuBar.add

MenuBar.add

Syntax
public synchronized Menu add( Menu m )
Parameters
m
the menu to be added.
Returns
the menu added.
Description
Adds the specified menu to the menu bar.

See Also
remove, remove


 MenuBar.addNotify

MenuBar.addNotify

Syntax
public void addNotify()
Description
Creates the menu bar's peer. The peer allows us to change the appearance of the menu bar without changing any of the menu bar's functionality.


 MenuBar.countMenus

MenuBar.countMenus

Syntax
public int countMenus()
Description
Note: countMenus() is deprecated. As of JDK version 1.1, replaced by getMenuCount().


 MenuBar.deleteShortcut

MenuBar.deleteShortcut

Syntax
public void deleteShortcut( MenuShortcut s )
Parameters
s
the menu shortcut to delete.
Description
Deletes the specified menu shortcut.


 MenuBar.getHelpMenu

MenuBar.getHelpMenu

Syntax
public Menu getHelpMenu()
Returns
the help menu on this menu bar.
Description
Gets the help menu on the menu bar.


 MenuBar.getMenu

MenuBar.getMenu

Syntax
public Menu getMenu( int i )
Parameters
i
the index position of the menu to be returned.
Returns
the menu at the specified index of this menu bar.
Description
Gets the specified menu.


 MenuBar.getMenuCount

MenuBar.getMenuCount

Syntax
public int getMenuCount()
Returns
the number of menus on the menu bar.
Description
Gets the number of menus on the menu bar.


 MenuBar.getShortcutMenuItem

MenuBar.getShortcutMenuItem

Syntax
public MenuItem getShortcutMenuItem( MenuShortcut s )
Parameters
s
the specified menu shortcut.
Description
Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none has been specified.

See Also
MenuItem, MenuShortcut


 MenuBar.remove

MenuBar.remove

Syntax 1
public synchronized void remove( int index )
Parameters
index
the position of the menu to be removed.
Description
Removes the menu located at the specified index from this menu bar.

See Also
add

Syntax 2
public synchronized void remove( MenuComponent m )
Parameters
m
the menu component to be removed.
Description
Removes the specified menu component from this menu bar.

See Also
add


 MenuBar.removeNotify

MenuBar.removeNotify

Syntax
public void removeNotify()
Description
Removes the menu bar's peer. The peer allows us to change the appearance of the menu bar without changing any of the menu bar's functionality.

Overrides
removeNotify in class MenuComponent


 MenuBar.setHelpMenu

MenuBar.setHelpMenu

Syntax
public synchronized void setHelpMenu( Menu m )
Parameters
m
the menu to be set as the help menu.
Description
Sets the help menu on this menu bar to be the specified menu.


 MenuBar.shortcuts

MenuBar.shortcuts

Syntax
public synchronized Enumeration shortcuts()
Returns
an enumeration of menu shortcuts that this menu bar is managing.
Description
Gets an enumeration of all menu shortcuts this menu bar is managing.

See Also
MenuShortcut


 Class MenuComponent

Class java.awt.MenuComponent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent

public abstract class MenuComponent
extends Object
implements Serializable

The abstract class MenuComponent is the superclass of all menu-related components. In this respect, the class MenuComponent is analogous to the abstract superclass Component for AWT components.

Menu components receive and process AWT events, just as components do, through the method processEvent.


 MenuComponent Members

MenuComponent Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MenuComponent() |

Methods
Name | Description
dispatchEvent(AWTEvent) |
getFont() | Gets the font used for this menu component.
getName() | Gets the name of the menu component.
getParent() | Returns the parent container for this menu component.
getPeer() | Deprecated.
paramString() | Returns the parameter string representing the state of this menu component.
postEvent(Event) | Posts the specified event to the menu. Deprecated.
processEvent(AWTEvent) | Processes events occurring on this menu component.
removeNotify() | Removes the menu component's peer.
setFont(Font) | Sets the font to be used for this menu component to the specified font.
setName(String) | Sets the name of the component to the specified string.
toString() | Returns a representation of this menu component as a string.


 MenuComponent.MenuComponent

MenuComponent.MenuComponent

Syntax
public MenuComponent()


 MenuComponent.dispatchEvent

MenuComponent.dispatchEvent

Syntax
public final void dispatchEvent( AWTEvent e )


 MenuComponent.getFont

MenuComponent.getFont

Syntax
public Font getFont()
Returns
the font used in this menu component, if there is one; null otherwise.
Description
Gets the font used for this menu component.

See Also
setFont


 MenuComponent.getName

MenuComponent.getName

Syntax
public String getName()
Returns
the name of the menu component.
Description
Gets the name of the menu component.

See Also
setName


 MenuComponent.getParent

MenuComponent.getParent

Syntax
public MenuContainer getParent()
Returns
the menu component containing this menu component, or null if this menu component is the outermost component, the menu bar itself.
Description
Returns the parent container for this menu component.


 MenuComponent.getPeer

MenuComponent.getPeer

Syntax
public MenuComponentPeer getPeer()
Description
Note: getPeer() is deprecated. As of JDK version 1.1, programs should not directly manipulate peers.


 MenuComponent.paramString

MenuComponent.paramString

Syntax
protected String paramString()
Returns
the parameter string of this menu component.
Description
Returns the parameter string representing the state of this menu component. This string is useful for debugging.


 MenuComponent.postEvent

MenuComponent.postEvent

Syntax
public boolean postEvent( Event evt )
Parameters
evt
the event which is to take place
Description
Note: postEvent() is deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).

Posts the specified event to the menu. This method is part of the Java 1.0 event system and it is maintained only for backwards compatibility. Its use is discouraged, and it may not be supported in the future.


 MenuComponent.processEvent

MenuComponent.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event
Description
Processes events occurring on this menu component.


 MenuComponent.removeNotify

MenuComponent.removeNotify

Syntax
public void removeNotify()
Description
Removes the menu component's peer. The peer allows us to modify the appearance of the menu component without changing the functionality of the menu component.


 MenuComponent.setFont

MenuComponent.setFont

Syntax
public void setFont( Font f )
Parameters
f
the font to be set.
Description
Sets the font to be used for this menu component to the specified font. This font is also used by all subcomponents of this menu component, unless those subcomponents specify a different font.

See Also
getFont


 MenuComponent.setName

MenuComponent.setName

Syntax
public void setName( String name )
Parameters
name
the name of the menu component.
Description
Sets the name of the component to the specified string.

See Also
getName


 MenuComponent.toString

MenuComponent.toString

Syntax
public String toString()
Returns
a string representation of this menu component.
Description
Returns a representation of this menu component as a string.

Overrides
toString in class Object


 Interface MenuContainer

Interface java.awt.MenuContainer

Interface Members | This Package | All Packages

public interface MenuContainer

The super class of all menu related containers.


 MenuContainer Members

MenuContainer Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getFont() |
postEvent(Event) | Deprecated.
remove(MenuComponent) |


 MenuContainer.getFont

MenuContainer.getFont

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Font getFont()


 MenuContainer.postEvent

MenuContainer.postEvent

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean postEvent( Event evt )
Description
Note: postEvent() is deprecated. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).


 MenuContainer.remove

MenuContainer.remove

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void remove( MenuComponent comp )


 Class MenuItem

Class java.awt.MenuItem

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent
           |
           +----java.awt.MenuItem

public class MenuItem
extends MenuComponent

All items in a menu must belong to the class MenuItem, or one of its subclasses.

The default MenuItem object embodies a simple labeled menu item.

This picture of a menu bar shows five menu items:
The first two items are simple menu items, labeled "Basic" and "Simple". Following these two items is a separator, which is itself a menu item, created with the label "-". Next is an instance of CheckboxMenuItem labeled "Check". The final menu item is a submenu labeled "More Examples", and this submenu is an instance of Menu.

When a menu item is selected, AWT sends an action event to the menu item. Since the event is an instance of ActionEvent, the processEvent method examines the event and passes it along to processActionEvent. The latter method redirects the event to any ActionListener objects that have registered an interest in action events generated by this menu item.

Note that the subclass Menu overrides this behavior and does not send any event to the frame until one of its subitems is selected.


 MenuItem Members

MenuItem Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MenuItem() | Constructs a new MenuItem with an empty label and no keyboard shortcut.
MenuItem(String) | Constructs a new MenuItem with the specified label and no keyboard shortcut.
MenuItem(String, MenuShortcut) | Create a menu item with an associated keyboard shortcut.

Methods
Name | Description
addActionListener(ActionListener) | Adds the specified action listener to receive action events from this menu item.
addNotify() | Creates the menu item's peer.
deleteShortcut() | Delete any MenuShortcut object associated with this menu item.
disable() | Deprecated.
disableEvents(long) | Disables event delivery to this menu item for events defined by the specified event mask parameter.
enable() | Deprecated.
enable(boolean) | Deprecated.
enableEvents(long) | Enables event delivery to this menu item for events to be defined by the specified event mask parameter Since event types are automatically enabled when a listener for that type is added to the menu item, this method only needs to be invoked by subclasses of MenuItem which desire to have the specified event types delivered to processEvent regardless of whether a listener is registered.
getActionCommand() | Gets the command name of the action event that is fired by this menu item.
getLabel() | Gets the label for this menu item.
getShortcut() | Get the MenuShortcut object associated with this menu item,
isEnabled() | Checks whether this menu item is enabled.
paramString() | Returns the parameter string representing the state of this menu item.
processActionEvent(ActionEvent) | Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.
processEvent(AWTEvent) | Processes events on this menu item.
removeActionListener(ActionListener) | Removes the specified action listener so it no longer receives action events from this menu item.
setActionCommand(String) | Sets the command name of the action event that is fired by this menu item.
setEnabled(boolean) | Sets whether or not this menu item can be chosen.
setLabel(String) | Sets the label for this menu item to the specified label.
setShortcut(MenuShortcut) | Set the MenuShortcut object associated with this menu item.


 MenuItem.MenuItem

MenuItem.MenuItem

Syntax 1
public MenuItem()
Description
Constructs a new MenuItem with an empty label and no keyboard shortcut.

Syntax 2
public MenuItem( String label )
Parameters
label
the label for this menu item.
Description
Constructs a new MenuItem with the specified label and no keyboard shortcut. Note that use of "-" in a label is reserved to indicate a separator between menu items. By default, all menu items except for separators are enabled.

Syntax 3
public MenuItem( String label, MenuShortcut s )
Parameters
label
the label for this menu item.
s
the instance of MenuShortcut associated with this menu item.
Description
Create a menu item with an associated keyboard shortcut. Note that use of "-" in a label is reserved to indicate a separator between menu items. By default, all menu items except for separators are enabled.


 MenuItem.addActionListener

MenuItem.addActionListener

Syntax
public synchronized void addActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Adds the specified action listener to receive action events from this menu item.

See Also
ActionEvent, ActionListener, removeActionListener


 MenuItem.addNotify

MenuItem.addNotify

Syntax
public void addNotify()
Description
Creates the menu item's peer. The peer allows us to modify the appearance of the menu item without changing its functionality.


 MenuItem.deleteShortcut

MenuItem.deleteShortcut

Syntax
public void deleteShortcut()
Description
Delete any MenuShortcut object associated with this menu item.


 MenuItem.disable

MenuItem.disable

Syntax
public synchronized void disable()
Description
Note: disable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).


 MenuItem.disableEvents

MenuItem.disableEvents

Syntax
protected final void disableEvents( long eventsToDisable )
Parameters
eventsToDisable
the event mask defining the event types.
Description
Disables event delivery to this menu item for events defined by the specified event mask parameter.

See Also
processEvent, enableEvents, disableEvents


 MenuItem.enable

MenuItem.enable

Syntax 1
public synchronized void enable()
Description
Note: enable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).

Syntax 2
public void enable( boolean b )
Description
Note: enable() is deprecated. As of JDK version 1.1, replaced by setEnabled(boolean).


 MenuItem.enableEvents

MenuItem.enableEvents

Syntax
protected final void enableEvents( long eventsToEnable )
Parameters
eventsToEnable
the event mask defining the event types.
Description
Enables event delivery to this menu item for events to be defined by the specified event mask parameter

Since event types are automatically enabled when a listener for that type is added to the menu item, this method only needs to be invoked by subclasses of MenuItem which desire to have the specified event types delivered to processEvent regardless of whether a listener is registered.

See Also
processEvent, disableEvents, enableEvents


 MenuItem.getActionCommand

MenuItem.getActionCommand

Syntax
public String getActionCommand()
Description
Gets the command name of the action event that is fired by this menu item.

See Also
setActionCommand


 MenuItem.getLabel

MenuItem.getLabel

Syntax
public String getLabel()
Returns
the label of this menu item, or null if this menu item has no label.
Description
Gets the label for this menu item.

See Also
setLabel


 MenuItem.getShortcut

MenuItem.getShortcut

Syntax
public MenuShortcut getShortcut()
Returns
the menu shortcut associated with this menu item, or null if none has been specified.
Description
Get the MenuShortcut object associated with this menu item,

See Also
setShortcut


 MenuItem.isEnabled

MenuItem.isEnabled

Syntax
public boolean isEnabled()
Description
Checks whether this menu item is enabled.

See Also
setEnabled


 MenuItem.paramString

MenuItem.paramString

Syntax
public String paramString()
Returns
the parameter string of this menu item.
Description
Returns the parameter string representing the state of this menu item. This string is useful for debugging.

Overrides
paramString in class MenuComponent


 MenuItem.processActionEvent

MenuItem.processActionEvent

Syntax
protected void processActionEvent( ActionEvent e )
Parameters
e
the action event.
Description
Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects. This method is not called unless action events are enabled for this component. Action events are enabled when one of the following occurs:

  • An ActionListener object is registered via addActionListener.
  • Action events are enabled via enableEvents.

See Also
ActionEvent, ActionListener, enableEvents


 MenuItem.processEvent

MenuItem.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this menu item. If the event is an instance of ActionEvent, it invokes processActionEvent, another method defined by MenuItem.

Currently, menu items only support action events.

Overrides
processEvent in class MenuComponent
See Also
processActionEvent


 MenuItem.removeActionListener

MenuItem.removeActionListener

Syntax
public synchronized void removeActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Removes the specified action listener so it no longer receives action events from this menu item.

See Also
ActionEvent, ActionListener, addActionListener


 MenuItem.setActionCommand

MenuItem.setActionCommand

Syntax
public void setActionCommand( String command )
Parameters
command
the action command to be set for this menu item.
Description
Sets the command name of the action event that is fired by this menu item.

By default, the action command is set to the label of the menu item.

See Also
getActionCommand


 MenuItem.setEnabled

MenuItem.setEnabled

Syntax
public synchronized void setEnabled( boolean b )
Parameters
b
if true, enables this menu item; if false, disables it.
Description
Sets whether or not this menu item can be chosen.

See Also
isEnabled


 MenuItem.setLabel

MenuItem.setLabel

Syntax
public synchronized void setLabel( String label )
Parameters
label
the new label, or null for no label.
Description
Sets the label for this menu item to the specified label.

See Also
getLabel


 MenuItem.setShortcut

MenuItem.setShortcut

Syntax
public void setShortcut( MenuShortcut s )
Parameters
s
the menu shortcut to associate with this menu item.
Description
Set the MenuShortcut object associated with this menu item. If a menu shortcut is already associated with this menu item, it is replaced.

See Also
getShortcut


 Class MenuShortcut

Class java.awt.MenuShortcut

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuShortcut

public class MenuShortcut
extends Object
implements Serializable

A class which represents a keyboard accelerator for a MenuItem.


 MenuShortcut Members

MenuShortcut Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MenuShortcut(int) | Constructs a new MenuShortcut for the specified key.
MenuShortcut(int, boolean) | Constructs a new MenuShortcut for the specified key.

Methods
Name | Description
equals(MenuShortcut) | Returns whether this MenuShortcut is the same as another: equality is defined to mean that both MenuShortcuts use the same key and both either use or don't use the SHIFT key.
getKey() | Return the raw keycode of this MenuShortcut.
paramString() |
toString() | Returns an internationalized description of the MenuShortcut.
usesShiftModifier() | Return whether this MenuShortcut must be invoked using the SHIFT key.


 MenuShortcut.MenuShortcut

MenuShortcut.MenuShortcut

Syntax 1
public MenuShortcut( int key )
Parameters
key
the raw keycode for this MenuShortcut, as would be returned in the keyCode field of a KeyEvent if this key were pressed.
Description
Constructs a new MenuShortcut for the specified key.

Syntax 2
public MenuShortcut( int key, boolean useShiftModifier )
Parameters
key
the raw keycode for this MenuShortcut, as would be returned in the keyCode field of a KeyEvent if this key were pressed.
useShiftModifier
indicates whether this MenuShortcut is invoked with the SHIFT key down.
Description
Constructs a new MenuShortcut for the specified key.


 MenuShortcut.equals

MenuShortcut.equals

Syntax
public boolean equals( MenuShortcut s )
Parameters
s
the MenuShortcut to compare with this.
Description
Returns whether this MenuShortcut is the same as another: equality is defined to mean that both MenuShortcuts use the same key and both either use or don't use the SHIFT key.


 MenuShortcut.getKey

MenuShortcut.getKey

Syntax
public int getKey()
Description
Return the raw keycode of this MenuShortcut.


 MenuShortcut.paramString

MenuShortcut.paramString

Syntax
protected String paramString()


 MenuShortcut.toString

MenuShortcut.toString

Syntax
public String toString()
Description
Returns an internationalized description of the MenuShortcut.

Overrides
toString in class Object


 MenuShortcut.usesShiftModifier

MenuShortcut.usesShiftModifier

Syntax
public boolean usesShiftModifier()
Description
Return whether this MenuShortcut must be invoked using the SHIFT key.


 Class Panel

Class java.awt.Panel

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Panel

public class Panel
extends Container

Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels.

The default layout manager for a panel is the FlowLayout layout manager.

See Also:
FlowLayout


 Panel Members

Panel Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Panel() | Creates a new panel using the default layout manager.
Panel(LayoutManager) | Creates a new panel with the specified layout manager.

Methods
Name | Description
addNotify() | Creates the Panel's peer.


 Panel.Panel

Panel.Panel

Syntax 1
public Panel()
Description
Creates a new panel using the default layout manager. The default layout manager for all panels is the FlowLayout class.

Syntax 2
public Panel( LayoutManager layout )
Parameters
layout
the layout manager for this panel.
Description
Creates a new panel with the specified layout manager.


 Panel.addNotify

Panel.addNotify

Syntax
public void addNotify()
Description
Creates the Panel's peer. The peer allows you to modify the appearance of the panel without changing its functionality.

Overrides
addNotify in class Container


 Class Point

Class java.awt.Point

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Point

public class Point
extends Object
implements Serializable

The Point class represents a location in a two-dimensional (x, y) coordinate space.


 Point Members

Point Members

Class Overview | This Package | All Packages

Fields
Name | Description
x | The x coordinate.
y | The y coordinate.

Constructors
Name | Description
Point() | Constructs and initializes a point at the origin (0, 0) of the coordinate space.
Point(int, int) | Constructs and initializes a point at the specified (x, y) location in the coordinate space.
Point(Point) | Constructs and initializes a point with the same location as the specified Point object.

Methods
Name | Description
equals(Object) | Determines whether two points are equal.
getLocation() | Returns the location of this point.
hashCode() | Returns the hashcode for this point.
move(int, int) | Moves this point to the specificed location in the (x, y) coordinate plane.
setLocation(int, int) | Changes the point to have the specificed location.
setLocation(Point) | Sets the location of the point to the specificed location.
toString() | Returns a representation of this point and its location in the (x, y) coordinate space as a string.
translate(int, int) | Translates this point, at location (x, y), by dx along the x axis and dy along the y axis so that it now represents the point (x + dx, y + dy).


 Point.x

Point.x

Syntax
public int x
Description
The x coordinate.


 Point.y

Point.y

Syntax
public int y
Description
The y coordinate.


 Point.Point

Point.Point

Syntax 1
public Point()
Parameters
x
the x coordinate.
y
the y coordinate.
Description
Constructs and initializes a point at the origin (0, 0) of the coordinate space.

Syntax 2
public Point( Point p )
Parameters
p
a point.
Description
Constructs and initializes a point with the same location as the specified Point object.

Syntax 3
public Point( int x, int y )
Parameters
x
the x coordinate.
y
the y coordinate.
Description
Constructs and initializes a point at the specified (x, y) location in the coordinate space.


 Point.equals

Point.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
an object to be compared with this point.
Returns
true if the object to be compared is an instance of Point and has the same values; false otherwise.
Description
Determines whether two points are equal. Two instances of Point are equal if the values of their x and y member fields, representing their position in the coordinate space, are the same.

Overrides
equals in class Object


 Point.getLocation

Point.getLocation

Syntax
public Point getLocation()
Returns
a copy of this point, at the same location.
Description
Returns the location of this point. This method is included for completeness, to parallel the getLocation method of Component.

See Also
getLocation, setLocation, setLocation


 Point.hashCode

Point.hashCode

Syntax
public int hashCode()
Returns
a hash code for this point.
Description
Returns the hashcode for this point.

Overrides
hashCode in class Object


 Point.move

Point.move

Syntax
public void move( int x, int y )
Parameters
x
the x coordinate of the new location.
y
the y coordinate of the new location.
Description
Moves this point to the specificed location in the (x, y) coordinate plane. This method is identical with setLocation(int, int).

See Also
setLocation


 Point.setLocation

Point.setLocation

Syntax 1
public void setLocation( Point p )
Parameters
p
a point, the new location for this point.
Description
Sets the location of the point to the specificed location. This method is included for completeness, to parallel the setLocation method of Component.

See Also
setLocation, getLocation

Syntax 2
public void setLocation( int x, int y )
Parameters
x
the x coordinate of the new location.
y
the y coordinate of the new location.
Description
Changes the point to have the specificed location.

This method is included for completeness, to parallel the setLocation method of Component. Its behavior is identical with move(int, int).

See Also
setLocation, getLocation, move


 Point.toString

Point.toString

Syntax
public String toString()
Returns
a string representation of this point, including the values of its member fields.
Description
Returns a representation of this point and its location in the (x, y) coordinate space as a string.

Overrides
toString in class Object


 Point.translate

Point.translate

Syntax
public void translate( int x, int y )
Parameters
dx
the distance to move this point along the x axis.
dy
the distance to move this point along the y axis.
Description
Translates this point, at location (x, y), by dx along the x axis and dy along the y axis so that it now represents the point (x + dx, y + dy).


 Class Polygon

Class java.awt.Polygon

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Polygon

public class Polygon
extends Object
implements Shape, Serializable

The Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space. This region is bounded by an arbitrary number of line segments, each of which is one side of the polygon. Internally, a polygon comprises of a list of (x, y) coordinate pairs, where each pair defines a vertex of the polygon, and two successive pairs are the endpoints of a line that is a side of the polygon. The first and final pairs of (x, y) points are joined by a line segment that closes the polygon.


 Polygon Members

Polygon Members

Class Overview | This Package | All Packages

Fields
Name | Description
bounds |
npoints | The total number of points.
xpoints | The array of x coordinates.
ypoints | The array of y coordinates.

Constructors
Name | Description
Polygon() | Creates an empty polygon.
Polygon(int[], int[], int) | Constructs and initializes a polygon from the specified parameters.

Methods
Name | Description
addPoint(int, int) | Appends a point to this polygon.
contains(int, int) | Determines whether the specified point is contained by this polygon.
contains(Point) | Determines whether the specified point is inside the Polygon.
getBoundingBox() | Deprecated.
getBounds() | Gets the bounding box of this polygon.
inside(int, int) | Deprecated.
translate(int, int) | Translates the vertices by deltaX along the x axis and by deltaY along the y axis.


 Polygon.bounds

Polygon.bounds

Syntax
protected Rectangle bounds


 Polygon.npoints

Polygon.npoints

Syntax
public int npoints
Description
The total number of points.


 Polygon.xpoints

Polygon.xpoints

Syntax
public int xpoints[]
Description
The array of x coordinates.


 Polygon.ypoints

Polygon.ypoints

Syntax
public int ypoints[]
Description
The array of y coordinates.


 Polygon.Polygon

Polygon.Polygon

Syntax 1
public Polygon()
Description
Creates an empty polygon.

Syntax 2
public Polygon( int xpoints[], int ypoints[], int npoints )
Parameters
xpoints
an array of x coordinates.
ypoints
an array of y coordinates.
npoints
the total number of points in the polygon.
Description
Constructs and initializes a polygon from the specified parameters.

Exceptions
NegativeArraySizeException if the value of npoints is negative.


 Polygon.addPoint

Polygon.addPoint

Syntax
public void addPoint( int x, int y )
Parameters
x
the x coordinate of the point.
y
the y coordinate of the point.
Description
Appends a point to this polygon.

If an operation that calculates the bounding box of this polygon has already been performed, such as getBounds or contains, then this method updates the bounding box.

See Also
getBounds, contains


 Polygon.contains

Polygon.contains

Syntax 1
public boolean contains( Point p )
Parameters
p
the point to be tested
Description
Determines whether the specified point is inside the Polygon. Uses an even-odd insideness rule (also known as an alternating rule).

Syntax 2
public boolean contains( int x, int y )
Parameters
x
the x coordinate of the point to be tested.
y
the y coordinate of the point to be tested.
Returns
true if the point (x, y) is contained by this polygon; false otherwise.
Description
Determines whether the specified point is contained by this polygon.

(The contains method is based on code by Hanpeter van Vliet [hvvliet@inter.nl.net].)


 Polygon.getBoundingBox

Polygon.getBoundingBox

Syntax
public Rectangle getBoundingBox()
Description
Note: getBoundingBox() is deprecated. As of JDK version 1.1, replaced by getBounds().


 Polygon.getBounds

Polygon.getBounds

Syntax
public Rectangle getBounds()
Returns
a rectangle that defines the bounds of this polygon.
Description
Gets the bounding box of this polygon. The bounding box is the smallest rectangle whose sides are parallel to the x and y axes of the coordinate space, and that can completely contain the polygon.


 Polygon.inside

Polygon.inside

Syntax
public boolean inside( int x, int y )
Description
Note: inside() is deprecated. As of JDK version 1.1, replaced by contains(int, int).


 Polygon.translate

Polygon.translate

Syntax
public void translate( int deltaX, int deltaY )
Parameters
deltaX
the amount to translate along the x axis
deltaY
the amount to translate along the y axis
Description
Translates the vertices by deltaX along the x axis and by deltaY along the y axis.


 Class PopupMenu

Class java.awt.PopupMenu

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.MenuComponent
           |
           +----java.awt.MenuItem
                   |
                   +----java.awt.Menu
                           |
                           +----java.awt.PopupMenu

public class PopupMenu
extends Menu

A class that implements a menu which can be dynamically popped up at a specified position within a component.


 PopupMenu Members

PopupMenu Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PopupMenu() | Creates a new popup menu.
PopupMenu(String) | Creates a new popup menu with the specified name.

Methods
Name | Description
addNotify() | Creates the popup menu's peer.
show(Component, int, int) | Shows the popup menu at the x, y position relative to an origin component.


 PopupMenu.PopupMenu

PopupMenu.PopupMenu

Syntax 1
public PopupMenu()
Description
Creates a new popup menu.

Syntax 2
public PopupMenu( String label )
Parameters
title
the title string for the popup menu
Description
Creates a new popup menu with the specified name.


 PopupMenu.addNotify

PopupMenu.addNotify

Syntax
public synchronized void addNotify()
Description
Creates the popup menu's peer. The peer allows us to change the appearance of the popup menu without changing any of the popup menu's functionality.

Overrides
addNotify in class Menu


 PopupMenu.show

PopupMenu.show

Syntax
public void show( Component origin, int x, int y )
Parameters
origin
the component which defines the coordinate space
x
the x coordinate position to popup the menu
y
the y coordinate position to popup the menu
Description
Shows the popup menu at the x, y position relative to an origin component. The origin component must be contained within the component hierarchy of the popup menu's parent. Both the origin and the parent must be showing on the screen for this method to be valid.


 Interface PrintGraphics

Interface java.awt.PrintGraphics

Interface Members | This Package | All Packages

public interface PrintGraphics

An abstract class which provides a print graphics context for a page.


 PrintGraphics Members

PrintGraphics Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getPrintJob() | Returns the PrintJob object from which this PrintGraphics object originated.


 PrintGraphics.getPrintJob

PrintGraphics.getPrintJob

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract PrintJob getPrintJob()
Description
Returns the PrintJob object from which this PrintGraphics object originated.


 Class PrintJob

Class java.awt.PrintJob

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.PrintJob

public abstract class PrintJob
extends Object

An abstract class which initiates and executes a print job. It provides access to a print graphics object which renders to an appropriate print device.

See Also:
getPrintJob


 PrintJob Members

PrintJob Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PrintJob() |

Methods
Name | Description
end() | Ends the print job and does any necessary cleanup.
finalize() | Ends this print job once it is no longer referenced.
getGraphics() | Gets a Graphics object that will draw to the next page.
getPageDimension() | Returns the dimensions of the page in pixels.
getPageResolution() | Returns the resolution of the page in pixels per inch.
lastPageFirst() | Returns true if the last page will be printed first.


 PrintJob.PrintJob

PrintJob.PrintJob

Syntax
public PrintJob()


 PrintJob.end

PrintJob.end

Syntax
public abstract void end()
Description
Ends the print job and does any necessary cleanup.


 PrintJob.finalize

PrintJob.finalize

Syntax
public void finalize()
Description
Ends this print job once it is no longer referenced.

Overrides
finalize in class Object
See Also
end


 PrintJob.getGraphics

PrintJob.getGraphics

Syntax
public abstract Graphics getGraphics()
Description
Gets a Graphics object that will draw to the next page. The page is sent to the printer when the graphics object is disposed. This graphics object will also implement the PrintGraphics interface.

See Also
PrintGraphics


 PrintJob.getPageDimension

PrintJob.getPageDimension

Syntax
public abstract Dimension getPageDimension()
Description
Returns the dimensions of the page in pixels. The resolution of the page is chosen so that it is similar to the screen resolution.


 PrintJob.getPageResolution

PrintJob.getPageResolution

Syntax
public abstract int getPageResolution()
Description
Returns the resolution of the page in pixels per inch. Note that this doesn't have to correspond to the physical resolution of the printer.


 PrintJob.lastPageFirst

PrintJob.lastPageFirst

Syntax
public abstract boolean lastPageFirst()
Description
Returns true if the last page will be printed first.


 Class Rectangle

Class java.awt.Rectangle

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Rectangle

public class Rectangle
extends Object
implements Shape, Serializable

A rectangle specifies an area in a coordinate space that is defined by the rectangle's top-left point (x, y) in the coordinate space, its width, and its height.

A rectangle's width and height are public fields. The constructors that allow you to create a rectangle, and the methods that allow you to modify one, do not prevent you from setting a negative value for width or height.

A rectangle whose width or height is negative is considered empty, and all methods defined by the Rectangle class behave accordingly. If the rectangle is empty, then the method isEmpty returns true. No point can be contained by or inside an empty rectangle, however the values of width and height are still valid. An empty rectangle still has a location in the coordinate space, and methods that change its size or location remain valid. The behavior of methods that operate on more than one rectangle is undefined if any of the participating rectangles has a negative width or height. These methods include intersects, intersection, and union.


 Rectangle Members

Rectangle Members

Class Overview | This Package | All Packages

Fields
Name | Description
height | The height of the rectangle.
width | The width of the rectangle.
x | The x coordinate of the rectangle.
y | The y coordinate of the rectangle.

Constructors
Name | Description
Rectangle() | Constructs a new rectangle whose top-left corner is at (0, 0) in the coordinate space, and whose width and height are zero.
Rectangle(Dimension) | Constructs a new rectangle whose top left corner is (0, 0) and whose width and height are specified by the dimension argument.
Rectangle(int, int) | Constructs a new rectangle whose top-left corner is at (0, 0) in the coordinate space, and whose width and height are specified by the arguments of the same name.
Rectangle(int, int, int, int) | Constructs a new rectangle whose top-left corner is specified as (x, y) and whose width and height are specified by the arguments of the same name.
Rectangle(Point) | Constructs a new rectangle whose top-left corner is the specified point, and whose width and height are zero.
Rectangle(Point, Dimension) | Constructs a new rectangle whose top-left corner is specified by the point argument, and whose width and height are specified by the dimension argument.
Rectangle(Rectangle) | Constructs a new rectangle, initialized to match the values of the specificed rectangle.

Methods
Name | Description
add(int, int) | Adds a point, specified by the integer arguments newx and newy, to a rectangle.
add(Point) | Adds a point to this rectangle.
add(Rectangle) | Adds a rectangle to this rectangle.
contains(int, int) | Checks whether this rectangle contains the point at the specified location (x, y).
contains(Point) | Checks whether this rectangle contains the specified point.
equals(Object) | Checks whether two rectangles are equal.
getBounds() | Gets the bounding rectangle of this rectangle.
getLocation() | Returns the location of this rectangle.
getSize() | Gets the size (width and height) of this rectangle.
grow(int, int) | Grows the rectangle both horizontally and vertically.
hashCode() | Returns the hashcode for this rectangle.
inside(int, int) | Deprecated.
intersection(Rectangle) | Computes the intersection of this rectangle with the specified rectangle.
intersects(Rectangle) | Determines whether this rectangle and the specified rectangle intersect.
isEmpty() | Determines whether this rectangle is empty.
move(int, int) | Deprecated.
reshape(int, int, int, int) | Deprecated.
resize(int, int) | Deprecated.
setBounds(int, int, int, int) | Sets the bounding rectangle of this rectangle to the specified values for x, y, width, and height.
setBounds(Rectangle) | Sets the bounding rectangle of this rectangle to match the specified rectangle.
setLocation(int, int) | Moves the rectangle to the specified location.
setLocation(Point) | Moves the rectangle to the specified location.
setSize(Dimension) | Sets the size of this rectangle to match the specified dimension.
setSize(int, int) | Sets the size of this rectangle to the specified width and height.
toString() | Returns a string representation of this rectangle and its values.
translate(int, int) | Translates the rectangle the indicated distance, to the right along the x coordinate axis, and downward along the y coordinate axis.
union(Rectangle) | Computes the union of this rectangle with the specified rectangle.


 Rectangle.height

Rectangle.height

Syntax
public int height
Description
The height of the rectangle.


 Rectangle.width

Rectangle.width

Syntax
public int width
Description
The width of the rectangle.


 Rectangle.x

Rectangle.x

Syntax
public int x
Description
The x coordinate of the rectangle.


 Rectangle.y

Rectangle.y

Syntax
public int y
Description
The y coordinate of the rectangle.


 Rectangle.Rectangle

Rectangle.Rectangle

Syntax 1
public Rectangle()
Description
Constructs a new rectangle whose top-left corner is at (0, 0) in the coordinate space, and whose width and height are zero.

Syntax 2
public Rectangle( Rectangle r )
Parameters
r
a rectangle from which to copy initial values.
Description
Constructs a new rectangle, initialized to match the values of the specificed rectangle.

Syntax 3
public Rectangle( int x, int y, int width, int height )
Parameters
x
the x coordinate.
y
the y coordinate.
width
the width of the rectangle.
height
the height of the rectangle.
Description
Constructs a new rectangle whose top-left corner is specified as (x, y) and whose width and height are specified by the arguments of the same name.

Syntax 4
public Rectangle( int width, int height )
Parameters
width
the width of the rectangle.
height
the height of the rectangle.
Description
Constructs a new rectangle whose top-left corner is at (0, 0) in the coordinate space, and whose width and height are specified by the arguments of the same name.

Syntax 5
public Rectangle( Point p, Dimension d )
Parameters
p
a point, the top-left corner of the rectangle.
d
a dimension, representing the width and height.
Description
Constructs a new rectangle whose top-left corner is specified by the point argument, and whose width and height are specified by the dimension argument.

Syntax 6
public Rectangle( Point p )
Parameters
p
the top left corner of the rectangle.
Description
Constructs a new rectangle whose top-left corner is the specified point, and whose width and height are zero.

Syntax 7
public Rectangle( Dimension d )
Parameters
d
a dimension, specifying width and height.
Description
Constructs a new rectangle whose top left corner is (0, 0) and whose width and height are specified by the dimension argument.


 Rectangle.add

Rectangle.add

Syntax 1
public void add( int newx, int newy )
Parameters
newx
the x coordinate of the new point.
newy
the y coordinate of the new point.
Description
Adds a point, specified by the integer arguments newx and newy, to a rectangle. The resulting rectangle is the smallest rectangle that contains both the rectangle and the specified point.

Syntax 2
public void add( Point pt )
Parameters
a
point.
Description
Adds a point to this rectangle. The resulting rectangle is the smallest rectangle that contains both the rectangle and the specified point.

Syntax 3
public void add( Rectangle r )
Parameters
a
rectangle.
Description
Adds a rectangle to this rectangle. The resulting rectangle is the union of the two rectangles.


 Rectangle.contains

Rectangle.contains

Syntax 1
public boolean contains( Point p )
Parameters
p
the point (location) to test.
Returns
true if the point (x, y) is inside this rectangle; false otherwise.
Description
Checks whether this rectangle contains the specified point.

Syntax 2
public boolean contains( int x, int y )
Parameters
x
the x coordinate.
y
the y coordinate.
Returns
true if the point (x, y) is inside this rectangle; false otherwise.
Description
Checks whether this rectangle contains the point at the specified location (x, y).


 Rectangle.equals

Rectangle.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are equal; false otherwise.
Description
Checks whether two rectangles are equal.

The result is true if and only if the argument is not null and is a Rectangle object that has the same top-left corner, width, and height as this rectangle.

Overrides
equals in class Object


 Rectangle.getBounds

Rectangle.getBounds

Syntax
public Rectangle getBounds()
Returns
a new rectangle, equal to the bounding rectangle for this rectangle.
Description
Gets the bounding rectangle of this rectangle.

This method is included for completeness, to parallel the getBounds method of Component.

See Also
getBounds


 Rectangle.getLocation

Rectangle.getLocation

Syntax
public Point getLocation()
Description
Returns the location of this rectangle.

This method is included for completeness, to parallel the getLocation method of Component.

See Also
getLocation


 Rectangle.getSize

Rectangle.getSize

Syntax
public Dimension getSize()
Returns
a dimension, representing the size.
Description
Gets the size (width and height) of this rectangle.

This method is included for completeness, to parallel the getSize method of Component.

See Also
getSize


 Rectangle.grow

Rectangle.grow

Syntax
public void grow( int h, int v )
Parameters
h
the horizontal expansion.
v
the vertical expansion.
Description
Grows the rectangle both horizontally and vertically.

This method modifies the rectangle so that it is h units larger on both the left and right side, and v units larger at both the top and bottom.

The new rectangle has (x - h, y - v) as its top-left corner, a width of width + 2h, and a height of height + 2v.

If negative values are supplied for h and v, the size of the rectangle decreases accordingly. The grow method does not check whether the resulting values of width and height are non-negative.


 Rectangle.hashCode

Rectangle.hashCode

Syntax
public int hashCode()
Returns
the hashcode for this rectangle.
Description
Returns the hashcode for this rectangle.

Overrides
hashCode in class Object


 Rectangle.inside

Rectangle.inside

Syntax
public boolean inside( int x, int y )
Description
Note: inside() is deprecated. As of JDK version 1.1, replaced by contains(int, int).


 Rectangle.intersection

Rectangle.intersection

Syntax
public Rectangle intersection( Rectangle r )
Parameters
r
a rectangle.
Returns
the largest rectangle contained in both the specified rectangle and in this rectangle.
Description
Computes the intersection of this rectangle with the specified rectangle. Returns a new rectangle that represents the intersection of the two rectangles.


 Rectangle.intersects

Rectangle.intersects

Syntax
public boolean intersects( Rectangle r )
Parameters
r
a rectangle.
Returns
true if the specified rectangle and this rectangle insersect; false otherwise.
Description
Determines whether this rectangle and the specified rectangle intersect. Two rectangles intersect if their intersection is nonempty.


 Rectangle.isEmpty

Rectangle.isEmpty

Syntax
public boolean isEmpty()
Returns
true if this rectangle is empty; false otherwise.
Description
Determines whether this rectangle is empty. A rectangle is empty if its width or its height is less than or equal to zero.


 Rectangle.move

Rectangle.move

Syntax
public void move( int x, int y )
Description
Note: move() is deprecated. As of JDK version 1.1, replaced by setLocation(int, int).


 Rectangle.reshape

Rectangle.reshape

Syntax
public void reshape( int x, int y, int width, int height )
Description
Note: reshape() is deprecated. As of JDK version 1.1, replaced by setBounds(int, int, int, int).


 Rectangle.resize

Rectangle.resize

Syntax
public void resize( int width, int height )
Description
Note: resize() is deprecated. As of JDK version 1.1, replaced by setSize(int, int).


 Rectangle.setBounds

Rectangle.setBounds

Syntax 1
public void setBounds( Rectangle r )
Parameters
r
a rectangle.
Description
Sets the bounding rectangle of this rectangle to match the specified rectangle.

This method is included for completeness, to parallel the setBounds method of Component.

See Also
setBounds

Syntax 2
public void setBounds( int x, int y, int width, int height )
Parameters
x
the new x coordinate for the top-left corner of this rectangle.
y
the new y coordinate for the top-left corner of this rectangle.
width
the new width for this rectangle.
height
the new height for this rectangle.
Description
Sets the bounding rectangle of this rectangle to the specified values for x, y, width, and height.

This method is included for completeness, to parallel the setBounds method of Component.

See Also
setBounds


 Rectangle.setLocation

Rectangle.setLocation

Syntax 1
public void setLocation( Point p )
Parameters
p
the new location for the point.
Description
Moves the rectangle to the specified location.

This method is included for completeness, to parallel the setLocation method of Component.

See Also
setLocation

Syntax 2
public void setLocation( int x, int y )
Parameters
x
the x coordinate of the new location.
y
the y coordinate of the new location.
Description
Moves the rectangle to the specified location.

This method is included for completeness, to parallel the setLocation method of Component.

See Also
setLocation


 Rectangle.setSize

Rectangle.setSize

Syntax 1
public void setSize( Dimension d )
Parameters
d
the new size for the Dimension object
Description
Sets the size of this rectangle to match the specified dimension.

This method is included for completeness, to parallel the setSize method of Component.

See Also
setSize

Syntax 2
public void setSize( int width, int height )
Parameters
width
the new width for this rectangle object.
height
the new height for this rectangle object.
Description
Sets the size of this rectangle to the specified width and height.

This method is included for completeness, to parallel the setSize method of Component.

See Also
setSize


 Rectangle.toString

Rectangle.toString

Syntax
public String toString()
Returns
a string representation of this rectangle.
Description
Returns a string representation of this rectangle and its values.

Overrides
toString in class Object


 Rectangle.translate

Rectangle.translate

Syntax
public void translate( int x, int y )
Parameters
dx
the distance to move the rectangle along the x axis.
dy
the distance to move the rectangle along the y axis.
Description
Translates the rectangle the indicated distance, to the right along the x coordinate axis, and downward along the y coordinate axis.

See Also
setLocation, setLocation


 Rectangle.union

Rectangle.union

Syntax
public Rectangle union( Rectangle r )
Parameters
r
a rectangle.
Returns
the smallest rectangle containing both the specified rectangle and this rectangle.
Description
Computes the union of this rectangle with the specified rectangle. Returns a new rectangle that represents the union of the two rectangles.


 Class ScrollPane

Class java.awt.ScrollPane

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.ScrollPane

public class ScrollPane
extends Container

A container class which implements automatic horizontal and/or vertical scrolling for a single child component. The display policy for the scrollbars can be set to:

  1. as needed: scrollbars created and shown only when needed by scrollpane
  2. always: scrollbars created and always shown by the scrollpane
  3. never: scrollbars never created or shown by the scrollpane

The state of the horizontal and vertical scrollbars is represented by two objects (one for each dimension) which implement the Adjustable interface. The API provides methods to access those objects such that the attributes on the Adjustable object (such as unitIncrement, value, etc.) can be manipulated.

Certain adjustable properties (minimum, maximum, blockIncrement, and visibleAmount) are set internally by the scrollpane in accordance with the geometry of the scrollpane and its child and these should not be set by programs using the scrollpane.

If the scrollbar display policy is defined as "never", then the scrollpane can still be programmatically scrolled using the setScrollPosition() method and the scrollpane will move and clip the child's contents appropriately. This policy is useful if the program needs to create and manage its own adjustable controls.

The placement of the scrollbars is controlled by platform-specific properties set by the user outside of the program.

The initial size of this container is set to 100x100, but can be reset using setSize().

Insets are used to define any space used by scrollbars and any borders created by the scroll pane. getInsets() can be used to get the current value for the insets. If the value of scrollbarsAlwaysVisible is false, then the value of the insets will change dynamically depending on whether the scrollbars are currently visible or not.


 ScrollPane Members

ScrollPane Members

Class Overview | This Package | All Packages

Fields
Name | Description
SCROLLBARS_ALWAYS | Specifies that horizontal/vertical scrollbars should always be shown regardless of the respective sizes of the scrollpane and child.
SCROLLBARS_AS_NEEDED | Specifies that horizontal/vertical scrollbar should be shown only when the size of the child exceeds the size of the scrollpane in the horizontal/vertical dimension.
SCROLLBARS_NEVER | Specifies that horizontal/vertical scrollbars should never be shown regardless of the respective sizes of the scrollpane and child.

Constructors
Name | Description
ScrollPane() | Create a new scrollpane container with a scrollbar display policy of "as needed".
ScrollPane(int) | Create a new scrollpane container.

Methods
Name | Description
addImpl(Component, Object, int) | Adds the specified component to this scroll pane container.
addNotify() | Creates the scroll pane's peer.
doLayout() | Lays out this container by resizing its child to its preferred size.
getHAdjustable() | Returns the Adjustable object which represents the state of the horizontal scrollbar.
getHScrollbarHeight() | Returns the height that would be occupied by a horizontal scrollbar, which is independent of whether it is currently displayed by the scroll pane or not.
getScrollbarDisplayPolicy() | Returns the display policy for the scrollbars.
getScrollPosition() | Returns the current x,y position within the child which is displayed at the 0,0 location of the scrolled panel's view port.
getVAdjustable() | Returns the Adjustable object which represents the state of the vertical scrollbar.
getViewportSize() | Returns the current size of the scroll pane's view port.
getVScrollbarWidth() | Returns the width that would be occupied by a vertical scrollbar, which is independent of whether it is currently displayed by the scroll pane or not.
layout() | Deprecated.
paramString() | Returns the parameter string representing the state of this container.
printComponents(Graphics) | Prints the component in this scroll pane.
setLayout(LayoutManager) | Sets the layout manager for this container.
setScrollPosition(int, int) | Scrolls to the specified position within the child component.
setScrollPosition(Point) | Scrolls to the specified position within the child component.


 ScrollPane.SCROLLBARS_ALWAYS

ScrollPane.SCROLLBARS_ALWAYS

Syntax
public static final int SCROLLBARS_ALWAYS
Description
Specifies that horizontal/vertical scrollbars should always be shown regardless of the respective sizes of the scrollpane and child.


 ScrollPane.SCROLLBARS_AS_NEEDED

ScrollPane.SCROLLBARS_AS_NEEDED

Syntax
public static final int SCROLLBARS_AS_NEEDED
Description
Specifies that horizontal/vertical scrollbar should be shown only when the size of the child exceeds the size of the scrollpane in the horizontal/vertical dimension.


 ScrollPane.SCROLLBARS_NEVER

ScrollPane.SCROLLBARS_NEVER

Syntax
public static final int SCROLLBARS_NEVER
Description
Specifies that horizontal/vertical scrollbars should never be shown regardless of the respective sizes of the scrollpane and child.


 ScrollPane.ScrollPane

ScrollPane.ScrollPane

Syntax 1
public ScrollPane()
Description
Create a new scrollpane container with a scrollbar display policy of "as needed".

Syntax 2
public ScrollPane( int scrollbarDisplayPolicy )
Parameters
scrollbarDisplayPolicy
policy for when scrollbars should be shown
Description
Create a new scrollpane container.


 ScrollPane.addImpl

ScrollPane.addImpl

Syntax
protected final void addImpl( Component comp, Object constraints, int index )
Parameters
comp
the component to be added
constraints
not applicable
index
position of child component (must be <= 0)
Description
Adds the specified component to this scroll pane container. If the scroll pane has an existing child component, that component is removed and the new one is added.

Overrides
addImpl in class Container


 ScrollPane.addNotify

ScrollPane.addNotify

Syntax
public void addNotify()
Description
Creates the scroll pane's peer.

Overrides
addNotify in class Container


 ScrollPane.doLayout

ScrollPane.doLayout

Syntax
public void doLayout()
Description
Lays out this container by resizing its child to its preferred size. If the new preferred size of the child causes the current scroll position to be invalid, the scroll position is set to the closest valid position.

Overrides
doLayout in class Container
See Also
validate


 ScrollPane.getHAdjustable

ScrollPane.getHAdjustable

Syntax
public Adjustable getHAdjustable()
Description
Returns the Adjustable object which represents the state of the horizontal scrollbar. If the scrollbar display policy is "never", this method returns null.


 ScrollPane.getHScrollbarHeight

ScrollPane.getHScrollbarHeight

Syntax
public int getHScrollbarHeight()
Returns
the height of a horizontal scrollbar in pixels
Description
Returns the height that would be occupied by a horizontal scrollbar, which is independent of whether it is currently displayed by the scroll pane or not.


 ScrollPane.getScrollbarDisplayPolicy

ScrollPane.getScrollbarDisplayPolicy

Syntax
public int getScrollbarDisplayPolicy()
Returns
the display policy for the scrollbars
Description
Returns the display policy for the scrollbars.


 ScrollPane.getScrollPosition

ScrollPane.getScrollPosition

Syntax
public Point getScrollPosition()
Returns
the coordinate position for the current scroll position
Description
Returns the current x,y position within the child which is displayed at the 0,0 location of the scrolled panel's view port. This is a convenience method which interfaces with the adjustable objects which respresent the state of the scrollbars.


 ScrollPane.getVAdjustable

ScrollPane.getVAdjustable

Syntax
public Adjustable getVAdjustable()
Description
Returns the Adjustable object which represents the state of the vertical scrollbar. If the scrollbar display policy is "never", this method returns null.


 ScrollPane.getViewportSize

ScrollPane.getViewportSize

Syntax
public Dimension getViewportSize()
Returns
the size of the view port in pixels
Description
Returns the current size of the scroll pane's view port.


 ScrollPane.getVScrollbarWidth

ScrollPane.getVScrollbarWidth

Syntax
public int getVScrollbarWidth()
Returns
the width of a vertical scrollbar in pixels
Description
Returns the width that would be occupied by a vertical scrollbar, which is independent of whether it is currently displayed by the scroll pane or not.


 ScrollPane.layout

ScrollPane.layout

Syntax
public void layout()
Description
Note: layout() is deprecated. As of JDK version 1.1, replaced by doLayout().

Overrides
layout in class Container


 ScrollPane.paramString

ScrollPane.paramString

Syntax
public String paramString()
Description
Returns the parameter string representing the state of this container.

Overrides
paramString in class Container


 ScrollPane.printComponents

ScrollPane.printComponents

Syntax
public void printComponents( Graphics g )
Parameters
g
the specified Graphics window
Description
Prints the component in this scroll pane.

Overrides
printComponents in class Container
See Also
print, printAll


 ScrollPane.setLayout

ScrollPane.setLayout

Syntax
public final void setLayout( LayoutManager mgr )
Parameters
mgr
the specified layout manager
Description
Sets the layout manager for this container. This method is overridden to prevent the layout mgr from being set.

Overrides
setLayout in class Container


 ScrollPane.setScrollPosition

ScrollPane.setScrollPosition

Syntax 1
public void setScrollPosition( int x, int y )
Parameters
x
the x position to scroll to
y
the y position to scroll to
Description
Scrolls to the specified position within the child component. A call to this method is only valid if the scroll pane contains a child. Specifying a position outside of the legal scrolling bounds of the child will scroll to the closest legal position. Legal bounds are defined to be the rectangle: x = 0, y = 0, width = (child width - view port width), height = (child height - view port height). This is a convenience method which interfaces with the Adjustable objects which respresent the state of the scrollbars.

Exceptions
IllegalArgumentException if specified coordinates are not within the legal scrolling bounds of the child component.

Syntax 2
public void setScrollPosition( Point p )
Parameters
p
the Point representing the position to scroll to
Description
Scrolls to the specified position within the child component. A call to this method is only valid if the scroll pane contains a child and the specified position is within legal scrolling bounds of the child. Legal bounds are defined to be the rectangle: x = 0, y = 0, width = (child width - view port width), height = (child height - view port height). This is a convenience method which interfaces with the Adjustable objects which respresent the state of the scrollbars.

Exceptions
IllegalArgumentException if specified coordinates are not within the legal scrolling bounds of the child component.


 Class Scrollbar

Class java.awt.Scrollbar

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Scrollbar

public class Scrollbar
extends Component
implements Adjustable

The Scrollbar class embodies a scroll bar, a familiar user-interface object. A scroll bar provides a convenient means for allowing a user to select from a range of values. The following three vertical scroll bars could be used as slider controls to pick the red, green, and blue components of a color:

Each scroll bar in this example could be created with code similar to the following:

 redSlider=new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 255);
 add(redSlider);

Alternatively, a scroll bar can represent a range of values. For example, if a scroll bar is used for scrolling through text, the width of the "bubble" or "thumb" can represent the amount of text that is visible. Here is an example of a scroll bar that represents a range:

The value range represented by the bubble is the visible range of the scroll bar. The horizontal scroll bar in this example could be created with code like the following:

 ranger = new Scrollbar(Scrollbar.HORIZONTAL, 0, 64, 0, 255);
 add(ranger);

Note that the maximum value above, 255, is the maximum value for the scroll bar's bubble. The actual width of the scroll bar's track is 255 + 64. When the scroll bar is set to its maximum value, the left side of the bubble is at 255, and the right side is at 255 + 64.

Normally, the user changes the value of the scroll bar by making a gesture with the mouse. For example, the user can drag the scroll bar's bubble up and down, or click in the scroll bar's unit increment or block increment areas. Keyboard gestures can also be mapped to the scroll bar. By convention, the Page Up and Page Down keys are equivalent to clicking in the scroll bar's block increment and block decrement areas.

When the user changes the value of the scroll bar, the scroll bar receives an instance of AdjustmentEvent. The scroll bar processes this event, passing it along to any registered listeners.

Any object that wishes to be notified of changes to the scroll bar's value should implement AdjustmentListener, an interface defined in the package java.awt.event. Listeners can be added and removed dynamically by calling the methods addAdjustmentListener and removeAdjustmentListener.

The AdjustmentEvent class defines five types of adjustment event, listed here:

  • AdjustmentEvent.TRACK is sent out when the user drags the scroll bar's bubble.
  • AdjustmentEvent.UNIT_INCREMENT is sent out when the user clicks in the left arrow of a horizontal scroll bar, or the top arrow of a vertical scroll bar, or makes the equivalent gesture from the keyboard.
  • AdjustmentEvent.UNIT_DECREMENT is sent out when the user clicks in the right arrow of a horizontal scroll bar, or the bottom arrow of a vertical scroll bar, or makes the equivalent gesture from the keyboard.
  • AdjustmentEvent.BLOCK_INCREMENT is sent out when the user clicks in the track, to the left of the bubble on a horizontal scroll bar, or above the bubble on a vertical scroll bar. By convention, the Page Up key is equivalent, if the user is using a keyboard that defines a Page Up key.
  • AdjustmentEvent.BLOCK_DECREMENT is sent out when the user clicks in the track, to the right of the bubble on a horizontal scroll bar, or below the bubble on a vertical scroll bar. By convention, the Page Down key is equivalent, if the user is using a keyboard that defines a Page Down key.

The JDK 1.0 event system is supported for backwards compatibility, but its use with newer versions of JDK is discouraged. The fives types of adjustment event introduced with JDK 1.1 correspond to the five event types that are associated with scroll bars in previous JDK versions. The following list gives the adjustment event type, and the corresponding JDK 1.0 event type it replaces.

  • AdjustmentEvent.TRACK replaces Event.SCROLL_ABSOLUTE
  • AdjustmentEvent.UNIT_INCREMENT replaces Event.SCROLL_LINE_UP
  • AdjustmentEvent.UNIT_DECREMENT replaces Event.SCROLL_LINE_DOWN
  • AdjustmentEvent.BLOCK_INCREMENT replaces Event.SCROLL_PAGE_UP
  • AdjustmentEvent.BLOCK_DECREMENT replaces Event.SCROLL_PAGE_DOWN

See Also:
AdjustmentEvent, AdjustmentListener


 Scrollbar Members

Scrollbar Members

Class Overview | This Package | All Packages

Fields
Name | Description
HORIZONTAL | A constant that indicates a horizontal scroll bar.
VERTICAL | A constant that indicates a vertical scroll bar.

Constructors
Name | Description
Scrollbar() | Constructs a new vertical scroll bar.
Scrollbar(int) | Constructs a new scroll bar with the specified orientation.
Scrollbar(int, int, int, int, int) | Constructs a new scroll bar with the specified orientation, initial value, page size, and minimum and maximum values.

Methods
Name | Description
addAdjustmentListener(AdjustmentListener) | Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.
addNotify() | Creates the Scrollbar's peer.
getBlockIncrement() | Gets the block increment of this scroll bar.
getLineIncrement() | Deprecated.
getMaximum() | Gets the maximum value of this scroll bar.
getMinimum() | Gets the minimum value of this scroll bar.
getOrientation() | Determines the orientation of this scroll bar.
getPageIncrement() | Deprecated.
getUnitIncrement() | Gets the unit increment for this scrollbar.
getValue() | Gets the current value of this scroll bar.
getVisible() | Deprecated.
getVisibleAmount() | Gets the visible amount of this scroll bar.
paramString() | Returns the parameter string representing the state of this scroll bar.
processAdjustmentEvent(AdjustmentEvent) | Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.
processEvent(AWTEvent) | Processes events on this scroll bar.
removeAdjustmentListener(AdjustmentListener) | Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.
setBlockIncrement(int) | Sets the block increment for this scroll bar.
setLineIncrement(int) | Deprecated.
setMaximum(int) | Sets the maximum value of this scroll bar.
setMinimum(int) | Sets the minimum value of this scroll bar.
setOrientation(int) | Sets the orientation for this scroll bar.
setPageIncrement(int) | Deprecated.
setUnitIncrement(int) | Sets the unit increment for this scroll bar.
setValue(int) | Sets the value of this scroll bar to the specified value.
setValues(int, int, int, int) | Sets the values of four properties for this scroll bar.
setVisibleAmount(int) | Sets the visible amount of this scroll bar.


 Scrollbar.HORIZONTAL

Scrollbar.HORIZONTAL

Syntax
public static final int HORIZONTAL
Description
A constant that indicates a horizontal scroll bar.


 Scrollbar.VERTICAL

Scrollbar.VERTICAL

Syntax
public static final int VERTICAL
Description
A constant that indicates a vertical scroll bar.


 Scrollbar.Scrollbar

Scrollbar.Scrollbar

Syntax 1
public Scrollbar()
Description
Constructs a new vertical scroll bar.

Syntax 2
public Scrollbar( int orientation )
Parameters
orientation
indicates the orientation of the scroll bar.
Description
Constructs a new scroll bar with the specified orientation.

The orientation argument must take one of the two values Scrollbar.HORIZONTAL, or Scrollbar.VERTICAL, indicating a horizontal or vertical scroll bar, respectively.

Exceptions
IllegalArgumentException when an illegal value for the orientation argument is supplied.

Syntax 3
public Scrollbar( int orientation, int value, int visible, int minimum, int maximum )
Parameters
orientation
indicates the orientation of the scroll bar.
value
the initial value of the scroll bar.
visible
the size of the scroll bar's bubble, representing the visible portion; the scroll bar uses this value when paging up or down by a page.
minimum
the minimum value of the scroll bar.
maximum
the maximum value of the scroll bar.
Description
Constructs a new scroll bar with the specified orientation, initial value, page size, and minimum and maximum values.

The orientation argument must take one of the two values Scrollbar.HORIZONTAL, or Scrollbar.VERTICAL, indicating a horizontal or vertical scroll bar, respectively.

If the specified maximum value is less than the minimum value, it is changed to be the same as the minimum value. If the initial value is lower than the minimum value, it is changed to be the minimum value; if it is greater than the maximum value, it is changed to be the maximum value.


 Scrollbar.addAdjustmentListener

Scrollbar.addAdjustmentListener

Syntax
public synchronized void addAdjustmentListener( AdjustmentListener l )
Parameters
l
the adjustment listener.
Description
Adds the specified adjustment listener to receive instances of AdjustmentEvent from this scroll bar.

See Also
AdjustmentEvent, AdjustmentListener, removeAdjustmentListener


 Scrollbar.addNotify

Scrollbar.addNotify

Syntax
public void addNotify()
Description
Creates the Scrollbar's peer. The peer allows you to modify the appearance of the Scrollbar without changing any of its functionality.

Overrides
addNotify in class Component


 Scrollbar.getBlockIncrement

Scrollbar.getBlockIncrement

Syntax
public int getBlockIncrement()
Returns
the block increment of this scroll bar.
Description
Gets the block increment of this scroll bar.

The block increment is the value that is added (subtracted) when the user activates the block increment area of the scroll bar, generally through a mouse or keyboard gesture that the scroll bar receives as an adjustment event.

See Also
setBlockIncrement


 Scrollbar.getLineIncrement

Scrollbar.getLineIncrement

Syntax
public int getLineIncrement()
Description
Note: getLineIncrement() is deprecated. As of JDK version 1.1, replaced by getUnitIncrement().


 Scrollbar.getMaximum

Scrollbar.getMaximum

Syntax
public int getMaximum()
Returns
the maximum value of this scroll bar.
Description
Gets the maximum value of this scroll bar.

See Also
getValue, getMinimum


 Scrollbar.getMinimum

Scrollbar.getMinimum

Syntax
public int getMinimum()
Returns
the minimum value of this scroll bar.
Description
Gets the minimum value of this scroll bar.

See Also
getValue, getMaximum


 Scrollbar.getOrientation

Scrollbar.getOrientation

Syntax
public int getOrientation()
Returns
the orientation of this scroll bar, either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
Description
Determines the orientation of this scroll bar.

See Also
setOrientation


 Scrollbar.getPageIncrement

Scrollbar.getPageIncrement

Syntax
public int getPageIncrement()
Description
Note: getPageIncrement() is deprecated. As of JDK version 1.1, replaced by getBlockIncrement().


 Scrollbar.getUnitIncrement

Scrollbar.getUnitIncrement

Syntax
public int getUnitIncrement()
Returns
the unit increment of this scroll bar.
Description
Gets the unit increment for this scrollbar.

The unit increment is the value that is added (subtracted) when the user activates the unit increment area of the scroll bar, generally through a mouse or keyboard gesture that the scroll bar receives as an adjustment event.

See Also
setUnitIncrement


 Scrollbar.getValue

Scrollbar.getValue

Syntax
public int getValue()
Returns
the current value of this scroll bar.
Description
Gets the current value of this scroll bar.

See Also
getMinimum, getMaximum


 Scrollbar.getVisible

Scrollbar.getVisible

Syntax
public int getVisible()
Description
Note: getVisible() is deprecated. As of JDK version 1.1, replaced by getVisibleAmount().


 Scrollbar.getVisibleAmount

Scrollbar.getVisibleAmount

Syntax
public int getVisibleAmount()
Returns
the visible amount of this scroll bar.
Description
Gets the visible amount of this scroll bar.

The visible amount of a scroll bar is the range of values represented by the width of the scroll bar's bubble. It is used to determine the scroll bar's block increment.

See Also
setVisibleAmount


 Scrollbar.paramString

Scrollbar.paramString

Syntax
protected String paramString()
Returns
the parameter string of this scroll bar.
Description
Returns the parameter string representing the state of this scroll bar. This string is useful for debugging.

Overrides
paramString in class Component


 Scrollbar.processAdjustmentEvent

Scrollbar.processAdjustmentEvent

Syntax
protected void processAdjustmentEvent( AdjustmentEvent e )
Parameters
e
the adjustment event.
Description
Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.

This method is not called unless adjustment events are enabled for this component. Adjustment events are enabled when one of the following occurs:

  • An AdjustmentListener object is registered via addAdjustmentListener.
  • Adjustment events are enabled via enableEvents.

See Also
AdjustmentEvent, AdjustmentListener, addAdjustmentListener, enableEvents


 Scrollbar.processEvent

Scrollbar.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this scroll bar. If the event is an instance of AdjustmentEvent, it invokes the processAdjustmentEvent method. Otherwise, it invokes its superclass's processEvent method.

Overrides
processEvent in class Component
See Also
AdjustmentEvent, processAdjustmentEvent


 Scrollbar.removeAdjustmentListener

Scrollbar.removeAdjustmentListener

Syntax
public synchronized void removeAdjustmentListener( AdjustmentListener l )
Parameters
l
the adjustment listener.
Description
Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.

See Also
AdjustmentEvent, AdjustmentListener, addAdjustmentListener


 Scrollbar.setBlockIncrement

Scrollbar.setBlockIncrement

Syntax
public synchronized void setBlockIncrement( int v )
Parameters
v
the amount by which to increment or decrement the scroll bar's value.
Description
Sets the block increment for this scroll bar.

The block increment is the value that is added (subtracted) when the user activates the block increment area of the scroll bar, generally through a mouse or keyboard gesture that the scroll bar receives as an adjustment event.

See Also
getBlockIncrement


 Scrollbar.setLineIncrement

Scrollbar.setLineIncrement

Syntax
public void setLineIncrement( int v )
Description
Note: setLineIncrement() is deprecated. As of JDK version 1.1, replaced by setUnitIncrement(int).


 Scrollbar.setMaximum

Scrollbar.setMaximum

Syntax
public synchronized void setMaximum( int newMaximum )
Parameters
newMaximum
the new maximum value for this scroll bar.
Description
Sets the maximum value of this scroll bar.

Normally, a program should change a scroll bar's maximum value only by calling setValues. The setValues method simultaneously and synchronously sets the minimum, maximum, visible amount, and value properties of a scroll bar, so that they are mutually consistent.

See Also
setValues, setMinimum


 Scrollbar.setMinimum

Scrollbar.setMinimum

Syntax
public synchronized void setMinimum( int newMinimum )
Parameters
newMinimum
the new minimum value for this scroll bar.
Description
Sets the minimum value of this scroll bar.

Normally, a program should change a scroll bar's minimum value only by calling setValues. The setValues method simultaneously and synchronously sets the minimum, maximum, visible amount, and value properties of a scroll bar, so that they are mutually consistent.

See Also
setValues, setMaximum


 Scrollbar.setOrientation

Scrollbar.setOrientation

Syntax
public synchronized void setOrientation( int orientation )
Parameters
the
orientation of this scroll bar, either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
Description
Sets the orientation for this scroll bar.

Exceptions
IllegalArgumentException if the value supplied for orientation is not a legal value.
See Also
getOrientation


 Scrollbar.setPageIncrement

Scrollbar.setPageIncrement

Syntax
public void setPageIncrement( int v )
Description
Note: setPageIncrement() is deprecated. As of JDK version 1.1, replaced by setBlockIncrement().


 Scrollbar.setUnitIncrement

Scrollbar.setUnitIncrement

Syntax
public synchronized void setUnitIncrement( int v )
Parameters
v
the amount by which to increment or decrement the scroll bar's value.
Description
Sets the unit increment for this scroll bar.

The unit increment is the value that is added (subtracted) when the user activates the unit increment area of the scroll bar, generally through a mouse or keyboard gesture that the scroll bar receives as an adjustment event.

See Also
getUnitIncrement


 Scrollbar.setValue

Scrollbar.setValue

Syntax
public synchronized void setValue( int newValue )
Parameters
newValue
the new value of the scroll bar.
Description
Sets the value of this scroll bar to the specified value.

If the value supplied is less than the current minimum or greater than the current maximum, then one of those values is substituted, as appropriate.

Normally, a program should change a scroll bar's value only by calling setValues. The setValues method simultaneously and synchronously sets the minimum, maximum, visible amount, and value properties of a scroll bar, so that they are mutually consistent.

See Also
setValues, getValue, getMinimum, getMaximum


 Scrollbar.setValues

Scrollbar.setValues

Syntax
public synchronized void setValues( int value, int visible, int minimum, int maximum )
Parameters
value
is the position in the current window.
visible
is the amount visible per page.
minimum
is the minimum value of the scroll bar.
maximum
is the maximum value of the scroll bar.
Description
Sets the values of four properties for this scroll bar.

This method simultaneously and synchronously sets the values of four scroll bar properties, assuring that the values of these properties are mutually consistent. It enforces the constraints that maximum cannot be less than minimum, and that value cannot be less than the minimum or greater than the maximum.


 Scrollbar.setVisibleAmount

Scrollbar.setVisibleAmount

Syntax
public synchronized void setVisibleAmount( int newAmount )
Parameters
newAmount
the amount visible per page.
Description
Sets the visible amount of this scroll bar.

The visible amount of a scroll bar is the range of values represented by the width of the scroll bar's bubble. It is used to determine the scroll bar's block increment.

Normally, a program should change a scroll bar's value only by calling setValues. The setValues method simultaneously and synchronously sets the minimum, maximum, visible amount, and value properties of a scroll bar, so that they are mutually consistent.

See Also
getVisibleAmount, setValues


 Interface Shape

Interface java.awt.Shape

Interface Members | This Package | All Packages

public interface Shape

The interface for objects which represent some form of geometric shape.

This interface will be revised in the upcoming Java2D project. It is meant to provide a common interface for various existing geometric AWT classes and methods which operate on them. Since it may be superseded or expanded in the future, developers should avoid implementing this interface in their own classes until it is completed in a later release.


 Shape Members

Shape Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getBounds() | Return the bounding box of the shape.


 Shape.getBounds

Shape.getBounds

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Rectangle getBounds()
Description
Return the bounding box of the shape.


 Class SystemColor

Class java.awt.SystemColor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Color
           |
           +----java.awt.SystemColor

public final class SystemColor
extends Color
implements Serializable

A class to encapsulate symbolic colors representing the color of GUI objects on a system. For systems which support the dynamic update of the system colors (when the user changes the colors) the actual RGB values of these symbolic colors will also change dynamically. In order to compare the "current" RGB value of a SystemColor object with a non-symbolic Color object, getRGB() should be used rather than equals().


 SystemColor Members

SystemColor Members

Class Overview | This Package | All Packages

Fields
Name | Description
ACTIVE_CAPTION | The array index for the active caption background color.
ACTIVE_CAPTION_BORDER | The array index for the active caption border color.
ACTIVE_CAPTION_TEXT | The array index for the action caption text color.
activeCaption | The background color for captions in window borders.
activeCaptionBorder | The border color for captions in window borders.
activeCaptionText | The text color for captions in window borders.
CONTROL | The array index for the control background color.
control | The background color for control objects.
CONTROL_DK_SHADOW | The array index for the control dark shadow color.
CONTROL_HIGHLIGHT | The array index for the control highlight color.
CONTROL_LT_HIGHLIGHT | The array index for the control light highlight color.
CONTROL_SHADOW | The array index for the control shadow color.
CONTROL_TEXT | The array index for the control text color.
controlDkShadow | The dark shadow color for control objects.
controlHighlight | The regular highlight color for control objects.
controlLtHighlight | The light highlight color for control objects.
controlShadow | The regular shadow color for control objects.
controlText | The text color for control objects.
desktop | The color of the desktop background.
DESKTOP | The array index for the desktop background color.
INACTIVE_CAPTION | The array index for the inactive caption background color.
INACTIVE_CAPTION_BORDER | The array index for the inactive caption border color.
INACTIVE_CAPTION_TEXT | The array index for the inactive caption text color.
inactiveCaption | The background color for inactive captions in window borders.
inactiveCaptionBorder | The border color for inactive captios in window borders.
inactiveCaptionText | The text color for inactive captions in window borders.
INFO | The array index for the info background color.
info | The background color for info(help) text.
INFO_TEXT | The array index for the info text color.
infoText | The text color for info(help) text.
menu | The background color for menus.
MENU | The array index for the menu background color.
MENU_TEXT | The array index for the menu text color.
menuText | The text color for menus.
NUM_COLORS | The number of system colors in the array.
scrollbar | The background color for scrollbars.
SCROLLBAR | The array index for the scrollbar background color.
TEXT | The array index for the text background color.
text | The background color for text components.
TEXT_HIGHLIGHT | The array index for the text highlight color.
TEXT_HIGHLIGHT_TEXT | The array index for the text highlight text color.
TEXT_INACTIVE_TEXT | The array index for the text inactive text color.
TEXT_TEXT | The array index for the text text color.
textHighlight | The background color for highlighted text.
textHighlightText | The text color for highlighted text.
textInactiveText | The text color for inactive text.
textText | The text color for text components.
WINDOW | The array index for the window background color.
window | The background color for windows.
WINDOW_BORDER | The array index for the window border color.
WINDOW_TEXT | The array index for the window text color.
windowBorder | The border color for windows.
windowText | The text color for windows.

Methods
Name | Description
getRGB() | Gets the "current" RGB value representing the symbolic color.
toString() | Returns the String representation of this Color's values.


 SystemColor.ACTIVE_CAPTION

SystemColor.ACTIVE_CAPTION

Syntax
public static final int ACTIVE_CAPTION
Description
The array index for the active caption background color.


 SystemColor.ACTIVE_CAPTION_BORDER

SystemColor.ACTIVE_CAPTION_BORDER

Syntax
public static final int ACTIVE_CAPTION_BORDER
Description
The array index for the active caption border color.


 SystemColor.ACTIVE_CAPTION_TEXT

SystemColor.ACTIVE_CAPTION_TEXT

Syntax
public static final int ACTIVE_CAPTION_TEXT
Description
The array index for the action caption text color.


 SystemColor.activeCaption

SystemColor.activeCaption

Syntax
public static final SystemColor activeCaption
Description
The background color for captions in window borders.


 SystemColor.activeCaptionBorder

SystemColor.activeCaptionBorder

Syntax
public static final SystemColor activeCaptionBorder
Description
The border color for captions in window borders.


 SystemColor.activeCaptionText

SystemColor.activeCaptionText

Syntax
public static final SystemColor activeCaptionText
Description
The text color for captions in window borders.


 SystemColor.CONTROL

SystemColor.CONTROL

Syntax
public static final int CONTROL
Description
The array index for the control background color.


 SystemColor.control

SystemColor.control

Syntax
public static final SystemColor control
Description
The background color for control objects.


 SystemColor.CONTROL_DK_SHADOW

SystemColor.CONTROL_DK_SHADOW

Syntax
public static final int CONTROL_DK_SHADOW
Description
The array index for the control dark shadow color.


 SystemColor.CONTROL_HIGHLIGHT

SystemColor.CONTROL_HIGHLIGHT

Syntax
public static final int CONTROL_HIGHLIGHT
Description
The array index for the control highlight color.


 SystemColor.CONTROL_LT_HIGHLIGHT

SystemColor.CONTROL_LT_HIGHLIGHT

Syntax
public static final int CONTROL_LT_HIGHLIGHT
Description
The array index for the control light highlight color.


 SystemColor.CONTROL_SHADOW

SystemColor.CONTROL_SHADOW

Syntax
public static final int CONTROL_SHADOW
Description
The array index for the control shadow color.


 SystemColor.CONTROL_TEXT

SystemColor.CONTROL_TEXT

Syntax
public static final int CONTROL_TEXT
Description
The array index for the control text color.


 SystemColor.controlDkShadow

SystemColor.controlDkShadow

Syntax
public static final SystemColor controlDkShadow
Description
The dark shadow color for control objects.


 SystemColor.controlHighlight

SystemColor.controlHighlight

Syntax
public static final SystemColor controlHighlight
Description
The regular highlight color for control objects.


 SystemColor.controlLtHighlight

SystemColor.controlLtHighlight

Syntax
public static final SystemColor controlLtHighlight
Description
The light highlight color for control objects.


 SystemColor.controlShadow

SystemColor.controlShadow

Syntax
public static final SystemColor controlShadow
Description
The regular shadow color for control objects.


 SystemColor.controlText

SystemColor.controlText

Syntax
public static final SystemColor controlText
Description
The text color for control objects.


 SystemColor.DESKTOP

SystemColor.DESKTOP

Syntax
public static final int DESKTOP
Description
The array index for the desktop background color.


 SystemColor.desktop

SystemColor.desktop

Syntax
public static final SystemColor desktop
Description
The color of the desktop background.


 SystemColor.INACTIVE_CAPTION

SystemColor.INACTIVE_CAPTION

Syntax
public static final int INACTIVE_CAPTION
Description
The array index for the inactive caption background color.


 SystemColor.INACTIVE_CAPTION_BORDER

SystemColor.INACTIVE_CAPTION_BORDER

Syntax
public static final int INACTIVE_CAPTION_BORDER
Description
The array index for the inactive caption border color.


 SystemColor.INACTIVE_CAPTION_TEXT

SystemColor.INACTIVE_CAPTION_TEXT

Syntax
public static final int INACTIVE_CAPTION_TEXT
Description
The array index for the inactive caption text color.


 SystemColor.inactiveCaption

SystemColor.inactiveCaption

Syntax
public static final SystemColor inactiveCaption
Description
The background color for inactive captions in window borders.


 SystemColor.inactiveCaptionBorder

SystemColor.inactiveCaptionBorder

Syntax
public static final SystemColor inactiveCaptionBorder
Description
The border color for inactive captios in window borders.


 SystemColor.inactiveCaptionText

SystemColor.inactiveCaptionText

Syntax
public static final SystemColor inactiveCaptionText
Description
The text color for inactive captions in window borders.


 SystemColor.INFO

SystemColor.INFO

Syntax
public static final int INFO
Description
The array index for the info background color.


 SystemColor.info

SystemColor.info

Syntax
public static final SystemColor info
Description
The background color for info(help) text.


 SystemColor.INFO_TEXT

SystemColor.INFO_TEXT

Syntax
public static final int INFO_TEXT
Description
The array index for the info text color.


 SystemColor.infoText

SystemColor.infoText

Syntax
public static final SystemColor infoText
Description
The text color for info(help) text.


 SystemColor.MENU

SystemColor.MENU

Syntax
public static final int MENU
Description
The array index for the menu background color.


 SystemColor.menu

SystemColor.menu

Syntax
public static final SystemColor menu
Description
The background color for menus.


 SystemColor.MENU_TEXT

SystemColor.MENU_TEXT

Syntax
public static final int MENU_TEXT
Description
The array index for the menu text color.


 SystemColor.menuText

SystemColor.menuText

Syntax
public static final SystemColor menuText
Description
The text color for menus.


 SystemColor.NUM_COLORS

SystemColor.NUM_COLORS

Syntax
public static final int NUM_COLORS
Description
The number of system colors in the array.


 SystemColor.SCROLLBAR

SystemColor.SCROLLBAR

Syntax
public static final int SCROLLBAR
Description
The array index for the scrollbar background color.


 SystemColor.scrollbar

SystemColor.scrollbar

Syntax
public static final SystemColor scrollbar
Description
The background color for scrollbars.


 SystemColor.TEXT

SystemColor.TEXT

Syntax
public static final int TEXT
Description
The array index for the text background color.


 SystemColor.text

SystemColor.text

Syntax
public static final SystemColor text
Description
The background color for text components.


 SystemColor.TEXT_HIGHLIGHT

SystemColor.TEXT_HIGHLIGHT

Syntax
public static final int TEXT_HIGHLIGHT
Description
The array index for the text highlight color.


 SystemColor.TEXT_HIGHLIGHT_TEXT

SystemColor.TEXT_HIGHLIGHT_TEXT

Syntax
public static final int TEXT_HIGHLIGHT_TEXT
Description
The array index for the text highlight text color.


 SystemColor.TEXT_INACTIVE_TEXT

SystemColor.TEXT_INACTIVE_TEXT

Syntax
public static final int TEXT_INACTIVE_TEXT
Description
The array index for the text inactive text color.


 SystemColor.TEXT_TEXT

SystemColor.TEXT_TEXT

Syntax
public static final int TEXT_TEXT
Description
The array index for the text text color.


 SystemColor.textHighlight

SystemColor.textHighlight

Syntax
public static final SystemColor textHighlight
Description
The background color for highlighted text.


 SystemColor.textHighlightText

SystemColor.textHighlightText

Syntax
public static final SystemColor textHighlightText
Description
The text color for highlighted text.


 SystemColor.textInactiveText

SystemColor.textInactiveText

Syntax
public static final SystemColor textInactiveText
Description
The text color for inactive text.


 SystemColor.textText

SystemColor.textText

Syntax
public static final SystemColor textText
Description
The text color for text components.


 SystemColor.WINDOW

SystemColor.WINDOW

Syntax
public static final int WINDOW
Description
The array index for the window background color.


 SystemColor.window

SystemColor.window

Syntax
public static final SystemColor window
Description
The background color for windows.


 SystemColor.WINDOW_BORDER

SystemColor.WINDOW_BORDER

Syntax
public static final int WINDOW_BORDER
Description
The array index for the window border color.


 SystemColor.WINDOW_TEXT

SystemColor.WINDOW_TEXT

Syntax
public static final int WINDOW_TEXT
Description
The array index for the window text color.


 SystemColor.windowBorder

SystemColor.windowBorder

Syntax
public static final SystemColor windowBorder
Description
The border color for windows.


 SystemColor.windowText

SystemColor.windowText

Syntax
public static final SystemColor windowText
Description
The text color for windows.


 SystemColor.getRGB

SystemColor.getRGB

Syntax
public int getRGB()
Description
Gets the "current" RGB value representing the symbolic color. (Bits 24-31 are 0xff, 16-23 are red, 8-15 are green, 0-7 are blue).

Overrides
getRGB in class Color
See Also
getRGBdefault, getBlue, getGreen, getRed


 SystemColor.toString

SystemColor.toString

Syntax
public String toString()
Description
Returns the String representation of this Color's values.

Overrides
toString in class Color


 Class TextArea

Class java.awt.TextArea

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.TextComponent
                   |
                   +----java.awt.TextArea

public class TextArea
extends TextComponent

A TextArea object is a multi-line region that displays text. It can be set to allow editing or to be read-only.

The following image shows the appearance of a text area:

This text area could be created by the following line of code:

 new TextArea("Hello", 5, 40);


 TextArea Members

TextArea Members

Class Overview | This Package | All Packages

Fields
Name | Description
SCROLLBARS_BOTH | Create and display both vertical and horizontal scrollbars.
SCROLLBARS_HORIZONTAL_ONLY | Create and display horizontal scrollbar only.
SCROLLBARS_NONE | Do not create or display any scrollbars for the text area.
SCROLLBARS_VERTICAL_ONLY | Create and display vertical scrollbar only.

Constructors
Name | Description
TextArea() | Constructs a new text area.
TextArea(int, int) | Constructs a new empty TextArea with the specified number of rows and columns.
TextArea(String) | Constructs a new text area with the specified text.
TextArea(String, int, int) | Constructs a new text area with the specified text, and with the specified number of rows and columns.
TextArea(String, int, int, int) | Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

Methods
Name | Description
addNotify() | Creates the TextArea's peer.
append(String) | Appends the given text to the text area's current text.
appendText(String) | Deprecated.
getColumns() | Gets the number of columns in this text area.
getMinimumSize() | Determines the minimum size of this text area.
getMinimumSize(int, int) | Determines the minimum size of a text area with the specified number of rows and columns.
getPreferredSize() | Determines the preferred size of this text area.
getPreferredSize(int, int) | Determines the preferred size of a text area with the specified number of rows and columns.
getRows() | Gets the number of rows in the text area.
getScrollbarVisibility() | Gets an enumerated value that indicates which scroll bars the text area uses.
insert(String, int) | Inserts the specified text at the specified position in this text area.
insertText(String, int) | Deprecated.
minimumSize() | Deprecated.
minimumSize(int, int) | Deprecated.
paramString() | Returns the parameter string representing the state of this text area.
preferredSize() | Deprecated.
preferredSize(int, int) | Deprecated.
replaceRange(String, int, int) | Replaces text between the indicated start and end positions with the specified replacement text.
replaceText(String, int, int) | Deprecated.
setColumns(int) | Sets the number of columns for this text area.
setRows(int) | Sets the number of rows for this text area.


 TextArea.SCROLLBARS_BOTH

TextArea.SCROLLBARS_BOTH

Syntax
public static final int SCROLLBARS_BOTH
Description
Create and display both vertical and horizontal scrollbars.


 TextArea.SCROLLBARS_HORIZONTAL_ONLY

TextArea.SCROLLBARS_HORIZONTAL_ONLY

Syntax
public static final int SCROLLBARS_HORIZONTAL_ONLY
Description
Create and display horizontal scrollbar only.


 TextArea.SCROLLBARS_NONE

TextArea.SCROLLBARS_NONE

Syntax
public static final int SCROLLBARS_NONE
Description
Do not create or display any scrollbars for the text area.


 TextArea.SCROLLBARS_VERTICAL_ONLY

TextArea.SCROLLBARS_VERTICAL_ONLY

Syntax
public static final int SCROLLBARS_VERTICAL_ONLY
Description
Create and display vertical scrollbar only.


 TextArea.TextArea

TextArea.TextArea

Syntax 1
public TextArea()
Description
Constructs a new text area. This text area is created with both vertical and horizontal scroll bars.

Syntax 2
public TextArea( String text )
Parameters
text
the text to be displayed.
Description
Constructs a new text area with the specified text. This text area is created with both vertical and horizontal scroll bars.

Syntax 3
public TextArea( int rows, int columns )
Parameters
rows
the number of rows
columns
the number of columns
Description
Constructs a new empty TextArea with the specified number of rows and columns.

Syntax 4
public TextArea( String text, int rows, int columns )
Parameters
text
the text to be displayed.
rows
the number of rows.
columns
the number of columns.
Description
Constructs a new text area with the specified text, and with the specified number of rows and columns. This text area is created with both vertical and horizontal scroll bars.

Syntax 5
public TextArea( String text, int rows, int columns, int scrollbars )
Parameters
text
the text to be displayed.
rows
the number of rows.
columns
the number of columns.
scrollbars
a constant that determines what scrollbars are created to view the text area.
Description
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.

The TextArea class defines several constants that can be supplied as values for the scrollbars argument: SCROLLBARS_BOTH, SCROLLBARS_VERTICAL_ONLY, SCROLLBARS_HORIZONTAL_ONLY, and SCROLLBARS_NONE.


 TextArea.addNotify

TextArea.addNotify

Syntax
public void addNotify()
Description
Creates the TextArea's peer. The peer allows us to modify the appearance of the TextArea without changing any of its functionality.

Overrides
addNotify in class Component


 TextArea.append

TextArea.append

Syntax
public synchronized void append( String str )
Parameters
str
the text to append.
Description
Appends the given text to the text area's current text.

See Also
insert


 TextArea.appendText

TextArea.appendText

Syntax
public void appendText( String str )
Description
Note: appendText() is deprecated. As of JDK version 1.1, replaced by append(String).


 TextArea.getColumns

TextArea.getColumns

Syntax
public int getColumns()
Returns
the number of columns in the text area.
Description
Gets the number of columns in this text area.

See Also
setColumns, getRows


 TextArea.getMinimumSize

TextArea.getMinimumSize

Syntax 1
public Dimension getMinimumSize( int rows, int columns )
Parameters
rows
the number of rows.
cols
the number of columns.
Returns
the minimum dimensions required to display the text area with the specified number of rows and columns.
Description
Determines the minimum size of a text area with the specified number of rows and columns.

See Also
getMinimumSize

Syntax 2
public Dimension getMinimumSize()
Returns
the preferred dimensions needed for this text area.
Description
Determines the minimum size of this text area.

Overrides
getMinimumSize in class Component
See Also
getPreferredSize


 TextArea.getPreferredSize

TextArea.getPreferredSize

Syntax 1
public Dimension getPreferredSize( int rows, int columns )
Parameters
rows
the number of rows.
cols
the number of columns.
Returns
the preferred dimensions required to display the text area with the specified number of rows and columns.
Description
Determines the preferred size of a text area with the specified number of rows and columns.

See Also
getPreferredSize

Syntax 2
public Dimension getPreferredSize()
Returns
the preferred dimensions needed for this text area.
Description
Determines the preferred size of this text area.

Overrides
getPreferredSize in class Component
See Also
getPreferredSize


 TextArea.getRows

TextArea.getRows

Syntax
public int getRows()
Returns
the number of rows in the text area.
Description
Gets the number of rows in the text area.

See Also
setRows, getColumns


 TextArea.getScrollbarVisibility

TextArea.getScrollbarVisibility

Syntax
public int getScrollbarVisibility()
Returns
an integer that indicates which scroll bars are used.
Description
Gets an enumerated value that indicates which scroll bars the text area uses.

The TextArea class defines four integer constants that are used to specify which scroll bars are available. TextArea has one constructor that gives the application discretion over scroll bars.

See Also
SCROLLBARS_BOTH, SCROLLBARS_VERTICAL_ONLY, SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE, TextArea


 TextArea.insert

TextArea.insert

Syntax
public synchronized void insert( String str, int pos )
Parameters
str
the text to insert.
pos
the position at which to insert.
Description
Inserts the specified text at the specified position in this text area.

See Also
setText, replaceRange, append


 TextArea.insertText

TextArea.insertText

Syntax
public void insertText( String str, int pos )
Description
Note: insertText() is deprecated. As of JDK version 1.1, replaced by insert(String, int).


 TextArea.minimumSize

TextArea.minimumSize

Syntax 1
public Dimension minimumSize( int rows, int columns )
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize(int, int).

Syntax 2
public Dimension minimumSize()
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Overrides
minimumSize in class Component


 TextArea.paramString

TextArea.paramString

Syntax
protected String paramString()
Returns
the parameter string of this text area.
Description
Returns the parameter string representing the state of this text area. This string is useful for debugging.

Overrides
paramString in class TextComponent


 TextArea.preferredSize

TextArea.preferredSize

Syntax 1
public Dimension preferredSize( int rows, int columns )
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize(int, int).

Syntax 2
public Dimension preferredSize()
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Overrides
preferredSize in class Component


 TextArea.replaceRange

TextArea.replaceRange

Syntax
public synchronized void replaceRange( String str, int start, int end )
Parameters
str
the text to use as the replacement.
start
the start position.
end
the end position.
Description
Replaces text between the indicated start and end positions with the specified replacement text.

See Also
insert


 TextArea.replaceText

TextArea.replaceText

Syntax
public void replaceText( String str, int start, int end )
Description
Note: replaceText() is deprecated. As of JDK version 1.1, replaced by replaceRange(String, int, int).


 TextArea.setColumns

TextArea.setColumns

Syntax
public void setColumns( int columns )
Parameters
columns
the number of columns.
Description
Sets the number of columns for this text area.

Exceptions
IllegalArgumentException if the value supplied for columns is less than zero.
See Also
getColumns, setRows


 TextArea.setRows

TextArea.setRows

Syntax
public void setRows( int rows )
Parameters
rows
the number of rows.
Description
Sets the number of rows for this text area.

Exceptions
IllegalArgumentException if the value supplied for rows is less than zero.
See Also
getRows, setColumns


 Class TextComponent

Class java.awt.TextComponent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.TextComponent

public class TextComponent
extends Component

The TextComponent class is the superclass of any component that allows the editing of some text.

A text component embodies a string of text. The TextComponent class defines a set of methods that determine whether or not this text is editable. If the component is editable, it defines another set of methods that supports a text insertion caret.

In addition, the class defines methods that are used to maintain a current selection from the text. The text selection, a substring of the component's text, is the target of editing operations. It is also referred to as the selected text.


 TextComponent Members

TextComponent Members

Class Overview | This Package | All Packages

Fields
Name | Description
textListener |

Methods
Name | Description
addTextListener(TextListener) | Adds the specified text event listener to recieve text events from this textcomponent.
getCaretPosition() | Gets the position of the text insertion caret for this text component.
getSelectedText() | Gets the selected text from the text that is presented by this text component.
getSelectionEnd() | Gets the end position of the selected text in this text component.
getSelectionStart() | Gets the start position of the selected text in this text component.
getText() | Gets the text that is presented by this text component.
isEditable() | Indicates whether or not this text component is editable.
paramString() | Returns the parameter string representing the state of this text component.
processEvent(AWTEvent) | Processes events on this textcomponent.
processTextEvent(TextEvent) | Processes text events occurring on this text component by dispatching them to any registered TextListener objects.
removeNotify() | Removes the TextComponent's peer.
removeTextListener(TextListener) | Removes the specified text event listener so that it no longer receives text events from this textcomponent
select(int, int) | Selects the text between the specified start and end positions.
selectAll() | Selects all the text in this text component.
setCaretPosition(int) | Sets the position of the text insertion caret for this text component.
setEditable(boolean) | Sets the flag that determines whether or not this text component is editable.
setSelectionEnd(int) | Sets the selection end for this text component to the specified position.
setSelectionStart(int) | Sets the selection start for this text component to the specified position.
setText(String) | Sets the text that is presented by this text component to be the specified text.


 TextComponent.textListener

TextComponent.textListener

Syntax
protected transient TextListener textListener


 TextComponent.addTextListener

TextComponent.addTextListener

Syntax
public synchronized void addTextListener( TextListener l )
Parameters
l
the text event listener
Description
Adds the specified text event listener to recieve text events from this textcomponent.


 TextComponent.getCaretPosition

TextComponent.getCaretPosition

Syntax
public int getCaretPosition()
Returns
the position of the text insertion caret.
Description
Gets the position of the text insertion caret for this text component.


 TextComponent.getSelectedText

TextComponent.getSelectedText

Syntax
public synchronized String getSelectedText()
Returns
the selected text of this text component.
Description
Gets the selected text from the text that is presented by this text component.

See Also
select


 TextComponent.getSelectionEnd

TextComponent.getSelectionEnd

Syntax
public synchronized int getSelectionEnd()
Returns
the end position of the selected text.
Description
Gets the end position of the selected text in this text component.

See Also
setSelectionEnd, getSelectionStart


 TextComponent.getSelectionStart

TextComponent.getSelectionStart

Syntax
public synchronized int getSelectionStart()
Returns
the start position of the selected text.
Description
Gets the start position of the selected text in this text component.

See Also
setSelectionStart, getSelectionEnd


 TextComponent.getText

TextComponent.getText

Syntax
public synchronized String getText()
Description
Gets the text that is presented by this text component.

See Also
setText


 TextComponent.isEditable

TextComponent.isEditable

Syntax
public boolean isEditable()
Returns
true if this text component is editable; false otherwise.
Description
Indicates whether or not this text component is editable.

See Also
setEditable


 TextComponent.paramString

TextComponent.paramString

Syntax
protected String paramString()
Returns
the parameter string of this text component.
Description
Returns the parameter string representing the state of this text component. This string is useful for debugging.

Overrides
paramString in class Component


 TextComponent.processEvent

TextComponent.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event
Description
Processes events on this textcomponent. If the event is a TextEvent, it invokes the processTextEvent method, else it invokes its superclass's processEvent.

Overrides
processEvent in class Component


 TextComponent.processTextEvent

TextComponent.processTextEvent

Syntax
protected void processTextEvent( TextEvent e )
Parameters
e
the text event
Description
Processes text events occurring on this text component by dispatching them to any registered TextListener objects. NOTE: This method will not be called unless text events are enabled for this component; this happens when one of the following occurs: a) A TextListener object is registered via addTextListener() b) Text events are enabled via enableEvents()

See Also
enableEvents


 TextComponent.removeNotify

TextComponent.removeNotify

Syntax
public void removeNotify()
Description
Removes the TextComponent's peer. The peer allows us to modify the appearance of the TextComponent without changing its functionality.

Overrides
removeNotify in class Component


 TextComponent.removeTextListener

TextComponent.removeTextListener

Syntax
public void removeTextListener( TextListener l )
Description
Removes the specified text event listener so that it no longer receives text events from this textcomponent


 TextComponent.select

TextComponent.select

Syntax
public synchronized void select( int selectionStart, int selectionEnd )
Parameters
selectionStart
the start position of the text to select.
selectionEnd
the end position of the text to select.
Description
Selects the text between the specified start and end positions.

This method sets the start and end positions of the selected text, enforcing the restriction that the end position must be greater than or equal to the start position. The start position must be greater than zero, and the end position must be less that or equal to the length of the text component's text. If the caller supplies values that are inconsistent or out of bounds, the method enforces these constraints silently, and without failure.

See Also
setSelectionStart, setSelectionEnd, selectAll


 TextComponent.selectAll

TextComponent.selectAll

Syntax
public synchronized void selectAll()
Description
Selects all the text in this text component.

See Also
TextComponent@select


 TextComponent.setCaretPosition

TextComponent.setCaretPosition

Syntax
public void setCaretPosition( int position )
Parameters
position
the position of the text insertion caret.
Description
Sets the position of the text insertion caret for this text component.

Exceptions
IllegalArgumentException if the value supplied for position is less than zero.


 TextComponent.setEditable

TextComponent.setEditable

Syntax
public synchronized void setEditable( boolean b )
Parameters
t
a flag indicating whether this text component should be user editable.
Description
Sets the flag that determines whether or not this text component is editable.

If the flag is set to true, this text component becomes user editable. If the flag is set to false, the user cannot change the text of this text component.

See Also
isEditable


 TextComponent.setSelectionEnd

TextComponent.setSelectionEnd

Syntax
public synchronized void setSelectionEnd( int selectionEnd )
Parameters
selectionEnd
the end position of the selected text.
Description
Sets the selection end for this text component to the specified position. The new end point is constrained to be at or after the current selection start. It also cannot be set beyond the end of the component's text. If the caller supplies a value for selectionEnd that is out of bounds, the method enforces these constraints silently, and without failure.

See Also
getSelectionEnd, setSelectionStart


 TextComponent.setSelectionStart

TextComponent.setSelectionStart

Syntax
public synchronized void setSelectionStart( int selectionStart )
Parameters
selectionStart
the start position of the selected text.
Description
Sets the selection start for this text component to the specified position. The new start point is constrained to be at or before the current selection end. It also cannot be set to less than zero, the beginning of the component's text. If the caller supplies a value for selectionStart that is out of bounds, the method enforces these constraints silently, and without failure.

See Also
getSelectionStart, setSelectionEnd


 TextComponent.setText

TextComponent.setText

Syntax
public synchronized void setText( String t )
Parameters
t
the new text.
Description
Sets the text that is presented by this text component to be the specified text.

See Also
getText


 Class TextField

Class java.awt.TextField

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.TextComponent
                   |
                   +----java.awt.TextField

public class TextField
extends TextComponent

A TextField object is a text component that allows for the editing of a single line of text.

For example, the following image depicts a frame with four text fields of varying widths. Two of these text fields display the predefined text "Hello".

Here is the code that produces these four text fields:

 TextField tf1, tf2, tf3, tf4;
 // a blank text field
 tf1 = new TextField();
 // blank field of 20 columns
 tf2 = new TextField("", 20);
 // predefined text displayed
 tf3 = new TextField("Hello!");
 // predefined text in 30 columns
 tf4 = new TextField("Hello", 30);

Every time the user types a key in the text field, AWT sends two action events to the text field. The first one represents the key press and the second one, the key release. Each action event embodies the state of the system at the time that some action occurred. The properties of an action event indicate which key was pressed, what modifier keys were also pressed, and the time at which the event occurred.

Since the event is an instance of ActionEvent, the TextField class's processEvent method examines the event and passes it along to processActionEvent. The latter method redirects the event to any ActionListener objects that have registered an interest in action events generated by this text field.

See Also:
ActionEvent, processEvent, processActionEvent


 TextField Members

TextField Members

Class Overview | This Package | All Packages

Constructors
Name | Description
TextField() | Constructs a new text field.
TextField(int) | Constructs a new empty TextField with the specified number of columns.
TextField(String) | Constructs a new text field initialized with the specified text.
TextField(String, int) | Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of characters.

Methods
Name | Description
addActionListener(ActionListener) | Adds the specified action listener to recieve action events from this text field.
addNotify() | Creates the TextField's peer.
echoCharIsSet() | Indicates whether or not this text field has a character set for echoing.
getColumns() | Gets the number of columns in this text field.
getEchoChar() | Gets the character that is to be used for echoing.
getMinimumSize() | Gets the minumum dimensions for this text field.
getMinimumSize(int) | Gets the minumum dimensions for a text field with the specified number of columns.
getPreferredSize() | Gets the preferred size of this text field.
getPreferredSize(int) | Gets the preferred size of this text field with the specified number of columns.
minimumSize() | Deprecated.
minimumSize(int) | Deprecated.
paramString() | Returns the parameter string representing the state of this text field.
preferredSize() | Deprecated.
preferredSize(int) | Deprecated.
processActionEvent(ActionEvent) | Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.
processEvent(AWTEvent) | Processes events on this text field.
removeActionListener(ActionListener) | Removes the specified action listener so that it no longer receives action events from this text field.
setColumns(int) | Sets the number of columns in this text field.
setEchoChar(char) | Sets the echo character for this text field.
setEchoCharacter(char) | Deprecated.


 TextField.TextField

TextField.TextField

Syntax 1
public TextField()
Description
Constructs a new text field.

Syntax 2
public TextField( String text )
Parameters
text
the text to be displayed.
Description
Constructs a new text field initialized with the specified text.

Syntax 3
public TextField( int columns )
Parameters
columns
the number of columns
Description
Constructs a new empty TextField with the specified number of columns.

Syntax 4
public TextField( String text, int columns )
Parameters
text
the text to be displayed.
columns
the number of characters.
Description
Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of characters.


 TextField.addActionListener

TextField.addActionListener

Syntax
public synchronized void addActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Adds the specified action listener to recieve action events from this text field.

See Also
ActionListener, removeActionListener


 TextField.addNotify

TextField.addNotify

Syntax
public void addNotify()
Description
Creates the TextField's peer. The peer allows us to modify the appearance of the TextField without changing its functionality.

Overrides
addNotify in class Component


 TextField.echoCharIsSet

TextField.echoCharIsSet

Syntax
public boolean echoCharIsSet()
Returns
true if this text field has a character set for echoing; false otherwise.
Description
Indicates whether or not this text field has a character set for echoing.

An echo character is useful for text fields where user input should not be echoed to the screen, as in the case of a text field for entering a password.

See Also
setEchoChar, getEchoChar


 TextField.getColumns

TextField.getColumns

Syntax
public int getColumns()
Returns
the number of columns.
Description
Gets the number of columns in this text field.

See Also
setColumns


 TextField.getEchoChar

TextField.getEchoChar

Syntax
public char getEchoChar()
Returns
the echo character for this text field.
Description
Gets the character that is to be used for echoing.

An echo character is useful for text fields where user input should not be echoed to the screen, as in the case of a text field for entering a password.

See Also
echoCharIsSet, setEchoChar


 TextField.getMinimumSize

TextField.getMinimumSize

Syntax 1
public Dimension getMinimumSize( int columns )
Parameters
columns
the number of columns in this text field.
Description
Gets the minumum dimensions for a text field with the specified number of columns.

Syntax 2
public Dimension getMinimumSize()
Returns
the minimum dimensions for displaying this text field.
Description
Gets the minumum dimensions for this text field.

Overrides
getMinimumSize in class Component


 TextField.getPreferredSize

TextField.getPreferredSize

Syntax 1
public Dimension getPreferredSize( int columns )
Parameters
columns
the number of columns in this text field.
Returns
the preferred dimensions for displaying this text field.
Description
Gets the preferred size of this text field with the specified number of columns.

Syntax 2
public Dimension getPreferredSize()
Returns
the preferred dimensions for displaying this text field.
Description
Gets the preferred size of this text field.

Overrides
getPreferredSize in class Component


 TextField.minimumSize

TextField.minimumSize

Syntax 1
public Dimension minimumSize( int columns )
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).

Syntax 2
public Dimension minimumSize()
Description
Note: minimumSize() is deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Overrides
minimumSize in class Component


 TextField.paramString

TextField.paramString

Syntax
protected String paramString()
Returns
the parameter string of this text field.
Description
Returns the parameter string representing the state of this text field. This string is useful for debugging.

Overrides
paramString in class TextComponent


 TextField.preferredSize

TextField.preferredSize

Syntax 1
public Dimension preferredSize( int columns )
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).

Syntax 2
public Dimension preferredSize()
Description
Note: preferredSize() is deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Overrides
preferredSize in class Component


 TextField.processActionEvent

TextField.processActionEvent

Syntax
protected void processActionEvent( ActionEvent e )
Parameters
e
the action event.
Description
Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.

This method is not called unless action events are enabled for this component. Action events are enabled when one of the following occurs:

  • An ActionListener object is registered via addActionListener.
  • Action events are enabled via enableEvents.

See Also
ActionListener, addActionListener, enableEvents


 TextField.processEvent

TextField.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event.
Description
Processes events on this text field. If the event is an instance of ActionEvent, it invokes the processActionEvent method. Otherwise, it invokes processEvent on the superclass.

Overrides
processEvent in class TextComponent
See Also
ActionEvent, processActionEvent


 TextField.removeActionListener

TextField.removeActionListener

Syntax
public synchronized void removeActionListener( ActionListener l )
Parameters
l
the action listener.
Description
Removes the specified action listener so that it no longer receives action events from this text field.

See Also
ActionListener, addActionListener


 TextField.setColumns

TextField.setColumns

Syntax
public void setColumns( int columns )
Parameters
columns
the number of columns.
Description
Sets the number of columns in this text field.

Exceptions
IllegalArgumentException if the value supplied for columns is less than zero.
See Also
getColumns


 TextField.setEchoChar

TextField.setEchoChar

Syntax
public void setEchoChar( char c )
Parameters
c
the echo character for this text field.
Description
Sets the echo character for this text field.

An echo character is useful for text fields where user input should not be echoed to the screen, as in the case of a text field for entering a password.

See Also
echoCharIsSet, getEchoChar


 TextField.setEchoCharacter

TextField.setEchoCharacter

Syntax
public void setEchoCharacter( char c )
Description
Note: setEchoCharacter() is deprecated. As of JDK version 1.1, replaced by setEchoChar(char).


 Class Toolkit

Class java.awt.Toolkit

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Toolkit

public abstract class Toolkit
extends Object

This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of Toolkit are used to bind the various components to particular native toolkit implementations.

Most applications should not call any of the methods in this class directly. The methods defined by Toolkit are the "glue" that joins the platform-independent classes in the java.awt package with their counterparts in java.awt.peer. Some methods defined by Toolkit query the native operating system directly.


 Toolkit Members

Toolkit Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Toolkit() |

Methods
Name | Description
beep() | Emits an audio beep.
checkImage(Image, int, int, ImageObserver) | Indicates the construction status of a specified image that is being prepared for display.
createButton(Button) | Creates this toolkit's implementation of Button using the specified peer interface.
createCanvas(Canvas) | Creates this toolkit's implementation of Canvas using the specified peer interface.
createCheckbox(Checkbox) | Creates this toolkit's implementation of Checkbox using the specified peer interface.
createCheckboxMenuItem(CheckboxMenuItem) | Creates this toolkit's implementation of CheckboxMenuItem using the specified peer interface.
createChoice(Choice) | Creates this toolkit's implementation of Choice using the specified peer interface.
createComponent(Component) | Creates a peer for a component or container.
createDialog(Dialog) | Creates this toolkit's implementation of Dialog using the specified peer interface.
createFileDialog(FileDialog) | Creates this toolkit's implementation of FileDialog using the specified peer interface.
createFrame(Frame) | Creates this toolkit's implementation of Frame using the specified peer interface.
createImage(byte[]) | Creates an image which decodes the image stored in the specified byte array.
createImage(byte[], int, int) | Creates an image which decodes the image stored in the specified byte array, and at the specified offset and length.
createImage(ImageProducer) | Creates an image with the specified image producer.
createLabel(Label) | Creates this toolkit's implementation of Label using the specified peer interface.
createList(List) | Creates this toolkit's implementation of List using the specified peer interface.
createMenu(Menu) | Creates this toolkit's implementation of Menu using the specified peer interface.
createMenuBar(MenuBar) | Creates this toolkit's implementation of MenuBar using the specified peer interface.
createMenuItem(MenuItem) | Creates this toolkit's implementation of MenuItem using the specified peer interface.
createPanel(Panel) | Creates this toolkit's implementation of Panel using the specified peer interface.
createPopupMenu(PopupMenu) | Creates this toolkit's implementation of PopupMenu using the specified peer interface.
createScrollbar(Scrollbar) | Creates this toolkit's implementation of Scrollbar using the specified peer interface.
createScrollPane(ScrollPane) | Creates this toolkit's implementation of ScrollPane using the specified peer interface.
createTextArea(TextArea) | Creates this toolkit's implementation of TextArea using the specified peer interface.
createTextField(TextField) | Creates this toolkit's implementation of TextField using the specified peer interface.
createWindow(Window) | Creates this toolkit's implementation of Window using the specified peer interface.
getColorModel() | Determines the color model of this toolkit's screen.
getDefaultToolkit() | Gets the default toolkit.
getFontList() Returns the names of the available fonts in this toolkit.

For 1.1, the following font names are deprecated (the replacement name follows):

  • TimesRoman (use Serif)
  • Helvetica (use SansSerif)
  • Courier (use Monospaced)

The ZapfDingbats font is also deprecated in 1.1, but only as a separate fontname.

getFontMetrics(Font) | Gets the screen metrics of the font.
getFontPeer(String, int) | Creates this toolkit's implementation of Font using the specified peer interface.
getImage(String) | Returns an image which gets pixel data from the specified file.
getImage(URL) | Returns an image which gets pixel data from the specified URL.
getMenuShortcutKeyMask() | Determines which modifier key is the appropriate accelerator key for menu shortcuts.
getNativeContainer(Component) | Give native peers the ability to query the native container given a native component (eg the direct parent may be lightweight).
getPrintJob(Frame, String, Properties) | Gets a PrintJob object which is the result of initiating a print operation on the toolkit's platform.
getProperty(String, String) | Gets a property with the specified key and default.
getScreenResolution() | Returns the screen resolution in dots-per-inch.
getScreenSize() | Gets the size of the screen.
getSystemClipboard() | Gets an instance of the system clipboard which interfaces with clipboard facilities provided by the native platform.
getSystemEventQueue() | Get the application's or applet's EventQueue instance.
getSystemEventQueueImpl()
loadSystemColors(int[]) | Fills in the integer array that is supplied as an argument with the current system color values.
prepareImage(Image, int, int, ImageObserver) | Prepares an image for rendering.
sync() | Synchronizes this toolkit's graphics state.


 Toolkit.Toolkit

Toolkit.Toolkit

Syntax
public Toolkit()


 Toolkit.beep

Toolkit.beep

Syntax
public abstract void beep()
Description
Emits an audio beep.


 Toolkit.checkImage

Toolkit.checkImage

Syntax
public abstract int checkImage( Image image, int width, int height, ImageObserver observer )
Parameters
image
the image whose status is being checked.
width
the width of the scaled version whose status is being checked, or -1.
height
the height of the scaled version whose status is being checked, or -1.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
the bitwise inclusive OR of the ImageObserver flags for the image data that is currently available.
Description
Indicates the construction status of a specified image that is being prepared for display.

If the values of the width and height arguments are both -1, this method returns the construction status of a screen representation of the specified image in this toolkit. Otherwise, this method returns the construction status of a scaled representation of the image at the specified width and height.

This method does not cause the image to begin loading. An application must call prepareImage to force the loading of an image.

This method is called by the component's checkImage methods.

Information on the flags returned by this method can be found with the definition of the ImageObserver interface.

See Also
prepareImage, checkImage, checkImage, ImageObserver


 Toolkit.createButton

Toolkit.createButton

Syntax
protected abstract ButtonPeer createButton( Button target )
Parameters
target
the button to be implemented.
Returns
this toolkit's implementation of Button.
Description
Creates this toolkit's implementation of Button using the specified peer interface.

See Also
Button, ButtonPeer


 Toolkit.createCanvas

Toolkit.createCanvas

Syntax
protected abstract CanvasPeer createCanvas( Canvas target )
Parameters
target
the canvas to be implemented.
Returns
this toolkit's implementation of Canvas.
Description
Creates this toolkit's implementation of Canvas using the specified peer interface.

See Also
Canvas, CanvasPeer


 Toolkit.createCheckbox

Toolkit.createCheckbox

Syntax
protected abstract CheckboxPeer createCheckbox( Checkbox target )
Parameters
target
the check box to be implemented.
Returns
this toolkit's implementation of Checkbox.
Description
Creates this toolkit's implementation of Checkbox using the specified peer interface.

See Also
Checkbox, CheckboxPeer


 Toolkit.createCheckboxMenuItem

Toolkit.createCheckboxMenuItem

Syntax
protected abstract CheckboxMenuItemPeer createCheckboxMenuItem( CheckboxMenuItem target )
Parameters
target
the checkbox menu item to be implemented.
Returns
this toolkit's implementation of CheckboxMenuItem.
Description
Creates this toolkit's implementation of CheckboxMenuItem using the specified peer interface.

See Also
CheckboxMenuItem, CheckboxMenuItemPeer


 Toolkit.createChoice

Toolkit.createChoice

Syntax
protected abstract ChoicePeer createChoice( Choice target )
Parameters
target
the choice to be implemented.
Returns
this toolkit's implementation of Choice.
Description
Creates this toolkit's implementation of Choice using the specified peer interface.

See Also
Choice, ChoicePeer


 Toolkit.createComponent

Toolkit.createComponent

Syntax
protected LightweightPeer createComponent( Component target )
Parameters
target
The Component to be created.
Description
Creates a peer for a component or container. This peer is windowless and allows the Component and Container classes to be extended directly to create windowless components that are defined entirely in java.


 Toolkit.createDialog

Toolkit.createDialog

Syntax
protected abstract DialogPeer createDialog( Dialog target )
Parameters
target
the dialog to be implemented.
Returns
this toolkit's implementation of Dialog.
Description
Creates this toolkit's implementation of Dialog using the specified peer interface.

See Also
Dialog, DialogPeer


 Toolkit.createFileDialog

Toolkit.createFileDialog

Syntax
protected abstract FileDialogPeer createFileDialog( FileDialog target )
Parameters
target
the file dialog to be implemented.
Returns
this toolkit's implementation of FileDialog.
Description
Creates this toolkit's implementation of FileDialog using the specified peer interface.

See Also
FileDialog, FileDialogPeer


 Toolkit.createFrame

Toolkit.createFrame

Syntax
protected abstract FramePeer createFrame( Frame target )
Parameters
target
the frame to be implemented.
Returns
this toolkit's implementation of Frame.
Description
Creates this toolkit's implementation of Frame using the specified peer interface.

See Also
Frame, FramePeer


 Toolkit.createImage

Toolkit.createImage

Syntax 1
public abstract Image createImage( ImageProducer producer )
Parameters
producer
the image producer to be used.
Returns
an image with the specified image producer.
Description
Creates an image with the specified image producer.

See Also
Image, ImageProducer, createImage

Syntax 2
public Image createImage( byte imagedata[] )
Parameters
imagedata
an array of bytes, representing image data in a supported image format.
Returns
an image.
Description
Creates an image which decodes the image stored in the specified byte array.

The data must be in some image format, such as GIF or JPEG, that is supported by this toolkit.

Syntax 3
public abstract Image createImage( byte imagedata[], int imageoffset, int imagelength )
Parameters
imagedata
an array of bytes, representing image data in a supported image format.
imageoffset
the offset of the beginning of the data in the array.
imagelength
the length of the data in the array.
Returns
an image.
Description
Creates an image which decodes the image stored in the specified byte array, and at the specified offset and length. The data must be in some image format, such as GIF or JPEG, that is supported by this toolkit.


 Toolkit.createLabel

Toolkit.createLabel

Syntax
protected abstract LabelPeer createLabel( Label target )
Parameters
target
the label to be implemented.
Returns
this toolkit's implementation of Label.
Description
Creates this toolkit's implementation of Label using the specified peer interface.

See Also
Label, LabelPeer


 Toolkit.createList

Toolkit.createList

Syntax
protected abstract ListPeer createList( List target )
Parameters
target
the list to be implemented.
Returns
this toolkit's implementation of List.
Description
Creates this toolkit's implementation of List using the specified peer interface.

See Also
List, ListPeer


 Toolkit.createMenu

Toolkit.createMenu

Syntax
protected abstract MenuPeer createMenu( Menu target )
Parameters
target
the menu to be implemented.
Returns
this toolkit's implementation of Menu.
Description
Creates this toolkit's implementation of Menu using the specified peer interface.

See Also
Menu, MenuPeer


 Toolkit.createMenuBar

Toolkit.createMenuBar

Syntax
protected abstract MenuBarPeer createMenuBar( MenuBar target )
Parameters
target
the menu bar to be implemented.
Returns
this toolkit's implementation of MenuBar.
Description
Creates this toolkit's implementation of MenuBar using the specified peer interface.

See Also
MenuBar, MenuBarPeer


 Toolkit.createMenuItem

Toolkit.createMenuItem

Syntax
protected abstract MenuItemPeer createMenuItem( MenuItem target )
Parameters
target
the menu item to be implemented.
Returns
this toolkit's implementation of MenuItem.
Description
Creates this toolkit's implementation of MenuItem using the specified peer interface.

See Also
MenuItem, MenuItemPeer


 Toolkit.createPanel

Toolkit.createPanel

Syntax
protected abstract PanelPeer createPanel( Panel target )
Parameters
target
the panel to be implemented.
Returns
this toolkit's implementation of Panel.
Description
Creates this toolkit's implementation of Panel using the specified peer interface.

See Also
Panel, PanelPeer


 Toolkit.createPopupMenu

Toolkit.createPopupMenu

Syntax
protected abstract PopupMenuPeer createPopupMenu( PopupMenu target )
Parameters
target
the popup menu to be implemented.
Returns
this toolkit's implementation of PopupMenu.
Description
Creates this toolkit's implementation of PopupMenu using the specified peer interface.

See Also
PopupMenu, PopupMenuPeer


 Toolkit.createScrollbar

Toolkit.createScrollbar

Syntax
protected abstract ScrollbarPeer createScrollbar( Scrollbar target )
Parameters
target
the scroll bar to be implemented.
Returns
this toolkit's implementation of Scrollbar.
Description
Creates this toolkit's implementation of Scrollbar using the specified peer interface.

See Also
Scrollbar, ScrollbarPeer


 Toolkit.createScrollPane

Toolkit.createScrollPane

Syntax
protected abstract ScrollPanePeer createScrollPane( ScrollPane target )
Parameters
target
the scroll pane to be implemented.
Returns
this toolkit's implementation of ScrollPane.
Description
Creates this toolkit's implementation of ScrollPane using the specified peer interface.

See Also
ScrollPane, ScrollPanePeer


 Toolkit.createTextArea

Toolkit.createTextArea

Syntax
protected abstract TextAreaPeer createTextArea( TextArea target )
Parameters
target
the text area to be implemented.
Returns
this toolkit's implementation of TextArea.
Description
Creates this toolkit's implementation of TextArea using the specified peer interface.

See Also
TextArea, TextAreaPeer


 Toolkit.createTextField

Toolkit.createTextField

Syntax
protected abstract TextFieldPeer createTextField( TextField target )
Parameters
target
the text field to be implemented.
Returns
this toolkit's implementation of TextField.
Description
Creates this toolkit's implementation of TextField using the specified peer interface.

See Also
TextField, TextFieldPeer


 Toolkit.createWindow

Toolkit.createWindow

Syntax
protected abstract WindowPeer createWindow( Window target )
Parameters
target
the window to be implemented.
Returns
this toolkit's implementation of Window.
Description
Creates this toolkit's implementation of Window using the specified peer interface.

See Also
Window, WindowPeer


 Toolkit.getColorModel

Toolkit.getColorModel

Syntax
public abstract ColorModel getColorModel()
Returns
the color model of this toolkit's screen.
Description
Determines the color model of this toolkit's screen.

ColorModel is an abstract class that encapsulates the ability to translate between the pixel values of an image and its red, green, blue, and alpha components.

This toolkit method is called by the getColorModel method of the Component class.

See Also
ColorModel, getColorModel


 Toolkit.getDefaultToolkit

Toolkit.getDefaultToolkit

Syntax
public static synchronized Toolkit getDefaultToolkit()
Returns
the default toolkit.
Description
Gets the default toolkit.

If there is a system property named "awt.toolkit", that property is treated as the name of a class that is a subclass of Toolkit.

If the system property does not exist, then the default toolkit used is the class named "sun.awt.motif.MToolkit", which is a motif implementation of the Abstract Window Toolkit.

Exceptions
AWTError if a toolkit could not be found, or if one could not be accessed or instantiated.


 Toolkit.getFontList

Toolkit.getFontList

Syntax
public abstract String[] getFontList()
Returns
the names of the available fonts in this toolkit.
Description
Returns the names of the available fonts in this toolkit.

For 1.1, the following font names are deprecated (the replacement name follows):

  • TimesRoman (use Serif)
  • Helvetica (use SansSerif)
  • Courier (use Monospaced)

The ZapfDingbats font is also deprecated in 1.1, but only as a separate fontname. Unicode defines the ZapfDingbat characters starting at ?, and as of 1.1 Java supports those characters.


 Toolkit.getFontMetrics

Toolkit.getFontMetrics

Syntax
public abstract FontMetrics getFontMetrics( Font font )
Parameters
font
a font.
Returns
the screen metrics of the specified font in this toolkit.
Description
Gets the screen metrics of the font.


 Toolkit.getFontPeer

Toolkit.getFontPeer

Syntax
protected abstract FontPeer getFontPeer( String name, int style )
Parameters
target
the font to be implemented.
Returns
this toolkit's implementation of Font.
Description
Creates this toolkit's implementation of Font using the specified peer interface.

See Also
Font, FontPeer


 Toolkit.getImage

Toolkit.getImage

Syntax 1
public abstract Image getImage( String filename )
Parameters
filename
the name of a file containing pixel data in a recognized file format.
Returns
an image which gets its pixel data from the specified file.
Description
Returns an image which gets pixel data from the specified file.

Syntax 2
public abstract Image getImage( URL url )
Parameters
url
the URL to use in fetching the pixel data.
Returns
an image which gets its pixel data from the specified URL.
Description
Returns an image which gets pixel data from the specified URL.


 Toolkit.getMenuShortcutKeyMask

Toolkit.getMenuShortcutKeyMask

Syntax
public int getMenuShortcutKeyMask()
Returns
the modifier mask on the Event class that is used for menu shortcuts on this toolkit.
Description
Determines which modifier key is the appropriate accelerator key for menu shortcuts.

Menu shortcuts, which are embodied in the MenuShortcut class, are handled by the MenuBar class.

By default, this method returns Event.CTRL_MASK. Toolkit implementations should override this method if the Control key isn't the correct key for accelerators.

See Also
MenuBar, MenuShortcut


 Toolkit.getNativeContainer

Toolkit.getNativeContainer

Syntax
protected static Container getNativeContainer( Component c )
Description
Give native peers the ability to query the native container given a native component (eg the direct parent may be lightweight).


 Toolkit.getPrintJob

Toolkit.getPrintJob

Syntax
public abstract PrintJob getPrintJob( Frame frame, String jobtitle, Properties props )
Returns
a PrintJob object, or null if the user cancelled the print job.
Description
Gets a PrintJob object which is the result of initiating a print operation on the toolkit's platform.

See Also
PrintJob


 Toolkit.getProperty

Toolkit.getProperty

Syntax
public static String getProperty( String key, String defaultValue )
Description
Gets a property with the specified key and default. This method returns defaultValue if the property is not found.


 Toolkit.getScreenResolution

Toolkit.getScreenResolution

Syntax
public abstract int getScreenResolution()
Returns
this toolkit's screen resolution, in dots-per-inch.
Description
Returns the screen resolution in dots-per-inch.


 Toolkit.getScreenSize

Toolkit.getScreenSize

Syntax
public abstract Dimension getScreenSize()
Returns
the size of this toolkit's screen, in pixels.
Description
Gets the size of the screen.


 Toolkit.getSystemClipboard

Toolkit.getSystemClipboard

Syntax
public abstract Clipboard getSystemClipboard()
Returns
an instance of the system clipboard.
Description
Gets an instance of the system clipboard which interfaces with clipboard facilities provided by the native platform.

This clipboard enables data transfer between Java programs and native applications which use native clipboard facilities.

See Also
Clipboard


 Toolkit.getSystemEventQueue

Toolkit.getSystemEventQueue

Syntax
public final EventQueue getSystemEventQueue()
Description
Get the application's or applet's EventQueue instance. Depending on the Toolkit implementation, different EventQueues may be returned for different applets. Applets should therefore not assume that the EventQueue instance returned by this method will be shared by other applets or the system.


 Toolkit.getSystemEventQueueImpl

Toolkit.getSystemEventQueueImpl

Syntax
protected abstract EventQueue getSystemEventQueueImpl()


 Toolkit.loadSystemColors

Toolkit.loadSystemColors

Syntax
protected void loadSystemColors( int systemColors[] )
Parameters
an
integer array.
Description
Fills in the integer array that is supplied as an argument with the current system color values.


 Toolkit.prepareImage

Toolkit.prepareImage

Syntax
public abstract boolean prepareImage( Image image, int width, int height, ImageObserver observer )
Parameters
image
the image for which to prepare a screen representation.
width
the width of the desired screen representation, or -1.
height
the height of the desired screen representation, or -1.
observer
the ImageObserver object to be notified as the image is being prepared.
Returns
true if the image has already been fully prepared; false otherwise.
Description
Prepares an image for rendering.

If the values of the width and height arguments are both -1, this method prepares the image for rendering on the default screen; otherwise, this method prepares an image for rendering on the default screen at the specified width and height.

The image data is downloaded asynchronously in another thread, and an appropriately scaled screen representation of the image is generated.

This method is called by components prepareImage methods.

Information on the flags returned by this method can be found with the definition of the ImageObserver interface.

See Also
prepareImage, prepareImage, ImageObserver


 Toolkit.sync

Toolkit.sync

Syntax
public abstract void sync()
Description
Synchronizes this toolkit's graphics state. Some window systems may do buffering of graphics events.

This method ensures that the display is up-to-date. It is useful for animation.


 Class Window

Class java.awt.Window

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.Component
           |
           +----java.awt.Container
                   |
                   +----java.awt.Window

public class Window
extends Container

A Window object is a top-level window with no borders and no menubar. It could be used to implement a pop-up menu. The default layout for a window is BorderLayout. A Window object blocks input to other application windows when it is shown.

Windows are capable of generating the following window events: WindowOpened, WindowClosed.

See Also:
WindowEvent, addWindowListener, BorderLayout


 Window Members

Window Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Window(Frame) | Constructs a new invisible window.

Methods
Name | Description
addNotify() | Creates the Window's peer.
addWindowListener(WindowListener) | Adds the specified window listener to receive window events from this window.
dispose() | Disposes of this window.
getFocusOwner() | Returns the child component of this Window which has focus if and only if this Window is active.
getLocale() | Gets the Locale object that is associated with this window, if the locale has been set.
getToolkit() | Returns the toolkit of this frame.
getWarningString() | Gets the warning string that is displayed with this window.
isShowing() | Checks if this Window is showing on screen.
pack() | Causes subcomponents of this window to be laid out at their preferred size.
postEvent(Event) | Deprecated.
processEvent(AWTEvent) | Processes events on this window.
processWindowEvent(WindowEvent) | Processes window events occurring on this window by dispatching them to any registered WindowListener objects.
removeWindowListener(WindowListener) | Removes the specified window listener so that it no longer receives window events from this window.
show() | Shows this window, and brings it to the front.
toBack() | Sends this window to the back.
toFront() | Brings this window to the front.


 Window.Window

Window.Window

Syntax
public Window( Frame parent )
Parameters
parent
the main application frame.
Description
Constructs a new invisible window.

The window is not initially visible. Call the show method to cause the window to become visible.

See Also
show, setSize


 Window.addNotify

Window.addNotify

Syntax
public void addNotify()
Description
Creates the Window's peer. The peer allows us to modify the appearance of the Window without changing its functionality.

Overrides
addNotify in class Container


 Window.addWindowListener

Window.addWindowListener

Syntax
public synchronized void addWindowListener( WindowListener l )
Parameters
l
the window listener
Description
Adds the specified window listener to receive window events from this window.


 Window.dispose

Window.dispose

Syntax
public void dispose()
Description
Disposes of this window. This method must be called to release the resources that are used for the window.


 Window.getFocusOwner

Window.getFocusOwner

Syntax
public Component getFocusOwner()
Returns
the component with focus, or null if no children have focus assigned to them.
Description
Returns the child component of this Window which has focus if and only if this Window is active.


 Window.getLocale

Window.getLocale

Syntax
public Locale getLocale()
Returns
the locale that is set for this window.
Description
Gets the Locale object that is associated with this window, if the locale has been set. If no locale has been set, then the default locale is returned.

Overrides
getLocale in class Component
See Also
Locale


 Window.getToolkit

Window.getToolkit

Syntax
public Toolkit getToolkit()
Returns
the toolkit of this window.
Description
Returns the toolkit of this frame.

Overrides
getToolkit in class Component
See Also
Toolkit, getDefaultToolkit, getToolkit


 Window.getWarningString

Window.getWarningString

Syntax
public final String getWarningString()
Returns
the warning string for this window.
Description
Gets the warning string that is displayed with this window. If this window is insecure, the warning string is displayed somewhere in the visible area of the window. A window is insecure if there is a security manager, and the security manager's checkTopLevelWindow method returns false when this window is passed to it as an argument.

If the window is secure, then getWarningString returns null. If the window is insecure, this methods checks for the system property awt.appletWarning and returns the string value of that property.

See Also
checkTopLevelWindow


 Window.isShowing

Window.isShowing

Syntax
public boolean isShowing()
Description
Checks if this Window is showing on screen.

Overrides
isShowing in class Component
See Also
setVisible


 Window.pack

Window.pack

Syntax
public void pack()
Description
Causes subcomponents of this window to be laid out at their preferred size.


 Window.postEvent

Window.postEvent

Syntax
public boolean postEvent( Event e )
Description
Note: postEvent() is deprecated. As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).

Overrides
postEvent in class Component


 Window.processEvent

Window.processEvent

Syntax
protected void processEvent( AWTEvent e )
Parameters
e
the event
Description
Processes events on this window. If the event is an WindowEvent, it invokes the processWindowEvent method, else it invokes its superclass's processEvent.

Overrides
processEvent in class Container


 Window.processWindowEvent

Window.processWindowEvent

Syntax
protected void processWindowEvent( WindowEvent e )
Parameters
e
the window event
Description
Processes window events occurring on this window by dispatching them to any registered WindowListener objects. NOTE: This method will not be called unless window events are enabled for this component; this happens when one of the following occurs: a) A WindowListener object is registered via addWindowListener() b) Window events are enabled via enableEvents()

See Also
enableEvents


 Window.removeWindowListener

Window.removeWindowListener

Syntax
public synchronized void removeWindowListener( WindowListener l )
Parameters
l
the window listener
Description
Removes the specified window listener so that it no longer receives window events from this window.


 Window.show

Window.show

Syntax
public void show()
Description
Shows this window, and brings it to the front.

If this window is not yet visible, show makes it visible. If this window is already visible, then this method brings it to the front.

Overrides
show in class Component
See Also
toFront, setVisible


 Window.toBack

Window.toBack

Syntax
public void toBack()
Description
Sends this window to the back. Places this window at the bottom of the stacking order and makes the corresponding adjustment to other visible windows.

See Also
toFront


 Window.toFront

Window.toFront

Syntax
public void toFront()
Description
Brings this window to the front. Places this window at the top of the stacking order and shows it in front of any other windows.

See Also
toBack


 Package java.awt.datatransfer

Package java.awt.datatransfer

All Packages

Interfaces

  • ClipboardOwner
  • Transferable

    • Classes

  • Clipboard
  • DataFlavor
  • StringSelection

    • Exceptions

  • UnsupportedFlavorException


 Class Clipboard

Class java.awt.datatransfer.Clipboard

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.datatransfer.Clipboard

public class Clipboard
extends Object

A class which implements a mechanism to transfer data using cut/copy/paste operations.


 Clipboard Members

Clipboard Members

Class Overview | This Package | All Packages

Fields
Name | Description
contents |
owner |

Constructors
Name | Description
Clipboard(String) | Creates a clipboard object.

Methods
Name | Description
getContents(Object) | Returns a transferable object representing the current contents of the clipboard.
getName() | Returns the name of this clipboard object.
setContents(Transferable, ClipboardOwner) | Sets the current contents of the clipboard to the specified transferable object and registers the specified clipboard owner as the owner of the new contents.


 Clipboard.contents

Clipboard.contents

Syntax
protected Transferable contents


 Clipboard.owner

Clipboard.owner

Syntax
protected ClipboardOwner owner


 Clipboard.Clipboard

Clipboard.Clipboard

Syntax
public Clipboard( String name )
Description
Creates a clipboard object.


 Clipboard.getContents

Clipboard.getContents

Syntax
public synchronized Transferable getContents( Object requestor )
Parameters
requestor
the object requesting the clip data
Returns
the current transferable object on the clipboard
Description
Returns a transferable object representing the current contents of the clipboard. If the clipboard currently has no contents, it returns null.


 Clipboard.getName

Clipboard.getName

Syntax
public String getName()
Description
Returns the name of this clipboard object.


 Clipboard.setContents

Clipboard.setContents

Syntax
public synchronized void setContents( Transferable contents, ClipboardOwner owner )
Parameters
content
the transferable object representing the clipboard content
owner
the object which owns the clipboard content
Description
Sets the current contents of the clipboard to the specified transferable object and registers the specified clipboard owner as the owner of the new contents. If there is an existing owner registered, that owner is notified that it no longer holds ownership of the clipboard contents.


 Interface ClipboardOwner

Interface java.awt.datatransfer.ClipboardOwner

Interface Members | This Package | All Packages

public interface ClipboardOwner

Defines the interface for classes that will provide data to a clipboard.


 ClipboardOwner Members

ClipboardOwner Members

Interface Overview | This Package | All Packages

Methods
Name | Description
lostOwnership(Clipboard, Transferable) | Notifies this object that it is no longer the owner of the contents of the clipboard.


 ClipboardOwner.lostOwnership

ClipboardOwner.lostOwnership

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void lostOwnership( Clipboard clipboard, Transferable contents )
Parameters
clipboard
the clipboard that is no longer owned
contents
the contents which this owner had placed on the clipboard
Description
Notifies this object that it is no longer the owner of the contents of the clipboard.


 Class DataFlavor

Class java.awt.datatransfer.DataFlavor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.datatransfer.DataFlavor

public class DataFlavor
extends Object

Each instance represents the opaque concept of a data format as would appear on a clipboard, during drag and drop, or in a file system.


 DataFlavor Members

DataFlavor Members

Class Overview | This Package | All Packages

Fields
Name | Description
plainTextFlavor | The DataFlavor representing plain text with unicode encoding, where: representationClass = InputStream mimeType = "text/plain; charset=unicode"
stringFlavor | The DataFlavor representing a Java Unicode String class, where: representationClass = java.lang.String mimeType = "application/x-java-serialized-object"

Constructors
Name | Description
DataFlavor(Class, String) | Construct a DataFlavor that represents a Java class The returned DataFlavor will have the following characteristics representationClass = representationClass mimeType = application/x-java-serialized-object
DataFlavor(String, String) | Construct a DataFlavor that represents a MimeType The returned DataFlavor will have the following characteristics: If the mimeType is "application/x-java-serialized-object; class=", the result is the same as calling new DataFlavor(Class:forName() as above otherwise: representationClass = InputStream mimeType = mimeType

Methods
Name | Description
equals(DataFlavor) |
getHumanPresentableName() | Returns the human presentable name for the data foramt that this DataFlavor represents.
getMimeType() | Returns the MIME type string for this DataFlavor
getRepresentationClass() | Returns the Class which objects supporting this DataFlavor will return when this DataFlavor is requested.
isMimeTypeEqual(DataFlavor) | Convenience function equivalent to calling: isMimeTypeEqual(dataFlavor.getMimeType());
isMimeTypeEqual(String) | Is the string representation of the MIME type passed in equivalent to the MIME type of this DataFlavor.
normalizeMimeType(String) | Called for each MIME type string to give DataFlavor subtypes the opportunity to change how the normalization of MIME types is accomplished.
normalizeMimeTypeParameter(String, String) | Called on DataFlavor for every MIME Type parameter to allow DataFlavor subclasses to handle special parameters like the text/plain charset parameters, whose values are case insensitive.
setHumanPresentableName(String) | Sets the human presentable name for the data format that this DataFlavor represents.


 DataFlavor.plainTextFlavor

DataFlavor.plainTextFlavor

Syntax
public static DataFlavor plainTextFlavor
Description
The DataFlavor representing plain text with unicode encoding, where:

representationClass = InputStream
mimeType = "text/plain; charset=unicode"


 DataFlavor.stringFlavor

DataFlavor.stringFlavor

Syntax
public static DataFlavor stringFlavor
Description
The DataFlavor representing a Java Unicode String class, where:

representationClass = java.lang.String
mimeType = "application/x-java-serialized-object"


 DataFlavor.DataFlavor

DataFlavor.DataFlavor

Syntax 1
public DataFlavor( Class representationClass, String humanPresentableName )
Parameters
representationClass
the class used to transfer data in this flavor
humanPresentableName
the human-readible string used to identify this flavor
Description
Construct a DataFlavor that represents a Java class

The returned DataFlavor will have the following characteristics

representationClass = representationClass
mimeType = application/x-java-serialized-object

Syntax 2
public DataFlavor( String mimeType, String humanPresentableName )
Parameters
mimeType
the string used to identify the MIME type for this flavor
humanPresentableName
the human-readible string used to identify this flavor
Description
Construct a DataFlavor that represents a MimeType

The returned DataFlavor will have the following characteristics:

If the mimeType is "application/x-java-serialized-object; class=", the result is the same as calling new DataFlavor(Class:forName() as above

otherwise:

representationClass = InputStream
mimeType = mimeType


 DataFlavor.equals

DataFlavor.equals

Syntax
public boolean equals( DataFlavor dataFlavor )


 DataFlavor.getHumanPresentableName

DataFlavor.getHumanPresentableName

Syntax
public String getHumanPresentableName()
Description
Returns the human presentable name for the data foramt that this DataFlavor represents. This name would be localized for different countries


 DataFlavor.getMimeType

DataFlavor.getMimeType

Syntax
public String getMimeType()
Description
Returns the MIME type string for this DataFlavor


 DataFlavor.getRepresentationClass

DataFlavor.getRepresentationClass

Syntax
public Class getRepresentationClass()
Description
Returns the Class which objects supporting this DataFlavor will return when this DataFlavor is requested.


 DataFlavor.isMimeTypeEqual

DataFlavor.isMimeTypeEqual

Syntax 1
public boolean isMimeTypeEqual( String mimeType )
Description
Is the string representation of the MIME type passed in equivalent to the MIME type of this DataFlavor. This may involve adding default attributes for some MIME types (like adding charset=US-ASCII to text/plain MIME types that have no charset parameter specified)

Syntax 2
public final boolean isMimeTypeEqual( DataFlavor dataFlavor )
Description
Convenience function equivalent to calling: isMimeTypeEqual(dataFlavor.getMimeType());


 DataFlavor.normalizeMimeType

DataFlavor.normalizeMimeType

Syntax
protected String normalizeMimeType( String mimeType )
Description
Called for each MIME type string to give DataFlavor subtypes the opportunity to change how the normalization of MIME types is accomplished. One possible use would be to add default parameter/value pairs in cases where none are present in the MIME type string passed in


 DataFlavor.normalizeMimeTypeParameter

DataFlavor.normalizeMimeTypeParameter

Syntax
protected String normalizeMimeTypeParameter( String parameterName, String parameterValue )
Description
Called on DataFlavor for every MIME Type parameter to allow DataFlavor subclasses to handle special parameters like the text/plain charset parameters, whose values are case insensitive. (MIME type parameter values are supposed to be case sensitive.

This method is called for each parameter name/value pair and should return the normalized representation of the parameterValue


 DataFlavor.setHumanPresentableName

DataFlavor.setHumanPresentableName

Syntax
public void setHumanPresentableName( String humanPresentableName )
Description
Sets the human presentable name for the data format that this DataFlavor represents. This name would be localized for different countries


 Class StringSelection

Class java.awt.datatransfer.StringSelection

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.datatransfer.StringSelection

public class StringSelection
extends Object
implements Transferable, ClipboardOwner

A class which implements the capability required to transfer a simple java String in plain text format.


 StringSelection Members

StringSelection Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringSelection(String) | Creates a transferable object capable of transferring the specified string in plain text format.

Methods
Name | Description
getTransferData(DataFlavor) | If the data was requested in the "java.lang.String" flavor, return the String representing the selection.
getTransferDataFlavors() | Returns the array of flavors in which it can provide the data.
isDataFlavorSupported(DataFlavor) | Returns whether the requested flavor is supported by this object.
lostOwnership(Clipboard, Transferable) |


 StringSelection.StringSelection

StringSelection.StringSelection

Syntax
public StringSelection( String data )
Description
Creates a transferable object capable of transferring the specified string in plain text format.


 StringSelection.getTransferData

StringSelection.getTransferData

Syntax
public synchronized Object getTransferData( DataFlavor flavor ) throws UnsupportedFlavorException, IOException
Parameters
flavor
the requested flavor for the data
Description
If the data was requested in the "java.lang.String" flavor, return the String representing the selection.

Exceptions
UnsupportedFlavorException if the requested data flavor is not supported in the "java.lang.String" flavor.


 StringSelection.getTransferDataFlavors

StringSelection.getTransferDataFlavors

Syntax
public synchronized DataFlavor[] getTransferDataFlavors()
Description
Returns the array of flavors in which it can provide the data.


 StringSelection.isDataFlavorSupported

StringSelection.isDataFlavorSupported

Syntax
public boolean isDataFlavorSupported( DataFlavor flavor )
Parameters
flavor
the requested flavor for the data
Description
Returns whether the requested flavor is supported by this object.


 StringSelection.lostOwnership

StringSelection.lostOwnership

Syntax
public void lostOwnership( Clipboard clipboard, Transferable contents )


 Interface Transferable

Interface java.awt.datatransfer.Transferable

Interface Members | This Package | All Packages

public interface Transferable

Defines the interface for classes that can be used to provide data for a transfer operation.


 Transferable Members

Transferable Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getTransferData(DataFlavor) | Returns an object which represents the data to be transferred.
getTransferDataFlavors() | Returns an array of DataFlavor objects indicating the flavors the data can be provided in.
isDataFlavorSupported(DataFlavor) | Returns whether or not the specified data flavor is supported for this object.


 Transferable.getTransferData

Transferable.getTransferData

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object getTransferData( DataFlavor flavor ) throws UnsupportedFlavorException, IOException
Parameters
flavor
the requested flavor for the data
Description
Returns an object which represents the data to be transferred. The class of the object returned is defined by the representation class of the flavor.

Exceptions
IOException if the data is no longer available in the requested flavor.
Exceptions
UnsupportedFlavorException if the requested data flavor is not supported.
See Also
getRepresentationClass


 Transferable.getTransferDataFlavors

Transferable.getTransferDataFlavors

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract DataFlavor[] getTransferDataFlavors()
Returns
an array of data flavors in which this data can be transferred
Description
Returns an array of DataFlavor objects indicating the flavors the data can be provided in. The array should be ordered according to preference for providing the data (from most richly descriptive to least descriptive).


 Transferable.isDataFlavorSupported

Transferable.isDataFlavorSupported

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isDataFlavorSupported( DataFlavor flavor )
Parameters
flavor
the requested flavor for the data
Returns
boolean indicating wjether or not the data flavor is supported
Description
Returns whether or not the specified data flavor is supported for this object.


 Class UnsupportedFlavorException

Class java.awt.datatransfer.UnsupportedFlavorException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.awt.datatransfer.UnsupportedFlavorException

public class UnsupportedFlavorException
extends Exception

Signals that the requested data is not supported in this flavor.

See Also:
getTransferData


 UnsupportedFlavorException Members

UnsupportedFlavorException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnsupportedFlavorException(DataFlavor) | Constructs an UnsupportedFlavorException.


 UnsupportedFlavorException.UnsupportedFlavorException

UnsupportedFlavorException.UnsupportedFlavorException

Syntax
public UnsupportedFlavorException( DataFlavor flavor )
Parameters
flavor
the flavor object which caused the exception
Description
Constructs an UnsupportedFlavorException.


 Package java.awt.event

Package java.awt.event

All Packages

Interfaces

  • ActionListener
  • AdjustmentListener
  • ComponentListener
  • ContainerListener
  • FocusListener
  • ItemListener
  • KeyListener
  • MouseListener
  • MouseMotionListener
  • TextListener
  • WindowListener

    • Classes

  • ActionEvent
  • AdjustmentEvent
  • ComponentAdapter
  • ComponentEvent
  • ContainerAdapter
  • ContainerEvent
  • FocusAdapter
  • FocusEvent
  • InputEvent
  • ItemEvent
  • KeyAdapter
  • KeyEvent
  • MouseAdapter
  • MouseEvent
  • MouseMotionAdapter
  • PaintEvent
  • TextEvent
  • WindowAdapter
  • WindowEvent


 Class ActionEvent

Class java.awt.event.ActionEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ActionEvent

public class ActionEvent
extends AWTEvent

The action semantic event.

See Also:
ActionListener


 ActionEvent Members

ActionEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
ACTION_FIRST | Marks the first integer id for the range of action event ids.
ACTION_LAST | Marks the last integer id for the range of action event ids.
ACTION_PERFORMED | An action performed event type.
ALT_MASK | The alt modifier constant.
CTRL_MASK | The control modifier constant.
META_MASK | The meta modifier constant.
SHIFT_MASK | The shift modifier constant.

Constructors
Name | Description
ActionEvent(Object, int, String) | Constructs an ActionEvent object with the specified source object.
ActionEvent(Object, int, String, int) | Constructs an ActionEvent object with the specified source object.

Methods
Name | Description
getActionCommand() | Returns the command name associated with this action.
getModifiers() | Returns the modifiers held down during this action event.
paramString() |


 ActionEvent.ACTION_FIRST

ActionEvent.ACTION_FIRST

Syntax
public static final int ACTION_FIRST
Description
Marks the first integer id for the range of action event ids.


 ActionEvent.ACTION_LAST

ActionEvent.ACTION_LAST

Syntax
public static final int ACTION_LAST
Description
Marks the last integer id for the range of action event ids.


 ActionEvent.ACTION_PERFORMED

ActionEvent.ACTION_PERFORMED

Syntax
public static final int ACTION_PERFORMED
Description
An action performed event type.


 ActionEvent.ALT_MASK

ActionEvent.ALT_MASK

Syntax
public static final int ALT_MASK
Description
The alt modifier constant.


 ActionEvent.CTRL_MASK

ActionEvent.CTRL_MASK

Syntax
public static final int CTRL_MASK
Description
The control modifier constant.


 ActionEvent.META_MASK

ActionEvent.META_MASK

Syntax
public static final int META_MASK
Description
The meta modifier constant.


 ActionEvent.SHIFT_MASK

ActionEvent.SHIFT_MASK

Syntax
public static final int SHIFT_MASK
Description
The shift modifier constant.


 ActionEvent.ActionEvent

ActionEvent.ActionEvent

Syntax 1
public ActionEvent( Object source, int id, String command )
Parameters
source
the object where the event originated
id
the type of event
command
the command string for this action event
Description
Constructs an ActionEvent object with the specified source object.

Syntax 2
public ActionEvent( Object source, int id, String command, int modifiers )
Parameters
source
the object where the event originated
id
the type of event
command
the command string for this action event
modifiers
the modifiers held down during this action
Description
Constructs an ActionEvent object with the specified source object.


 ActionEvent.getActionCommand

ActionEvent.getActionCommand

Syntax
public String getActionCommand()
Description
Returns the command name associated with this action.


 ActionEvent.getModifiers

ActionEvent.getModifiers

Syntax
public int getModifiers()
Description
Returns the modifiers held down during this action event.


 ActionEvent.paramString

ActionEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class AWTEvent


 Interface ActionListener

Interface java.awt.event.ActionListener

Interface Members | This Package | All Packages

public interface ActionListener
extends EventListener

The listener interface for receiving action events.


 ActionListener Members

ActionListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
actionPerformed(ActionEvent) | Invoked when an action occurs.


 ActionListener.actionPerformed

ActionListener.actionPerformed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void actionPerformed( ActionEvent e )
Description
Invoked when an action occurs.


 Class AdjustmentEvent

Class java.awt.event.AdjustmentEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.AdjustmentEvent

public class AdjustmentEvent
extends AWTEvent

The adjustment event emitted by Adjustable objects.

See Also:
Adjustable, AdjustmentListener


 AdjustmentEvent Members

AdjustmentEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
ADJUSTMENT_FIRST | Marks the first integer id for the range of adjustment event ids.
ADJUSTMENT_LAST | Marks the last integer id for the range of adjustment event ids.
ADJUSTMENT_VALUE_CHANGED | The adjustment value changed event.
BLOCK_DECREMENT | The block decrement adjustment type.
BLOCK_INCREMENT | The block increment adjustment type.
TRACK | The absolute tracking adjustment type.
UNIT_DECREMENT | The unit decrement adjustment type.
UNIT_INCREMENT | The unit increment adjustment type.

Constructors
Name | Description
AdjustmentEvent(Adjustable, int, int, int) | Constructs a AdjustmentEvent object with the specified Adjustable source, type, and value.

Methods
Name | Description
getAdjustable() | Returns the Adjustable object where this event originated.
getAdjustmentType() | Returns the type of adjustment which caused the value changed event.
getValue() | Returns the current value in the adjustment event.
paramString() |


 AdjustmentEvent.ADJUSTMENT_FIRST

AdjustmentEvent.ADJUSTMENT_FIRST

Syntax
public static final int ADJUSTMENT_FIRST
Description
Marks the first integer id for the range of adjustment event ids.


 AdjustmentEvent.ADJUSTMENT_LAST

AdjustmentEvent.ADJUSTMENT_LAST

Syntax
public static final int ADJUSTMENT_LAST
Description
Marks the last integer id for the range of adjustment event ids.


 AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED

AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED

Syntax
public static final int ADJUSTMENT_VALUE_CHANGED
Description
The adjustment value changed event.


 AdjustmentEvent.BLOCK_DECREMENT

AdjustmentEvent.BLOCK_DECREMENT

Syntax
public static final int BLOCK_DECREMENT
Description
The block decrement adjustment type.


 AdjustmentEvent.BLOCK_INCREMENT

AdjustmentEvent.BLOCK_INCREMENT

Syntax
public static final int BLOCK_INCREMENT
Description
The block increment adjustment type.


 AdjustmentEvent.TRACK

AdjustmentEvent.TRACK

Syntax
public static final int TRACK
Description
The absolute tracking adjustment type.


 AdjustmentEvent.UNIT_DECREMENT

AdjustmentEvent.UNIT_DECREMENT

Syntax
public static final int UNIT_DECREMENT
Description
The unit decrement adjustment type.


 AdjustmentEvent.UNIT_INCREMENT

AdjustmentEvent.UNIT_INCREMENT

Syntax
public static final int UNIT_INCREMENT
Description
The unit increment adjustment type.


 AdjustmentEvent.AdjustmentEvent

AdjustmentEvent.AdjustmentEvent

Syntax
public AdjustmentEvent( Adjustable source, int id, int type, int value )
Parameters
source
the Adjustable object where the event originated
Description
Constructs a AdjustmentEvent object with the specified Adjustable source, type, and value.


 AdjustmentEvent.getAdjustable

AdjustmentEvent.getAdjustable

Syntax
public Adjustable getAdjustable()
Description
Returns the Adjustable object where this event originated.


 AdjustmentEvent.getAdjustmentType

AdjustmentEvent.getAdjustmentType

Syntax
public int getAdjustmentType()
Description
Returns the type of adjustment which caused the value changed event.

See Also
UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT, BLOCK_DECREMENT, TRACK


 AdjustmentEvent.getValue

AdjustmentEvent.getValue

Syntax
public int getValue()
Description
Returns the current value in the adjustment event.


 AdjustmentEvent.paramString

AdjustmentEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class AWTEvent


 Interface AdjustmentListener

Interface java.awt.event.AdjustmentListener

Interface Members | This Package | All Packages

public interface AdjustmentListener
extends EventListener

The listener interface for receiving adjustment events.


 AdjustmentListener Members

AdjustmentListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
adjustmentValueChanged(AdjustmentEvent) | Invoked when the value of the adjustable has changed.


 AdjustmentListener.adjustmentValueChanged

AdjustmentListener.adjustmentValueChanged

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void adjustmentValueChanged( AdjustmentEvent e )
Description
Invoked when the value of the adjustable has changed.


 Class ComponentAdapter

Class java.awt.event.ComponentAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.ComponentAdapter

public abstract class ComponentAdapter
extends Object
implements ComponentListener

The adapter which receives component events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 ComponentAdapter Members

ComponentAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ComponentAdapter() |

Methods
Name | Description
componentHidden(ComponentEvent) |
componentMoved(ComponentEvent) |
componentResized(ComponentEvent) |
componentShown(ComponentEvent) |


 ComponentAdapter.ComponentAdapter

ComponentAdapter.ComponentAdapter

Syntax
public ComponentAdapter()


 ComponentAdapter.componentHidden

ComponentAdapter.componentHidden

Syntax
public void componentHidden( ComponentEvent e )


 ComponentAdapter.componentMoved

ComponentAdapter.componentMoved

Syntax
public void componentMoved( ComponentEvent e )


 ComponentAdapter.componentResized

ComponentAdapter.componentResized

Syntax
public void componentResized( ComponentEvent e )


 ComponentAdapter.componentShown

ComponentAdapter.componentShown

Syntax
public void componentShown( ComponentEvent e )


 Class ComponentEvent

Class java.awt.event.ComponentEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent

public class ComponentEvent
extends AWTEvent

The root event class for all component-level events. These events are provided for notification purposes ONLY; The AWT will automatically handle component moves and resizes internally so that GUI layout works properly regardless of whether a program is receiving these events or not.

See Also:
ComponentListener


 ComponentEvent Members

ComponentEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
COMPONENT_FIRST | Marks the first integer id for the range of component event ids.
COMPONENT_HIDDEN | The component hidden event type.
COMPONENT_LAST | Marks the last integer id for the range of component event ids.
COMPONENT_MOVED | The component moved event type.
COMPONENT_RESIZED | The component resized event type.
COMPONENT_SHOWN | The component shown event type.

Constructors
Name | Description
ComponentEvent(Component, int) | Constructs a ComponentEvent object with the specified source component and type.

Methods
Name | Description
getComponent() | Returns the component where this event originated.
paramString() |


 ComponentEvent.COMPONENT_FIRST

ComponentEvent.COMPONENT_FIRST

Syntax
public static final int COMPONENT_FIRST
Description
Marks the first integer id for the range of component event ids.


 ComponentEvent.COMPONENT_HIDDEN

ComponentEvent.COMPONENT_HIDDEN

Syntax
public static final int COMPONENT_HIDDEN
Description
The component hidden event type.


 ComponentEvent.COMPONENT_LAST

ComponentEvent.COMPONENT_LAST

Syntax
public static final int COMPONENT_LAST
Description
Marks the last integer id for the range of component event ids.


 ComponentEvent.COMPONENT_MOVED

ComponentEvent.COMPONENT_MOVED

Syntax
public static final int COMPONENT_MOVED
Description
The component moved event type.


 ComponentEvent.COMPONENT_RESIZED

ComponentEvent.COMPONENT_RESIZED

Syntax
public static final int COMPONENT_RESIZED
Description
The component resized event type.


 ComponentEvent.COMPONENT_SHOWN

ComponentEvent.COMPONENT_SHOWN

Syntax
public static final int COMPONENT_SHOWN
Description
The component shown event type.


 ComponentEvent.ComponentEvent

ComponentEvent.ComponentEvent

Syntax
public ComponentEvent( Component source, int id )
Parameters
source
the component where the event originated
Description
Constructs a ComponentEvent object with the specified source component and type.


 ComponentEvent.getComponent

ComponentEvent.getComponent

Syntax
public Component getComponent()
Description
Returns the component where this event originated.


 ComponentEvent.paramString

ComponentEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class AWTEvent


 Interface ComponentListener

Interface java.awt.event.ComponentListener

Interface Members | This Package | All Packages

public interface ComponentListener
extends EventListener

The listener interface for receiving component events. Component events are provided for notification purposes ONLY; The AWT will automatically handle component moves and resizes internally so that GUI layout works properly regardless of whether a program registers a ComponentListener or not.


 ComponentListener Members

ComponentListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
componentHidden(ComponentEvent) | Invoked when component has been hidden.
componentMoved(ComponentEvent) | Invoked when component has been moved.
componentResized(ComponentEvent) | Invoked when component has been resized.
componentShown(ComponentEvent) | Invoked when component has been shown.


 ComponentListener.componentHidden

ComponentListener.componentHidden

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentHidden( ComponentEvent e )
Description
Invoked when component has been hidden.


 ComponentListener.componentMoved

ComponentListener.componentMoved

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentMoved( ComponentEvent e )
Description
Invoked when component has been moved.


 ComponentListener.componentResized

ComponentListener.componentResized

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentResized( ComponentEvent e )
Description
Invoked when component has been resized.


 ComponentListener.componentShown

ComponentListener.componentShown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentShown( ComponentEvent e )
Description
Invoked when component has been shown.


 Class ContainerAdapter

Class java.awt.event.ContainerAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.ContainerAdapter

public abstract class ContainerAdapter
extends Object
implements ContainerListener

The adapter which receives container events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 ContainerAdapter Members

ContainerAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ContainerAdapter() |

Methods
Name | Description
componentAdded(ContainerEvent) |
componentRemoved(ContainerEvent) |


 ContainerAdapter.ContainerAdapter

ContainerAdapter.ContainerAdapter

Syntax
public ContainerAdapter()


 ContainerAdapter.componentAdded

ContainerAdapter.componentAdded

Syntax
public void componentAdded( ContainerEvent e )


 ContainerAdapter.componentRemoved

ContainerAdapter.componentRemoved

Syntax
public void componentRemoved( ContainerEvent e )


 Class ContainerEvent

Class java.awt.event.ContainerEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.ContainerEvent

public class ContainerEvent
extends ComponentEvent

The class for container-level events. These events are provided for notification purposes ONLY; The AWT will automatically handle container add and remove operations internally.

See Also:
ContainerListener


 ContainerEvent Members

ContainerEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
COMPONENT_ADDED | The component moved event type.
COMPONENT_REMOVED | The component resized event type.
CONTAINER_FIRST | Marks the first integer id for the range of container event ids.
CONTAINER_LAST | Marks the last integer id for the range of container event ids.

Constructors
Name | Description
ContainerEvent(Component, int, Component) | Constructs a ContainerEvent object with the specified source container, type, and child which is being added or removed.

Methods
Name | Description
getChild() | Returns the child component that was added or removed in this event.
getContainer() | Returns the container where this event originated.
paramString() |


 ContainerEvent.COMPONENT_ADDED

ContainerEvent.COMPONENT_ADDED

Syntax
public static final int COMPONENT_ADDED
Description
The component moved event type.


 ContainerEvent.COMPONENT_REMOVED

ContainerEvent.COMPONENT_REMOVED

Syntax
public static final int COMPONENT_REMOVED
Description
The component resized event type.


 ContainerEvent.CONTAINER_FIRST

ContainerEvent.CONTAINER_FIRST

Syntax
public static final int CONTAINER_FIRST
Description
Marks the first integer id for the range of container event ids.


 ContainerEvent.CONTAINER_LAST

ContainerEvent.CONTAINER_LAST

Syntax
public static final int CONTAINER_LAST
Description
Marks the last integer id for the range of container event ids.


 ContainerEvent.ContainerEvent

ContainerEvent.ContainerEvent

Syntax
public ContainerEvent( Component source, int id, Component child )
Parameters
source
the container where the event originated
Description
Constructs a ContainerEvent object with the specified source container, type, and child which is being added or removed.


 ContainerEvent.getChild

ContainerEvent.getChild

Syntax
public Component getChild()
Description
Returns the child component that was added or removed in this event.


 ContainerEvent.getContainer

ContainerEvent.getContainer

Syntax
public Container getContainer()
Description
Returns the container where this event originated.


 ContainerEvent.paramString

ContainerEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 Interface ContainerListener

Interface java.awt.event.ContainerListener

Interface Members | This Package | All Packages

public interface ContainerListener
extends EventListener

The listener interface for receiving container events. Container events are provided for notification purposes ONLY; The AWT will automatically handle add and remove operations internally.


 ContainerListener Members

ContainerListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
componentAdded(ContainerEvent) | Invoked when a component has been added to the container.
componentRemoved(ContainerEvent) | Invoked when a component has been removed from the container.


 ContainerListener.componentAdded

ContainerListener.componentAdded

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentAdded( ContainerEvent e )
Description
Invoked when a component has been added to the container.


 ContainerListener.componentRemoved

ContainerListener.componentRemoved

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void componentRemoved( ContainerEvent e )
Description
Invoked when a component has been removed from the container.


 Class FocusAdapter

Class java.awt.event.FocusAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.FocusAdapter

public abstract class FocusAdapter
extends Object
implements FocusListener

The adapter which receives focus events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 FocusAdapter Members

FocusAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FocusAdapter() |

Methods
Name | Description
focusGained(FocusEvent) |
focusLost(FocusEvent) |


 FocusAdapter.FocusAdapter

FocusAdapter.FocusAdapter

Syntax
public FocusAdapter()


 FocusAdapter.focusGained

FocusAdapter.focusGained

Syntax
public void focusGained( FocusEvent e )


 FocusAdapter.focusLost

FocusAdapter.focusLost

Syntax
public void focusLost( FocusEvent e )


 Class FocusEvent

Class java.awt.event.FocusEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.FocusEvent

public class FocusEvent
extends ComponentEvent

The component-level focus event. There are two levels of focus change events: permanent and temporary. Permanent focus change events occur when focus is directly moved from one component to another, such as through calls to requestFocus() or as the user uses the Tab key to traverse components. Temporary focus change events occur when focus is temporarily gained or lost for a component as the indirect result of another operation, such as window deactivation or a scrollbar drag. In this case, the original focus state will automatically be restored once that operation is finished, or, for the case of window deactivation, when the window is reactivated. Both permanent and temporary focus events are delivered using the FOCUS_GAINED and FOCUS_LOST event ids; the levels may be distinguished in the event using the isTemporary() method.


 FocusEvent Members

FocusEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
FOCUS_FIRST | Marks the first integer id for the range of focus event ids.
FOCUS_GAINED | The focus gained event type.
FOCUS_LAST | Marks the last integer id for the range of focus event ids.
FOCUS_LOST | The focus lost event type.

Constructors
Name | Description
FocusEvent(Component, int) | Constructs a permanent-level FocusEvent object with the specified source component and type.
FocusEvent(Component, int, boolean) | Constructs a FocusEvent object with the specified source component, type, and whether or not the focus event is a temporary level event.

Methods
Name | Description
isTemporary() | Returns whether or not this focus change event is a temporary change.
paramString() |


 FocusEvent.FOCUS_FIRST

FocusEvent.FOCUS_FIRST

Syntax
public static final int FOCUS_FIRST
Description
Marks the first integer id for the range of focus event ids.


 FocusEvent.FOCUS_GAINED

FocusEvent.FOCUS_GAINED

Syntax
public static final int FOCUS_GAINED
Description
The focus gained event type.


 FocusEvent.FOCUS_LAST

FocusEvent.FOCUS_LAST

Syntax
public static final int FOCUS_LAST
Description
Marks the last integer id for the range of focus event ids.


 FocusEvent.FOCUS_LOST

FocusEvent.FOCUS_LOST

Syntax
public static final int FOCUS_LOST
Description
The focus lost event type.


 FocusEvent.FocusEvent

FocusEvent.FocusEvent

Syntax 1
public FocusEvent( Component source, int id, boolean temporary )
Parameters
source
the object where the event originated
Description
Constructs a FocusEvent object with the specified source component, type, and whether or not the focus event is a temporary level event.

Syntax 2
public FocusEvent( Component source, int id )
Parameters
source
the object where the event originated
Description
Constructs a permanent-level FocusEvent object with the specified source component and type.


 FocusEvent.isTemporary

FocusEvent.isTemporary

Syntax
public boolean isTemporary()
Description
Returns whether or not this focus change event is a temporary change.


 FocusEvent.paramString

FocusEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 Interface FocusListener

Interface java.awt.event.FocusListener

Interface Members | This Package | All Packages

public interface FocusListener
extends EventListener

The listener interface for receiving keyboard focus events on a component.


 FocusListener Members

FocusListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
focusGained(FocusEvent) | Invoked when a component gains the keyboard focus.
focusLost(FocusEvent) | Invoked when a component loses the keyboard focus.


 FocusListener.focusGained

FocusListener.focusGained

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void focusGained( FocusEvent e )
Description
Invoked when a component gains the keyboard focus.


 FocusListener.focusLost

FocusListener.focusLost

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void focusLost( FocusEvent e )
Description
Invoked when a component loses the keyboard focus.


 Class InputEvent

Class java.awt.event.InputEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.InputEvent

public abstract class InputEvent
extends ComponentEvent

The root event class for all component-level input events. Input events are delivered to listeners before they are processed normally by the source where they originated. This allows listeners and component subclasses to "consume" the event so that the source will not process them in their default manner. For example, consuming mousePressed events on a Button component will prevent the Button from being activated.


 InputEvent Members

InputEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
ALT_MASK | The alt key modifier constant.
BUTTON1_MASK | The mouse button1 modifier constant.
BUTTON2_MASK | The mouse button2 modifier constant.
BUTTON3_MASK | The mouse button3 modifier constant.
CTRL_MASK | The control key modifier constant.
META_MASK | The meta key modifier constant.
SHIFT_MASK | The shift key modifier constant.

Methods
Name | Description
consume() | Consumes this event so that it will not be processed in the default manner by the source which originated it.
getModifiers() | Returns the modifiers flag for this event.
getWhen() | Returns the timestamp of when this event occurred.
isAltDown() | Returns whether or not the Alt modifier is down on this event.
isConsumed() | Returns whether or not this event has been consumed.
isControlDown() | Returns whether or not the Control modifier is down on this event.
isMetaDown() | Returns whether or not the Meta modifier is down on this event.
isShiftDown() | Returns whether or not the Shift modifier is down on this event.


 InputEvent.ALT_MASK

InputEvent.ALT_MASK

Syntax
public static final int ALT_MASK
Description
The alt key modifier constant.


 InputEvent.BUTTON1_MASK

InputEvent.BUTTON1_MASK

Syntax
public static final int BUTTON1_MASK
Description
The mouse button1 modifier constant.


 InputEvent.BUTTON2_MASK

InputEvent.BUTTON2_MASK

Syntax
public static final int BUTTON2_MASK
Description
The mouse button2 modifier constant.


 InputEvent.BUTTON3_MASK

InputEvent.BUTTON3_MASK

Syntax
public static final int BUTTON3_MASK
Description
The mouse button3 modifier constant.


 InputEvent.CTRL_MASK

InputEvent.CTRL_MASK

Syntax
public static final int CTRL_MASK
Description
The control key modifier constant.


 InputEvent.META_MASK

InputEvent.META_MASK

Syntax
public static final int META_MASK
Description
The meta key modifier constant.


 InputEvent.SHIFT_MASK

InputEvent.SHIFT_MASK

Syntax
public static final int SHIFT_MASK
Description
The shift key modifier constant.


 InputEvent.consume

InputEvent.consume

Syntax
public void consume()
Description
Consumes this event so that it will not be processed in the default manner by the source which originated it.

Overrides
consume in class AWTEvent


 InputEvent.getModifiers

InputEvent.getModifiers

Syntax
public int getModifiers()
Description
Returns the modifiers flag for this event.


 InputEvent.getWhen

InputEvent.getWhen

Syntax
public long getWhen()
Description
Returns the timestamp of when this event occurred.


 InputEvent.isAltDown

InputEvent.isAltDown

Syntax
public boolean isAltDown()
Description
Returns whether or not the Alt modifier is down on this event.


 InputEvent.isConsumed

InputEvent.isConsumed

Syntax
public boolean isConsumed()
Description
Returns whether or not this event has been consumed.

Overrides
isConsumed in class AWTEvent
See Also
consume


 InputEvent.isControlDown

InputEvent.isControlDown

Syntax
public boolean isControlDown()
Description
Returns whether or not the Control modifier is down on this event.


 InputEvent.isMetaDown

InputEvent.isMetaDown

Syntax
public boolean isMetaDown()
Description
Returns whether or not the Meta modifier is down on this event.


 InputEvent.isShiftDown

InputEvent.isShiftDown

Syntax
public boolean isShiftDown()
Description
Returns whether or not the Shift modifier is down on this event.


 Class ItemEvent

Class java.awt.event.ItemEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ItemEvent

public class ItemEvent
extends AWTEvent

The item event emitted by ItemSelectable objects. This event is generated when an item is selected or de-selected.

See Also:
ItemSelectable, ItemListener


 ItemEvent Members

ItemEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
DESELECTED | The item de-selected state change type.
ITEM_FIRST | Marks the first integer id for the range of item event ids.
ITEM_LAST | Marks the last integer id for the range of item event ids.
ITEM_STATE_CHANGED | The item state changed event type.
SELECTED | The item selected state change type.

Constructors
Name | Description
ItemEvent(ItemSelectable, int, Object, int) | Constructs a ItemSelectEvent object with the specified ItemSelectable source, type, item, and item select state.

Methods
Name | Description
getItem() | Returns the item where the event occurred.
getItemSelectable() | Returns the ItemSelectable object where this event originated.
getStateChange() | Returns the state change type which generated the event.
paramString() |


 ItemEvent.DESELECTED

ItemEvent.DESELECTED

Syntax
public static final int DESELECTED
Description
The item de-selected state change type.


 ItemEvent.ITEM_FIRST

ItemEvent.ITEM_FIRST

Syntax
public static final int ITEM_FIRST
Description
Marks the first integer id for the range of item event ids.


 ItemEvent.ITEM_LAST

ItemEvent.ITEM_LAST

Syntax
public static final int ITEM_LAST
Description
Marks the last integer id for the range of item event ids.


 ItemEvent.ITEM_STATE_CHANGED

ItemEvent.ITEM_STATE_CHANGED

Syntax
public static final int ITEM_STATE_CHANGED
Description
The item state changed event type.


 ItemEvent.SELECTED

ItemEvent.SELECTED

Syntax
public static final int SELECTED
Description
The item selected state change type.


 ItemEvent.ItemEvent

ItemEvent.ItemEvent

Syntax
public ItemEvent( ItemSelectable source, int id, Object item, int stateChange )
Parameters
source
the ItemSelectable object where the event originated
Description
Constructs a ItemSelectEvent object with the specified ItemSelectable source, type, item, and item select state.


 ItemEvent.getItem

ItemEvent.getItem

Syntax
public Object getItem()
Description
Returns the item where the event occurred.


 ItemEvent.getItemSelectable

ItemEvent.getItemSelectable

Syntax
public ItemSelectable getItemSelectable()
Description
Returns the ItemSelectable object where this event originated.


 ItemEvent.getStateChange

ItemEvent.getStateChange

Syntax
public int getStateChange()
Description
Returns the state change type which generated the event.

See Also
SELECTED, DESELECTED


 ItemEvent.paramString

ItemEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class AWTEvent


 Interface ItemListener

Interface java.awt.event.ItemListener

Interface Members | This Package | All Packages

public interface ItemListener
extends EventListener

The listener interface for receiving item events.

See Also:
ItemSelectable


 ItemListener Members

ItemListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
itemStateChanged(ItemEvent) | Invoked when an item's state has been changed.


 ItemListener.itemStateChanged

ItemListener.itemStateChanged

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void itemStateChanged( ItemEvent e )
Description
Invoked when an item's state has been changed.


 Class KeyAdapter

Class java.awt.event.KeyAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.KeyAdapter

public abstract class KeyAdapter
extends Object
implements KeyListener

The adapter which receives keyboard events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 KeyAdapter Members

KeyAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
KeyAdapter() |

Methods
Name | Description
keyPressed(KeyEvent) |
keyReleased(KeyEvent) |
keyTyped(KeyEvent) |


 KeyAdapter.KeyAdapter

KeyAdapter.KeyAdapter

Syntax
public KeyAdapter()


 KeyAdapter.keyPressed

KeyAdapter.keyPressed

Syntax
public void keyPressed( KeyEvent e )


 KeyAdapter.keyReleased

KeyAdapter.keyReleased

Syntax
public void keyReleased( KeyEvent e )


 KeyAdapter.keyTyped

KeyAdapter.keyTyped

Syntax
public void keyTyped( KeyEvent e )


 Class KeyEvent

Class java.awt.event.KeyEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.InputEvent
                                   |
                                   +----java.awt.event.KeyEvent

public class KeyEvent
extends InputEvent

The component-level keyboard event.


 KeyEvent Members

KeyEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
CHAR_UNDEFINED | KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character do not have a defined keyChar.
KEY_FIRST | Marks the first integer id for the range of key event ids.
KEY_LAST | Marks the last integer id for the range of key event ids.
KEY_PRESSED | The key pressed event type.
KEY_RELEASED | The key released event type.
KEY_TYPED | The key typed event type.
VK_0 | VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
VK_1 |
VK_2 |
VK_3 |
VK_4 |
VK_5 |
VK_6 |
VK_7 |
VK_8 |
VK_9 |
VK_A | VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
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 | Virtual key codes.
VK_EQUALS |
VK_ESCAPE |
VK_F |
VK_F1 |
VK_F10 |
VK_F11 |
VK_F12 |
VK_F2 |
VK_F3 |
VK_F4 |
VK_F5 |
VK_F6 |
VK_F7 |
VK_F8 |
VK_F9 |
VK_FINAL | for Asian Keyboard
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 |
VK_SHIFT |
VK_SLASH |
VK_SPACE |
VK_SUBTRACT |
VK_T |
VK_TAB |
VK_U |
VK_UNDEFINED | KEY_TYPED events do not have a defined keyCode.
VK_UP |
VK_V |
VK_W |
VK_X |
VK_Y |
VK_Z |

Constructors
Name | Description
KeyEvent(Component, int, long, int, int) |
KeyEvent(Component, int, long, int, int, char) | Constructs a KeyEvent object with the specified source component, type, modifiers, and key.

Methods
Name | Description
getKeyChar() | Returns the character associated with the key in this event.
getKeyCode() | Returns the integer key-code associated with the key in this event.
getKeyModifiersText(int) | Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".
getKeyText(int) | Returns a String describing the keyCode, such as "HOME", "F1" or "A".
isActionKey() | Returns whether or not the key in this event is an "action" key, as defined in Event.java.
paramString() |
setKeyChar(char) |
setKeyCode(int) |
setModifiers(int) |


 KeyEvent.CHAR_UNDEFINED

KeyEvent.CHAR_UNDEFINED

Syntax
public static final char CHAR_UNDEFINED
Description
KEY_PRESSED and KEY_RELEASED events which do not map to a valid Unicode character do not have a defined keyChar.


 KeyEvent.KEY_FIRST

KeyEvent.KEY_FIRST

Syntax
public static final int KEY_FIRST
Description
Marks the first integer id for the range of key event ids.


 KeyEvent.KEY_LAST

KeyEvent.KEY_LAST

Syntax
public static final int KEY_LAST
Description
Marks the last integer id for the range of key event ids.


 KeyEvent.KEY_PRESSED

KeyEvent.KEY_PRESSED

Syntax
public static final int KEY_PRESSED
Description
The key pressed event type.


 KeyEvent.KEY_RELEASED

KeyEvent.KEY_RELEASED

Syntax
public static final int KEY_RELEASED
Description
The key released event type.


 KeyEvent.KEY_TYPED

KeyEvent.KEY_TYPED

Syntax
public static final int KEY_TYPED
Description
The key typed event type. This type is generated by a combination of a key press followed by a key release.


 KeyEvent.VK_0

KeyEvent.VK_0

Syntax
public static final int VK_0
Description
VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)


 KeyEvent.VK_1

KeyEvent.VK_1

Syntax
public static final int VK_1


 KeyEvent.VK_2

KeyEvent.VK_2

Syntax
public static final int VK_2


 KeyEvent.VK_3

KeyEvent.VK_3

Syntax
public static final int VK_3


 KeyEvent.VK_4

KeyEvent.VK_4

Syntax
public static final int VK_4


 KeyEvent.VK_5

KeyEvent.VK_5

Syntax
public static final int VK_5


 KeyEvent.VK_6

KeyEvent.VK_6

Syntax
public static final int VK_6


 KeyEvent.VK_7

KeyEvent.VK_7

Syntax
public static final int VK_7


 KeyEvent.VK_8

KeyEvent.VK_8

Syntax
public static final int VK_8


 KeyEvent.VK_9

KeyEvent.VK_9

Syntax
public static final int VK_9


 KeyEvent.VK_A

KeyEvent.VK_A

Syntax
public static final int VK_A
Description
VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)


 KeyEvent.VK_ACCEPT

KeyEvent.VK_ACCEPT

Syntax
public static final int VK_ACCEPT


 KeyEvent.VK_ADD

KeyEvent.VK_ADD

Syntax
public static final int VK_ADD


 KeyEvent.VK_ALT

KeyEvent.VK_ALT

Syntax
public static final int VK_ALT


 KeyEvent.VK_B

KeyEvent.VK_B

Syntax
public static final int VK_B


 KeyEvent.VK_BACK_QUOTE

KeyEvent.VK_BACK_QUOTE

Syntax
public static final int VK_BACK_QUOTE


 KeyEvent.VK_BACK_SLASH

KeyEvent.VK_BACK_SLASH

Syntax
public static final int VK_BACK_SLASH


 KeyEvent.VK_BACK_SPACE

KeyEvent.VK_BACK_SPACE

Syntax
public static final int VK_BACK_SPACE


 KeyEvent.VK_C

KeyEvent.VK_C

Syntax
public static final int VK_C


 KeyEvent.VK_CANCEL

KeyEvent.VK_CANCEL

Syntax
public static final int VK_CANCEL


 KeyEvent.VK_CAPS_LOCK

KeyEvent.VK_CAPS_LOCK

Syntax
public static final int VK_CAPS_LOCK


 KeyEvent.VK_CLEAR

KeyEvent.VK_CLEAR

Syntax
public static final int VK_CLEAR


 KeyEvent.VK_CLOSE_BRACKET

KeyEvent.VK_CLOSE_BRACKET

Syntax
public static final int VK_CLOSE_BRACKET


 KeyEvent.VK_COMMA

KeyEvent.VK_COMMA

Syntax
public static final int VK_COMMA


 KeyEvent.VK_CONTROL

KeyEvent.VK_CONTROL

Syntax
public static final int VK_CONTROL


 KeyEvent.VK_CONVERT

KeyEvent.VK_CONVERT

Syntax
public static final int VK_CONVERT


 KeyEvent.VK_D

KeyEvent.VK_D

Syntax
public static final int VK_D


 KeyEvent.VK_DECIMAL

KeyEvent.VK_DECIMAL

Syntax
public static final int VK_DECIMAL


 KeyEvent.VK_DELETE

KeyEvent.VK_DELETE

Syntax
public static final int VK_DELETE


 KeyEvent.VK_DIVIDE

KeyEvent.VK_DIVIDE

Syntax
public static final int VK_DIVIDE


 KeyEvent.VK_DOWN

KeyEvent.VK_DOWN

Syntax
public static final int VK_DOWN


 KeyEvent.VK_E

KeyEvent.VK_E

Syntax
public static final int VK_E


 KeyEvent.VK_END

KeyEvent.VK_END

Syntax
public static final int VK_END


 KeyEvent.VK_ENTER

KeyEvent.VK_ENTER

Syntax
public static final int VK_ENTER
Description
Virtual key codes. These codes report which keyboard key has been pressed, rather than any character generated by one or more keys being pressed. For example, pressing the Shift key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is released, a KEY_RELEASED event will be fired with VK_A, followed by a KEY_TYPED event with a keyChar value of 'A'. Key combinations which do not result in characters, such as action keys like F1, will not generate KEY_TYPED events. Note: not all keyboards or systems are capable of generating all virtual key codes. No attempt is made in Java to artificially generate these keys. WARNING: aside from those keys where are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of these constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.


 KeyEvent.VK_EQUALS

KeyEvent.VK_EQUALS

Syntax
public static final int VK_EQUALS


 KeyEvent.VK_ESCAPE

KeyEvent.VK_ESCAPE

Syntax
public static final int VK_ESCAPE


 KeyEvent.VK_F

KeyEvent.VK_F

Syntax
public static final int VK_F


 KeyEvent.VK_F1

KeyEvent.VK_F1

Syntax
public static final int VK_F1


 KeyEvent.VK_F10

KeyEvent.VK_F10

Syntax
public static final int VK_F10


 KeyEvent.VK_F11

KeyEvent.VK_F11

Syntax
public static final int VK_F11


 KeyEvent.VK_F12

KeyEvent.VK_F12

Syntax
public static final int VK_F12


 KeyEvent.VK_F2

KeyEvent.VK_F2

Syntax
public static final int VK_F2


 KeyEvent.VK_F3

KeyEvent.VK_F3

Syntax
public static final int VK_F3


 KeyEvent.VK_F4

KeyEvent.VK_F4

Syntax
public static final int VK_F4


 KeyEvent.VK_F5

KeyEvent.VK_F5

Syntax
public static final int VK_F5


 KeyEvent.VK_F6

KeyEvent.VK_F6

Syntax
public static final int VK_F6


 KeyEvent.VK_F7

KeyEvent.VK_F7

Syntax
public static final int VK_F7


 KeyEvent.VK_F8

KeyEvent.VK_F8

Syntax
public static final int VK_F8


 KeyEvent.VK_F9

KeyEvent.VK_F9

Syntax
public static final int VK_F9


 KeyEvent.VK_FINAL

KeyEvent.VK_FINAL

Syntax
public static final int VK_FINAL
Description
for Asian Keyboard


 KeyEvent.VK_G

KeyEvent.VK_G

Syntax
public static final int VK_G


 KeyEvent.VK_H

KeyEvent.VK_H

Syntax
public static final int VK_H


 KeyEvent.VK_HELP

KeyEvent.VK_HELP

Syntax
public static final int VK_HELP


 KeyEvent.VK_HOME

KeyEvent.VK_HOME

Syntax
public static final int VK_HOME


 KeyEvent.VK_I

KeyEvent.VK_I

Syntax
public static final int VK_I


 KeyEvent.VK_INSERT

KeyEvent.VK_INSERT

Syntax
public static final int VK_INSERT


 KeyEvent.VK_J

KeyEvent.VK_J

Syntax
public static final int VK_J


 KeyEvent.VK_K

KeyEvent.VK_K

Syntax
public static final int VK_K


 KeyEvent.VK_KANA

KeyEvent.VK_KANA

Syntax
public static final int VK_KANA


 KeyEvent.VK_KANJI

KeyEvent.VK_KANJI

Syntax
public static final int VK_KANJI


 KeyEvent.VK_L

KeyEvent.VK_L

Syntax
public static final int VK_L


 KeyEvent.VK_LEFT

KeyEvent.VK_LEFT

Syntax
public static final int VK_LEFT


 KeyEvent.VK_M

KeyEvent.VK_M

Syntax
public static final int VK_M


 KeyEvent.VK_META

KeyEvent.VK_META

Syntax
public static final int VK_META


 KeyEvent.VK_MODECHANGE

KeyEvent.VK_MODECHANGE

Syntax
public static final int VK_MODECHANGE


 KeyEvent.VK_MULTIPLY

KeyEvent.VK_MULTIPLY

Syntax
public static final int VK_MULTIPLY


 KeyEvent.VK_N

KeyEvent.VK_N

Syntax
public static final int VK_N


 KeyEvent.VK_NONCONVERT

KeyEvent.VK_NONCONVERT

Syntax
public static final int VK_NONCONVERT


 KeyEvent.VK_NUM_LOCK

KeyEvent.VK_NUM_LOCK

Syntax
public static final int VK_NUM_LOCK


 KeyEvent.VK_NUMPAD0

KeyEvent.VK_NUMPAD0

Syntax
public static final int VK_NUMPAD0


 KeyEvent.VK_NUMPAD1

KeyEvent.VK_NUMPAD1

Syntax
public static final int VK_NUMPAD1


 KeyEvent.VK_NUMPAD2

KeyEvent.VK_NUMPAD2

Syntax
public static final int VK_NUMPAD2


 KeyEvent.VK_NUMPAD3

KeyEvent.VK_NUMPAD3

Syntax
public static final int VK_NUMPAD3


 KeyEvent.VK_NUMPAD4

KeyEvent.VK_NUMPAD4

Syntax
public static final int VK_NUMPAD4


 KeyEvent.VK_NUMPAD5

KeyEvent.VK_NUMPAD5

Syntax
public static final int VK_NUMPAD5


 KeyEvent.VK_NUMPAD6

KeyEvent.VK_NUMPAD6

Syntax
public static final int VK_NUMPAD6


 KeyEvent.VK_NUMPAD7

KeyEvent.VK_NUMPAD7

Syntax
public static final int VK_NUMPAD7


 KeyEvent.VK_NUMPAD8

KeyEvent.VK_NUMPAD8

Syntax
public static final int VK_NUMPAD8


 KeyEvent.VK_NUMPAD9

KeyEvent.VK_NUMPAD9

Syntax
public static final int VK_NUMPAD9


 KeyEvent.VK_O

KeyEvent.VK_O

Syntax
public static final int VK_O


 KeyEvent.VK_OPEN_BRACKET

KeyEvent.VK_OPEN_BRACKET

Syntax
public static final int VK_OPEN_BRACKET


 KeyEvent.VK_P

KeyEvent.VK_P

Syntax
public static final int VK_P


 KeyEvent.VK_PAGE_DOWN

KeyEvent.VK_PAGE_DOWN

Syntax
public static final int VK_PAGE_DOWN


 KeyEvent.VK_PAGE_UP

KeyEvent.VK_PAGE_UP

Syntax
public static final int VK_PAGE_UP


 KeyEvent.VK_PAUSE

KeyEvent.VK_PAUSE

Syntax
public static final int VK_PAUSE


 KeyEvent.VK_PERIOD

KeyEvent.VK_PERIOD

Syntax
public static final int VK_PERIOD


 KeyEvent.VK_PRINTSCREEN

KeyEvent.VK_PRINTSCREEN

Syntax
public static final int VK_PRINTSCREEN


 KeyEvent.VK_Q

KeyEvent.VK_Q

Syntax
public static final int VK_Q


 KeyEvent.VK_QUOTE

KeyEvent.VK_QUOTE

Syntax
public static final int VK_QUOTE


 KeyEvent.VK_R

KeyEvent.VK_R

Syntax
public static final int VK_R


 KeyEvent.VK_RIGHT

KeyEvent.VK_RIGHT

Syntax
public static final int VK_RIGHT


 KeyEvent.VK_S

KeyEvent.VK_S

Syntax
public static final int VK_S


 KeyEvent.VK_SCROLL_LOCK

KeyEvent.VK_SCROLL_LOCK

Syntax
public static final int VK_SCROLL_LOCK


 KeyEvent.VK_SEMICOLON

KeyEvent.VK_SEMICOLON

Syntax
public static final int VK_SEMICOLON


 KeyEvent.VK_SEPARATER

KeyEvent.VK_SEPARATER

Syntax
public static final int VK_SEPARATER


 KeyEvent.VK_SHIFT

KeyEvent.VK_SHIFT

Syntax
public static final int VK_SHIFT


 KeyEvent.VK_SLASH

KeyEvent.VK_SLASH

Syntax
public static final int VK_SLASH


 KeyEvent.VK_SPACE

KeyEvent.VK_SPACE

Syntax
public static final int VK_SPACE


 KeyEvent.VK_SUBTRACT

KeyEvent.VK_SUBTRACT

Syntax
public static final int VK_SUBTRACT


 KeyEvent.VK_T

KeyEvent.VK_T

Syntax
public static final int VK_T


 KeyEvent.VK_TAB

KeyEvent.VK_TAB

Syntax
public static final int VK_TAB


 KeyEvent.VK_U

KeyEvent.VK_U

Syntax
public static final int VK_U


 KeyEvent.VK_UNDEFINED

KeyEvent.VK_UNDEFINED

Syntax
public static final int VK_UNDEFINED
Description
KEY_TYPED events do not have a defined keyCode.


 KeyEvent.VK_UP

KeyEvent.VK_UP

Syntax
public static final int VK_UP


 KeyEvent.VK_V

KeyEvent.VK_V

Syntax
public static final int VK_V


 KeyEvent.VK_W

KeyEvent.VK_W

Syntax
public static final int VK_W


 KeyEvent.VK_X

KeyEvent.VK_X

Syntax
public static final int VK_X


 KeyEvent.VK_Y

KeyEvent.VK_Y

Syntax
public static final int VK_Y


 KeyEvent.VK_Z

KeyEvent.VK_Z

Syntax
public static final int VK_Z


 KeyEvent.KeyEvent

KeyEvent.KeyEvent

Syntax 1
public KeyEvent( Component source, int id, long when, int modifiers, int keyCode, char keyChar )
Parameters
source
the object where the event originated
Description
Constructs a KeyEvent object with the specified source component, type, modifiers, and key.

Syntax 2
public KeyEvent( Component source, int id, long when, int modifiers, int keyCode )


 KeyEvent.getKeyChar

KeyEvent.getKeyChar

Syntax
public char getKeyChar()
Description
Returns the character associated with the key in this event. If no valid Unicode character exists for this key event, keyChar is CHAR_UNDEFINED.


 KeyEvent.getKeyCode

KeyEvent.getKeyCode

Syntax
public int getKeyCode()
Description
Returns the integer key-code associated with the key in this event. For KEY_TYPED events, keyCode is VK_UNDEFINED.


 KeyEvent.getKeyModifiersText

KeyEvent.getKeyModifiersText

Syntax
public static String getKeyModifiersText( int modifiers )
Description
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift". These strings can be localized by changing the awt.properties file.


 KeyEvent.getKeyText

KeyEvent.getKeyText

Syntax
public static String getKeyText( int keyCode )
Description
Returns a String describing the keyCode, such as "HOME", "F1" or "A". These strings can be localized by changing the awt.properties file.


 KeyEvent.isActionKey

KeyEvent.isActionKey

Syntax
public boolean isActionKey()
Description
Returns whether or not the key in this event is an "action" key, as defined in Event.java.


 KeyEvent.paramString

KeyEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 KeyEvent.setKeyChar

KeyEvent.setKeyChar

Syntax
public void setKeyChar( char keyChar )


 KeyEvent.setKeyCode

KeyEvent.setKeyCode

Syntax
public void setKeyCode( int keyCode )


 KeyEvent.setModifiers

KeyEvent.setModifiers

Syntax
public void setModifiers( int modifiers )


 Interface KeyListener

Interface java.awt.event.KeyListener

Interface Members | This Package | All Packages

public interface KeyListener
extends EventListener

The listener interface for receiving keyboard events.


 KeyListener Members

KeyListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
keyPressed(KeyEvent) | Invoked when a key has been pressed.
keyReleased(KeyEvent) | Invoked when a key has been released.
keyTyped(KeyEvent) | Invoked when a key has been typed.


 KeyListener.keyPressed

KeyListener.keyPressed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void keyPressed( KeyEvent e )
Description
Invoked when a key has been pressed.


 KeyListener.keyReleased

KeyListener.keyReleased

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void keyReleased( KeyEvent e )
Description
Invoked when a key has been released.


 KeyListener.keyTyped

KeyListener.keyTyped

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void keyTyped( KeyEvent e )
Description
Invoked when a key has been typed. This event occurs when a key press is followed by a key release.


 Class MouseAdapter

Class java.awt.event.MouseAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.MouseAdapter

public abstract class MouseAdapter
extends Object
implements MouseListener

The adapter which receives mouse events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 MouseAdapter Members

MouseAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MouseAdapter() |

Methods
Name | Description
mouseClicked(MouseEvent) |
mouseEntered(MouseEvent) |
mouseExited(MouseEvent) |
mousePressed(MouseEvent) |
mouseReleased(MouseEvent) |


 MouseAdapter.MouseAdapter

MouseAdapter.MouseAdapter

Syntax
public MouseAdapter()


 MouseAdapter.mouseClicked

MouseAdapter.mouseClicked

Syntax
public void mouseClicked( MouseEvent e )


 MouseAdapter.mouseEntered

MouseAdapter.mouseEntered

Syntax
public void mouseEntered( MouseEvent e )


 MouseAdapter.mouseExited

MouseAdapter.mouseExited

Syntax
public void mouseExited( MouseEvent e )


 MouseAdapter.mousePressed

MouseAdapter.mousePressed

Syntax
public void mousePressed( MouseEvent e )


 MouseAdapter.mouseReleased

MouseAdapter.mouseReleased

Syntax
public void mouseReleased( MouseEvent e )


 Class MouseEvent

Class java.awt.event.MouseEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.InputEvent
                                   |
                                   +----java.awt.event.MouseEvent

public class MouseEvent
extends InputEvent

The mouse event.


 MouseEvent Members

MouseEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
MOUSE_CLICKED | The mouse clicked event type.
MOUSE_DRAGGED | The mouse dragged event type.
MOUSE_ENTERED | The mouse entered event type.
MOUSE_EXITED | The mouse exited event type.
MOUSE_FIRST | Marks the first integer id for the range of mouse event ids.
MOUSE_LAST | Marks the last integer id for the range of mouse event ids.
MOUSE_MOVED | The mouse moved event type.
MOUSE_PRESSED | The mouse pressed event type.
MOUSE_RELEASED | The mouse released event type.

Constructors
Name | Description
MouseEvent(Component, int, long, int, int, int, int, boolean) | Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.

Methods
Name | Description
getClickCount() | Return the number of mouse clicks associated with this event.
getPoint() | Returns the x,y position of the event relative to the source component.
getX() | Returns the x position of the event relative to the source component.
getY() | Returns the y position of the event relative to the source component.
isPopupTrigger() | Returns whether or not this mouse event is the popup-menu trigger event for the platform.
paramString() |
translatePoint(int, int) | Translates the coordinate position of the event by x, y.


 MouseEvent.MOUSE_CLICKED

MouseEvent.MOUSE_CLICKED

Syntax
public static final int MOUSE_CLICKED
Description
The mouse clicked event type.


 MouseEvent.MOUSE_DRAGGED

MouseEvent.MOUSE_DRAGGED

Syntax
public static final int MOUSE_DRAGGED
Description
The mouse dragged event type.


 MouseEvent.MOUSE_ENTERED

MouseEvent.MOUSE_ENTERED

Syntax
public static final int MOUSE_ENTERED
Description
The mouse entered event type.


 MouseEvent.MOUSE_EXITED

MouseEvent.MOUSE_EXITED

Syntax
public static final int MOUSE_EXITED
Description
The mouse exited event type.


 MouseEvent.MOUSE_FIRST

MouseEvent.MOUSE_FIRST

Syntax
public static final int MOUSE_FIRST
Description
Marks the first integer id for the range of mouse event ids.


 MouseEvent.MOUSE_LAST

MouseEvent.MOUSE_LAST

Syntax
public static final int MOUSE_LAST
Description
Marks the last integer id for the range of mouse event ids.


 MouseEvent.MOUSE_MOVED

MouseEvent.MOUSE_MOVED

Syntax
public static final int MOUSE_MOVED
Description
The mouse moved event type.


 MouseEvent.MOUSE_PRESSED

MouseEvent.MOUSE_PRESSED

Syntax
public static final int MOUSE_PRESSED
Description
The mouse pressed event type.


 MouseEvent.MOUSE_RELEASED

MouseEvent.MOUSE_RELEASED

Syntax
public static final int MOUSE_RELEASED
Description
The mouse released event type.


 MouseEvent.MouseEvent

MouseEvent.MouseEvent

Syntax
public MouseEvent( Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger )
Parameters
source
the object where the event originated
Description
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, and click count.


 MouseEvent.getClickCount

MouseEvent.getClickCount

Syntax
public int getClickCount()
Description
Return the number of mouse clicks associated with this event.


 MouseEvent.getPoint

MouseEvent.getPoint

Syntax
public Point getPoint()
Description
Returns the x,y position of the event relative to the source component.


 MouseEvent.getX

MouseEvent.getX

Syntax
public int getX()
Description
Returns the x position of the event relative to the source component.


 MouseEvent.getY

MouseEvent.getY

Syntax
public int getY()
Description
Returns the y position of the event relative to the source component.


 MouseEvent.isPopupTrigger

MouseEvent.isPopupTrigger

Syntax
public boolean isPopupTrigger()
Description
Returns whether or not this mouse event is the popup-menu trigger event for the platform.


 MouseEvent.paramString

MouseEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 MouseEvent.translatePoint

MouseEvent.translatePoint

Syntax
public synchronized void translatePoint( int x, int y )
Parameters
x
the x value added to the current x coordinate position
y
the y value added to the current y coordinate position
Description
Translates the coordinate position of the event by x, y.


 Interface MouseListener

Interface java.awt.event.MouseListener

Interface Members | This Package | All Packages

public interface MouseListener
extends EventListener

The listener interface for receiving mouse events on a component.


 MouseListener Members

MouseListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
mouseClicked(MouseEvent) | Invoked when the mouse has been clicked on a component.
mouseEntered(MouseEvent) | Invoked when the mouse enters a component.
mouseExited(MouseEvent) | Invoked when the mouse exits a component.
mousePressed(MouseEvent) | Invoked when a mouse button has been pressed on a component.
mouseReleased(MouseEvent) | Invoked when a mouse button has been released on a component.


 MouseListener.mouseClicked

MouseListener.mouseClicked

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseClicked( MouseEvent e )
Description
Invoked when the mouse has been clicked on a component.


 MouseListener.mouseEntered

MouseListener.mouseEntered

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseEntered( MouseEvent e )
Description
Invoked when the mouse enters a component.


 MouseListener.mouseExited

MouseListener.mouseExited

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseExited( MouseEvent e )
Description
Invoked when the mouse exits a component.


 MouseListener.mousePressed

MouseListener.mousePressed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mousePressed( MouseEvent e )
Description
Invoked when a mouse button has been pressed on a component.


 MouseListener.mouseReleased

MouseListener.mouseReleased

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseReleased( MouseEvent e )
Description
Invoked when a mouse button has been released on a component.


 Class MouseMotionAdapter

Class java.awt.event.MouseMotionAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.MouseMotionAdapter

public abstract class MouseMotionAdapter
extends Object
implements MouseMotionListener

The adapter which receives mouse motion events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 MouseMotionAdapter Members

MouseMotionAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MouseMotionAdapter() |

Methods
Name | Description
mouseDragged(MouseEvent) |
mouseMoved(MouseEvent) |


 MouseMotionAdapter.MouseMotionAdapter

MouseMotionAdapter.MouseMotionAdapter

Syntax
public MouseMotionAdapter()


 MouseMotionAdapter.mouseDragged

MouseMotionAdapter.mouseDragged

Syntax
public void mouseDragged( MouseEvent e )


 MouseMotionAdapter.mouseMoved

MouseMotionAdapter.mouseMoved

Syntax
public void mouseMoved( MouseEvent e )


 Interface MouseMotionListener

Interface java.awt.event.MouseMotionListener

Interface Members | This Package | All Packages

public interface MouseMotionListener
extends EventListener

The listener interface for receiving mouse motion events on a component.


 MouseMotionListener Members

MouseMotionListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
mouseDragged(MouseEvent) | Invoked when a mouse button is pressed on a component and then dragged.
mouseMoved(MouseEvent) | Invoked when the mouse button has been moved on a component (with no buttons no down).


 MouseMotionListener.mouseDragged

MouseMotionListener.mouseDragged

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseDragged( MouseEvent e )
Description
Invoked when a mouse button is pressed on a component and then dragged. Mouse drag events will continue to be delivered to the component where the first originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component).


 MouseMotionListener.mouseMoved

MouseMotionListener.mouseMoved

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void mouseMoved( MouseEvent e )
Description
Invoked when the mouse button has been moved on a component (with no buttons no down).


 Class PaintEvent

Class java.awt.event.PaintEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.PaintEvent

public class PaintEvent
extends ComponentEvent

The component-level paint event. This event is a special type which is used to ensure that paint/update method calls are serialized along with the other events delivered from the event queue. This event is not designed to be used with the Event Listener model; programs should continue to override paint/update methods in order render themselves properly.


 PaintEvent Members

PaintEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
PAINT | The paint event type.
PAINT_FIRST | Marks the first integer id for the range of paint event ids.
PAINT_LAST | Marks the last integer id for the range of paint event ids.
UPDATE | The update event type.

Constructors
Name | Description
PaintEvent(Component, int, Rectangle) | Constructs a PaintEvent object with the specified source component and type.

Methods
Name | Description
getUpdateRect() | Returns the rectangle representing the area which needs to be repainted in response to this event.
paramString() |
setUpdateRect(Rectangle) | Sets the rectangle representing the area which needs to be repainted in response to this event.


 PaintEvent.PAINT

PaintEvent.PAINT

Syntax
public static final int PAINT
Description
The paint event type.


 PaintEvent.PAINT_FIRST

PaintEvent.PAINT_FIRST

Syntax
public static final int PAINT_FIRST
Description
Marks the first integer id for the range of paint event ids.


 PaintEvent.PAINT_LAST

PaintEvent.PAINT_LAST

Syntax
public static final int PAINT_LAST
Description
Marks the last integer id for the range of paint event ids.


 PaintEvent.UPDATE

PaintEvent.UPDATE

Syntax
public static final int UPDATE
Description
The update event type.


 PaintEvent.PaintEvent

PaintEvent.PaintEvent

Syntax
public PaintEvent( Component source, int id, Rectangle updateRect )
Parameters
source
the object where the event originated
Description
Constructs a PaintEvent object with the specified source component and type.


 PaintEvent.getUpdateRect

PaintEvent.getUpdateRect

Syntax
public Rectangle getUpdateRect()
Description
Returns the rectangle representing the area which needs to be repainted in response to this event.


 PaintEvent.paramString

PaintEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 PaintEvent.setUpdateRect

PaintEvent.setUpdateRect

Syntax
public void setUpdateRect( Rectangle updateRect )
Parameters
updateRect
the rectangle area which needs to be repainted
Description
Sets the rectangle representing the area which needs to be repainted in response to this event.


 Class TextEvent

Class java.awt.event.TextEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.TextEvent

public class TextEvent
extends AWTEvent

The text event emitted by TextComponents.

See Also:
TextComponent, TextEventListener


 TextEvent Members

TextEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
TEXT_FIRST | Marks the first integer id for the range of adjustment event ids.
TEXT_LAST | Marks the last integer id for the range of adjustment event ids.
TEXT_VALUE_CHANGED | The adjustment value changed event.

Constructors
Name | Description
TextEvent(Object, int) | Constructs a TextEvent object with the specified TextComponent source, and type.

Methods
Name | Description
paramString() |


 TextEvent.TEXT_FIRST

TextEvent.TEXT_FIRST

Syntax
public static final int TEXT_FIRST
Description
Marks the first integer id for the range of adjustment event ids.


 TextEvent.TEXT_LAST

TextEvent.TEXT_LAST

Syntax
public static final int TEXT_LAST
Description
Marks the last integer id for the range of adjustment event ids.


 TextEvent.TEXT_VALUE_CHANGED

TextEvent.TEXT_VALUE_CHANGED

Syntax
public static final int TEXT_VALUE_CHANGED
Description
The adjustment value changed event.


 TextEvent.TextEvent

TextEvent.TextEvent

Syntax
public TextEvent( Object source, int id )
Parameters
source
the TextComponent where the event originated
Description
Constructs a TextEvent object with the specified TextComponent source, and type.


 TextEvent.paramString

TextEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class AWTEvent


 Interface TextListener

Interface java.awt.event.TextListener

Interface Members | This Package | All Packages

public interface TextListener
extends EventListener

The listener interface for receiving adjustment events.


 TextListener Members

TextListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
textValueChanged(TextEvent) | Invoked when the value of the text has changed.


 TextListener.textValueChanged

TextListener.textValueChanged

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void textValueChanged( TextEvent e )
Description
Invoked when the value of the text has changed.


 Class WindowAdapter

Class java.awt.event.WindowAdapter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.event.WindowAdapter

public abstract class WindowAdapter
extends Object
implements WindowListener

The adapter which receives window events. The methods in this class are empty; this class is provided as a convenience for easily creating listeners by extending this class and overriding only the methods of interest.


 WindowAdapter Members

WindowAdapter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
WindowAdapter() |

Methods
Name | Description
windowActivated(WindowEvent) |
windowClosed(WindowEvent) |
windowClosing(WindowEvent) |
windowDeactivated(WindowEvent) |
windowDeiconified(WindowEvent) |
windowIconified(WindowEvent) |
windowOpened(WindowEvent) |


 WindowAdapter.WindowAdapter

WindowAdapter.WindowAdapter

Syntax
public WindowAdapter()


 WindowAdapter.windowActivated

WindowAdapter.windowActivated

Syntax
public void windowActivated( WindowEvent e )


 WindowAdapter.windowClosed

WindowAdapter.windowClosed

Syntax
public void windowClosed( WindowEvent e )


 WindowAdapter.windowClosing

WindowAdapter.windowClosing

Syntax
public void windowClosing( WindowEvent e )


 WindowAdapter.windowDeactivated

WindowAdapter.windowDeactivated

Syntax
public void windowDeactivated( WindowEvent e )


 WindowAdapter.windowDeiconified

WindowAdapter.windowDeiconified

Syntax
public void windowDeiconified( WindowEvent e )


 WindowAdapter.windowIconified

WindowAdapter.windowIconified

Syntax
public void windowIconified( WindowEvent e )


 WindowAdapter.windowOpened

WindowAdapter.windowOpened

Syntax
public void windowOpened( WindowEvent e )


 Class WindowEvent

Class java.awt.event.WindowEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.awt.AWTEvent
                   |
                   +----java.awt.event.ComponentEvent
                           |
                           +----java.awt.event.WindowEvent

public class WindowEvent
extends ComponentEvent

The window-level event.


 WindowEvent Members

WindowEvent Members

Class Overview | This Package | All Packages

Fields
Name | Description
WINDOW_ACTIVATED | The window activated event type.
WINDOW_CLOSED | The window closed event type.
WINDOW_CLOSING | The window closing event type.
WINDOW_DEACTIVATED | The window deactivated event type.
WINDOW_DEICONIFIED | The window deiconified event type.
WINDOW_FIRST | Marks the first integer id for the range of window event ids.
WINDOW_ICONIFIED | The window iconified event type.
WINDOW_LAST | Marks the last integer id for the range of window event ids.
WINDOW_OPENED | The window opened event type.

Constructors
Name | Description
WindowEvent(Window, int) | Constructs a WindowEvent object with the specified source window and type.

Methods
Name | Description
getWindow() | Returns the window where this event originated.
paramString() |


 WindowEvent.WINDOW_ACTIVATED

WindowEvent.WINDOW_ACTIVATED

Syntax
public static final int WINDOW_ACTIVATED
Description
The window activated event type.


 WindowEvent.WINDOW_CLOSED

WindowEvent.WINDOW_CLOSED

Syntax
public static final int WINDOW_CLOSED
Description
The window closed event type. This event is delivered after the window has been closed as the result of a call to hide or destroy.


 WindowEvent.WINDOW_CLOSING

WindowEvent.WINDOW_CLOSING

Syntax
public static final int WINDOW_CLOSING
Description
The window closing event type. This event is delivered when the user selects "Quit" from the window's system menu. If the program does not explicitly hide or destroy the window as a result of this event, the window close operation will be cancelled.


 WindowEvent.WINDOW_DEACTIVATED

WindowEvent.WINDOW_DEACTIVATED

Syntax
public static final int WINDOW_DEACTIVATED
Description
The window deactivated event type.


 WindowEvent.WINDOW_DEICONIFIED

WindowEvent.WINDOW_DEICONIFIED

Syntax
public static final int WINDOW_DEICONIFIED
Description
The window deiconified event type.


 WindowEvent.WINDOW_FIRST

WindowEvent.WINDOW_FIRST

Syntax
public static final int WINDOW_FIRST
Description
Marks the first integer id for the range of window event ids.


 WindowEvent.WINDOW_ICONIFIED

WindowEvent.WINDOW_ICONIFIED

Syntax
public static final int WINDOW_ICONIFIED
Description
The window iconified event type.


 WindowEvent.WINDOW_LAST

WindowEvent.WINDOW_LAST

Syntax
public static final int WINDOW_LAST
Description
Marks the last integer id for the range of window event ids.


 WindowEvent.WINDOW_OPENED

WindowEvent.WINDOW_OPENED

Syntax
public static final int WINDOW_OPENED
Description
The window opened event type. This event is delivered only the first time a window is made visible.


 WindowEvent.WindowEvent

WindowEvent.WindowEvent

Syntax
public WindowEvent( Window source, int id )
Parameters
source
the component where the event originated
Description
Constructs a WindowEvent object with the specified source window and type.


 WindowEvent.getWindow

WindowEvent.getWindow

Syntax
public Window getWindow()
Description
Returns the window where this event originated.


 WindowEvent.paramString

WindowEvent.paramString

Syntax
public String paramString()
Overrides
paramString in class ComponentEvent


 Interface WindowListener

Interface java.awt.event.WindowListener

Interface Members | This Package | All Packages

public interface WindowListener
extends EventListener

The listener interface for receiving window events.


 WindowListener Members

WindowListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
windowActivated(WindowEvent) | Invoked when a window is activated.
windowClosed(WindowEvent) | Invoked when a window has been closed.
windowClosing(WindowEvent) | Invoked when a window is in the process of being closed.
windowDeactivated(WindowEvent) | Invoked when a window is de-activated.
windowDeiconified(WindowEvent) | Invoked when a window is de-iconified.
windowIconified(WindowEvent) | Invoked when a window is iconified.
windowOpened(WindowEvent) | Invoked when a window has been opened.


 WindowListener.windowActivated

WindowListener.windowActivated

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowActivated( WindowEvent e )
Description
Invoked when a window is activated.


 WindowListener.windowClosed

WindowListener.windowClosed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowClosed( WindowEvent e )
Description
Invoked when a window has been closed.


 WindowListener.windowClosing

WindowListener.windowClosing

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowClosing( WindowEvent e )
Description
Invoked when a window is in the process of being closed. The close operation can be overridden at this point.


 WindowListener.windowDeactivated

WindowListener.windowDeactivated

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowDeactivated( WindowEvent e )
Description
Invoked when a window is de-activated.


 WindowListener.windowDeiconified

WindowListener.windowDeiconified

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowDeiconified( WindowEvent e )
Description
Invoked when a window is de-iconified.


 WindowListener.windowIconified

WindowListener.windowIconified

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowIconified( WindowEvent e )
Description
Invoked when a window is iconified.


 WindowListener.windowOpened

WindowListener.windowOpened

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void windowOpened( WindowEvent e )
Description
Invoked when a window has been opened.


 Package java.awt.image

Package java.awt.image

All Packages

Interfaces

  • ImageConsumer
  • ImageObserver
  • ImageProducer

    • Classes

  • AreaAveragingScaleFilter
  • ColorModel
  • CropImageFilter
  • DirectColorModel
  • FilteredImageSource
  • ImageFilter
  • IndexColorModel
  • MemoryImageSource
  • PixelGrabber
  • RGBImageFilter
  • ReplicateScaleFilter


 Class AreaAveragingScaleFilter

Class java.awt.image.AreaAveragingScaleFilter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ImageFilter
           |
           +----java.awt.image.ReplicateScaleFilter
                   |
                   +----java.awt.image.AreaAveragingScaleFilter

public class AreaAveragingScaleFilter
extends ReplicateScaleFilter

An ImageFilter class for scaling images using a simple area averaging algorithm that produces smoother results than the nearest neighbor algorithm. This class extends the basic ImageFilter Class to scale an existing image and provide a source for a new image containing the resampled image. The pixels in the source image are blended to produce pixels for an image of the specified size. The blending process is analogous to scaling up the source image to a multiple of the destination size using pixel replication and then scaling it back down to the destination size by simply averaging all the pixels in the supersized image that fall within a given pixel of the destination image. If the data from the source is not delivered in TopDownLeftRight order then the filter will back off to a simple pixel replication behavior and utilize the requestTopDownLeftRightResend() method to refilter the pixels in a better way at the end. It is meant to be used in conjunction with a FilteredImageSource object to produce scaled versions of existing images.

See Also:
FilteredImageSource, ReplicateImageFilter, ImageFilter


 AreaAveragingScaleFilter Members

AreaAveragingScaleFilter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
AreaAveragingScaleFilter(int, int) | Constructs an AreaAveragingScaleFilter that scales the pixels from its source Image as specified by the width and height parameters.

Methods
Name | Description
setHints(int) | Detect if the data is being delivered with the necessary hints to allow the averaging algorithm to do its work.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | Combine the components for the delivered byte pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete.
setPixels(int, int, int, int, ColorModel, int[], int, int) | Combine the components for the delivered int pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete.


 AreaAveragingScaleFilter.AreaAveragingScaleFilter

AreaAveragingScaleFilter.AreaAveragingScaleFilter

Syntax
public AreaAveragingScaleFilter( int width, int height )
Parameters
width
the target width to scale the image
height
the target height to scale the image
Description
Constructs an AreaAveragingScaleFilter that scales the pixels from its source Image as specified by the width and height parameters.


 AreaAveragingScaleFilter.setHints

AreaAveragingScaleFilter.setHints

Syntax
public void setHints( int hints )
Description
Detect if the data is being delivered with the necessary hints to allow the averaging algorithm to do its work.

Overrides
setHints in class ImageFilter
See Also
setHints


 AreaAveragingScaleFilter.setPixels

AreaAveragingScaleFilter.setPixels

Syntax 1
public void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
Combine the components for the delivered byte pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete. If the correct hints were not specified in the setHints call then relay the work to our superclass which is capable of scaling pixels regardless of the delivery hints.

Overrides
setPixels in class ReplicateScaleFilter
See Also
ReplicateScaleFilter

Syntax 2
public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
Combine the components for the delivered int pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete. If the correct hints were not specified in the setHints call then relay the work to our superclass which is capable of scaling pixels regardless of the delivery hints.

Overrides
setPixels in class ReplicateScaleFilter
See Also
ReplicateScaleFilter


 Class ColorModel

Class java.awt.image.ColorModel

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ColorModel

public abstract class ColorModel
extends Object

A class that encapsulates the methods for translating from pixel values to alpha, red, green, and blue color components for an image. This class is abstract.

See Also:
IndexColorModel, DirectColorModel


 ColorModel Members

ColorModel Members

Class Overview | This Package | All Packages

Fields
Name | Description
pixel_bits |

Constructors
Name | Description
ColorModel(int) | Constructs a ColorModel which describes a pixel of the specified number of bits.

Methods
Name | Description
finalize() | Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
getAlpha(int) | The subclass must provide a function which provides the alpha color compoment for the specified pixel.
getBlue(int) | The subclass must provide a function which provides the blue color compoment for the specified pixel.
getGreen(int) | The subclass must provide a function which provides the green color compoment for the specified pixel.
getPixelSize() | Returns the number of bits per pixel described by this ColorModel.
getRed(int) | The subclass must provide a function which provides the red color compoment for the specified pixel.
getRGB(int) | Returns the color of the pixel in the default RGB color model.
getRGBdefault() | Return a ColorModel which describes the default format for integer RGB values used throughout the AWT image interfaces.


 ColorModel.pixel_bits

ColorModel.pixel_bits

Syntax
protected int pixel_bits


 ColorModel.ColorModel

ColorModel.ColorModel

Syntax
public ColorModel( int bits )
Description
Constructs a ColorModel which describes a pixel of the specified number of bits.


 ColorModel.finalize

ColorModel.finalize

Syntax
public void finalize()
Description
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Overrides
finalize in class Object


 ColorModel.getAlpha

ColorModel.getAlpha

Syntax
public abstract int getAlpha( int pixel )
Returns
The alpha transparency value ranging from 0 to 255
Description
The subclass must provide a function which provides the alpha color compoment for the specified pixel.


 ColorModel.getBlue

ColorModel.getBlue

Syntax
public abstract int getBlue( int pixel )
Returns
The blue color component ranging from 0 to 255
Description
The subclass must provide a function which provides the blue color compoment for the specified pixel.


 ColorModel.getGreen

ColorModel.getGreen

Syntax
public abstract int getGreen( int pixel )
Returns
The green color component ranging from 0 to 255
Description
The subclass must provide a function which provides the green color compoment for the specified pixel.


 ColorModel.getPixelSize

ColorModel.getPixelSize

Syntax
public int getPixelSize()
Description
Returns the number of bits per pixel described by this ColorModel.


 ColorModel.getRed

ColorModel.getRed

Syntax
public abstract int getRed( int pixel )
Returns
The red color component ranging from 0 to 255
Description
The subclass must provide a function which provides the red color compoment for the specified pixel.


 ColorModel.getRGB

ColorModel.getRGB

Syntax
public int getRGB( int pixel )
Description
Returns the color of the pixel in the default RGB color model.

See Also
getRGBdefault


 ColorModel.getRGBdefault

ColorModel.getRGBdefault

Syntax
public static ColorModel getRGBdefault()
Description
Return a ColorModel which describes the default format for integer RGB values used throughout the AWT image interfaces. The format for the RGB values is an integer with 8 bits each of alpha, red, green, and blue color components ordered correspondingly from the most significant byte to the least significant byte, as in: 0xAARRGGBB


 Class CropImageFilter

Class java.awt.image.CropImageFilter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ImageFilter
           |
           +----java.awt.image.CropImageFilter

public class CropImageFilter
extends ImageFilter

An ImageFilter class for cropping images. This class extends the basic ImageFilter Class to extract a given rectangular region of an existing Image and provide a source for a new image containing just the extracted region. It is meant to be used in conjunction with a FilteredImageSource object to produce cropped versions of existing images.

See Also:
FilteredImageSource, ImageFilter


 CropImageFilter Members

CropImageFilter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CropImageFilter(int, int, int, int) | Constructs a CropImageFilter that extracts the absolute rectangular region of pixels from its source Image as specified by the x, y, w, and h parameters.

Methods
Name | Description
setDimensions(int, int) | Override the source image's dimensions and pass the dimensions of the rectangular cropped region to the ImageConsumer.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | Determine whether the delivered byte pixels intersect the region to be extracted and passes through only that subset of pixels that appear in the output region.
setPixels(int, int, int, int, ColorModel, int[], int, int) | Determine if the delivered int pixels intersect the region to be extracted and pass through only that subset of pixels that appear in the output region.
setProperties(Hashtable) | Passes along the properties from the source object after adding a property indicating the cropped region.


 CropImageFilter.CropImageFilter

CropImageFilter.CropImageFilter

Syntax
public CropImageFilter( int x, int y, int w, int h )
Parameters
x
the x location of the top of the rectangle to be extracted
y
the y location of the top of the rectangle to be extracted
w
the width of the rectangle to be extracted
h
the height of the rectangle to be extracted
Description
Constructs a CropImageFilter that extracts the absolute rectangular region of pixels from its source Image as specified by the x, y, w, and h parameters.


 CropImageFilter.setDimensions

CropImageFilter.setDimensions

Syntax
public void setDimensions( int w, int h )
Description
Override the source image's dimensions and pass the dimensions of the rectangular cropped region to the ImageConsumer.

Overrides
setDimensions in class ImageFilter
See Also
ImageConsumer


 CropImageFilter.setPixels

CropImageFilter.setPixels

Syntax 1
public void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
Determine whether the delivered byte pixels intersect the region to be extracted and passes through only that subset of pixels that appear in the output region.

Overrides
setPixels in class ImageFilter

Syntax 2
public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
Determine if the delivered int pixels intersect the region to be extracted and pass through only that subset of pixels that appear in the output region.

Overrides
setPixels in class ImageFilter


 CropImageFilter.setProperties

CropImageFilter.setProperties

Syntax
public void setProperties( Hashtable props )
Description
Passes along the properties from the source object after adding a property indicating the cropped region.

Overrides
setProperties in class ImageFilter


 Class DirectColorModel

Class java.awt.image.DirectColorModel

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ColorModel
           |
           +----java.awt.image.DirectColorModel

public class DirectColorModel
extends ColorModel

A ColorModel class that specifies a translation from pixel values to alpha, red, green, and blue color components for pixels which have the color components embedded directly in the bits of the pixel itself. This color model is similar to an X11 TrueColor visual.

Many of the methods in this class are final. This is because the underlying native graphics code makes assumptions about the layout and operation of this class and those assumptions are reflected in the implementations of the methods here that are marked final. You can subclass this class for other reaons, but you cannot override or modify the behaviour of those methods.

See Also:
ColorModel


 DirectColorModel Members

DirectColorModel Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DirectColorModel(int, int, int, int) | Constructs a DirectColorModel from the given masks specifying which bits in the pixel contain the red, green and blue color components.
DirectColorModel(int, int, int, int, int) | Constructs a DirectColorModel from the given masks specifying which bits in the pixel contain the alhpa, red, green and blue color components.

Methods
Name | Description
getAlpha(int) | Return the alpha transparency value for the specified pixel in the range 0-255.
getAlphaMask() | Returns the mask indicating which bits in a pixel contain the alpha transparency component.
getBlue(int) | Returns the blue color compoment for the specified pixel in the range 0-255.
getBlueMask() | Returns the mask indicating which bits in a pixel contain the blue color component.
getGreen(int) | Returns the green color compoment for the specified pixel in the range 0-255.
getGreenMask() | Returns the mask indicating which bits in a pixel contain the green color component.
getRed(int) | Returns the red color compoment for the specified pixel in the range 0-255.
getRedMask() | Returns the mask indicating which bits in a pixel contain the red color component.
getRGB(int) | Returns the color of the pixel in the default RGB color model.


 DirectColorModel.DirectColorModel

DirectColorModel.DirectColorModel

Syntax 1
public DirectColorModel( int bits, int rmask, int gmask, int bmask )
Description
Constructs a DirectColorModel from the given masks specifying which bits in the pixel contain the red, green and blue color components. Pixels described by this color model will all have alpha components of 255 (fully opaque). All of the bits in each mask must be contiguous and fit in the specified number of least significant bits of the integer.

Syntax 2
public DirectColorModel( int bits, int rmask, int gmask, int bmask, int amask )
Description
Constructs a DirectColorModel from the given masks specifying which bits in the pixel contain the alhpa, red, green and blue color components. All of the bits in each mask must be contiguous and fit in the specified number of least significant bits of the integer.


 DirectColorModel.getAlpha

DirectColorModel.getAlpha

Syntax
public final int getAlpha( int pixel )
Description
Return the alpha transparency value for the specified pixel in the range 0-255.

Overrides
getAlpha in class ColorModel


 DirectColorModel.getAlphaMask

DirectColorModel.getAlphaMask

Syntax
public final int getAlphaMask()
Description
Returns the mask indicating which bits in a pixel contain the alpha transparency component.


 DirectColorModel.getBlue

DirectColorModel.getBlue

Syntax
public final int getBlue( int pixel )
Description
Returns the blue color compoment for the specified pixel in the range 0-255.

Overrides
getBlue in class ColorModel


 DirectColorModel.getBlueMask

DirectColorModel.getBlueMask

Syntax
public final int getBlueMask()
Description
Returns the mask indicating which bits in a pixel contain the blue color component.


 DirectColorModel.getGreen

DirectColorModel.getGreen

Syntax
public final int getGreen( int pixel )
Description
Returns the green color compoment for the specified pixel in the range 0-255.

Overrides
getGreen in class ColorModel


 DirectColorModel.getGreenMask

DirectColorModel.getGreenMask

Syntax
public final int getGreenMask()
Description
Returns the mask indicating which bits in a pixel contain the green color component.


 DirectColorModel.getRed

DirectColorModel.getRed

Syntax
public final int getRed( int pixel )
Description
Returns the red color compoment for the specified pixel in the range 0-255.

Overrides
getRed in class ColorModel


 DirectColorModel.getRedMask

DirectColorModel.getRedMask

Syntax
public final int getRedMask()
Description
Returns the mask indicating which bits in a pixel contain the red color component.


 DirectColorModel.getRGB

DirectColorModel.getRGB

Syntax
public final int getRGB( int pixel )
Description
Returns the color of the pixel in the default RGB color model.

Overrides
getRGB in class ColorModel
See Also
getRGBdefault


 Class FilteredImageSource

Class java.awt.image.FilteredImageSource

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.FilteredImageSource

public class FilteredImageSource
extends Object
implements ImageProducer

This class is an implementation of the ImageProducer interface which takes an existing image and a filter object and uses them to produce image data for a new filtered version of the original image. Here is an example which filters an image by swapping the red and blue compents:

    Image src = getImage("doc:///demo/images/duke/T1.gif");
    ImageFilter colorfilter = new RedBlueSwapFilter();
    Image img = createImage(new FilteredImageSource(src.getSource(),
                            colorfilter));

See Also:
ImageProducer


 FilteredImageSource Members

FilteredImageSource Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FilteredImageSource(ImageProducer, ImageFilter) | Constructs an ImageProducer object from an existing ImageProducer and a filter object.

Methods
Name | Description
addConsumer(ImageConsumer) | Adds an ImageConsumer to the list of consumers interested in data for this image.
isConsumer(ImageConsumer) | Determines whether an ImageConsumer is on the list of consumers currently interested in data for this image.
removeConsumer(ImageConsumer) | Removes an ImageConsumer from the list of consumers interested in data for this image.
requestTopDownLeftRightResend(ImageConsumer) | Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.
startProduction(ImageConsumer) | Adds an ImageConsumer to the list of consumers interested in data for this image, and immediately starts delivery of the image data through the ImageConsumer interface.


 FilteredImageSource.FilteredImageSource

FilteredImageSource.FilteredImageSource

Syntax
public FilteredImageSource( ImageProducer orig, ImageFilter imgf )
Description
Constructs an ImageProducer object from an existing ImageProducer and a filter object.

See Also
ImageFilter, createImage


 FilteredImageSource.addConsumer

FilteredImageSource.addConsumer

Syntax
public synchronized void addConsumer( ImageConsumer ic )
Description
Adds an ImageConsumer to the list of consumers interested in data for this image.

See Also
ImageConsumer


 FilteredImageSource.isConsumer

FilteredImageSource.isConsumer

Syntax
public synchronized boolean isConsumer( ImageConsumer ic )
Returns
true if the ImageConsumer is on the list; false otherwise
Description
Determines whether an ImageConsumer is on the list of consumers currently interested in data for this image.

See Also
ImageConsumer


 FilteredImageSource.removeConsumer

FilteredImageSource.removeConsumer

Syntax
public synchronized void removeConsumer( ImageConsumer ic )
Description
Removes an ImageConsumer from the list of consumers interested in data for this image.

See Also
ImageConsumer


 FilteredImageSource.requestTopDownLeftRightResend

FilteredImageSource.requestTopDownLeftRightResend

Syntax
public void requestTopDownLeftRightResend( ImageConsumer ic )
Description
Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order. The request is handed to the ImageFilter for further processing, since the ability to preserve the pixel ordering depends on the filter.

See Also
ImageConsumer


 FilteredImageSource.startProduction

FilteredImageSource.startProduction

Syntax
public void startProduction( ImageConsumer ic )
Description
Adds an ImageConsumer to the list of consumers interested in data for this image, and immediately starts delivery of the image data through the ImageConsumer interface.

See Also
ImageConsumer


 Interface ImageConsumer

Interface java.awt.image.ImageConsumer

Interface Members | This Package | All Packages

public interface ImageConsumer

The interface for objects expressing interest in image data through the ImageProducer interfaces. When a consumer is added to an image producer, the producer delivers all of the data about the image using the method calls defined in this interface.

See Also:
ImageProducer


 ImageConsumer Members

ImageConsumer Members

Interface Overview | This Package | All Packages

Fields
Name | Description
COMPLETESCANLINES | The pixels will be delivered in (multiples of) complete scanlines at a time.
IMAGEABORTED | The image creation process was deliberately aborted.
IMAGEERROR | An error was encountered while producing the image.
RANDOMPIXELORDER | The pixels will be delivered in a random order.
SINGLEFRAME | The image contain a single static image.
SINGLEFRAMEDONE | One frame of the image is complete but there are more frames to be delivered.
SINGLEPASS | The pixels will be delivered in a single pass.
STATICIMAGEDONE | The image is complete and there are no more pixels or frames to be delivered.
TOPDOWNLEFTRIGHT | The pixels will be delivered in top-down, left-to-right order.

Methods
Name | Description
imageComplete(int) | The imageComplete method is called when the ImageProducer is finished delivering all of the pixels that the source image contains, or when a single frame of a multi-frame animation has been completed, or when an error in loading or producing the image has occured.
setColorModel(ColorModel) | The ColorModel object used for the majority of the pixels reported using the setPixels method calls.
setDimensions(int, int) | The dimensions of the source image are reported using the setDimensions method call.
setHints(int) | The ImageProducer can deliver the pixels in any order, but the ImageConsumer may be able to scale or convert the pixels to the destination ColorModel more efficiently or with higher quality if it knows some information about how the pixels will be delivered up front.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | The pixels of the image are delivered using one or more calls to the setPixels method.
setPixels(int, int, int, int, ColorModel, int[], int, int) | The pixels of the image are delivered using one or more calls to the setPixels method.
setProperties(Hashtable) | Sets the extensible list of properties associated with this image.


 ImageConsumer.COMPLETESCANLINES

ImageConsumer.COMPLETESCANLINES

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int COMPLETESCANLINES
Description
The pixels will be delivered in (multiples of) complete scanlines at a time.

See Also
setHints


 ImageConsumer.IMAGEABORTED

ImageConsumer.IMAGEABORTED

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int IMAGEABORTED
Description
The image creation process was deliberately aborted.

See Also
imageComplete


 ImageConsumer.IMAGEERROR

ImageConsumer.IMAGEERROR

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int IMAGEERROR
Description
An error was encountered while producing the image.

See Also
imageComplete


 ImageConsumer.RANDOMPIXELORDER

ImageConsumer.RANDOMPIXELORDER

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int RANDOMPIXELORDER
Description
The pixels will be delivered in a random order. This tells the ImageConsumer not to use any optimizations that depend on the order of pixel delivery, which should be the default assumption in the absence of any call to the setHints method.

See Also
setHints


 ImageConsumer.SINGLEFRAME

ImageConsumer.SINGLEFRAME

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int SINGLEFRAME
Description
The image contain a single static image. The pixels will be defined in calls to the setPixels methods and then the imageComplete method will be called with the STATICIMAGEDONE flag after which no more image data will be delivered. An example of an image type which would not meet these criteria would be the output of a video feed, or the representation of a 3D rendering being manipulated by the user. The end of each frame in those types of images will be indicated by calling imageComplete with the SINGLEFRAMEDONE flag.

See Also
setHints, imageComplete


 ImageConsumer.SINGLEFRAMEDONE

ImageConsumer.SINGLEFRAMEDONE

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int SINGLEFRAMEDONE
Description
One frame of the image is complete but there are more frames to be delivered.

See Also
imageComplete


 ImageConsumer.SINGLEPASS

ImageConsumer.SINGLEPASS

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int SINGLEPASS
Description
The pixels will be delivered in a single pass. Each pixel will appear in only one call to any of the setPixels methods. An example of an image format which does not meet this criterion is a progressive JPEG image which defines pixels in multiple passes, each more refined than the previous.

See Also
setHints


 ImageConsumer.STATICIMAGEDONE

ImageConsumer.STATICIMAGEDONE

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int STATICIMAGEDONE
Description
The image is complete and there are no more pixels or frames to be delivered.

See Also
imageComplete


 ImageConsumer.TOPDOWNLEFTRIGHT

ImageConsumer.TOPDOWNLEFTRIGHT

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TOPDOWNLEFTRIGHT
Description
The pixels will be delivered in top-down, left-to-right order.

See Also
setHints


 ImageConsumer.imageComplete

ImageConsumer.imageComplete

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void imageComplete( int status )
Description
The imageComplete method is called when the ImageProducer is finished delivering all of the pixels that the source image contains, or when a single frame of a multi-frame animation has been completed, or when an error in loading or producing the image has occured. The ImageConsumer should remove itself from the list of consumers registered with the ImageProducer at this time, unless it is interested in successive frames.

See Also
removeConsumer


 ImageConsumer.setColorModel

ImageConsumer.setColorModel

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setColorModel( ColorModel model )
Description
The ColorModel object used for the majority of the pixels reported using the setPixels method calls. Note that each set of pixels delivered using setPixels contains its own ColorModel object, so no assumption should be made that this model will be the only one used in delivering pixel values. A notable case where multiple ColorModel objects may be seen is a filtered image when for each set of pixels that it filters, the filter determines whether the pixels can be sent on untouched, using the original ColorModel, or whether the pixels should be modified (filtered) and passed on using a ColorModel more convenient for the filtering process.

See Also
ColorModel


 ImageConsumer.setDimensions

ImageConsumer.setDimensions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setDimensions( int width, int height )
Description
The dimensions of the source image are reported using the setDimensions method call.


 ImageConsumer.setHints

ImageConsumer.setHints

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setHints( int hintflags )
Description
The ImageProducer can deliver the pixels in any order, but the ImageConsumer may be able to scale or convert the pixels to the destination ColorModel more efficiently or with higher quality if it knows some information about how the pixels will be delivered up front. The setHints method should be called before any calls to any of the setPixels methods with a bit mask of hints about the manner in which the pixels will be delivered. If the ImageProducer does not follow the guidelines for the indicated hint, the results are undefined.


 ImageConsumer.setPixels

ImageConsumer.setPixels

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
The pixels of the image are delivered using one or more calls to the setPixels method. Each call specifies the location and size of the rectangle of source pixels that are contained in the array of pixels. The specified ColorModel object should be used to convert the pixels into their corresponding color and alpha components. Pixel (m,n) is stored in the pixels array at index (n * scansize + m + off). The pixels delivered using this method are all stored as bytes.

See Also
ColorModel

Syntax 2
public abstract void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
The pixels of the image are delivered using one or more calls to the setPixels method. Each call specifies the location and size of the rectangle of source pixels that are contained in the array of pixels. The specified ColorModel object should be used to convert the pixels into their corresponding color and alpha components. Pixel (m,n) is stored in the pixels array at index (n * scansize + m + off). The pixels delivered using this method are all stored as ints.

See Also
ColorModel


 ImageConsumer.setProperties

ImageConsumer.setProperties

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setProperties( Hashtable props )
Description
Sets the extensible list of properties associated with this image.


 Class ImageFilter

Class java.awt.image.ImageFilter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ImageFilter

public class ImageFilter
extends Object
implements ImageConsumer, Cloneable

This class implements a filter for the set of interface methods that are used to deliver data from an ImageProducer to an ImageConsumer. It is meant to be used in conjunction with a FilteredImageSource object to produce filtered versions of existing images. It is a base class that provides the calls needed to implement a "Null filter" which has no effect on the data being passed through. Filters should subclass this class and override the methods which deal with the data that needs to be filtered and modify it as necessary.

See Also:
FilteredImageSource, ImageConsumer


 ImageFilter Members

ImageFilter Members

Class Overview | This Package | All Packages

Fields
Name | Description
consumer | The consumer of the particular image data stream for which this instance of the ImageFilter is filtering data.

Constructors
Name | Description
ImageFilter() |

Methods
Name | Description
clone() | Clones this object.
getFilterInstance(ImageConsumer) | Returns a unique instance of an ImageFilter object which will actually perform the filtering for the specified ImageConsumer.
imageComplete(int) | Filters the information provided in the imageComplete method of the ImageConsumer interface.
resendTopDownLeftRight(ImageProducer) | Responds to a request for a TopDownLeftRight (TDLR) ordered resend of the pixel data from an ImageConsumer.
setColorModel(ColorModel) | Filter the information provided in the setColorModel method of the ImageConsumer interface.
setDimensions(int, int) | Filters the information provided in the setDimensions method of the ImageConsumer interface.
setHints(int) | Filters the information provided in the setHints method of the ImageConsumer interface.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of bytes.
setPixels(int, int, int, int, ColorModel, int[], int, int) | Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of integers.
setProperties(Hashtable) | Passes the properties from the source object along after adding a property indicating the stream of filters it has been run through.


 ImageFilter.consumer

ImageFilter.consumer

Syntax
protected ImageConsumer consumer
Description
The consumer of the particular image data stream for which this instance of the ImageFilter is filtering data. It is not initialized during the constructor, but rather during the getFilterInstance() method call when the FilteredImageSource is creating a unique instance of this object for a particular image data stream.

See Also
getFilterInstance, ImageConsumer


 ImageFilter.ImageFilter

ImageFilter.ImageFilter

Syntax
public ImageFilter()


 ImageFilter.clone

ImageFilter.clone

Syntax
public Object clone()
Description
Clones this object.

Overrides
clone in class Object


 ImageFilter.getFilterInstance

ImageFilter.getFilterInstance

Syntax
public ImageFilter getFilterInstance( ImageConsumer ic )
Description
Returns a unique instance of an ImageFilter object which will actually perform the filtering for the specified ImageConsumer. The default implementation just clones this object.


 ImageFilter.imageComplete

ImageFilter.imageComplete

Syntax
public void imageComplete( int status )
Description
Filters the information provided in the imageComplete method of the ImageConsumer interface.

See Also
imageComplete


 ImageFilter.resendTopDownLeftRight

ImageFilter.resendTopDownLeftRight

Syntax
public void resendTopDownLeftRight( ImageProducer ip )
Parameters
ip
The ImageProducer that is feeding this instance of the filter - also the ImageProducer that the request should be forwarded to if necessary.
Description
Responds to a request for a TopDownLeftRight (TDLR) ordered resend of the pixel data from an ImageConsumer. The ImageFilter can respond to this request in one of three ways.
  1. If the filter can determine that it will forward the pixels in TDLR order if its upstream producer object sends them in TDLR order, then the request is automatically forwarded by default to the indicated ImageProducer using this filter as the requesting ImageConsumer, so no override is necessary.
  2. If the filter can resend the pixels in the right order on its own (presumably because the generated pixels have been saved in some sort of buffer), then it can override this method and simply resend the pixels in TDLR order as specified in the ImageProducer API.
  3. If the filter simply returns from this method then the request will be ignored and no resend will occur.

See Also
requestTopDownLeftRightResend


 ImageFilter.setColorModel

ImageFilter.setColorModel

Syntax
public void setColorModel( ColorModel model )
Description
Filter the information provided in the setColorModel method of the ImageConsumer interface.

See Also
setColorModel


 ImageFilter.setDimensions

ImageFilter.setDimensions

Syntax
public void setDimensions( int width, int height )
Description
Filters the information provided in the setDimensions method of the ImageConsumer interface.

See Also
setDimensions


 ImageFilter.setHints

ImageFilter.setHints

Syntax
public void setHints( int hints )
Description
Filters the information provided in the setHints method of the ImageConsumer interface.

See Also
setHints


 ImageFilter.setPixels

ImageFilter.setPixels

Syntax 1
public void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of bytes.

See Also
setPixels

Syntax 2
public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of integers.

See Also
setPixels


 ImageFilter.setProperties

ImageFilter.setProperties

Syntax
public void setProperties( Hashtable props )
Description
Passes the properties from the source object along after adding a property indicating the stream of filters it has been run through.


 Interface ImageObserver

Interface java.awt.image.ImageObserver

Interface Members | This Package | All Packages

public interface ImageObserver

An asynchronous update interface for receiving notifications about Image information as the Image is constructed.


 ImageObserver Members

ImageObserver Members

Interface Overview | This Package | All Packages

Fields
Name | Description
ABORT | An image which was being tracked asynchronously was aborted before production was complete.
ALLBITS | A static image which was previously drawn is now complete and can be drawn again in its final form.
ERROR | An image which was being tracked asynchronously has encountered an error.
FRAMEBITS | Another complete frame of a multi-frame image which was previously drawn is now available to be drawn again.
HEIGHT | The height of the base image is now available and can be taken from the height argument to the imageUpdate callback method.
PROPERTIES | The properties of the image are now available.
SOMEBITS | More pixels needed for drawing a scaled variation of the image are available.
WIDTH | The width of the base image is now available and can be taken from the width argument to the imageUpdate callback method.

Methods
Name | Description
imageUpdate(Image, int, int, int, int, int) | This method is called when information about an image which was previously requested using an asynchronous interface becomes available.


 ImageObserver.ABORT

ImageObserver.ABORT

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ABORT
Description
An image which was being tracked asynchronously was aborted before production was complete. No more information will become available without further action to trigger another image production sequence. If the ERROR flag was not also set in this image update, then accessing any of the data in the image will restart the production again, probably from the beginning.

See Also
imageUpdate


 ImageObserver.ALLBITS

ImageObserver.ALLBITS

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ALLBITS
Description
A static image which was previously drawn is now complete and can be drawn again in its final form. The x, y, width, and height arguments to the imageUpdate callback method should be ignored.

See Also
drawImage, imageUpdate


 ImageObserver.ERROR

ImageObserver.ERROR

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ERROR
Description
An image which was being tracked asynchronously has encountered an error. No further information will become available and drawing the image will fail. As a convenience, the ABORT flag will be indicated at the same time to indicate that the image production was aborted.

See Also
imageUpdate


 ImageObserver.FRAMEBITS

ImageObserver.FRAMEBITS

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int FRAMEBITS
Description
Another complete frame of a multi-frame image which was previously drawn is now available to be drawn again. The x, y, width, and height arguments to the imageUpdate callback method should be ignored.

See Also
drawImage, imageUpdate


 ImageObserver.HEIGHT

ImageObserver.HEIGHT

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int HEIGHT
Description
The height of the base image is now available and can be taken from the height argument to the imageUpdate callback method.

See Also
getHeight, imageUpdate


 ImageObserver.PROPERTIES

ImageObserver.PROPERTIES

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int PROPERTIES
Description
The properties of the image are now available.

See Also
getProperty, imageUpdate


 ImageObserver.SOMEBITS

ImageObserver.SOMEBITS

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int SOMEBITS
Description
More pixels needed for drawing a scaled variation of the image are available. The bounding box of the new pixels can be taken from the x, y, width, and height arguments to the imageUpdate callback method.

See Also
drawImage, imageUpdate


 ImageObserver.WIDTH

ImageObserver.WIDTH

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int WIDTH
Description
The width of the base image is now available and can be taken from the width argument to the imageUpdate callback method.

See Also
getWidth, imageUpdate


 ImageObserver.imageUpdate

ImageObserver.imageUpdate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean imageUpdate( Image img, int infoflags, int x, int y, int width, int height )
Description
This method is called when information about an image which was previously requested using an asynchronous interface becomes available. Asynchronous interfaces are method calls such as getWidth(ImageObserver) and drawImage(img, x, y, ImageObserver) which take an ImageObserver object as an argument. Those methods register the caller as interested either in information about the overall image itself (in the case of getWidth(ImageObserver)) or about an output version of an image (in the case of the drawImage(img, x, y, [w, h,] ImageObserver) call).

This method should return true if further updates are needed or false if the required information has been acquired. The image which was being tracked is passed in using the img argument. Various constants are combined to form the infoflags argument which indicates what information about the image is now available. The interpretation of the x, y, width, and height arguments depends on the contents of the infoflags argument.

See Also
getWidth, getHeight, drawImage


 Interface ImageProducer

Interface java.awt.image.ImageProducer

Interface Members | This Package | All Packages

public interface ImageProducer

The interface for objects which can produce the image data for Images. Each image contains an ImageProducer which is used to reconstruct the image whenever it is needed, for example, when a new size of the Image is scaled, or when the width or height of the Image is being requested.

See Also:
ImageConsumer


 ImageProducer Members

ImageProducer Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addConsumer(ImageConsumer) | This method is used to register an ImageConsumer with the ImageProducer for access to the image data during a later reconstruction of the Image.
isConsumer(ImageConsumer) | This method determines if a given ImageConsumer object is currently registered with this ImageProducer as one of its consumers.
removeConsumer(ImageConsumer) | This method removes the given ImageConsumer object from the list of consumers currently registered to receive image data.
requestTopDownLeftRightResend(ImageConsumer) | This method is used by an ImageConsumer to request that the ImageProducer attempt to resend the image data one more time in TOPDOWNLEFTRIGHT order so that higher quality conversion algorithms which depend on receiving pixels in order can be used to produce a better output version of the image.
startProduction(ImageConsumer) | This method both registers the given ImageConsumer object as a consumer and starts an immediate reconstruction of the image data which will then be delivered to this consumer and any other consumer which may have already been registered with the producer.


 ImageProducer.addConsumer

ImageProducer.addConsumer

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addConsumer( ImageConsumer ic )
Description
This method is used to register an ImageConsumer with the ImageProducer for access to the image data during a later reconstruction of the Image. The ImageProducer may, at its discretion, start delivering the image data to the consumer using the ImageConsumer interface immediately, or when the next available image reconstruction is triggered by a call to the startProduction method.

See Also
startProduction


 ImageProducer.isConsumer

ImageProducer.isConsumer

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isConsumer( ImageConsumer ic )
Description
This method determines if a given ImageConsumer object is currently registered with this ImageProducer as one of its consumers.


 ImageProducer.removeConsumer

ImageProducer.removeConsumer

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removeConsumer( ImageConsumer ic )
Description
This method removes the given ImageConsumer object from the list of consumers currently registered to receive image data. It is not considered an error to remove a consumer that is not currently registered. The ImageProducer should stop sending data to this consumer as soon as is feasible.


 ImageProducer.requestTopDownLeftRightResend

ImageProducer.requestTopDownLeftRightResend

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void requestTopDownLeftRightResend( ImageConsumer ic )
Description
This method is used by an ImageConsumer to request that the ImageProducer attempt to resend the image data one more time in TOPDOWNLEFTRIGHT order so that higher quality conversion algorithms which depend on receiving pixels in order can be used to produce a better output version of the image. The ImageProducer is free to ignore this call if it cannot resend the data in that order. If the data can be resent, then the ImageProducer should respond by executing the following minimum set of ImageConsumer method calls:
    ic.setHints(TOPDOWNLEFTRIGHT | < otherhints >);
    ic.setPixels(...);	// As many times as needed
    ic.imageComplete();

See Also
setHints


 ImageProducer.startProduction

ImageProducer.startProduction

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void startProduction( ImageConsumer ic )
Description
This method both registers the given ImageConsumer object as a consumer and starts an immediate reconstruction of the image data which will then be delivered to this consumer and any other consumer which may have already been registered with the producer. This method differs from the addConsumer method in that a reproduction of the image data should be triggered as soon as possible.

See Also
addConsumer


 Class IndexColorModel

Class java.awt.image.IndexColorModel

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ColorModel
           |
           +----java.awt.image.IndexColorModel

public class IndexColorModel
extends ColorModel

A ColorModel class that specifies a translation from pixel values to alpha, red, green, and blue color components for pixels which represent indices into a fixed colormap. An optional transparent pixel value can be supplied which indicates a completely transparent pixel, regardless of any alpha value recorded for that pixel value. This color model is similar to an X11 PseudoColor visual.

Many of the methods in this class are final. The reason for this is that the underlying native graphics code makes assumptions about the layout and operation of this class and those assumptions are reflected in the implementations of the methods here that are marked final. You can subclass this class for other reaons, but you cannot override or modify the behaviour of those methods.

See Also:
ColorModel


 IndexColorModel Members

IndexColorModel Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IndexColorModel(int, int, byte[], byte[], byte[]) | Constructs an IndexColorModel from the given arrays of red, green, and blue components.
IndexColorModel(int, int, byte[], byte[], byte[], byte[]) | Constructs an IndexColorModel from the given arrays of red, green, blue and alpha components.
IndexColorModel(int, int, byte[], byte[], byte[], int) | Constructs an IndexColorModel from the given arrays of red, green, and blue components.
IndexColorModel(int, int, byte[], int, boolean) | Constructs an IndexColorModel from a single arrays of packed red, green, blue and optional alpha components.
IndexColorModel(int, int, byte[], int, boolean, int) | Constructs an IndexColorModel from a single arrays of packed red, green, blue and optional alpha components.

Methods
Name | Description
getAlpha(int) | Returns the alpha transparency value for the specified pixel in the range 0-255.
getAlphas(byte[]) | Copies the array of alpha transparency values into the given array.
getBlue(int) | Returns the blue color compoment for the specified pixel in the range 0-255.
getBlues(byte[]) | Copies the array of blue color components into the given array.
getGreen(int) | Returns the green color compoment for the specified pixel in the range 0-255.
getGreens(byte[]) | Copies the array of green color components into the given array.
getMapSize() | Returns the size of the color component arrays in this IndexColorModel.
getRed(int) | Returns the red color compoment for the specified pixel in the range 0-255.
getReds(byte[]) | Copies the array of red color components into the given array.
getRGB(int) | Returns the color of the pixel in the default RGB color model.
getTransparentPixel() | Returns the index of the transparent pixel in this IndexColorModel or -1 if there is no transparent pixel.


 IndexColorModel.IndexColorModel

IndexColorModel.IndexColorModel

Syntax 1
public IndexColorModel( int bits, int size, byte r[], byte g[], byte b[] )
Parameters
bits
The number of bits each pixel occupies.
size
The size of the color component arrays.
r
The array of red color components.
g
The array of green color components.
b
The array of blue color components.
Description
Constructs an IndexColorModel from the given arrays of red, green, and blue components. Pixels described by this color model will all have alpha components of 255 (fully opaque). All of the arrays specifying the color components must have at least the specified number of entries.

Syntax 2
public IndexColorModel( int bits, int size, byte r[], byte g[], byte b[], int trans )
Parameters
bits
The number of bits each pixel occupies.
size
The size of the color component arrays.
r
The array of red color components.
g
The array of green color components.
b
The array of blue color components.
trans
The index of the transparent pixel.
Description
Constructs an IndexColorModel from the given arrays of red, green, and blue components. Pixels described by this color model will all have alpha components of 255 (fully opaque), except for the indicated transparent pixel. All of the arrays specifying the color components must have at least the specified number of entries.

Syntax 3
public IndexColorModel( int bits, int size, byte r[], byte g[], byte b[], byte a[] )
Parameters
bits
The number of bits each pixel occupies.
size
The size of the color component arrays.
r
The array of red color components.
g
The array of green color components.
b
The array of blue color components.
a
The array of alpha value components.
Description
Constructs an IndexColorModel from the given arrays of red, green, blue and alpha components. All of the arrays specifying the color components must have at least the specified number of entries.

Syntax 4
public IndexColorModel( int bits, int size, byte cmap[], int start, boolean hasalpha )
Parameters
bits
The number of bits each pixel occupies.
size
The size of the color component arrays.
cmap
The array of color components.
start
The starting offset of the first color component.
hasalpha
Indicates whether alpha values are contained in the cmap array.
Description
Constructs an IndexColorModel from a single arrays of packed red, green, blue and optional alpha components. The array must have enough values in it to fill all of the needed component arrays of the specified size.

Syntax 5
public IndexColorModel( int bits, int size, byte cmap[], int start, boolean hasalpha, int trans )
Parameters
bits
The number of bits each pixel occupies.
size
The size of the color component arrays.
cmap
The array of color components.
start
The starting offset of the first color component.
hasalpha
Indicates whether alpha values are contained in the cmap array.
trans
The index of the fully transparent pixel.
Description
Constructs an IndexColorModel from a single arrays of packed red, green, blue and optional alpha components. The specified transparent index represents a pixel which will be considered entirely transparent regardless of any alpha value specified for it. The array must have enough values in it to fill all of the needed component arrays of the specified size.


 IndexColorModel.getAlpha

IndexColorModel.getAlpha

Syntax
public final int getAlpha( int pixel )
Description
Returns the alpha transparency value for the specified pixel in the range 0-255.

Overrides
getAlpha in class ColorModel


 IndexColorModel.getAlphas

IndexColorModel.getAlphas

Syntax
public final void getAlphas( byte a[] )
Description
Copies the array of alpha transparency values into the given array. Only the initial entries of the array as specified by getMapSize() will be written.


 IndexColorModel.getBlue

IndexColorModel.getBlue

Syntax
public final int getBlue( int pixel )
Description
Returns the blue color compoment for the specified pixel in the range 0-255.

Overrides
getBlue in class ColorModel


 IndexColorModel.getBlues

IndexColorModel.getBlues

Syntax
public final void getBlues( byte b[] )
Description
Copies the array of blue color components into the given array. Only the initial entries of the array as specified by getMapSize() will be written.


 IndexColorModel.getGreen

IndexColorModel.getGreen

Syntax
public final int getGreen( int pixel )
Description
Returns the green color compoment for the specified pixel in the range 0-255.

Overrides
getGreen in class ColorModel


 IndexColorModel.getGreens

IndexColorModel.getGreens

Syntax
public final void getGreens( byte g[] )
Description
Copies the array of green color components into the given array. Only the initial entries of the array as specified by getMapSize() are written.


 IndexColorModel.getMapSize

IndexColorModel.getMapSize

Syntax
public final int getMapSize()
Description
Returns the size of the color component arrays in this IndexColorModel.


 IndexColorModel.getRed

IndexColorModel.getRed

Syntax
public final int getRed( int pixel )
Description
Returns the red color compoment for the specified pixel in the range 0-255.

Overrides
getRed in class ColorModel


 IndexColorModel.getReds

IndexColorModel.getReds

Syntax
public final void getReds( byte r[] )
Description
Copies the array of red color components into the given array. Only the initial entries of the array as specified by getMapSize() are written.


 IndexColorModel.getRGB

IndexColorModel.getRGB

Syntax
public final int getRGB( int pixel )
Description
Returns the color of the pixel in the default RGB color model.

Overrides
getRGB in class ColorModel
See Also
getRGBdefault


 IndexColorModel.getTransparentPixel

IndexColorModel.getTransparentPixel

Syntax
public final int getTransparentPixel()
Description
Returns the index of the transparent pixel in this IndexColorModel or -1 if there is no transparent pixel.


 Class MemoryImageSource

Class java.awt.image.MemoryImageSource

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.MemoryImageSource

public class MemoryImageSource
extends Object
implements ImageProducer

This class is an implementation of the ImageProducer interface which uses an array to produce pixel values for an Image. Here is an example which calculates a 100x100 image representing a fade from black to blue along the X axis and a fade from black to red along the Y axis:

    int w = 100;
    int h = 100;
    int pix[] = new int[w * h];
    int index = 0;
    for (int y = 0; y < h; y++) {
        int red = (y * 255) / (h - 1);
        for (int x = 0; x < w; x++) {
        int blue = (x * 255) / (w - 1);
        pix[index++] = (255 << 24) | (red << 16) | blue;
        }
    }
    Image img = createImage(new MemoryImageSource(w, h, pix, 0, w));
The MemoryImageSource is also capable of managing a memory image which varies over time to allow animation or custom rendering. Here is an example showing how to set up the animation source and signal changes in the data (adapted from the MemoryAnimationSourceDemo by Garth Dickie):
    int pixels[];
    MemoryImageSource source;
    public void init() {
        int width = 50;
        int height = 50;
        int size = width * height;
        pixels = new int[size];
        int value = getBackground().getRGB();
        for (int i = 0; i < size; i++) {
        pixels[i] = value;
        }
        source = new MemoryImageSource(width, height, pixels, 0, width);
        source.setAnimated(true);
        image = createImage(source);
    }
    public void run() {
        Thread me = Thread.currentThread( );
        me.setPriority(Thread.MIN_PRIORITY);
        while (true) {
        try {
            thread.sleep(10);
        } catch( InterruptedException e ) {
            return;
        }
        // Modify the values in the pixels array at (x, y, w, h)
        // Send the new data to the interested ImageConsumers
        source.newPixels(x, y, w, h);
        }
    }

See Also:
ImageProducer


 MemoryImageSource Members

MemoryImageSource Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MemoryImageSource(int, int, ColorModel, byte[], int, int) | Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, byte[], int, int, Hashtable) | Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, int[], int, int) | Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, int[], int, int, Hashtable) | Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.
MemoryImageSource(int, int, int[], int, int) | Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.
MemoryImageSource(int, int, int[], int, int, Hashtable) | Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.

Methods
Name | Description
addConsumer(ImageConsumer) | Adds an ImageConsumer to the list of consumers interested in data for this image.
isConsumer(ImageConsumer) | Determine if an ImageConsumer is on the list of consumers currently interested in data for this image.
newPixels() | Send a whole new buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete.
newPixels(byte[], ColorModel, int, int) | Change to a new byte array to hold the pixels for this image.
newPixels(int, int, int, int) | Send a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete.
newPixels(int, int, int, int, boolean) | Send a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image.
newPixels(int[], ColorModel, int, int) | Change to a new int array to hold the pixels for this image.
removeConsumer(ImageConsumer) | Remove an ImageConsumer from the list of consumers interested in data for this image.
requestTopDownLeftRightResend(ImageConsumer) | Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.
setAnimated(boolean) | Change this memory image into a multi-frame animation or a single-frame static image depending on the animated parameter.
setFullBufferUpdates(boolean) | Specify whether this animated memory image should always be updated by sending the complete buffer of pixels whenever there is a change.
startProduction(ImageConsumer) | Adds an ImageConsumer to the list of consumers interested in data for this image, and immediately start delivery of the image data through the ImageConsumer interface.


 MemoryImageSource.MemoryImageSource

MemoryImageSource.MemoryImageSource

Syntax 1
public MemoryImageSource( int w, int h, ColorModel cm, byte pix[], int off, int scan )
Description
Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.

See Also
createImage

Syntax 2
public MemoryImageSource( int w, int h, ColorModel cm, byte pix[], int off, int scan, Hashtable props )
Description
Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.

See Also
createImage

Syntax 3
public MemoryImageSource( int w, int h, ColorModel cm, int pix[], int off, int scan )
Description
Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.

See Also
createImage

Syntax 4
public MemoryImageSource( int w, int h, ColorModel cm, int pix[], int off, int scan, Hashtable props )
Description
Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.

See Also
createImage

Syntax 5
public MemoryImageSource( int w, int h, int pix[], int off, int scan )
Description
Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.

See Also
createImage, getRGBdefault

Syntax 6
public MemoryImageSource( int w, int h, int pix[], int off, int scan, Hashtable props )
Description
Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.

See Also
createImage, getRGBdefault


 MemoryImageSource.addConsumer

MemoryImageSource.addConsumer

Syntax
public synchronized void addConsumer( ImageConsumer ic )
Description
Adds an ImageConsumer to the list of consumers interested in data for this image.

See Also
ImageConsumer


 MemoryImageSource.isConsumer

MemoryImageSource.isConsumer

Syntax
public synchronized boolean isConsumer( ImageConsumer ic )
Returns
true if the ImageConsumer is on the list; false otherwise
Description
Determine if an ImageConsumer is on the list of consumers currently interested in data for this image.

See Also
ImageConsumer


 MemoryImageSource.newPixels

MemoryImageSource.newPixels

Syntax 1
public void newPixels()
Description
Send a whole new buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete. This method only has effect if the animation flag has been turned on through the setAnimated() method.

See Also
ImageConsumer, setAnimated

Syntax 2
public synchronized void newPixels( int x, int y, int w, int h )
Parameters
x
the x coordinate of the upper left corner of the rectangle of pixels to be sent
y
the y coordinate of the upper left corner of the rectangle of pixels to be sent
w
the width of the rectangle of pixels to be sent
h
the height of the rectangle of pixels to be sent
Description
Send a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete. This method only has effect if the animation flag has been turned on through the setAnimated() method. If the full buffer update flag was turned on with the setFullBufferUpdates() method then the rectangle parameters will be ignored and the entire buffer will always be sent.

See Also
ImageConsumer, setAnimated, setFullBufferUpdates

Syntax 3
public synchronized void newPixels( int x, int y, int w, int h, boolean framenotify )
Parameters
x
the x coordinate of the upper left corner of the rectangle of pixels to be sent
y
the y coordinate of the upper left corner of the rectangle of pixels to be sent
w
the width of the rectangle of pixels to be sent
h
the height of the rectangle of pixels to be sent
framenotify
true if the consumers should be sent a SINGLEFRAMEDONE notification
Description
Send a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image. If the framenotify parameter is true then the consumers are also notified that an animation frame is complete. This method only has effect if the animation flag has been turned on through the setAnimated() method. If the full buffer update flag was turned on with the setFullBufferUpdates() method then the rectangle parameters will be ignored and the entire buffer will always be sent.

See Also
ImageConsumer, setAnimated, setFullBufferUpdates

Syntax 4
public synchronized void newPixels( byte newpix[], ColorModel newmodel, int offset, int scansize )
Description
Change to a new byte array to hold the pixels for this image. If the animation flag has been turned on through the setAnimated() method, then the new pixels will be immediately delivered to any ImageConsumers that are currently interested in the data for this image.

See Also
setAnimated

Syntax 5
public synchronized void newPixels( int newpix[], ColorModel newmodel, int offset, int scansize )
Description
Change to a new int array to hold the pixels for this image. If the animation flag has been turned on through the setAnimated() method, then the new pixels will be immediately delivered to any ImageConsumers that are currently interested in the data for this image.

See Also
setAnimated


 MemoryImageSource.removeConsumer

MemoryImageSource.removeConsumer

Syntax
public synchronized void removeConsumer( ImageConsumer ic )
Description
Remove an ImageConsumer from the list of consumers interested in data for this image.

See Also
ImageConsumer


 MemoryImageSource.requestTopDownLeftRightResend

MemoryImageSource.requestTopDownLeftRightResend

Syntax
public void requestTopDownLeftRightResend( ImageConsumer ic )
Description
Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.

See Also
ImageConsumer


 MemoryImageSource.setAnimated

MemoryImageSource.setAnimated

Syntax
public synchronized void setAnimated( boolean animated )
Parameters
animated
true if the image is a multi-frame animation
Description
Change this memory image into a multi-frame animation or a single-frame static image depending on the animated parameter.

This method should be called immediately after the MemoryImageSource is constructed and before an image is created with it to ensure that all ImageConsumers will receive the correct multi-frame data. If an ImageConsumer is added to this ImageProducer before this flag is set then that ImageConsumer will see only a snapshot of the pixel data that was available when it connected.


 MemoryImageSource.setFullBufferUpdates

MemoryImageSource.setFullBufferUpdates

Syntax
public synchronized void setFullBufferUpdates( boolean fullbuffers )
Parameters
fullbuffers
true if the complete pixel buffer should always be sent
Description
Specify whether this animated memory image should always be updated by sending the complete buffer of pixels whenever there is a change. This flag is ignored if the animation flag is not turned on through the setAnimated() method.

This method should be called immediately after the MemoryImageSource is constructed and before an image is created with it to ensure that all ImageConsumers will receive the correct pixel delivery hints.

See Also
setAnimated


 MemoryImageSource.startProduction

MemoryImageSource.startProduction

Syntax
public void startProduction( ImageConsumer ic )
Description
Adds an ImageConsumer to the list of consumers interested in data for this image, and immediately start delivery of the image data through the ImageConsumer interface.

See Also
ImageConsumer


 Class PixelGrabber

Class java.awt.image.PixelGrabber

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.PixelGrabber

public class PixelGrabber
extends Object
implements ImageConsumer

The PixelGrabber class implements an ImageConsumer which can be attached to an Image or ImageProducer object to retrieve a subset of the pixels in that image. Here is an example:

 public void handlesinglepixel(int x, int y, int pixel) {
    int alpha = (pixel >> 24) & 0xff;
    int red   = (pixel >> 16) & 0xff;
    int green = (pixel >>  8) & 0xff;
    int blue  = (pixel      ) & 0xff;
    // Deal with the pixel as necessary...
 }
 public void handlepixels(Image img, int x, int y, int w, int h) {
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        System.err.println("interrupted waiting for pixels!");
        return;
    }
    if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
        System.err.println("image fetch aborted or errored");
        return;
    }
    for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
        handlesinglepixel(x+i, y+j, pixels[j * w + i]);
        }
    }
 }

See Also:
getRGBdefault


 PixelGrabber Members

PixelGrabber Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PixelGrabber(Image, int, int, int, int, boolean) | Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image.
PixelGrabber(Image, int, int, int, int, int[], int, int) | Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image into the given array.
PixelGrabber(ImageProducer, int, int, int, int, int[], int, int) | Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the image produced by the specified ImageProducer into the given array.

Methods
Name | Description
abortGrabbing() | Request the PixelGrabber to abort the image fetch.
getColorModel() | Get the ColorModel for the pixels stored in the array.
getHeight() | Get the height of the pixel buffer (after adjusting for image height).
getPixels() | Get the pixel buffer.
getStatus() | Return the status of the pixels.
getWidth() | Get the width of the pixel buffer (after adjusting for image width).
grabPixels() | Request the Image or ImageProducer to start delivering pixels and wait for all of the pixels in the rectangle of interest to be delivered.
grabPixels(long) | Request the Image or ImageProducer to start delivering pixels and wait for all of the pixels in the rectangle of interest to be delivered or until the specified timeout has elapsed.
imageComplete(int) | The imageComplete method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setColorModel(ColorModel) | The setColorModel method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setDimensions(int, int) | The setDimensions method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setHints(int) | The setHints method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setPixels(int, int, int, int, ColorModel, int[], int, int) | The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
setProperties(Hashtable) | The setProperties method is part of the ImageConsumer API which this class must implement to retrieve the pixels.
startGrabbing() | Request the PixelGrabber to start fetching the pixels.
status() | DEPRECATED: Replaced by getStatus().


 PixelGrabber.PixelGrabber

PixelGrabber.PixelGrabber

Syntax 1
public PixelGrabber( Image img, int x, int y, int w, int h, int pix[], int off, int scansize )
Parameters
img
the image to retrieve pixels from
x
the x coordinate of the upper left corner of the rectangle of pixels to retrieve from the image, relative to the default (unscaled) size of the image
y
the y coordinate of the upper left corner of the rectangle of pixels to retrieve from the image
w
the width of the rectangle of pixels to retrieve
h
the height of the rectangle of pixels to retrieve
pix
the array of integers which are to be used to hold the RGB pixels retrieved from the image
off
the offset into the array of where to store the first pixel
scansize
the distance from one row of pixels to the next in the array
Description
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image into the given array. The pixels are stored into the array in the default RGB ColorModel. The RGB data for pixel (i, j) where (i, j) is inside the rectangle (x, y, w, h) is stored in the array at pix[(j - y) * scansize + (i - x) + off].

See Also
getRGBdefault

Syntax 2
public PixelGrabber( ImageProducer ip, int x, int y, int w, int h, int pix[], int off, int scansize )
Parameters
img
the image to retrieve pixels from
x
the x coordinate of the upper left corner of the rectangle of pixels to retrieve from the image, relative to the default (unscaled) size of the image
y
the y coordinate of the upper left corner of the rectangle of pixels to retrieve from the image
w
the width of the rectangle of pixels to retrieve
h
the height of the rectangle of pixels to retrieve
pix
the array of integers which are to be used to hold the RGB pixels retrieved from the image
off
the offset into the array of where to store the first pixel
scansize
the distance from one row of pixels to the next in the array
Description
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the image produced by the specified ImageProducer into the given array. The pixels are stored into the array in the default RGB ColorModel. The RGB data for pixel (i, j) where (i, j) is inside the rectangle (x, y, w, h) is stored in the array at pix[(j - y) * scansize + (i - x) + off].

See Also
getRGBdefault

Syntax 3
public PixelGrabber( Image img, int x, int y, int w, int h, boolean forceRGB )
Parameters
img
the image to retrieve the image data from
x
the x coordinate of the upper left corner of the rectangle of pixels to retrieve from the image, relative to the default (unscaled) size of the image
y
the y coordinate of the upper left corner of the rectangle of pixels to retrieve from the image
w
the width of the rectangle of pixels to retrieve
h
the height of the rectangle of pixels to retrieve
forceRGB
true if the pixels should always be converted to the default RGB ColorModel
Description
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image. The pixels are accumulated in the original ColorModel if the same ColorModel is used for every call to setPixels, otherwise the pixels are accumulated in the default RGB ColorModel. If the forceRGB parameter is true, then the pixels will be accumulated in the default RGB ColorModel anywya. A buffer is allocated by the PixelGrabber to hold the pixels in either case. If (w < 0) or (h < 0), then they will default to the remaining width and height of the source data when that information is delivered.


 PixelGrabber.abortGrabbing

PixelGrabber.abortGrabbing

Syntax
public synchronized void abortGrabbing()
Description
Request the PixelGrabber to abort the image fetch.


 PixelGrabber.getColorModel

PixelGrabber.getColorModel

Syntax
public synchronized ColorModel getColorModel()
Returns
the ColorModel object used for storing the pixels
Description
Get the ColorModel for the pixels stored in the array. If the PixelGrabber was constructed with an explicit pixel buffer then this method will always return the default RGB ColorModel, otherwise it may return null until the ColorModel used by the ImageProducer is known. Since the PixelGrabber may fall back on accumulating the data in the default RGB ColorModel at any time if the source image uses more than one ColorModel to deliver the data, the ColorModel object returned by this method may change over time until the image grab is complete.

See Also
getStatus, getRGBdefault


 PixelGrabber.getHeight

PixelGrabber.getHeight

Syntax
public synchronized int getHeight()
Returns
the final height used for the pixel buffer or -1 if the height is not yet known
Description
Get the height of the pixel buffer (after adjusting for image height). If no width was specified for the rectangle of pixels to grab then then this information will only be available after the image has delivered the dimensions.

See Also
getStatus


 PixelGrabber.getPixels

PixelGrabber.getPixels

Syntax
public synchronized Object getPixels()
Returns
either a byte array or an int array
Description
Get the pixel buffer. If the PixelGrabber was not constructed with an explicit pixel buffer to hold the pixels then this method will return null until the size and format of the image data is known. Since the PixelGrabber may fall back on accumulating the data in the default RGB ColorModel at any time if the source image uses more than one ColorModel to deliver the data, the array object returned by this method may change over time until the image grab is complete.

See Also
getStatus


 PixelGrabber.getStatus

PixelGrabber.getStatus

Syntax
public synchronized int getStatus()
Returns
the bitwise OR of all relevant ImageObserver flags
Description
Return the status of the pixels. The ImageObserver flags representing the available pixel information are returned.

See Also
ImageObserver


 PixelGrabber.getWidth

PixelGrabber.getWidth

Syntax
public synchronized int getWidth()
Returns
the final width used for the pixel buffer or -1 if the width is not yet known
Description
Get the width of the pixel buffer (after adjusting for image width). If no width was specified for the rectangle of pixels to grab then then this information will only be available after the image has delivered the dimensions.

See Also
getStatus


 PixelGrabber.grabPixels

PixelGrabber.grabPixels

Syntax 1
public boolean grabPixels() throws InterruptedException
Returns
true if the pixels were successfully grabbed, false on abort, error or timeout
Description
Request the Image or ImageProducer to start delivering pixels and wait for all of the pixels in the rectangle of interest to be delivered.

Exceptions
InterruptedException Another thread has interrupted this thread.

Syntax 2
public synchronized boolean grabPixels( long ms ) throws InterruptedException
Parameters
ms
the number of milliseconds to wait for the image pixels to arrive before timing out
Returns
true if the pixels were successfully grabbed, false on abort, error or timeout
Description
Request the Image or ImageProducer to start delivering pixels and wait for all of the pixels in the rectangle of interest to be delivered or until the specified timeout has elapsed.

Exceptions
InterruptedException Another thread has interrupted this thread.


 PixelGrabber.imageComplete

PixelGrabber.imageComplete

Syntax
public synchronized void imageComplete( int status )
Description
The imageComplete method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.setColorModel

PixelGrabber.setColorModel

Syntax
public void setColorModel( ColorModel model )
Description
The setColorModel method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.setDimensions

PixelGrabber.setDimensions

Syntax
public void setDimensions( int width, int height )
Description
The setDimensions method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.setHints

PixelGrabber.setHints

Syntax
public void setHints( int hints )
Description
The setHints method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.setPixels

PixelGrabber.setPixels

Syntax 1
public void setPixels( int srcX, int srcY, int srcW, int srcH, ColorModel model, byte pixels[], int srcOff, int srcScan )
Description
The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

Syntax 2
public void setPixels( int srcX, int srcY, int srcW, int srcH, ColorModel model, int pixels[], int srcOff, int srcScan )
Description
The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.setProperties

PixelGrabber.setProperties

Syntax
public void setProperties( Hashtable props )
Description
The setProperties method is part of the ImageConsumer API which this class must implement to retrieve the pixels.


 PixelGrabber.startGrabbing

PixelGrabber.startGrabbing

Syntax
public synchronized void startGrabbing()
Description
Request the PixelGrabber to start fetching the pixels.


 PixelGrabber.status

PixelGrabber.status

Syntax
public synchronized int status()
Description
DEPRECATED: Replaced by getStatus().


 Class RGBImageFilter

Class java.awt.image.RGBImageFilter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ImageFilter
           |
           +----java.awt.image.RGBImageFilter

public abstract class RGBImageFilter
extends ImageFilter

This class provides an easy way to create an ImageFilter which modifies the pixels of an image in the default RGB ColorModel. It is meant to be used in conjunction with a FilteredImageSource object to produce filtered versions of existing images. It is an abstract class that provides the calls needed to channel all of the pixel data through a single method which converts pixels one at a time in the default RGB ColorModel regardless of the ColorModel being used by the ImageProducer. The only method which needs to be defined to create a useable image filter is the filterRGB method. Here is an example of a definition of a filter which swaps the red and blue components of an image:

    class RedBlueSwapFilter extends RGBImageFilter {
        public RedBlueSwapFilter() {
        // The filter's operation does not depend on the
        // pixel's location, so IndexColorModels can be
        // filtered directly.
        canFilterIndexColorModel = true;
        }
        public int filterRGB(int x, int y, int rgb) {
        return ((rgb & 0xff00ff00)
            | ((rgb & 0xff0000) >> 16)
            | ((rgb & 0xff) << 16));
        }
    }

See Also:
FilteredImageSource, ImageFilter, getRGBdefault


 RGBImageFilter Members

RGBImageFilter Members

Class Overview | This Package | All Packages

Fields
Name | Description
canFilterIndexColorModel | This boolean indicates whether or not it is acceptable to apply the color filtering of the filterRGB method to the color table entries of an IndexColorModel object in lieu of pixel by pixel filtering.
newmodel |
origmodel |

Constructors
Name | Description
RGBImageFilter() |

Methods
Name | Description
filterIndexColorModel(IndexColorModel) | Filters an IndexColorModel object by running each entry in its color tables through the filterRGB function that RGBImageFilter subclasses must provide.
filterRGB(int, int, int) | Subclasses must specify a method to convert a single input pixel in the default RGB ColorModel to a single output pixel.
filterRGBPixels(int, int, int, int, int[], int, int) | Filters a buffer of pixels in the default RGB ColorModel by passing them one by one through the filterRGB method.
setColorModel(ColorModel) | If the ColorModel is an IndexColorModel, and the subclass has set the canFilterIndexColorModel flag to true, we substitute a filtered version of the color model here and wherever that original ColorModel object appears in the setPixels methods.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel.
setPixels(int, int, int, int, ColorModel, int[], int, int) | If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel, otherwise converts the buffer of integer pixels to the default RGB ColorModel and passes the converted buffer to the filterRGBPixels method to be converted one by one.
substituteColorModel(ColorModel, ColorModel) | Registers two ColorModel objects for substitution.


 RGBImageFilter.canFilterIndexColorModel

RGBImageFilter.canFilterIndexColorModel

Syntax
protected boolean canFilterIndexColorModel
Description
This boolean indicates whether or not it is acceptable to apply the color filtering of the filterRGB method to the color table entries of an IndexColorModel object in lieu of pixel by pixel filtering. Subclasses should set this variable to true in their constructor if their filterRGB method does not depend on the coordinate of the pixel being filtered.

See Also
substituteColorModel, filterRGB, IndexColorModel


 RGBImageFilter.newmodel

RGBImageFilter.newmodel

Syntax
protected ColorModel newmodel


 RGBImageFilter.origmodel

RGBImageFilter.origmodel

Syntax
protected ColorModel origmodel


 RGBImageFilter.RGBImageFilter

RGBImageFilter.RGBImageFilter

Syntax
public RGBImageFilter()


 RGBImageFilter.filterIndexColorModel

RGBImageFilter.filterIndexColorModel

Syntax
public IndexColorModel filterIndexColorModel( IndexColorModel icm )
Parameters
icm
the IndexColorModel object to be filtered
Returns
a new IndexColorModel representing the filtered colors
Description
Filters an IndexColorModel object by running each entry in its color tables through the filterRGB function that RGBImageFilter subclasses must provide. Uses coordinates of -1 to indicate that a color table entry is being filtered rather than an actual pixel value.


 RGBImageFilter.filterRGB

RGBImageFilter.filterRGB

Syntax
public abstract int filterRGB( int x, int y, int rgb )
Description
Subclasses must specify a method to convert a single input pixel in the default RGB ColorModel to a single output pixel.

See Also
getRGBdefault, filterRGBPixels


 RGBImageFilter.filterRGBPixels

RGBImageFilter.filterRGBPixels

Syntax
public void filterRGBPixels( int x, int y, int w, int h, int pixels[], int off, int scansize )
Description
Filters a buffer of pixels in the default RGB ColorModel by passing them one by one through the filterRGB method.

See Also
getRGBdefault, filterRGB


 RGBImageFilter.setColorModel

RGBImageFilter.setColorModel

Syntax
public void setColorModel( ColorModel model )
Description
If the ColorModel is an IndexColorModel, and the subclass has set the canFilterIndexColorModel flag to true, we substitute a filtered version of the color model here and wherever that original ColorModel object appears in the setPixels methods. Otherwise overrides the default ColorModel used by the ImageProducer and specifies the default RGB ColorModel instead.

Overrides
setColorModel in class ImageFilter
See Also
ImageConsumer, getRGBdefault


 RGBImageFilter.setPixels

RGBImageFilter.setPixels

Syntax 1
public void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel. Otherwise converts the buffer of byte pixels to the default RGB ColorModel and passes the converted buffer to the filterRGBPixels method to be converted one by one.

Overrides
setPixels in class ImageFilter
See Also
getRGBdefault, filterRGBPixels

Syntax 2
public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel, otherwise converts the buffer of integer pixels to the default RGB ColorModel and passes the converted buffer to the filterRGBPixels method to be converted one by one. Converts a buffer of integer pixels to the default RGB ColorModel and passes the converted buffer to the filterRGBPixels method.

Overrides
setPixels in class ImageFilter
See Also
getRGBdefault, filterRGBPixels


 RGBImageFilter.substituteColorModel

RGBImageFilter.substituteColorModel

Syntax
public void substituteColorModel( ColorModel oldcm, ColorModel newcm )
Parameters
oldcm
the ColorModel object to be replaced on the fly
newcm
the ColorModel object to replace oldcm on the fly
Description
Registers two ColorModel objects for substitution. If the oldcm is encountered during any of the setPixels methods, the newcm is substituted and the pixels passed through untouched (but with the new ColorModel object).


 Class ReplicateScaleFilter

Class java.awt.image.ReplicateScaleFilter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.awt.image.ImageFilter
           |
           +----java.awt.image.ReplicateScaleFilter

public class ReplicateScaleFilter
extends ImageFilter

An ImageFilter class for scaling images using the simplest algorithm. This class extends the basic ImageFilter Class to scale an existing image and provide a source for a new image containing the resampled image. The pixels in the source image are sampled to produce pixels for an image of the specified size by replicating rows and columns of pixels to scale up or omitting rows and columns of pixels to scale down. It is meant to be used in conjunction with a FilteredImageSource object to produce scaled versions of existing images.

See Also:
FilteredImageSource, ImageFilter


 ReplicateScaleFilter Members

ReplicateScaleFilter Members

Class Overview | This Package | All Packages

Fields
Name | Description
destHeight |
destWidth |
outpixbuf |
srccols |
srcHeight |
srcrows |
srcWidth |

Constructors
Name | Description
ReplicateScaleFilter(int, int) | Constructs a ReplicateScaleFilter that scales the pixels from its source Image as specified by the width and height parameters.

Methods
Name | Description
setDimensions(int, int) | Override the dimensions of the source image and pass the dimensions of the new scaled size to the ImageConsumer.
setPixels(int, int, int, int, ColorModel, byte[], int, int) | Choose which rows and columns of the delivered byte pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.
setPixels(int, int, int, int, ColorModel, int[], int, int) | Choose which rows and columns of the delivered int pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.
setProperties(Hashtable) | Passes along the properties from the source object after adding a property indicating the scale applied.


 ReplicateScaleFilter.destHeight

ReplicateScaleFilter.destHeight

Syntax
protected int destHeight


 ReplicateScaleFilter.destWidth

ReplicateScaleFilter.destWidth

Syntax
protected int destWidth


 ReplicateScaleFilter.outpixbuf

ReplicateScaleFilter.outpixbuf

Syntax
protected Object outpixbuf


 ReplicateScaleFilter.srccols

ReplicateScaleFilter.srccols

Syntax
protected int srccols[]


 ReplicateScaleFilter.srcHeight

ReplicateScaleFilter.srcHeight

Syntax
protected int srcHeight


 ReplicateScaleFilter.srcrows

ReplicateScaleFilter.srcrows

Syntax
protected int srcrows[]


 ReplicateScaleFilter.srcWidth

ReplicateScaleFilter.srcWidth

Syntax
protected int srcWidth


 ReplicateScaleFilter.ReplicateScaleFilter

ReplicateScaleFilter.ReplicateScaleFilter

Syntax
public ReplicateScaleFilter( int width, int height )
Parameters
width
the target width to scale the image
height
the target height to scale the image
Description
Constructs a ReplicateScaleFilter that scales the pixels from its source Image as specified by the width and height parameters.


 ReplicateScaleFilter.setDimensions

ReplicateScaleFilter.setDimensions

Syntax
public void setDimensions( int w, int h )
Description
Override the dimensions of the source image and pass the dimensions of the new scaled size to the ImageConsumer.

Overrides
setDimensions in class ImageFilter
See Also
ImageConsumer


 ReplicateScaleFilter.setPixels

ReplicateScaleFilter.setPixels

Syntax 1
public void setPixels( int x, int y, int w, int h, ColorModel model, byte pixels[], int off, int scansize )
Description
Choose which rows and columns of the delivered byte pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.

Overrides
setPixels in class ImageFilter

Syntax 2
public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize )
Description
Choose which rows and columns of the delivered int pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.

Overrides
setPixels in class ImageFilter


 ReplicateScaleFilter.setProperties

ReplicateScaleFilter.setProperties

Syntax
public void setProperties( Hashtable props )
Description
Passes along the properties from the source object after adding a property indicating the scale applied.

Overrides
setProperties in class ImageFilter


 Package java.beans

Package java.beans

All Packages

Interfaces

  • BeanInfo
  • Customizer
  • PropertyChangeListener
  • PropertyEditor
  • VetoableChangeListener
  • Visibility

    • Classes

  • BeanDescriptor
  • Beans
  • EventSetDescriptor
  • FeatureDescriptor
  • IndexedPropertyDescriptor
  • Introspector
  • MethodDescriptor
  • ParameterDescriptor
  • PropertyChangeEvent
  • PropertyChangeSupport
  • PropertyDescriptor
  • PropertyEditorManager
  • PropertyEditorSupport
  • SimpleBeanInfo
  • VetoableChangeSupport

    • Exceptions

  • IntrospectionException
  • PropertyVetoException


 Class BeanDescriptor

Class java.beans.BeanDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.BeanDescriptor

public class BeanDescriptor
extends FeatureDescriptor

A BeanDescriptor provides global information about a "bean", including its Java class, its displayName, etc.

This is one of the kinds of descriptor returned by a BeanInfo object, which also returns descriptors for properties, method, and events.


 BeanDescriptor Members

BeanDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BeanDescriptor(Class) | Create a BeanDescriptor for a bean that doesn't have a customizer.
BeanDescriptor(Class, Class) | Create a BeanDescriptor for a bean that has a customizer.

Methods
Name | Description
getBeanClass() |
getCustomizerClass() |


 BeanDescriptor.BeanDescriptor

BeanDescriptor.BeanDescriptor

Syntax 1
public BeanDescriptor( Class beanClass )
Parameters
beanClass
The Class object of the Java class that implements the bean. For example sun.beans.OurButton.class.
Description
Create a BeanDescriptor for a bean that doesn't have a customizer.

Syntax 2
public BeanDescriptor( Class beanClass, Class customizerClass )
Parameters
beanClass
The Class object of the Java class that implements the bean. For example sun.beans.OurButton.class.
customizerClass
The Class object of the Java class that implements the bean's Customizer. For example sun.beans.OurButtonCustomizer.class.
Description
Create a BeanDescriptor for a bean that has a customizer.


 BeanDescriptor.getBeanClass

BeanDescriptor.getBeanClass

Syntax
public Class getBeanClass()
Returns
The Class object for the bean.


 BeanDescriptor.getCustomizerClass

BeanDescriptor.getCustomizerClass

Syntax
public Class getCustomizerClass()
Returns
The Class object for the bean's customizer. This may be null if the bean doesn't have a customizer.


 Interface BeanInfo

Interface java.beans.BeanInfo

Interface Members | This Package | All Packages

public interface BeanInfo

A bean implementor who wishes to provide explicit information about their bean may provide a BeanInfo class that implements this BeanInfo interface and provides explicit information about the methods, properties, events, etc, of their bean.

A bean implementor doesn't need to provide a complete set of explicit information. You can pick and choose which information you want to provide and the rest will be obtained by automatic analysis using low-level reflection of the bean classes' methods and applying standard design patterns.

You get the opportunity to provide lots and lots of different information as part of the various XyZDescriptor classes. But don't panic, you only really need to provide the minimal core information required by the various constructors.

See also the SimpleBeanInfo class which provides a convenient "noop" base class for BeanInfo classes, which you can override for those specific places where you want to return explicit info.

To learn about all the behaviour of a bean see the Introspector class.


 BeanInfo Members

BeanInfo Members

Interface Overview | This Package | All Packages

Fields
Name | Description
ICON_COLOR_16x16 | Constant to indicate a 16 x 16 color icon.
ICON_COLOR_32x32 | Constant to indicate a 32 x 32 color icon.
ICON_MONO_16x16 | Constant to indicate a 16 x 16 monochrome icon.
ICON_MONO_32x32 | Constant to indicate a 32 x 32 monochrome icon.

Methods
Name | Description
getAdditionalBeanInfo() | This method allows a BeanInfo object to return an arbitrary collection of other BeanInfo objects that provide additional information on the current bean.
getBeanDescriptor() |
getDefaultEventIndex() | A bean may have a "default" event that is the event that will mostly commonly be used by human's when using the bean.
getDefaultPropertyIndex() | A bean may have a "default" property that is the property that will mostly commonly be initially chosen for update by human's who are customizing the bean.
getEventSetDescriptors() |
getIcon(int) | This method returns an image object that can be used to represent the bean in toolboxes, toolbars, etc.
getMethodDescriptors() |
getPropertyDescriptors() |


 BeanInfo.ICON_COLOR_16x16

BeanInfo.ICON_COLOR_16x16

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ICON_COLOR_16x16
Description
Constant to indicate a 16 x 16 color icon.


 BeanInfo.ICON_COLOR_32x32

BeanInfo.ICON_COLOR_32x32

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ICON_COLOR_32x32
Description
Constant to indicate a 32 x 32 color icon.


 BeanInfo.ICON_MONO_16x16

BeanInfo.ICON_MONO_16x16

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ICON_MONO_16x16
Description
Constant to indicate a 16 x 16 monochrome icon.


 BeanInfo.ICON_MONO_32x32

BeanInfo.ICON_MONO_32x32

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int ICON_MONO_32x32
Description
Constant to indicate a 32 x 32 monochrome icon.


 BeanInfo.getAdditionalBeanInfo

BeanInfo.getAdditionalBeanInfo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BeanInfo[] getAdditionalBeanInfo()
Returns
an array of BeanInfo objects. May return null.
Description
This method allows a BeanInfo object to return an arbitrary collection of other BeanInfo objects that provide additional information on the current bean.

If there are conflicts or overlaps between the information provided by different BeanInfo objects, then the current BeanInfo takes precedence over the getAdditionalBeanInfo objects, and later elements in the array take precedence over earlier ones.


 BeanInfo.getBeanDescriptor

BeanInfo.getBeanDescriptor

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BeanDescriptor getBeanDescriptor()
Returns
A BeanDescriptor providing overall information about the bean, such as its displayName, its customizer, etc. May return null if the information should be obtained by automatic analysis.


 BeanInfo.getDefaultEventIndex

BeanInfo.getDefaultEventIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getDefaultEventIndex()
Returns
Index of default event in the EventSetDescriptor array returned by getEventSetDescriptors.

Returns -1 if there is no default event.

Description
A bean may have a "default" event that is the event that will mostly commonly be used by human's when using the bean.


 BeanInfo.getDefaultPropertyIndex

BeanInfo.getDefaultPropertyIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getDefaultPropertyIndex()
Returns
Index of default property in the PropertyDescriptor array returned by getPropertyDescriptors.

Returns -1 if there is no default property.

Description
A bean may have a "default" property that is the property that will mostly commonly be initially chosen for update by human's who are customizing the bean.


 BeanInfo.getEventSetDescriptors

BeanInfo.getEventSetDescriptors

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract EventSetDescriptor[] getEventSetDescriptors()
Returns
An array of EventSetDescriptors describing the kinds of events fired by this bean. May return null if the information should be obtained by automatic analysis.


 BeanInfo.getIcon

BeanInfo.getIcon

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Image getIcon( int iconKind )
Parameters
iconKind
The kind of icon requested. This should be one of the constant values ICON_COLOR_16x16, ICON_COLOR_32x32, ICON_MONO_16x16, or ICON_MONO_32x32.
Returns
An image object representing the requested icon. May return null if no suitable icon is available.
Description
This method returns an image object that can be used to represent the bean in toolboxes, toolbars, etc. Icon images will typically be GIFs, but may in future include other formats.

Beans aren't required to provide icons and may return null from this method.

There are four possible flavors of icons (16x16 color, 32x32 color, 16x16 mono, 32x32 mono). If a bean choses to only support a single icon we recommend supporting 16x16 color.

We recommend that icons have a "transparent" background so they can be rendered onto an existing background.


 BeanInfo.getMethodDescriptors

BeanInfo.getMethodDescriptors

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract MethodDescriptor[] getMethodDescriptors()
Returns
An array of MethodDescriptors describing the externally visible methods supported by this bean. May return null if the information should be obtained by automatic analysis.


 BeanInfo.getPropertyDescriptors

BeanInfo.getPropertyDescriptors

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract PropertyDescriptor[] getPropertyDescriptors()
Returns
An array of PropertyDescriptors describing the editable properties supported by this bean. May return null if the information should be obtained by automatic analysis.

If a property is indexed, then its entry in the result array will belong to the IndexedPropertyDescriptor subclass of PropertyDescriptor. A client of getPropertyDescriptors can use "instanceof" to check if a given PropertyDescriptor is an IndexedPropertyDescriptor.


 Class Beans

Class java.beans.Beans

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.Beans

public class Beans
extends Object

This class provides some general purpose beans control methods.


 Beans Members

Beans Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Beans() |

Methods
Name | Description
getInstanceOf(Object, Class) | From a given bean, obtain an object representing a specified type view of that source object.
instantiate(ClassLoader, String) | Instantiate a bean.
isDesignTime() | Test if we are in design-mode.
isGuiAvailable() |
isInstanceOf(Object, Class) | Check if a bean can be viewed as a given target type.
setDesignTime(boolean) | Used to indicate whether of not we are running in an application builder environment.
setGuiAvailable(boolean) | Used to indicate whether of not we are running in an environment where GUI interaction is available.


 Beans.Beans

Beans.Beans

Syntax
public Beans()


 Beans.getInstanceOf

Beans.getInstanceOf

Syntax
public static Object getInstanceOf( Object bean, Class targetType )
Parameters
obj
Object from which we want to obtain a view.
targetType
The type of view we'd like to get.
Description
From a given bean, obtain an object representing a specified type view of that source object.

The result may be the same object or a different object. If the requested target view isn't available then the given bean is returned.

This method is provided in Beans 1.0 as a hook to allow the addition of more flexible bean behaviour in the future.


 Beans.instantiate

Beans.instantiate

Syntax
public static Object instantiate( ClassLoader cls, String beanName ) throws IOException, ClassNotFoundException
Parameters
classLoader
the class-loader from which we should create the bean. If this is null, then the system class-loader is used.
beanName
the name of the bean within the class-loader. For example "sun.beanbox.foobah"
Description
Instantiate a bean.

The bean is created based on a name relative to a class-loader. This name should be a dot-separated name such as "a.b.c".

In Beans 1.0 the given name can indicate either a serialized object or a class. Other mechanisms may be added in the future. In beans 1.0 we first try to treat the beanName as a serialized object name then as a class name.

When using the beanName as a serialized object name we convert the given beanName to a resource pathname and add a trailing ".ser" suffix. We then try to load a serialized object from that resource.

For example, given a beanName of "x.y", Beans.instantiate would first try to read a serialized object from the resource "x/y.ser" and if that failed it would try to load the class "x.y" and create an instance of that class.

If the bean is a subtype of java.applet.Applet, then it is given some special initialization. First, it is supplied with a default AppletStub and AppletContext. Second, if it was instantiated from a classname the applet's "init" method is called. (If the bean was deserialized this step is skipped.)

Note that for beans which are applets, it is the caller's responsiblity to call "start" on the applet. For correct behaviour, this should be done after the applet has been added into a visible AWT container.

Note that applets created via beans.instantiate run in a slightly different environment than applets running inside browsers. In particular, bean applets have no access to "parameters", so they may wish to provide property get/set methods to set parameter values. We advise bean-applet developers to test their bean-applets against both the JDK appletviewer (for a reference browser environment) and the BDK BeanBox (for a reference bean container).

Exceptions
ClassNotFoundException if the class of a serialized object could not be found.
Exceptions
IOException if an I/O error occurs.


 Beans.isDesignTime

Beans.isDesignTime

Syntax
public static boolean isDesignTime()
Returns
True if we are running in an application construction environment.
Description
Test if we are in design-mode.


 Beans.isGuiAvailable

Beans.isGuiAvailable

Syntax
public static boolean isGuiAvailable()
Returns
True if we are running in an environment where beans can assume that an interactive GUI is available, so they can pop up dialog boxes, etc. This will normally return true in a windowing environment, and will normally return false in a server environment or if an application is running as part of a batch job.


 Beans.isInstanceOf

Beans.isInstanceOf

Syntax
public static boolean isInstanceOf( Object bean, Class targetType )
Parameters
bean
Bean from which we want to obtain a view.
targetType
The type of view we'd like to get.
Returns
"true" if the given bean supports the given targetType.
Description
Check if a bean can be viewed as a given target type. The result will be true if the Beans.getInstanceof method can be used on the given bean to obtain an object that represents the specified targetType type view.


 Beans.setDesignTime

Beans.setDesignTime

Syntax
public static void setDesignTime( boolean isDesignTime ) throws SecurityException
Parameters
isDesignTime
True if we're in an application builder tool.
Description
Used to indicate whether of not we are running in an application builder environment. Note that this method is security checked and is not available to (for example) untrusted applets.


 Beans.setGuiAvailable

Beans.setGuiAvailable

Syntax
public static void setGuiAvailable( boolean isGuiAvailable ) throws SecurityException
Parameters
isGuiAvailable
True if GUI interaction is available.
Description
Used to indicate whether of not we are running in an environment where GUI interaction is available. Note that this method is security checked and is not available to (for example) untrusted applets.


 Interface Customizer

Interface java.beans.Customizer

Interface Members | This Package | All Packages

public interface Customizer

A customizer class provides a complete custom GUI for customizing a target Java Bean.

Each customizer should inherit from the java.awt.Component class so it can be instantiated inside an AWT dialog or panel.

Each customizer should have a null constructor.


 Customizer Members

Customizer Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addPropertyChangeListener(PropertyChangeListener) | Register a listener for the PropertyChange event.
removePropertyChangeListener(PropertyChangeListener) | Remove a listener for the PropertyChange event.
setObject(Object) | Set the object to be customized.


 Customizer.addPropertyChangeListener

Customizer.addPropertyChangeListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addPropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
An object to be invoked when a PropertyChange event is fired.
Description
Register a listener for the PropertyChange event. The customizer should fire a PropertyChange event whenever it changes the target bean in a way that might require the displayed properties to be refreshed.


 Customizer.removePropertyChangeListener

Customizer.removePropertyChangeListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removePropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
The PropertyChange listener to be removed.
Description
Remove a listener for the PropertyChange event.


 Customizer.setObject

Customizer.setObject

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setObject( Object bean )
Parameters
bean
The object to be customized.
Description
Set the object to be customized. This method should be called only once, before the Customizer has been added to any parent AWT container.


 Class EventSetDescriptor

Class java.beans.EventSetDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.EventSetDescriptor

public class EventSetDescriptor
extends FeatureDescriptor

An EventSetDescriptor describes a group of events that a given Java bean fires.

The given group of events are all delivered as method calls on a single event listener interface, and an event listener object can be registered via a call on a registration method supplied by the event source.


 EventSetDescriptor Members

EventSetDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
EventSetDescriptor(Class, String, Class, String) | This constructor creates an EventSetDescriptor assuming that you are following the most simple standard design pattern where a named event "fred" is (1) delivered as a call on the single method of interface FredListener, (2) has a single argument of type FredEvent, and (3) where the FredListener may be registered with a call on an addFredListener method of the source component and removed with a call on a removeFredListener method.
EventSetDescriptor(Class, String, Class, String[], String, String) | This constructor creates an EventSetDescriptor from scratch using string names.
EventSetDescriptor(String, Class, Method[], Method, Method) | This constructor creates an EventSetDescriptor from scratch using java.lang.reflect.Method and java.lang.Class objects.
EventSetDescriptor(String, Class, MethodDescriptor[], Method, Method) | This constructor creates an EventSetDescriptor from scratch using java.lang.reflect.MethodDescriptor and java.lang.Class objects.

Methods
Name | Description
getAddListenerMethod() |
getListenerMethodDescriptors() |
getListenerMethods() |
getListenerType() |
getRemoveListenerMethod() |
isInDefaultEventSet() | Report if an event set is in the "default set".
isUnicast() | Normally event sources are multicast.
setInDefaultEventSet(boolean) | Mark an event set as being in the "default" set (or not).
setUnicast(boolean) | Mark an event set as unicast (or not).


 EventSetDescriptor.EventSetDescriptor

EventSetDescriptor.EventSetDescriptor

Syntax 1
public EventSetDescriptor( Class sourceClass, String eventSetName, Class listenerType, String listenerMethodName ) throws IntrospectionException
Parameters
sourceClass
The class firing the event.
eventSetName
The programmatic name of the event. E.g. "fred". Note that this should normally start with a lower-case character.
listenerType
The target interface that events will get delivered to.
listenerMethodName
The method that will get called when the event gets delivered to its target listener interface.
Description
This constructor creates an EventSetDescriptor assuming that you are following the most simple standard design pattern where a named event "fred" is (1) delivered as a call on the single method of interface FredListener, (2) has a single argument of type FredEvent, and (3) where the FredListener may be registered with a call on an addFredListener method of the source component and removed with a call on a removeFredListener method.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 2
public EventSetDescriptor( Class sourceClass, String eventSetName, Class listenerType, String listenerMethodNames[], String addListenerMethodName, String removeListenerMethodName ) throws IntrospectionException
Parameters
sourceClass
The class firing the event.
eventSetName
The programmatic name of the event set. Note that this should normally start with a lower-case character.
listenerType
The Class of the target interface that events will get delivered to.
listenerMethodNames
The names of the methods that will get called when the event gets delivered to its target listener interface.
addListenerMethodName
The name of the method on the event source that can be used to register an event listener object.
removeListenerMethodName
The name of the method on the event source that can be used to de-register an event listener object.
Description
This constructor creates an EventSetDescriptor from scratch using string names.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 3
public EventSetDescriptor( String eventSetName, Class listenerType, Method listenerMethods[], Method addListenerMethod, Method removeListenerMethod ) throws IntrospectionException
Parameters
eventSetName
The programmatic name of the event set.
listenerType
The Class for the listener interface.
listenerMethods
An array of Method objects describing each of the event handling methods in the target listener.
addListenerMethod
The method on the event source that can be used to register an event listener object.
removeListenerMethod
The method on the event source that can be used to de-register an event listener object.
Description
This constructor creates an EventSetDescriptor from scratch using java.lang.reflect.Method and java.lang.Class objects.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 4
public EventSetDescriptor( String eventSetName, Class listenerType, MethodDescriptor listenerMethodDescriptors[], Method addListenerMethod, Method removeListenerMethod ) throws IntrospectionException
Parameters
eventSetName
The programmatic name of the event set.
listenerType
The Class for the listener interface.
listenerMethodDescriptors
An array of MethodDescriptor objects describing each of the event handling methods in the target listener.
addListenerMethod
The method on the event source that can be used to register an event listener object.
removeListenerMethod
The method on the event source that can be used to de-register an event listener object.
Description
This constructor creates an EventSetDescriptor from scratch using java.lang.reflect.MethodDescriptor and java.lang.Class objects.

Exceptions
IntrospectionException if an exception occurs during introspection.


 EventSetDescriptor.getAddListenerMethod

EventSetDescriptor.getAddListenerMethod

Syntax
public Method getAddListenerMethod()
Returns
The method used to register a listener at the event source.


 EventSetDescriptor.getListenerMethodDescriptors

EventSetDescriptor.getListenerMethodDescriptors

Syntax
public MethodDescriptor[] getListenerMethodDescriptors()
Returns
An array of MethodDescriptor objects for the target methods within the target listener interface that will get called when events are fired.


 EventSetDescriptor.getListenerMethods

EventSetDescriptor.getListenerMethods

Syntax
public Method[] getListenerMethods()
Returns
An array of Method objects for the target methods within the target listener interface that will get called when events are fired.


 EventSetDescriptor.getListenerType

EventSetDescriptor.getListenerType

Syntax
public Class getListenerType()
Returns
The Class object for the target interface that will get invoked when the event is fired.


 EventSetDescriptor.getRemoveListenerMethod

EventSetDescriptor.getRemoveListenerMethod

Syntax
public Method getRemoveListenerMethod()
Returns
The method used to register a listener at the event source.


 EventSetDescriptor.isInDefaultEventSet

EventSetDescriptor.isInDefaultEventSet

Syntax
public boolean isInDefaultEventSet()
Returns
True if the event set is in the "default set". Defaults to "true".
Description
Report if an event set is in the "default set".


 EventSetDescriptor.isUnicast

EventSetDescriptor.isUnicast

Syntax
public boolean isUnicast()
Returns
True if the event set is unicast. Defaults to "false".
Description
Normally event sources are multicast. However there are some exceptions that are strictly unicast.


 EventSetDescriptor.setInDefaultEventSet

EventSetDescriptor.setInDefaultEventSet

Syntax
public void setInDefaultEventSet( boolean inDefaultEventSet )
Parameters
unicast
True if the event set is unicast.
Description
Mark an event set as being in the "default" set (or not). By default this is true.


 EventSetDescriptor.setUnicast

EventSetDescriptor.setUnicast

Syntax
public void setUnicast( boolean unicast )
Parameters
unicast
True if the event set is unicast.
Description
Mark an event set as unicast (or not).


 Class FeatureDescriptor

Class java.beans.FeatureDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor

public class FeatureDescriptor
extends Object

The FeatureDescriptor class is the common baseclass for PropertyDescriptor, EventSetDescriptor, and MethodDescriptor, etc.

It supports some common information that can be set and retrieved for any of the introspection descriptors.

In addition it provides an extension mechanism so that arbitrary attribute/value pairs can be associated with a design feature.


 FeatureDescriptor Members

FeatureDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FeatureDescriptor() |

Methods
Name | Description
attributeNames() |
getDisplayName() |
getName() |
getShortDescription() |
getValue(String) | Retrieve a named attribute with this feature.
isExpert() | The "expert" flag is used to distinguish between those features that are intended for expert users from those that are intended for normal users.
isHidden() | The "hidden" flag is used to identify features that are intended only for tool use, and which should not be exposed to humans.
setDisplayName(String) |
setExpert(boolean) | The "expert" flag is used to distinguish between features that are intended for expert users from those that are intended for normal users.
setHidden(boolean) | The "hidden" flag is used to identify features that are intended only for tool use, and which should not be exposed to humans.
setName(String) |
setShortDescription(String) | You can associate a short descriptive string with a feature.
setValue(String, Object) | Associate a named attribute with this feature.


 FeatureDescriptor.FeatureDescriptor

FeatureDescriptor.FeatureDescriptor

Syntax
public FeatureDescriptor()


 FeatureDescriptor.attributeNames

FeatureDescriptor.attributeNames

Syntax
public Enumeration attributeNames()
Returns
An enumeration of the locale-independent names of any attributes that have been registered with setValue.


 FeatureDescriptor.getDisplayName

FeatureDescriptor.getDisplayName

Syntax
public String getDisplayName()
Returns
The localized display name for the property/method/event. This defaults to the same as its programmatic name from getName.


 FeatureDescriptor.getName

FeatureDescriptor.getName

Syntax
public String getName()
Returns
The programmatic name of the property/method/event


 FeatureDescriptor.getShortDescription

FeatureDescriptor.getShortDescription

Syntax
public String getShortDescription()
Returns
A localized short description associated with this property/method/event. This defaults to be the display name.


 FeatureDescriptor.getValue

FeatureDescriptor.getValue

Syntax
public Object getValue( String attributeName )
Parameters
attributeName
The locale-independent name of the attribute
Returns
The value of the attribute. May be null if the attribute is unknown.
Description
Retrieve a named attribute with this feature.


 FeatureDescriptor.isExpert

FeatureDescriptor.isExpert

Syntax
public boolean isExpert()
Returns
True if this feature is intended for use by experts only.
Description
The "expert" flag is used to distinguish between those features that are intended for expert users from those that are intended for normal users.


 FeatureDescriptor.isHidden

FeatureDescriptor.isHidden

Syntax
public boolean isHidden()
Returns
True if this feature should be hidden from human users.
Description
The "hidden" flag is used to identify features that are intended only for tool use, and which should not be exposed to humans.


 FeatureDescriptor.setDisplayName

FeatureDescriptor.setDisplayName

Syntax
public void setDisplayName( String displayName )
Parameters
displayName
The localized display name for the property/method/event.


 FeatureDescriptor.setExpert

FeatureDescriptor.setExpert

Syntax
public void setExpert( boolean expert )
Parameters
expert
True if this feature is intended for use by experts only.
Description
The "expert" flag is used to distinguish between features that are intended for expert users from those that are intended for normal users.


 FeatureDescriptor.setHidden

FeatureDescriptor.setHidden

Syntax
public void setHidden( boolean hidden )
Parameters
hidden
True if this feature should be hidden from human users.
Description
The "hidden" flag is used to identify features that are intended only for tool use, and which should not be exposed to humans.


 FeatureDescriptor.setName

FeatureDescriptor.setName

Syntax
public void setName( String name )
Parameters
name
The programmatic name of the property/method/event


 FeatureDescriptor.setShortDescription

FeatureDescriptor.setShortDescription

Syntax
public void setShortDescription( String text )
Parameters
text
A (localized) short description to be associated with this property/method/event.
Description
You can associate a short descriptive string with a feature. Normally these descriptive strings should be less than about 40 characters.


 FeatureDescriptor.setValue

FeatureDescriptor.setValue

Syntax
public void setValue( String attributeName, Object value )
Parameters
attributeName
The locale-independent name of the attribute
value
The value.
Description
Associate a named attribute with this feature.


 Class IndexedPropertyDescriptor

Class java.beans.IndexedPropertyDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.PropertyDescriptor
                   |
                   +----java.beans.IndexedPropertyDescriptor

public class IndexedPropertyDescriptor
extends PropertyDescriptor

An IndexedPropertyDescriptor describes a property that acts like an array and has an indexed read and/or indexed write method to access specific elements of the array.

An indexed property may also provide simple non-indexed read and write methods. If these are present, they read and write arrays of the type returned by the indexed read method.


 IndexedPropertyDescriptor Members

IndexedPropertyDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IndexedPropertyDescriptor(String, Class) | This constructor constructs an IndexedPropertyDescriptor for a property that follows the standard Java conventions by having getFoo and setFoo accessor methods, for both indexed access and array access.
IndexedPropertyDescriptor(String, Class, String, String, String, String) | This constructor takes the name of a simple property, and method names for reading and writing the property, both indexed and non-indexed.
IndexedPropertyDescriptor(String, Method, Method, Method, Method) | This constructor takes the name of a simple property, and Method objects for reading and writing the property.

Methods
Name | Description
getIndexedPropertyType() |
getIndexedReadMethod() |
getIndexedWriteMethod() |


 IndexedPropertyDescriptor.IndexedPropertyDescriptor

IndexedPropertyDescriptor.IndexedPropertyDescriptor

Syntax 1
public IndexedPropertyDescriptor( String propertyName, Class beanClass ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
beanClass
The Class object for the target bean.
Description
This constructor constructs an IndexedPropertyDescriptor for a property that follows the standard Java conventions by having getFoo and setFoo accessor methods, for both indexed access and array access.

Thus if the argument name is "fred", it will assume that there is an indexed reader method "getFred", a non-indexed (array) reader method also called "getFred", an indexed writer method "setFred", and finally a non-indexed writer method "setFred".

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 2
public IndexedPropertyDescriptor( String propertyName, Class beanClass, String getterName, String setterName, String indexedGetterName, String indexedSetterName ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
beanClass
The Class object for the target bean.
getterName
The name of the method used for reading the property values as an array. May be null if the property is write-only or must be indexed.
setterName
The name of the method used for writing the property values as an array. May be null if the property is read-only or must be indexed.
indexedGetterName
The name of the method used for reading an indexed property value. May be null if the property is write-only.
indexedSetterName
The name of the method used for writing an indexed property value. May be null if the property is read-only.
Description
This constructor takes the name of a simple property, and method names for reading and writing the property, both indexed and non-indexed.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 3
public IndexedPropertyDescriptor( String propertyName, Method getter, Method setter, Method indexedGetter, Method indexedSetter ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
getter
The method used for reading the property values as an array. May be null if the property is write-only or must be indexed.
setter
The method used for writing the property values as an array. May be null if the property is read-only or must be indexed.
indexedGetter
The method used for reading an indexed property value. May be null if the property is write-only.
indexedSetter
The method used for writing an indexed property value. May be null if the property is read-only.
Description
This constructor takes the name of a simple property, and Method objects for reading and writing the property.

Exceptions
IntrospectionException if an exception occurs during introspection.


 IndexedPropertyDescriptor.getIndexedPropertyType

IndexedPropertyDescriptor.getIndexedPropertyType

Syntax
public Class getIndexedPropertyType()
Returns
The Java Class for the indexed properties type. Note that the Class may describe a primitive Java type such as "int".

This is the type that will be returned by the indexedReadMethod.


 IndexedPropertyDescriptor.getIndexedReadMethod

IndexedPropertyDescriptor.getIndexedReadMethod

Syntax
public Method getIndexedReadMethod()
Returns
The method that should be used to read an indexed property value. May return null if the property isn't indexed or is write-only.


 IndexedPropertyDescriptor.getIndexedWriteMethod

IndexedPropertyDescriptor.getIndexedWriteMethod

Syntax
public Method getIndexedWriteMethod()
Returns
The method that should be used to write an indexed property value. May return null if the property isn't indexed or is read-only.


 Class IntrospectionException

Class java.beans.IntrospectionException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.beans.IntrospectionException

public class IntrospectionException
extends Exception

Thrown when an exception happens during Introspection.

Typical causes include not being able to map a string class name to a Class object, not being able to resolve a string method name, or specifying a method name that has the wrong type signature for its intended use.


 IntrospectionException Members

IntrospectionException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IntrospectionException(String) |


 IntrospectionException.IntrospectionException

IntrospectionException.IntrospectionException

Syntax
public IntrospectionException( String mess )
Parameters
mess
Descriptive message


 Class Introspector

Class java.beans.Introspector

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.Introspector

public class Introspector
extends Object

The Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean.

For each of those three kinds of information, the Introspector will separately analyze the bean's class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean.

For each class "Foo", explicit information may be available if there exists a corresponding "FooBeanInfo" class that provides a non-null value when queried for the information. We first look for the BeanInfo class by taking the full package-qualified name of the target bean class and appending "BeanInfo" to form a new class name. If this fails, then we take the final classname component of this name, and look for that class in each of the packages specified in the BeanInfo package search path.

Thus for a class such as "sun.xyz.OurButton" we would first look for a BeanInfo class called "sun.xyz.OurButtonBeanInfo" and if that failed we'd look in each package in the BeanInfo search path for an OurButtonBeanInfo class. With the default search path, this would mean looking for "sun.beans.infos.OurButtonBeanInfo".

If a class provides explicit BeanInfo about itself then we add that to the BeanInfo information we obtained from analyzing any derived classes, but we regard the explicit information as being definitive for the current class and its base classes, and do not proceed any further up the superclass chain.

If we don't find explicit BeanInfo on a class, we use low-level reflection to study the methods of the class and apply standard design patterns to identify property accessors, event sources, or public methods. We then proceed to analyze the class's superclass and add in the information from it (and possibly on up the superclass chain).


 Introspector Members

Introspector Members

Class Overview | This Package | All Packages

Methods
Name | Description
decapitalize(String) | Utility method to take a string and convert it to normal Java variable name capitalization.
getBeanInfo(Class) | Introspect on a Java bean and learn about all its properties, exposed methods, and events.
getBeanInfo(Class, Class) | Introspect on a Java bean and learn all about its properties, exposed methods, below a given "stop" point.
getBeanInfoSearchPath() |
setBeanInfoSearchPath(String[]) | Change the list of package names that will be used for finding BeanInfo classes.


 Introspector.decapitalize

Introspector.decapitalize

Syntax
public static String decapitalize( String name )
Parameters
name
The string to be decapitalized.
Returns
The decapitalized version of the string.
Description
Utility method to take a string and convert it to normal Java variable name capitalization. This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".


 Introspector.getBeanInfo

Introspector.getBeanInfo

Syntax 1
public static BeanInfo getBeanInfo( Class beanClass ) throws IntrospectionException
Parameters
beanClass
The bean class to be analyzed.
Returns
A BeanInfo object describing the target bean.
Description
Introspect on a Java bean and learn about all its properties, exposed methods, and events.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 2
public static BeanInfo getBeanInfo( Class beanClass, Class stopClass ) throws IntrospectionException
Parameters
bean
The bean class to be analyzed.
stopClass
The baseclass at which to stop the analysis. Any methods/properties/events in the stopClass or in its baseclasses will be ignored in the analysis.
Description
Introspect on a Java bean and learn all about its properties, exposed methods, below a given "stop" point.

Exceptions
IntrospectionException if an exception occurs during introspection.


 Introspector.getBeanInfoSearchPath

Introspector.getBeanInfoSearchPath

Syntax
public static String[] getBeanInfoSearchPath()
Returns
The array of package names that will be searched in order to find BeanInfo classes.

This is initially set to {"sun.beans.infos"}.


 Introspector.setBeanInfoSearchPath

Introspector.setBeanInfoSearchPath

Syntax
public static void setBeanInfoSearchPath( String path[] )
Parameters
path
Array of package names.
Description
Change the list of package names that will be used for finding BeanInfo classes.


 Class MethodDescriptor

Class java.beans.MethodDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.MethodDescriptor

public class MethodDescriptor
extends FeatureDescriptor

A MethodDescriptor describes a particular method that a Java Bean supports for external access from other components.


 MethodDescriptor Members

MethodDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MethodDescriptor(Method) |
MethodDescriptor(Method, ParameterDescriptor[]) |

Methods
Name | Description
getMethod() |
getParameterDescriptors() |


 MethodDescriptor.MethodDescriptor

MethodDescriptor.MethodDescriptor

Syntax 1
public MethodDescriptor( Method method )
Parameters
method
The low-level method information.

Syntax 2
public MethodDescriptor( Method method, ParameterDescriptor parameterDescriptors[] )
Parameters
method
The low-level method information.
parameterDescriptors
Descriptive information for each of the method's parameters.


 MethodDescriptor.getMethod

MethodDescriptor.getMethod

Syntax
public Method getMethod()
Returns
The low-level description of the method


 MethodDescriptor.getParameterDescriptors

MethodDescriptor.getParameterDescriptors

Syntax
public ParameterDescriptor[] getParameterDescriptors()
Returns
The locale-independent names of the parameters. May return a null array if the parameter names aren't known.


 Class ParameterDescriptor

Class java.beans.ParameterDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.ParameterDescriptor

public class ParameterDescriptor
extends FeatureDescriptor

The ParameterDescriptor class allows bean implementors to provide additional information on each of their parameters, beyond the low level type information provided by the java.lang.reflect.Method class.

Currently all our state comes from the FeatureDescriptor base class.


 ParameterDescriptor Members

ParameterDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ParameterDescriptor() |


 ParameterDescriptor.ParameterDescriptor

ParameterDescriptor.ParameterDescriptor

Syntax
public ParameterDescriptor()


 Class PropertyChangeEvent

Class java.beans.PropertyChangeEvent

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject
           |
           +----java.beans.PropertyChangeEvent

public class PropertyChangeEvent
extends EventObject

A "PropertyChange" event gets delivered whenever a bean changes a "bound" or "constrained" property. A PropertyChangeEvent object is sent as an argument to the PropertyChangeListener and VetoableChangeListener methods.

Normally PropertyChangeEvents are accompanied by the name and the old and new value of the changed property. If the new value is a builtin type (such as int or boolean) it must be wrapped as the corresponding java.lang.* Object type (such as Integer or Boolean).

Null values may be provided for the old and the new values if their true values are not known.

An event source may send a null object as the name to indicate that an arbitrary set of if its properties have changed. In this case the old and new values should also be null.


 PropertyChangeEvent Members

PropertyChangeEvent Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyChangeEvent(Object, String, Object, Object) |

Methods
Name | Description
getNewValue() |
getOldValue() |
getPropagationId() | The "propagationId" field is reserved for future use.
getPropertyName() |
setPropagationId(Object) |


 PropertyChangeEvent.PropertyChangeEvent

PropertyChangeEvent.PropertyChangeEvent

Syntax
public PropertyChangeEvent( Object source, String propertyName, Object oldValue, Object newValue )
Parameters
source
The bean that fired the event.
propertyName
The programmatic name of the property that was changed.
oldValue
The old value of the property.
newValue
The new value of the property.


 PropertyChangeEvent.getNewValue

PropertyChangeEvent.getNewValue

Syntax
public Object getNewValue()
Returns
The new value for the property, expressed as an Object. May be null if multiple properties have changed.


 PropertyChangeEvent.getOldValue

PropertyChangeEvent.getOldValue

Syntax
public Object getOldValue()
Returns
The old value for the property, expressed as an Object. May be null if multiple properties have changed.


 PropertyChangeEvent.getPropagationId

PropertyChangeEvent.getPropagationId

Syntax
public Object getPropagationId()
Returns
the propagationId object associated with a bound/constrained property update.
Description
The "propagationId" field is reserved for future use. In Beans 1.0 the sole requirement is that if a listener catches a PropertyChangeEvent and then fires a PropertyChangeEvent of its own, then it should make sure that it propagates the propagationId field from its incoming event to its outgoing event.


 PropertyChangeEvent.getPropertyName

PropertyChangeEvent.getPropertyName

Syntax
public String getPropertyName()
Returns
The programmatic name of the property that was changed. May be null if multiple properties have changed.


 PropertyChangeEvent.setPropagationId

PropertyChangeEvent.setPropagationId

Syntax
public void setPropagationId( Object propagationId )
Parameters
propagationId
The propagationId object for the event.


 Interface PropertyChangeListener

Interface java.beans.PropertyChangeListener

Interface Members | This Package | All Packages

public interface PropertyChangeListener
extends EventListener

A "PropertyChange" event gets fired whenever a bean changes a "bound" property. You can register a PropertyChangeListener with a source bean so as to be notified of any bound property updates.


 PropertyChangeListener Members

PropertyChangeListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
propertyChange(PropertyChangeEvent) | This method gets called when a bound property is changed.


 PropertyChangeListener.propertyChange

PropertyChangeListener.propertyChange

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void propertyChange( PropertyChangeEvent evt )
Parameters
evt
A PropertyChangeEvent object describing the event source and the property that has changed.
Description
This method gets called when a bound property is changed.


 Class PropertyChangeSupport

Class java.beans.PropertyChangeSupport

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.PropertyChangeSupport

public class PropertyChangeSupport
extends Object
implements Serializable

This is a utility class that can be used by beans that support bound properties. You can use an instance of this class as a member field of your bean and delegate various work to it.


 PropertyChangeSupport Members

PropertyChangeSupport Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyChangeSupport(Object) |

Methods
Name | Description
addPropertyChangeListener(PropertyChangeListener) | Add a PropertyChangeListener to the listener list.
firePropertyChange(String, Object, Object) | Report a bound property update to any registered listeners.
removePropertyChangeListener(PropertyChangeListener) | Remove a PropertyChangeListener from the listener list.


 PropertyChangeSupport.PropertyChangeSupport

PropertyChangeSupport.PropertyChangeSupport

Syntax
public PropertyChangeSupport( Object sourceBean )


 PropertyChangeSupport.addPropertyChangeListener

PropertyChangeSupport.addPropertyChangeListener

Syntax
public synchronized void addPropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
The PropertyChangeListener to be added
Description
Add a PropertyChangeListener to the listener list.


 PropertyChangeSupport.firePropertyChange

PropertyChangeSupport.firePropertyChange

Syntax
public void firePropertyChange( String propertyName, Object oldValue, Object newValue )
Parameters
propertyName
The programmatic name of the property that was changed.
oldValue
The old value of the property.
newValue
The new value of the property.
Description
Report a bound property update to any registered listeners. No event is fired if old and new are equal and non-null.


 PropertyChangeSupport.removePropertyChangeListener

PropertyChangeSupport.removePropertyChangeListener

Syntax
public synchronized void removePropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
The PropertyChangeListener to be removed
Description
Remove a PropertyChangeListener from the listener list.


 Class PropertyDescriptor

Class java.beans.PropertyDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.FeatureDescriptor
           |
           +----java.beans.PropertyDescriptor

public class PropertyDescriptor
extends FeatureDescriptor

A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods.


 PropertyDescriptor Members

PropertyDescriptor Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyDescriptor(String, Class) | Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods.
PropertyDescriptor(String, Class, String, String) | This constructor takes the name of a simple property, and method names for reading and writing the property.
PropertyDescriptor(String, Method, Method) | This constructor takes the name of a simple property, and Method objects for reading and writing the property.

Methods
Name | Description
getPropertyEditorClass() |
getPropertyType() |
getReadMethod() |
getWriteMethod() |
isBound() | Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.
isConstrained() | Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.
setBound(boolean) | Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.
setConstrained(boolean) | Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.
setPropertyEditorClass(Class) | Normally PropertyEditors will be found using the PropertyEditorManager.


 PropertyDescriptor.PropertyDescriptor

PropertyDescriptor.PropertyDescriptor

Syntax 1
public PropertyDescriptor( String propertyName, Class beanClass ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
beanClass
The Class object for the target bean. For example sun.beans.OurButton.class.
Description
Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods. Thus if the argument name is "fred", it will assume that the reader method is "getFred" and the writer method is "setFred". Note that the property name should start with a lower case character, which will be capitalized in the method names.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 2
public PropertyDescriptor( String propertyName, Class beanClass, String getterName, String setterName ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
beanClass
The Class object for the target bean. For example sun.beans.OurButton.class.
getterName
The name of the method used for reading the property value. May be null if the property is write-only.
setterName
The name of the method used for writing the property value. May be null if the property is read-only.
Description
This constructor takes the name of a simple property, and method names for reading and writing the property.

Exceptions
IntrospectionException if an exception occurs during introspection.

Syntax 3
public PropertyDescriptor( String propertyName, Method getter, Method setter ) throws IntrospectionException
Parameters
propertyName
The programmatic name of the property.
getter
The method used for reading the property value. May be null if the property is write-only.
setter
The method used for writing the property value. May be null if the property is read-only.
Description
This constructor takes the name of a simple property, and Method objects for reading and writing the property.

Exceptions
IntrospectionException if an exception occurs during introspection.


 PropertyDescriptor.getPropertyEditorClass

PropertyDescriptor.getPropertyEditorClass

Syntax
public Class getPropertyEditorClass()
Returns
Any explicit PropertyEditor Class that has been registered for this property. Normally this will return "null", indicating that no special editor has been registered, so the PropertyEditorManager should be used to locate a suitable PropertyEditor.


 PropertyDescriptor.getPropertyType

PropertyDescriptor.getPropertyType

Syntax
public Class getPropertyType()
Returns
The Java type info for the property. Note that the "Class" object may describe a built-in Java type such as "int". The result may be "null" if this is an indexed property that does not support non-indexed access.

This is the type that will be returned by the ReadMethod.


 PropertyDescriptor.getReadMethod

PropertyDescriptor.getReadMethod

Syntax
public Method getReadMethod()
Returns
The method that should be used to read the property value. May return null if the property can't be read.


 PropertyDescriptor.getWriteMethod

PropertyDescriptor.getWriteMethod

Syntax
public Method getWriteMethod()
Returns
The method that should be used to write the property value. May return null if the property can't be written.


 PropertyDescriptor.isBound

PropertyDescriptor.isBound

Syntax
public boolean isBound()
Returns
True if this is a bound property.
Description
Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.


 PropertyDescriptor.isConstrained

PropertyDescriptor.isConstrained

Syntax
public boolean isConstrained()
Returns
True if this is a constrained property.
Description
Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.


 PropertyDescriptor.setBound

PropertyDescriptor.setBound

Syntax
public void setBound( boolean bound )
Parameters
bound
True if this is a bound property.
Description
Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.


 PropertyDescriptor.setConstrained

PropertyDescriptor.setConstrained

Syntax
public void setConstrained( boolean constrained )
Parameters
constrained
True if this is a constrained property.
Description
Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.


 PropertyDescriptor.setPropertyEditorClass

PropertyDescriptor.setPropertyEditorClass

Syntax
public void setPropertyEditorClass( Class propertyEditorClass )
Parameters
propertyEditorClass
The Class for the desired PropertyEditor.
Description
Normally PropertyEditors will be found using the PropertyEditorManager. However if for some reason you want to associate a particular PropertyEditor with a given property, then you can do it with this method.


 Interface PropertyEditor

Interface java.beans.PropertyEditor

Interface Members | This Package | All Packages

public interface PropertyEditor

A PropertyEditor class provides support for GUIs that want to allow users to edit a property value of a given type.

PropertyEditor supports a variety of different kinds of ways of displaying and updating property values. Most PropertyEditors will only need to support a subset of the different options available in this API.

Simple PropertyEditors may only support the getAsText and setAsText methods and need not support (say) paintValue or getCustomEditor. More complex types may be unable to support getAsText and setAsText but will instead support paintValue and getCustomEditor.

Every propertyEditor must support one or more of the three simple display styles. Thus it can either (1) support isPaintable or (2) both return a non-null String[] from getTags() and return a non-null value from getAsText or (3) simply return a non-null String from getAsText().

Every property editor must support a call on setValue when the argument object is of the type for which this is the corresponding propertyEditor. In addition, each property editor must either support a custom editor, or support setAsText.

Each PropertyEditor should have a null constructor.


 PropertyEditor Members

PropertyEditor Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addPropertyChangeListener(PropertyChangeListener) | Register a listener for the PropertyChange event.
getAsText() |
getCustomEditor() | A PropertyEditor may choose to make available a full custom Component that edits its property value.
getJavaInitializationString() | This method is intended for use when generating Java code to set the value of the property.
getTags() | If the property value must be one of a set of known tagged values, then this method should return an array of the tags.
getValue() |
isPaintable() |
paintValue(Graphics, Rectangle) | Paint a representation of the value into a given area of screen real estate.
removePropertyChangeListener(PropertyChangeListener) | Remove a listener for the PropertyChange event.
setAsText(String) | Set the property value by parsing a given String.
setValue(Object) | Set (or change) the object that is to be edited.
supportsCustomEditor() |


 PropertyEditor.addPropertyChangeListener

PropertyEditor.addPropertyChangeListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void addPropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
An object to be invoked when a PropertyChange event is fired.
Description
Register a listener for the PropertyChange event. When a PropertyEditor changes its value it should fire a PropertyChange event on all registered PropertyChangeListeners, specifying the null value for the property name and itself as the source.


 PropertyEditor.getAsText

PropertyEditor.getAsText

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getAsText()
Returns
The property value as a human editable string.

Returns null if the value can't be expressed as an editable string.

If a non-null value is returned, then the PropertyEditor should be prepared to parse that string back in setAsText().


 PropertyEditor.getCustomEditor

PropertyEditor.getCustomEditor

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Component getCustomEditor()
Returns
A java.awt.Component that will allow a human to directly edit the current property value. May be null if this is not supported.
Description
A PropertyEditor may choose to make available a full custom Component that edits its property value. It is the responsibility of the PropertyEditor to hook itself up to its editor Component itself and to report property value changes by firing a PropertyChange event.

The higher-level code that calls getCustomEditor may either embed the Component in some larger property sheet, or it may put it in its own individual dialog, or ...


 PropertyEditor.getJavaInitializationString

PropertyEditor.getJavaInitializationString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getJavaInitializationString()
Returns
A fragment of Java code representing an initializer for the current value.
Description
This method is intended for use when generating Java code to set the value of the property. It should return a fragment of Java code that can be used to initialize a variable with the current property value.

Example results are "2", "new Color(127,127,34)", "Color.orange", etc.


 PropertyEditor.getTags

PropertyEditor.getTags

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String[] getTags()
Returns
The tag values for this property. May be null if this property cannot be represented as a tagged value.
Description
If the property value must be one of a set of known tagged values, then this method should return an array of the tags. This can be used to represent (for example) enum values. If a PropertyEditor supports tags, then it should support the use of setAsText with a tag value as a way of setting the value and the use of getAsText to identify the current value.


 PropertyEditor.getValue

PropertyEditor.getValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object getValue()
Returns
The value of the property. Builtin types such as "int" will be wrapped as the corresponding object type such as "java.lang.Integer".


 PropertyEditor.isPaintable

PropertyEditor.isPaintable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isPaintable()
Returns
True if the class will honor the paintValue method.


 PropertyEditor.paintValue

PropertyEditor.paintValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void paintValue( Graphics gfx, Rectangle box )
Parameters
gfx
Graphics object to paint into.
box
Rectangle within graphics object into which we should paint.
Description
Paint a representation of the value into a given area of screen real estate. Note that the propertyEditor is responsible for doing its own clipping so that it fits into the given rectangle.

If the PropertyEditor doesn't honor paint requests (see isPaintable) this method should be a silent noop.

The given Graphics object will have the default font, color, etc of the parent container. The PropertyEditor may change graphics attributes such as font and color and doesn't need to restore the old values.


 PropertyEditor.removePropertyChangeListener

PropertyEditor.removePropertyChangeListener

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void removePropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
The PropertyChange listener to be removed.
Description
Remove a listener for the PropertyChange event.


 PropertyEditor.setAsText

PropertyEditor.setAsText

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setAsText( String text ) throws IllegalArgumentException
Parameters
text
The string to be parsed.
Description
Set the property value by parsing a given String. May raise java.lang.IllegalArgumentException if either the String is badly formatted or if this kind of property can't be expressed as text.


 PropertyEditor.setValue

PropertyEditor.setValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setValue( Object value )
Parameters
value
The new target object to be edited. Note that this object should not be modified by the PropertyEditor, rather the PropertyEditor should create a new object to hold any modified value.
Description
Set (or change) the object that is to be edited. Builtin types such as "int" must be wrapped as the corresponding object type such as "java.lang.Integer".


 PropertyEditor.supportsCustomEditor

PropertyEditor.supportsCustomEditor

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCustomEditor()
Returns
True if the propertyEditor can provide a custom editor.


 Class PropertyEditorManager

Class java.beans.PropertyEditorManager

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.PropertyEditorManager

public class PropertyEditorManager
extends Object

The PropertyEditorManager can be used to locate a property editor for any given type name. This property editor must support the java.beans.PropertyEditor interface for editing a given object.

The PropertyEditorManager uses three techniques for locating an editor for a given type. First, it provides a registerEditor method to allow an editor to be specifically registered for a given type. Second it tries to locate a suitable class by adding "Editor" to the full qualified classname of the given type (e.g. "foo.bah.FozEditor"). Finally it takes the simple classname (without the package name) adds "Editor" to it and looks in a search-path of packages for a matching class.

So for an input class foo.bah.Fred, the PropertyEditorManager would first look in its tables to see if an editor had been registered for foo.bah.Fred and if so use that. Then it will look for a foo.bah.FredEditor class. Then it will look for (say) standardEditorsPackage.FredEditor class.

Default PropertyEditors will be provided for the Java builtin types "boolean", "byte", "short", "int", "long", "float", and "double"; and for the classes java.lang.String. java.awt.Color, and java.awt.Font.


 PropertyEditorManager Members

PropertyEditorManager Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyEditorManager() |

Methods
Name | Description
findEditor(Class) | Locate a value editor for a given target type.
getEditorSearchPath() |
registerEditor(Class, Class) | Register an editor class to be used to editor values of a given target class.
setEditorSearchPath(String[]) | Change the list of package names that will be used for finding property editors.


 PropertyEditorManager.PropertyEditorManager

PropertyEditorManager.PropertyEditorManager

Syntax
public PropertyEditorManager()


 PropertyEditorManager.findEditor

PropertyEditorManager.findEditor

Syntax
public static PropertyEditor findEditor( Class targetType )
Parameters
targetType
The Class object for the type to be edited
Returns
An editor object for the given target class. The result is null if no suitable editor can be found.
Description
Locate a value editor for a given target type.


 PropertyEditorManager.getEditorSearchPath

PropertyEditorManager.getEditorSearchPath

Syntax
public static String[] getEditorSearchPath()
Returns
The array of package names that will be searched in order to find property editors.

This is initially set to {"sun.beans.editors"}.


 PropertyEditorManager.registerEditor

PropertyEditorManager.registerEditor

Syntax
public static void registerEditor( Class targetType, Class editorClass )
Parameters
targetType
the Class object of the type to be edited
editorClass
the Class object of the editor class. If this is null, then any existing definition will be removed.
Description
Register an editor class to be used to editor values of a given target class.


 PropertyEditorManager.setEditorSearchPath

PropertyEditorManager.setEditorSearchPath

Syntax
public static void setEditorSearchPath( String path[] )
Parameters
path
Array of package names.
Description
Change the list of package names that will be used for finding property editors.


 Class PropertyEditorSupport

Class java.beans.PropertyEditorSupport

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.PropertyEditorSupport

public class PropertyEditorSupport
extends Object
implements PropertyEditor


 PropertyEditorSupport Members

PropertyEditorSupport Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyEditorSupport() | Constructor for use by derived PropertyEditor classes.
PropertyEditorSupport(Object) | Constructor for use when a PropertyEditor is delegating to us.

Methods
Name | Description
addPropertyChangeListener(PropertyChangeListener) | Register a listener for the PropertyChange event.
firePropertyChange() | Report that we have been modified to any interested listeners.
getAsText() |
getCustomEditor() | A PropertyEditor may chose to make available a full custom Component that edits its property value.
getJavaInitializationString() | This method is intended for use when generating Java code to set the value of the property.
getTags() | If the property value must be one of a set of known tagged values, then this method should return an array of the tag values.
getValue() |
isPaintable() |
paintValue(Graphics, Rectangle) | Paint a representation of the value into a given area of screen real estate.
removePropertyChangeListener(PropertyChangeListener) | Remove a listener for the PropertyChange event.
setAsText(String) | Set the property value by parsing a given String.
setValue(Object) | Set (or change) the object that is to be edited.
supportsCustomEditor() |


 PropertyEditorSupport.PropertyEditorSupport

PropertyEditorSupport.PropertyEditorSupport

Syntax 1
protected PropertyEditorSupport()
Description
Constructor for use by derived PropertyEditor classes.

Syntax 2
protected PropertyEditorSupport( Object source )
Parameters
source
The source to use for any events we fire.
Description
Constructor for use when a PropertyEditor is delegating to us.


 PropertyEditorSupport.addPropertyChangeListener

PropertyEditorSupport.addPropertyChangeListener

Syntax
public synchronized void addPropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
An object to be invoked when a PropertyChange event is fired.
Description
Register a listener for the PropertyChange event. The class will fire a PropertyChange value whenever the value is updated.


 PropertyEditorSupport.firePropertyChange

PropertyEditorSupport.firePropertyChange

Syntax
public void firePropertyChange()
Parameters
source
The PropertyEditor that caused the event.
Description
Report that we have been modified to any interested listeners.


 PropertyEditorSupport.getAsText

PropertyEditorSupport.getAsText

Syntax
public String getAsText()
Returns
The property value as a string suitable for presentation to a human to edit.

Returns "null" is the value can't be expressed as a string.

If a non-null value is returned, then the PropertyEditor should be prepared to parse that string back in setAsText().


 PropertyEditorSupport.getCustomEditor

PropertyEditorSupport.getCustomEditor

Syntax
public Component getCustomEditor()
Returns
A java.awt.Component that will allow a human to directly edit the current property value. May be null if this is not supported.
Description
A PropertyEditor may chose to make available a full custom Component that edits its property value. It is the responsibility of the PropertyEditor to hook itself up to its editor Component itself and to report property value changes by firing a PropertyChange event.

The higher-level code that calls getCustomEditor may either embed the Component in some larger property sheet, or it may put it in its own individual dialog, or ...


 PropertyEditorSupport.getJavaInitializationString

PropertyEditorSupport.getJavaInitializationString

Syntax
public String getJavaInitializationString()
Returns
A fragment of Java code representing an initializer for the current value.
Description
This method is intended for use when generating Java code to set the value of the property. It should return a fragment of Java code that can be used to initialize a variable with the current property value.

Example results are "2", "new Color(127,127,34)", "Color.orange", etc.


 PropertyEditorSupport.getTags

PropertyEditorSupport.getTags

Syntax
public String[] getTags()
Returns
The tag values for this property. May be null if this property cannot be represented as a tagged value.
Description
If the property value must be one of a set of known tagged values, then this method should return an array of the tag values. This can be used to represent (for example) enum values. If a PropertyEditor supports tags, then it should support the use of setAsText with a tag value as a way of setting the value.


 PropertyEditorSupport.getValue

PropertyEditorSupport.getValue

Syntax
public Object getValue()
Returns
The value of the property.


 PropertyEditorSupport.isPaintable

PropertyEditorSupport.isPaintable

Syntax
public boolean isPaintable()
Returns
True if the class will honor the paintValue method.


 PropertyEditorSupport.paintValue

PropertyEditorSupport.paintValue

Syntax
public void paintValue( Graphics gfx, Rectangle box )
Parameters
gfx
Graphics object to paint into.
box
Rectangle within graphics object into which we should paint.
Description
Paint a representation of the value into a given area of screen real estate. Note that the propertyEditor is responsible for doing its own clipping so that it fits into the given rectangle.

If the PropertyEditor doesn't honor paint requests (see isPaintable) this method should be a silent noop.


 PropertyEditorSupport.removePropertyChangeListener

PropertyEditorSupport.removePropertyChangeListener

Syntax
public synchronized void removePropertyChangeListener( PropertyChangeListener listener )
Parameters
listener
The PropertyChange listener to be removed.
Description
Remove a listener for the PropertyChange event.


 PropertyEditorSupport.setAsText

PropertyEditorSupport.setAsText

Syntax
public void setAsText( String text ) throws IllegalArgumentException
Parameters
text
The string to be parsed.
Description
Set the property value by parsing a given String. May raise java.lang.IllegalArgumentException if either the String is badly formatted or if this kind of property can't be expressed as text.


 PropertyEditorSupport.setValue

PropertyEditorSupport.setValue

Syntax
public void setValue( Object value )
Parameters
value
The new target object to be edited. Note that this object should not be modified by the PropertyEditor, rather the PropertyEditor should create a new object to hold any modified value.
Description
Set (or change) the object that is to be edited.


 PropertyEditorSupport.supportsCustomEditor

PropertyEditorSupport.supportsCustomEditor

Syntax
public boolean supportsCustomEditor()
Returns
True if the propertyEditor can provide a custom editor.


 Class PropertyVetoException

Class java.beans.PropertyVetoException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.beans.PropertyVetoException

public class PropertyVetoException
extends Exception

A PropertyVetoException is thrown when a proposed change to a property represents an unacceptable value.


 PropertyVetoException Members

PropertyVetoException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyVetoException(String, PropertyChangeEvent) |

Methods
Name | Description
getPropertyChangeEvent() |


 PropertyVetoException.PropertyVetoException

PropertyVetoException.PropertyVetoException

Syntax
public PropertyVetoException( String mess, PropertyChangeEvent evt )
Parameters
mess
Descriptive message
evt
A PropertyChangeEvent describing the vetoed change.


 PropertyVetoException.getPropertyChangeEvent

PropertyVetoException.getPropertyChangeEvent

Syntax
public PropertyChangeEvent getPropertyChangeEvent()


 Class SimpleBeanInfo

Class java.beans.SimpleBeanInfo

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.SimpleBeanInfo

public class SimpleBeanInfo
extends Object
implements BeanInfo

This is a support class to make it easier for people to provide BeanInfo classes.

It defaults to providing "noop" information, and can be selectively overriden to provide more explicit information on chosen topics. When the introspector sees the "noop" values, it will apply low level introspection and design patterns to automatically analyze the target bean.


 SimpleBeanInfo Members

SimpleBeanInfo Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SimpleBeanInfo() |

Methods
Name | Description
getAdditionalBeanInfo() | Claim there are no other relevant BeanInfo objects.
getBeanDescriptor() | Deny knowledge about the class and customizer of the bean.
getDefaultEventIndex() | Deny knowledge of a default event.
getDefaultPropertyIndex() | Deny knowledge of a default property.
getEventSetDescriptors() | Deny knowledge of event sets.
getIcon(int) | Claim there are no icons available.
getMethodDescriptors() | Deny knowledge of methods.
getPropertyDescriptors() | Deny knowledge of properties.
loadImage(String) | This is a utility method to help in loading icon images.


 SimpleBeanInfo.SimpleBeanInfo

SimpleBeanInfo.SimpleBeanInfo

Syntax
public SimpleBeanInfo()


 SimpleBeanInfo.getAdditionalBeanInfo

SimpleBeanInfo.getAdditionalBeanInfo

Syntax
public BeanInfo[] getAdditionalBeanInfo()
Description
Claim there are no other relevant BeanInfo objects. You may override this if you want to (for example) return a BeanInfo for a base class.


 SimpleBeanInfo.getBeanDescriptor

SimpleBeanInfo.getBeanDescriptor

Syntax
public BeanDescriptor getBeanDescriptor()
Description
Deny knowledge about the class and customizer of the bean. You can override this if you wish to provide explicit info.


 SimpleBeanInfo.getDefaultEventIndex

SimpleBeanInfo.getDefaultEventIndex

Syntax
public int getDefaultEventIndex()
Description
Deny knowledge of a default event. You can override this if you wish to define a default event for the bean.


 SimpleBeanInfo.getDefaultPropertyIndex

SimpleBeanInfo.getDefaultPropertyIndex

Syntax
public int getDefaultPropertyIndex()
Description
Deny knowledge of a default property. You can override this if you wish to define a default property for the bean.


 SimpleBeanInfo.getEventSetDescriptors

SimpleBeanInfo.getEventSetDescriptors

Syntax
public EventSetDescriptor[] getEventSetDescriptors()
Description
Deny knowledge of event sets. You can override this if you wish to provide explicit event set info.


 SimpleBeanInfo.getIcon

SimpleBeanInfo.getIcon

Syntax
public Image getIcon( int iconKind )
Description
Claim there are no icons available. You can override this if you want to provide icons for your bean.


 SimpleBeanInfo.getMethodDescriptors

SimpleBeanInfo.getMethodDescriptors

Syntax
public MethodDescriptor[] getMethodDescriptors()
Description
Deny knowledge of methods. You can override this if you wish to provide explicit method info.


 SimpleBeanInfo.getPropertyDescriptors

SimpleBeanInfo.getPropertyDescriptors

Syntax
public PropertyDescriptor[] getPropertyDescriptors()
Description
Deny knowledge of properties. You can override this if you wish to provide explicit property info.


 SimpleBeanInfo.loadImage

SimpleBeanInfo.loadImage

Syntax
public Image loadImage( String resourceName )
Parameters
resourceName
A pathname relative to the directory holding the class file of the current class. For example, "wombat.gif".
Returns
an image object. May be null if the load failed.
Description
This is a utility method to help in loading icon images. It takes the name of a resource file associated with the current object's class file and loads an image object from that file. Typically images will be GIFs.


 Interface VetoableChangeListener

Interface java.beans.VetoableChangeListener

Interface Members | This Package | All Packages

public interface VetoableChangeListener
extends EventListener

A VetoableChange event gets fired whenever a bean changes a "constrained" property. You can register a VetoableChangeListener with a source bean so as to be notified of any constrained property updates.


 VetoableChangeListener Members

VetoableChangeListener Members

Interface Overview | This Package | All Packages

Methods
Name | Description
vetoableChange(PropertyChangeEvent) | This method gets called when a constrained property is changed.


 VetoableChangeListener.vetoableChange

VetoableChangeListener.vetoableChange

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void vetoableChange( PropertyChangeEvent evt ) throws PropertyVetoException
Parameters
evt
a PropertyChangeEvent object describing the event source and the property that has changed.
Description
This method gets called when a constrained property is changed.

Exceptions
PropertyVetoException if the recipient wishes the property change to be rolled back.


 Class VetoableChangeSupport

Class java.beans.VetoableChangeSupport

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.beans.VetoableChangeSupport

public class VetoableChangeSupport
extends Object
implements Serializable

This is a utility class that can be used by beans that support constrained properties. You can use an instance of this class as a member field of your bean and delegate various work to it.


 VetoableChangeSupport Members

VetoableChangeSupport Members

Class Overview | This Package | All Packages

Constructors
Name | Description
VetoableChangeSupport(Object) |

Methods
Name | Description
addVetoableChangeListener(VetoableChangeListener) | Add a VetoableListener to the listener list.
fireVetoableChange(String, Object, Object) | Report a vetoable property update to any registered listeners.
removeVetoableChangeListener(VetoableChangeListener) | Remove a VetoableChangeListener from the listener list.


 VetoableChangeSupport.VetoableChangeSupport

VetoableChangeSupport.VetoableChangeSupport

Syntax
public VetoableChangeSupport( Object sourceBean )


 VetoableChangeSupport.addVetoableChangeListener

VetoableChangeSupport.addVetoableChangeListener

Syntax
public synchronized void addVetoableChangeListener( VetoableChangeListener listener )
Parameters
listener
The VetoableChangeListener to be added
Description
Add a VetoableListener to the listener list.


 VetoableChangeSupport.fireVetoableChange

VetoableChangeSupport.fireVetoableChange

Syntax
public void fireVetoableChange( String propertyName, Object oldValue, Object newValue ) throws PropertyVetoException
Parameters
propertyName
The programmatic name of the property that was changed.
oldValue
The old value of the property.
newValue
The new value of the property.
Description
Report a vetoable property update to any registered listeners. If anyone vetos the change, then fire a new event reverting everyone to the old value and then rethrow the PropertyVetoException.

No event is fired if old and new are equal and non-null.

Exceptions
PropertyVetoException if the recipient wishes the property change to be rolled back.


 VetoableChangeSupport.removeVetoableChangeListener

VetoableChangeSupport.removeVetoableChangeListener

Syntax
public synchronized void removeVetoableChangeListener( VetoableChangeListener listener )
Parameters
listener
The VetoableChangeListener to be removed
Description
Remove a VetoableChangeListener from the listener list.


 Interface Visibility

Interface java.beans.Visibility

Interface Members | This Package | All Packages

public interface Visibility

Under some circumstances a bean may be run on servers where a GUI is not available. This interface can be used to query a bean to determine whether it absolutely needs a gui, and to advise the bean whether a GUI is available.

This interface is for expert developers, and is not needed for normal simple beans. To avoid confusing end-users we avoid using getXXX setXXX design patterns for these methods.


 Visibility Members

Visibility Members

Interface Overview | This Package | All Packages

Methods
Name | Description
avoidingGui() |
dontUseGui() | This method instructs the bean that it should not use the Gui.
needsGui() |
okToUseGui() | This method instructs the bean that it is OK to use the Gui.


 Visibility.avoidingGui

Visibility.avoidingGui

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean avoidingGui()
Returns
true if the bean is currently avoiding use of the Gui. e.g. due to a call on dontUseGui().


 Visibility.dontUseGui

Visibility.dontUseGui

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void dontUseGui()
Description
This method instructs the bean that it should not use the Gui.


 Visibility.needsGui

Visibility.needsGui

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean needsGui()
Returns
True if the bean absolutely needs a GUI available in order to get its work done.


 Visibility.okToUseGui

Visibility.okToUseGui

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void okToUseGui()
Description
This method instructs the bean that it is OK to use the Gui.


 Package java.io

Package java.io

All Packages

Interfaces

  • DataInput
  • DataOutput
  • Externalizable
  • FilenameFilter
  • ObjectInput
  • ObjectInputValidation
  • ObjectOutput
  • Serializable

    • Classes

  • BufferedInputStream
  • BufferedOutputStream
  • BufferedReader
  • BufferedWriter
  • ByteArrayInputStream
  • ByteArrayOutputStream
  • CharArrayReader
  • CharArrayWriter
  • DataInputStream
  • DataOutputStream
  • File
  • FileDescriptor
  • FileInputStream
  • FileOutputStream
  • FileReader
  • FileWriter
  • FilterInputStream
  • FilterOutputStream
  • FilterReader
  • FilterWriter
  • InputStream
  • InputStreamReader
  • LineNumberInputStream
  • LineNumberReader
  • ObjectInputStream
  • ObjectOutputStream
  • ObjectStreamClass
  • OutputStream
  • OutputStreamWriter
  • PipedInputStream
  • PipedOutputStream
  • PipedReader
  • PipedWriter
  • PrintStream
  • PrintWriter
  • PushbackInputStream
  • PushbackReader
  • RandomAccessFile
  • Reader
  • SequenceInputStream
  • StreamTokenizer
  • StringBufferInputStream
  • StringReader
  • StringWriter
  • Writer

    • Exceptions

  • CharConversionException
  • EOFException
  • FileNotFoundException
  • IOException
  • InterruptedIOException
  • InvalidClassException
  • InvalidObjectException
  • NotActiveException
  • NotSerializableException
  • ObjectStreamException
  • OptionalDataException
  • StreamCorruptedException
  • SyncFailedException
  • UTFDataFormatException
  • UnsupportedEncodingException
  • WriteAbortedException


 Class BufferedInputStream

Class java.io.BufferedInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.io.BufferedInputStream

public class BufferedInputStream
extends FilterInputStream

The class implements a buffered input stream. By setting up such an input stream, an application can read bytes from a stream without necessarily causing a call to the underlying system for each byte read. The data is read by blocks into a buffer; subsequent reads can access the data directly from the buffer.


 BufferedInputStream Members

BufferedInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The buffer where data is stored.
count | The index one greater than the index of the last valid byte in the buffer.
marklimit | The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail.
markpos | The value of the pos field at the time the last mark method was called.
pos | The current position in the buffer.

Constructors
Name | Description
BufferedInputStream(InputStream) | Creates a new buffered input stream to read data from the specified input stream with a default 512-byte buffer size.
BufferedInputStream(InputStream, int) | Creates a new buffered input stream to read data from the specified input stream with the specified buffer size.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
mark(int) | Marks the current position in this input stream.
markSupported() | Tests if this input stream supports the mark and reset methods.
read() | Reads the next byte of data from this buffered input stream.
read(byte[], int, int) | Reads bytes into a portion of an array.
reset() | Repositions this stream to the position at the time the mark method was last called on this input stream.
skip(long) | Skips over and discards n bytes of data from the input stream.


 BufferedInputStream.buf

BufferedInputStream.buf

Syntax
protected byte buf[]
Description
The buffer where data is stored.


 BufferedInputStream.count

BufferedInputStream.count

Syntax
protected int count
Description
The index one greater than the index of the last valid byte in the buffer.


 BufferedInputStream.marklimit

BufferedInputStream.marklimit

Syntax
protected int marklimit
Description
The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail.

See Also
mark, reset


 BufferedInputStream.markpos

BufferedInputStream.markpos

Syntax
protected int markpos
Description
The value of the pos field at the time the last mark method was called. The value of this field is -1 if there is no current mark.

See Also
mark, pos


 BufferedInputStream.pos

BufferedInputStream.pos

Syntax
protected int pos
Description
The current position in the buffer. This is the index of the next character to be read from the buf array.

See Also
buf


 BufferedInputStream.BufferedInputStream

BufferedInputStream.BufferedInputStream

Syntax 1
public BufferedInputStream( InputStream in )
Parameters
in
the underlying input stream.
Description
Creates a new buffered input stream to read data from the specified input stream with a default 512-byte buffer size.

Syntax 2
public BufferedInputStream( InputStream in, int size )
Parameters
in
the underlying input stream.
size
the buffer size.
Description
Creates a new buffered input stream to read data from the specified input stream with the specified buffer size.


 BufferedInputStream.available

BufferedInputStream.available

Syntax
public synchronized int available() throws IOException
Returns
the number of bytes that can be read from this input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking.

The available method of BufferedInputStream returns the sum of the the number of bytes remaining to be read in the buffer (count - pos) and the result of calling the available method of the underlying input stream.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class FilterInputStream
See Also
in


 BufferedInputStream.mark

BufferedInputStream.mark

Syntax
public synchronized void mark( int readlimit )
Parameters
readlimit
the maximum limit of bytes that can be read before the mark position becomes invalid.
Description
Marks the current position in this input stream. A subsequent call to the reset method repositions the stream at the last marked position so that subsequent reads re-read the same bytes.

The readlimit argument tells the input stream to allow that many bytes to be read before the mark position gets invalidated.

Overrides
mark in class FilterInputStream
See Also
reset


 BufferedInputStream.markSupported

BufferedInputStream.markSupported

Syntax
public boolean markSupported()
Returns
a boolean indicating if this stream type supports the mark and reset methods.
Description
Tests if this input stream supports the mark and reset methods. The markSupported method of BufferedInputStream returns true.

Overrides
markSupported in class FilterInputStream
See Also
mark, reset


 BufferedInputStream.read

BufferedInputStream.read

Syntax 1
public synchronized int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this buffered input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

The read method of BufferedInputStream returns the next byte of data from its buffer if the buffer is not empty. Otherwise, it refills the buffer from the underlying input stream and returns the next character, if the underlying stream has not returned an end-of-stream indicator.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
in

Syntax 2
public synchronized int read( byte b[], int off, int len ) throws IOException
Parameters
b
destination buffer.
off
offset at which to start storing bytes.
len
maximum number of bytes to read.
Returns
the number of bytes read, or -1 if the end of the stream has been reached.
Description
Reads bytes into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

If this stream's buffer is not empty, bytes are copied from it into the array argument. Otherwise, the buffer is refilled from the underlying input stream and, unless the stream returns an end-of-stream indication, the array argument is filled with characters from the newly-filled buffer.

As an optimization, if the buffer is empty, the mark is not valid, and len is at least as large as the buffer, then this method will read directly from the underlying stream into the given array. Thus redundant BufferedInputStreams will not copy data unnecessarily.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream


 BufferedInputStream.reset

BufferedInputStream.reset

Syntax
public synchronized void reset() throws IOException
Description
Repositions this stream to the position at the time the mark method was last called on this input stream.

If the stream has not been marked, or if the mark has been invalidated, an IOException is thrown. Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the parser, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it fails. If an exception gets tossed within readlimit bytes, the parser will allow the outer code to reset the stream and to try another parser.

Exceptions
IOException if this stream has not been marked or if the mark has been invalidated.
Overrides
reset in class FilterInputStream
See Also
mark


 BufferedInputStream.skip

BufferedInputStream.skip

Syntax
public synchronized long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly zero. The actual number of bytes skipped is returned.

The skip method of BufferedInputStream compares the number of bytes it has available in its buffer, k, where k = count - pos, with n. If n ≤ k, then the pos field is incremented by n. Otherwise, the pos field is incremented to have the value count, and the remaining bytes are skipped by calling the skip method on the underlying input stream, supplying the argument n - k.

Exceptions
IOException if an I/O error occurs.
Overrides
skip in class FilterInputStream


 Class BufferedOutputStream

Class java.io.BufferedOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.io.BufferedOutputStream

public class BufferedOutputStream
extends FilterOutputStream

The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. The data is written into a buffer, and then written to the underlying stream if the buffer reaches its capacity, the buffer output stream is closed, or the buffer output stream is explicity flushed.


 BufferedOutputStream Members

BufferedOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The buffer where data is stored.
count | The number of valid bytes in the buffer.

Constructors
Name | Description
BufferedOutputStream(OutputStream) | Creates a new buffered output stream to write data to the specified underlying output stream with a default 512-byte buffer size.
BufferedOutputStream(OutputStream, int) | Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Methods
Name | Description
flush() | Flushes this buffered output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this buffered output stream.
write(int) | Writes the specified byte to this buffered output stream.


 BufferedOutputStream.buf

BufferedOutputStream.buf

Syntax
protected byte buf[]
Description
The buffer where data is stored.


 BufferedOutputStream.count

BufferedOutputStream.count

Syntax
protected int count
Description
The number of valid bytes in the buffer.


 BufferedOutputStream.BufferedOutputStream

BufferedOutputStream.BufferedOutputStream

Syntax 1
public BufferedOutputStream( OutputStream out )
Parameters
out
the underlying output stream.
Description
Creates a new buffered output stream to write data to the specified underlying output stream with a default 512-byte buffer size.

Syntax 2
public BufferedOutputStream( OutputStream out, int size )
Parameters
out
the underlying output stream.
size
the buffer size.
Description
Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.


 BufferedOutputStream.flush

BufferedOutputStream.flush

Syntax
public synchronized void flush() throws IOException
Description
Flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
flush in class FilterOutputStream
See Also
out


 BufferedOutputStream.write

BufferedOutputStream.write

Syntax 1
public synchronized void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to this buffered output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream

Syntax 2
public synchronized void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Ordinarily this method stores bytes from the given array into this stream's buffer, flushing the buffer to the underlying output stream as needed. If the requested length is at least as large as this stream's buffer, however, then this method will flush the buffer and write the bytes directly to the underlying output stream. Thus redundant BufferedOutputStreams will not copy data unnecessarily.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream


 Class BufferedReader

Class java.io.BufferedReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.BufferedReader

public class BufferedReader
extends Reader

Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

See Also:
FileReader, InputStreamReader


 BufferedReader Members

BufferedReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BufferedReader(Reader) | Create a buffering character-input stream that uses a default-sized input buffer.
BufferedReader(Reader, int) | Create a buffering character-input stream that uses an input buffer of the specified size.

Methods
Name | Description
close() | Close the stream.
mark(int) | Mark the present position in the stream.
markSupported() | Tell whether this stream supports the mark() operation, which it does.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
readLine() | Read a line of text.
ready() | Tell whether this stream is ready to be read.
reset() | Reset the stream to the most recent mark.
skip(long) | Skip characters.


 BufferedReader.BufferedReader

BufferedReader.BufferedReader

Syntax 1
public BufferedReader( Reader in, int sz )
Parameters
in
A Reader
sz
Input-buffer size
Description
Create a buffering character-input stream that uses an input buffer of the specified size.

Exceptions
IllegalArgumentException If sz is <= 0

Syntax 2
public BufferedReader( Reader in )
Parameters
in
A Reader
Description
Create a buffering character-input stream that uses a default-sized input buffer.


 BufferedReader.close

BufferedReader.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Reader


 BufferedReader.mark

BufferedReader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Parameters
readAheadLimit
Limit on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care.
Description
Mark the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.

Exceptions
IllegalArgumentException If readAheadLimit is < 0
Exceptions
IOException If an I/O error occurs
Overrides
mark in class Reader


 BufferedReader.markSupported

BufferedReader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation, which it does.

Overrides
markSupported in class Reader


 BufferedReader.read

BufferedReader.read

Syntax 1
public int read() throws IOException
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The number of bytes read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Ordinarily this method takes characters from this stream's character buffer, filling it from the underlying stream as necessary. If, however, the buffer is empty, the mark is not valid, and the requested length is at least as large as the buffer, then this method will read characters directly from the underlying stream into the given array. Thus redundant BufferedReaders will not copy data unnecessarily.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 BufferedReader.readLine

BufferedReader.readLine

Syntax
public String readLine() throws IOException
Returns
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Description
Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Exceptions
IOException If an I/O error occurs


 BufferedReader.ready

BufferedReader.ready

Syntax
public boolean ready() throws IOException
Description
Tell whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.

Exceptions
IOException If an I/O error occurs
Overrides
ready in class Reader


 BufferedReader.reset

BufferedReader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream to the most recent mark.

Exceptions
IOException If the stream has never been marked, or if the mark has been invalidated
Overrides
reset in class Reader


 BufferedReader.skip

BufferedReader.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
The number of characters to skip
Returns
The number of characters actually skipped
Description
Skip characters.

Exceptions
IOException If an I/O error occurs
Overrides
skip in class Reader


 Class BufferedWriter

Class java.io.BufferedWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.BufferedWriter

public class BufferedWriter
extends Writer

Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

 PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

See Also:
PrintWriter, FileWriter, OutputStreamWriter


 BufferedWriter Members

BufferedWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BufferedWriter(Writer) | Create a buffered character-output stream that uses a default-sized output buffer.
BufferedWriter(Writer, int) | Create a new buffered character-output stream that uses an output buffer of the given size.

Methods
Name | Description
close() | Close the stream.
flush() | Flush the stream.
newLine() | Write a line separator.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String, int, int) | Write a portion of a String.


 BufferedWriter.BufferedWriter

BufferedWriter.BufferedWriter

Syntax 1
public BufferedWriter( Writer out )
Parameters
out
A Writer
Description
Create a buffered character-output stream that uses a default-sized output buffer.

Syntax 2
public BufferedWriter( Writer out, int sz )
Parameters
out
A Writer
sz
Output-buffer size, a positive integer
Description
Create a new buffered character-output stream that uses an output buffer of the given size.

Exceptions
IllegalArgumentException If sz is <= 0


 BufferedWriter.close

BufferedWriter.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Writer


 BufferedWriter.flush

BufferedWriter.flush

Syntax
public void flush() throws IOException
Description
Flush the stream.

Exceptions
IOException If an I/O error occurs
Overrides
flush in class Writer


 BufferedWriter.newLine

BufferedWriter.newLine

Syntax
public void newLine() throws IOException
Description
Write a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

Exceptions
IOException If an I/O error occurs


 BufferedWriter.write

BufferedWriter.write

Syntax 1
public void write( int c ) throws IOException
Description
Write a single character.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 2
public void write( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
A character array
off
Offset from which to start reading characters
len
Number of characters to write
Description
Write a portion of an array of characters.

Ordinarily this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed. If the requested length is at least as large as the buffer, however, then this method will flush the buffer and write the characters directly to the underlying stream. Thus redundant BufferedWriters will not copy data unnecessarily.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 3
public void write( String s, int off, int len ) throws IOException
Parameters
s
String to be written
off
Offset from which to start reading characters
len
Number of characters to be written
Description
Write a portion of a String.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer


 Class ByteArrayInputStream

Class java.io.ByteArrayInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.ByteArrayInputStream

public class ByteArrayInputStream
extends InputStream

This class allows an application to create an input stream in which the bytes read are supplied by the contents of a byte array. Applications can also read bytes from a string by using a StringBufferInputStream.

See Also:
StringBufferInputStream


 ByteArrayInputStream Members

ByteArrayInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The byte array containing the data.
count | The index one greater than the last valid character in the input stream buffer.
mark | The currently marked position in the stream.
pos | The index of the next character to read from the input stream buffer.

Constructors
Name | Description
ByteArrayInputStream(byte[]) | Creates a new byte array input stream that reads data from the specified byte array.
ByteArrayInputStream(byte[], int, int) | Creates a new byte array input stream that reads data from the specified byte array.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
mark(int) | Set the current marked position in the stream.
markSupported() | Tests if ByteArrayInputStream supports mark/reset.
read() | Reads the next byte of data from this input stream.
read(byte[], int, int) | Reads up to len bytes of data into an array of bytes from this input stream.
reset() | Resets the buffer to the marked position.
skip(long) | Skips n bytes of input from this input stream.


 ByteArrayInputStream.buf

ByteArrayInputStream.buf

Syntax
protected byte buf[]
Description
The byte array containing the data.


 ByteArrayInputStream.count

ByteArrayInputStream.count

Syntax
protected int count
Description
The index one greater than the last valid character in the input stream buffer.


 ByteArrayInputStream.mark

ByteArrayInputStream.mark

Syntax
protected int mark
Description
The currently marked position in the stream. ByteArrayInputStreams are marked at position zero by default when constructed. They may be marked at another position within the buffer by the mark() method. The current buffer position is set to this point by the reset() method.


 ByteArrayInputStream.pos

ByteArrayInputStream.pos

Syntax
protected int pos
Description
The index of the next character to read from the input stream buffer.


 ByteArrayInputStream.ByteArrayInputStream

ByteArrayInputStream.ByteArrayInputStream

Syntax 1
public ByteArrayInputStream( byte buf[] )
Parameters
buf
the input buffer.
Description
Creates a new byte array input stream that reads data from the specified byte array. The byte array is not copied.

Syntax 2
public ByteArrayInputStream( byte buf[], int offset, int length )
Parameters
buf
the input buffer.
offset
the offset in the buffer of the first byte to read.
length
the maximum number of bytes to read from the buffer.
Description
Creates a new byte array input stream that reads data from the specified byte array. Up to length characters are to be read from the byte array, starting at the indicated offset.

The byte array is not copied.


 ByteArrayInputStream.available

ByteArrayInputStream.available

Syntax
public synchronized int available()
Returns
the number of bytes that can be read from the input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking.

The available method of ByteArrayInputStream returns the value of count - pos, which is the number of bytes remaining to be read from the input buffer.

Overrides
available in class InputStream


 ByteArrayInputStream.mark

ByteArrayInputStream.mark

Syntax
public void mark( int markpos )
Description
Set the current marked position in the stream. ByteArrayInputStreams are marked at position zero by default when constructed. They may be marked at another position within the buffer by this method.

Overrides
mark in class InputStream


 ByteArrayInputStream.markSupported

ByteArrayInputStream.markSupported

Syntax
public boolean markSupported()
Description
Tests if ByteArrayInputStream supports mark/reset.

Overrides
markSupported in class InputStream


 ByteArrayInputStream.read

ByteArrayInputStream.read

Syntax 1
public synchronized int read()
Returns
the next byte of data, or -1 if the end of the stream has been reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

The read method of ByteArrayInputStream cannot block.

Overrides
read in class InputStream

Syntax 2
public synchronized int read( byte b[], int off, int len )
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data into an array of bytes from this input stream. This read method cannot block.

Overrides
read in class InputStream


 ByteArrayInputStream.reset

ByteArrayInputStream.reset

Syntax
public synchronized void reset()
Description
Resets the buffer to the marked position. The marked position is the beginning unless another position was marked.

Overrides
reset in class InputStream


 ByteArrayInputStream.skip

ByteArrayInputStream.skip

Syntax
public synchronized long skip( long n )
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached.

Overrides
skip in class InputStream


 Class ByteArrayOutputStream

Class java.io.ByteArrayOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.ByteArrayOutputStream

public class ByteArrayOutputStream
extends OutputStream

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().


 ByteArrayOutputStream Members

ByteArrayOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The buffer where data is stored.
count | The number of valid bytes in the buffer.

Constructors
Name | Description
ByteArrayOutputStream() | Creates a new byte array output stream.
ByteArrayOutputStream(int) | Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Methods
Name | Description
reset() | Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the ouput stream is discarded.
size() | Returns the current size of the buffer.
toByteArray() | Creates a newly allocated byte array.
toString() | Converts the buffer's contents into a string, translating bytes into characters according to the platform's default character encoding.
toString(int) | Creates a newly allocated string. Deprecated.
toString(String) | Converts the buffer's contents into a string, translating bytes into characters according to the specified character encoding.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
write(int) | Writes the specified byte to this byte array output stream.
writeTo(OutputStream) | Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).


 ByteArrayOutputStream.buf

ByteArrayOutputStream.buf

Syntax
protected byte buf[]
Description
The buffer where data is stored.


 ByteArrayOutputStream.count

ByteArrayOutputStream.count

Syntax
protected int count
Description
The number of valid bytes in the buffer.


 ByteArrayOutputStream.ByteArrayOutputStream

ByteArrayOutputStream.ByteArrayOutputStream

Syntax 1
public ByteArrayOutputStream()
Description
Creates a new byte array output stream. The buffer capacity is initially 32 bytes, though its size increases if necessary.

Syntax 2
public ByteArrayOutputStream( int size )
Parameters
size
the initial size.
Description
Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.


 ByteArrayOutputStream.reset

ByteArrayOutputStream.reset

Syntax
public synchronized void reset()
Description
Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the ouput stream is discarded. The output stream can be used again, reusing the already allocated buffer space.

See Also
count


 ByteArrayOutputStream.size

ByteArrayOutputStream.size

Syntax
public int size()
Returns
the value of the count field, which is the number of valid bytes in this output stream.
Description
Returns the current size of the buffer.

See Also
count


 ByteArrayOutputStream.toByteArray

ByteArrayOutputStream.toByteArray

Syntax
public synchronized byte[] toByteArray()
Returns
the current contents of this output stream, as a byte array.
Description
Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.

See Also
size


 ByteArrayOutputStream.toString

ByteArrayOutputStream.toString

Syntax 1
public String toString()
Description
Converts the buffer's contents into a string, translating bytes into characters according to the platform's default character encoding.

Overrides
toString in class Object

Syntax 2
public String toString( String enc ) throws UnsupportedEncodingException
Parameters
enc
a character-encoding name.
Description
Converts the buffer's contents into a string, translating bytes into characters according to the specified character encoding.

Syntax 3
public String toString( int hibyte )
Parameters
hibyte
the high byte of each resulting Unicode character.
Returns
the current contents of the output stream, as a string.
Description
Note: toString() is deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the toString(String enc) method, which takes an encoding-name argument, or the toString() method, which uses the platform's default character encoding.

Creates a newly allocated string. Its size is the current size of the output stream and the valid contents of the buffer have been copied into it. Each character c in the resulting string is constructed from the corresponding element b in the byte array such that:

    c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))

See Also
size, toString, toString


 ByteArrayOutputStream.write

ByteArrayOutputStream.write

Syntax 1
public synchronized void write( int b )
Parameters
b
the byte to be written.
Description
Writes the specified byte to this byte array output stream.

Overrides
write in class OutputStream

Syntax 2
public synchronized void write( byte b[], int off, int len )
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

Overrides
write in class OutputStream


 ByteArrayOutputStream.writeTo

ByteArrayOutputStream.writeTo

Syntax
public synchronized void writeTo( OutputStream out ) throws IOException
Parameters
out
the output stream to which to write the data.
Description
Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).

Exceptions
IOException if an I/O error occurs.


 Class CharArrayReader

Class java.io.CharArrayReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.CharArrayReader

public class CharArrayReader
extends Reader

This class implements a character buffer that can be used as a character-input stream.


 CharArrayReader Members

CharArrayReader Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | Character buffer
count | Number of valid characters in buffer
markedPos | Position of mark in buffer
pos | Current buffer position

Constructors
Name | Description
CharArrayReader(char[]) | Create an CharArrayReader from the specified array of chars.
CharArrayReader(char[], int, int) | Create an CharArrayReader from the specified array of chars.

Methods
Name | Description
close() | Close the stream.
mark(int) | Mark the present position in the stream.
markSupported() | Tell whether this stream supports the mark() operation, which it does.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.
reset() | Reset the stream to the most recent mark, or to the beginning if it has never been marked.
skip(long) | Skip characters.


 CharArrayReader.buf

CharArrayReader.buf

Syntax
protected char buf[]
Description
Character buffer


 CharArrayReader.count

CharArrayReader.count

Syntax
protected int count
Description
Number of valid characters in buffer


 CharArrayReader.markedPos

CharArrayReader.markedPos

Syntax
protected int markedPos
Description
Position of mark in buffer


 CharArrayReader.pos

CharArrayReader.pos

Syntax
protected int pos
Description
Current buffer position


 CharArrayReader.CharArrayReader

CharArrayReader.CharArrayReader

Syntax 1
public CharArrayReader( char buf[] )
Parameters
buf
Input buffer (not copied)
Description
Create an CharArrayReader from the specified array of chars.

Syntax 2
public CharArrayReader( char buf[], int offset, int length )
Parameters
buf
Input buffer (not copied)
offset
Offset of the first char to read
length
Number of chars to read
Description
Create an CharArrayReader from the specified array of chars.


 CharArrayReader.close

CharArrayReader.close

Syntax
public void close()
Description
Close the stream.

Overrides
close in class Reader


 CharArrayReader.mark

CharArrayReader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Parameters
readAheadLimit
Limit on the number of characters that may be read while still preserving the mark. Because the stream's input comes from a character array, there is no actual limit; hence this argument is ignored.
Description
Mark the present position in the stream. Subsequent calls to reset() will reposition the stream to this point.

Exceptions
IOException If an I/O error occurs
Overrides
mark in class Reader


 CharArrayReader.markSupported

CharArrayReader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation, which it does.

Overrides
markSupported in class Reader


 CharArrayReader.read

CharArrayReader.read

Syntax 1
public int read() throws IOException
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader

Syntax 2
public int read( char b[], int off, int len ) throws IOException
Parameters
b
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The actual number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 CharArrayReader.ready

CharArrayReader.ready

Syntax
public boolean ready() throws IOException
Description
Tell whether this stream is ready to be read. Character-array readers are always ready to be read.

Exceptions
IOException If an I/O error occurs
Overrides
ready in class Reader


 CharArrayReader.reset

CharArrayReader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream to the most recent mark, or to the beginning if it has never been marked.

Exceptions
IOException If an I/O error occurs
Overrides
reset in class Reader


 CharArrayReader.skip

CharArrayReader.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
The number of characters to skip
Returns
The number of characters actually skipped
Description
Skip characters.

Exceptions
IOException If an I/O error occurs
Overrides
skip in class Reader


 Class CharArrayWriter

Class java.io.CharArrayWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.CharArrayWriter

public class CharArrayWriter
extends Writer

This class implements a character buffer that can be used as an Writer. The buffer automatically grows when data is written to the stream. The data can be retrieved using toCharArray() and toString().


 CharArrayWriter Members

CharArrayWriter Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The buffer where data is stored.
count | The number of chars in the buffer.

Constructors
Name | Description
CharArrayWriter() | Creates a new CharArrayWriter.
CharArrayWriter(int) | Creates a new CharArrayWriter with the specified initial size.

Methods
Name | Description
close() | Close the stream.
flush() | Flush the stream.
reset() | Resets the buffer so that you can use it again without throwing away the already allocated buffer.
size() | Returns the current size of the buffer.
toCharArray() | Returns a copy of the input data.
toString() | Converts input data to a string.
write(char[], int, int) | Writes characters to the buffer.
write(int) | Writes a character to the buffer.
write(String, int, int) | Write a portion of a string to the buffer.
writeTo(Writer) | Writes the contents of the buffer to another character stream.


 CharArrayWriter.buf

CharArrayWriter.buf

Syntax
protected char buf[]
Description
The buffer where data is stored.


 CharArrayWriter.count

CharArrayWriter.count

Syntax
protected int count
Description
The number of chars in the buffer.


 CharArrayWriter.CharArrayWriter

CharArrayWriter.CharArrayWriter

Syntax 1
public CharArrayWriter()
Description
Creates a new CharArrayWriter.

Syntax 2
public CharArrayWriter( int initialSize )
Description
Creates a new CharArrayWriter with the specified initial size.


 CharArrayWriter.close

CharArrayWriter.close

Syntax
public void close()
Description
Close the stream. This method does not release the buffer, since its contents might still be required.

Overrides
close in class Writer


 CharArrayWriter.flush

CharArrayWriter.flush

Syntax
public void flush()
Description
Flush the stream.

Overrides
flush in class Writer


 CharArrayWriter.reset

CharArrayWriter.reset

Syntax
public void reset()
Description
Resets the buffer so that you can use it again without throwing away the already allocated buffer.


 CharArrayWriter.size

CharArrayWriter.size

Syntax
public int size()
Description
Returns the current size of the buffer.


 CharArrayWriter.toCharArray

CharArrayWriter.toCharArray

Syntax
public char[] toCharArray()
Description
Returns a copy of the input data.


 CharArrayWriter.toString

CharArrayWriter.toString

Syntax
public String toString()
Returns
the string.
Description
Converts input data to a string.

Overrides
toString in class Object


 CharArrayWriter.write

CharArrayWriter.write

Syntax 1
public void write( int c )
Description
Writes a character to the buffer.

Overrides
write in class Writer

Syntax 2
public void write( char c[], int off, int len )
Parameters
c
the data to be written
off
the start offset in the data
len
the number of chars that are written
Description
Writes characters to the buffer.

Overrides
write in class Writer

Syntax 3
public void write( String str, int off, int len )
Parameters
str
String to be written from
off
Offset from which to start reading characters
len
Number of characters to be written
Description
Write a portion of a string to the buffer.

Overrides
write in class Writer


 CharArrayWriter.writeTo

CharArrayWriter.writeTo

Syntax
public void writeTo( Writer out ) throws IOException
Parameters
out
the output stream to write to
Description
Writes the contents of the buffer to another character stream.


 Class CharConversionException

Class java.io.CharConversionException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.CharConversionException

public class CharConversionException
extends IOException

base class for character conversion exceptions


 CharConversionException Members

CharConversionException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CharConversionException() | provides no detailed message
CharConversionException(String) | provides a detailed message


 CharConversionException.CharConversionException

CharConversionException.CharConversionException

Syntax 1
public CharConversionException()
Description
provides no detailed message

Syntax 2
public CharConversionException( String s )
Parameters
s
detailed message
Description
provides a detailed message


 Interface DataInput

Interface java.io.DataInput

Interface Members | This Package | All Packages

public interface DataInput

The data input interface is implemented by streams that can read primitive Java data types from a stream in a machine-independent manner.

See Also:
DataInputStream, DataOutput


 DataInput Members

DataInput Members

Interface Overview | This Package | All Packages

Methods
Name | Description
readBoolean() | Reads a boolean value from the input stream.
readByte() | Reads a signed 8-bit value from the input stream.
readChar() | Reads a Unicode char value from the input stream.
readDouble() | Reads a double value from the input stream.
readFloat() | Reads a float value from the input stream.
readFully(byte[]) | Reads b.length bytes into the byte array.
readFully(byte[], int, int) | Reads b.length bytes into the byte array.
readInt() | Reads an int value from the input stream.
readLine() | Reads the next line of text from the input stream.
readLong() | Reads a long value from the input stream.
readShort() | Reads a 16-bit value from the input stream.
readUnsignedByte() | Reads an unsigned 8-bit value from the input stream.
readUnsignedShort() | Reads an unsigned 16-bit value from the input stream.
readUTF() | Reads in a string that has been encoded using a modified UTF-8 format.
skipBytes(int) | Skips exactly n bytes of input.


 DataInput.readBoolean

DataInput.readBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean readBoolean() throws IOException
Returns
the boolean value read.
Description
Reads a boolean value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readByte

DataInput.readByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte readByte() throws IOException
Returns
the 8-bit value read.
Description
Reads a signed 8-bit value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readChar

DataInput.readChar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char readChar() throws IOException
Returns
the Unicode char read.
Description
Reads a Unicode char value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readDouble

DataInput.readDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract double readDouble() throws IOException
Returns
the double value read.
Description
Reads a double value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readFloat

DataInput.readFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float readFloat() throws IOException
Returns
the float value read.
Description
Reads a float value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readFully

DataInput.readFully

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void readFully( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Description
Reads b.length bytes into the byte array. This method blocks until all the bytes are read.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.

Syntax 2
public abstract void readFully( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
Description
Reads b.length bytes into the byte array. This method blocks until all the bytes are read.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readInt

DataInput.readInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int readInt() throws IOException
Returns
the int value read.
Description
Reads an int value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readLine

DataInput.readLine

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String readLine() throws IOException
Returns
if this stream reaches the end before reading all the bytes.
Description
Reads the next line of text from the input stream.

Exceptions
IOException if an I/O error occurs.


 DataInput.readLong

DataInput.readLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long readLong() throws IOException
Returns
the long value read.
Description
Reads a long value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readShort

DataInput.readShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract short readShort() throws IOException
Returns
the 16-bit value read.
Description
Reads a 16-bit value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readUnsignedByte

DataInput.readUnsignedByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int readUnsignedByte() throws IOException
Returns
the unsigned 8-bit value read.
Description
Reads an unsigned 8-bit value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readUnsignedShort

DataInput.readUnsignedShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int readUnsignedShort() throws IOException
Returns
the unsigned 16-bit value read.
Description
Reads an unsigned 16-bit value from the input stream.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 DataInput.readUTF

DataInput.readUTF

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String readUTF() throws IOException
Returns
a Unicode string.
Description
Reads in a string that has been encoded using a modified UTF-8 format.

For an exact description of this method, see the discussion in Gosling, Joy, and Steele, The Java Language Specification.

Exceptions
EOFException if this stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.
Exceptions
UTFDataFormatException if the bytes do not represent a valid UTF-8 encoding of a string.


 DataInput.skipBytes

DataInput.skipBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int skipBytes( int n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the number of bytes skipped, which is always n.
Description
Skips exactly n bytes of input.

Exceptions
EOFException if this stream reaches the end before skipping all the bytes.
Exceptions
IOException if an I/O error occurs.


 Class DataInputStream

Class java.io.DataInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.io.DataInputStream

public class DataInputStream
extends FilterInputStream
implements DataInput

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.)

All characters in the range '\u0001' to '\u007F' are represented by a single byte:

0 bits 0-7

The null character '\u0000' and characters in the range '\u0080' to '\u07FF' are represented by a pair of bytes:

1 | 1 | 0 | bits 6-10
1 | 0 | bits 0-5

Characters in the range '\u0800' to '\uFFFF' are represented by three bytes:
1 | 1 | 1 | 0 | bits 12-15
1 | 0 | bits 6-11
1 | 0 | bits 0-5

The two differences between this format and the "standard" UTF-8 format are the following:

  • The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls.
  • Only the 1-byte, 2-byte, and 3-byte formats are used.

See Also:
DataOutputStream


 DataInputStream Members

DataInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DataInputStream(InputStream) | Creates a new data input stream to read data from the specified input stream.

Methods
Name | Description
read(byte[]) | Reads up to byte.length bytes of data from this data input stream into an array of bytes.
read(byte[], int, int) | Reads up to len bytes of data from this data input stream into an array of bytes.
readBoolean() | Reads a boolean from this data input stream.
readByte() | Reads a signed 8-bit value from this data input stream.
readChar() | Reads a Unicode character from this data input stream.
readDouble() | Reads a double from this data input stream.
readFloat() | Reads a float from this data input stream.
readFully(byte[]) | Reads b.length bytes from this data input stream into the byte array.
readFully(byte[], int, int) | Reads exactly len bytes from this data input stream into the byte array.
readInt() | Reads a signed 32-bit integer from this data input stream.
readLine() | Reads the next line of text from this data input stream. Deprecated.
readLong() | Reads a signed 64-bit integer from this data input stream.
readShort() | Reads a signed 16-bit number from this data input stream.
readUnsignedByte() | Reads an unsigned 8-bit number from this data input stream.
readUnsignedShort() | Reads an unsigned 16-bit number from this data input stream.
readUTF() | Reads in a string that has been encoded using a modified UTF-8 format from this data input stream.
readUTF(DataInput) | Reads in a string from the specified data input stream.
skipBytes(int) | Skips exactly n bytes of input in the underlying input stream.


 DataInputStream.DataInputStream

DataInputStream.DataInputStream

Syntax
public DataInputStream( InputStream in )
Parameters
in
the input stream.
Description
Creates a new data input stream to read data from the specified input stream.


 DataInputStream.read

DataInputStream.read

Syntax 1
public final int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to byte.length bytes of data from this data input stream into an array of bytes. This method blocks until some input is available.

The read method of DataInputStream calls the read method of its underlying input stream with the three arguments b, 0, and b.length and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
in, read

Syntax 2
public final int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this data input stream into an array of bytes. This method blocks until some input is available.

The read method of DataInputStream calls the read method of its underlying input stream with the same arguments and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
in, read


 DataInputStream.readBoolean

DataInputStream.readBoolean

Syntax
public final boolean readBoolean() throws IOException
Returns
the boolean value read.
Description
Reads a boolean from this data input stream. This method reads a single byte from the underlying input stream. A value of 0 represents false. Any other value represents true. This method blocks until either the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream has reached the end.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readByte

DataInputStream.readByte

Syntax
public final byte readByte() throws IOException
Returns
the next byte of this input stream as a signed 8-bit byte.
Description
Reads a signed 8-bit value from this data input stream. This method reads a byte from the underlying input stream. If the byte read is b, where 0 <= b <= 255, then the result is:
    (byte)(b)

This method blocks until either the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream has reached the end.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readChar

DataInputStream.readChar

Syntax
public final char readChar() throws IOException
Returns
the next two bytes of this input stream as a Unicode character.
Description
Reads a Unicode character from this data input stream. This method reads two bytes from the underlying input stream. If the bytes read, in order, are b1 and b2, where 0 <= b1, b1 <= 255, then the result is equal to:
    (char)((b1 << 8) | b2)

This method blocks until either the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readDouble

DataInputStream.readDouble

Syntax
public final double readDouble() throws IOException
Returns
the next eight bytes of this input stream, interpreted as a double.
Description
Reads a double from this data input stream. This method reads a long value as if by the readLong method and then converts that long to a double using the longBitsToDouble method in class Double.

This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading eight bytes.
Exceptions
IOException if an I/O error occurs.
See Also
readLong, longBitsToDouble


 DataInputStream.readFloat

DataInputStream.readFloat

Syntax
public final float readFloat() throws IOException
Returns
the next four bytes of this input stream, interpreted as a float.
Description
Reads a float from this data input stream. This method reads an int value as if by the readInt method and then converts that int to a float using the intBitsToFloat method in class Float. This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading four bytes.
Exceptions
IOException if an I/O error occurs.
See Also
readInt, intBitsToFloat


 DataInputStream.readFully

DataInputStream.readFully

Syntax 1
public final void readFully( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Description
Reads b.length bytes from this data input stream into the byte array. This method reads repeatedly from the underlying stream until all the bytes are read. This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in

Syntax 2
public final void readFully( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the number of bytes to read.
Description
Reads exactly len bytes from this data input stream into the byte array. This method reads repeatedly from the underlying stream until all the bytes are read. This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readInt

DataInputStream.readInt

Syntax
public final int readInt() throws IOException
Returns
the next four bytes of this input stream, interpreted as an int.
Description
Reads a signed 32-bit integer from this data input stream. This method reads four bytes from the underlying input stream. If the bytes read, in order, are b1, b2, b3, and b4, where 0 <= b1, b2, b3, b4 <= 255, then the result is equal to:
    (b1 << 24) | (b2 << 16) + (b3 << 8) +b4

This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading four bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readLine

DataInputStream.readLine

Syntax
public final String readLine() throws IOException
Returns
the next line of text from this input stream.
Description
Note: readLine() is deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form
    DataInputStream d = new DataInputStream(in);
with
    BufferedReader d = new BufferedReader(new InputStreamReader(in));

Reads the next line of text from this data input stream. This method successively reads bytes from the underlying input stream until it reaches the end of a line of text.

A line of text is terminated by a carriage return character ('\r'), a newline character ('\n'), a carriage return character immediately followed by a newline character, or the end of the input stream. The line-terminating character(s), if any, are not returned as part of the string that is returned.

This method blocks until a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the stream is detected, or an exception is thrown.

Exceptions
IOException if an I/O error occurs.
See Also
readLine, in


 DataInputStream.readLong

DataInputStream.readLong

Syntax
public final long readLong() throws IOException
Returns
the next eight bytes of this input stream, interpreted as a long.
Description
Reads a signed 64-bit integer from this data input stream. This method reads eight bytes from the underlying input stream. If the bytes read, in order, are b1, b2, b3, b4, b5, b6, b7, and b8, where
    0 <= b1, b2, b3, b4, b5, b6, b7, b8 <= 255,

then the result is equal to:

     ((long)b1 << 56) + ((long)b2 << 48) +
        ((long)b3 << 40) + ((long)b4 << 32) +
        ((long)b5 << 24) + (b6 << 16) +
        (b7 << 8) + b8

This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading eight bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readShort

DataInputStream.readShort

Syntax
public final short readShort() throws IOException
Returns
the next two bytes of this input stream, interpreted as a signed 16-bit number.
Description
Reads a signed 16-bit number from this data input stream. The method reads two bytes from the underlying input stream. If the two bytes read, in order, are b1 and b2, where each of the two values is between 0 and 255, inclusive, then the result is equal to:
    (short)((b1 << 8) | b2)

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readUnsignedByte

DataInputStream.readUnsignedByte

Syntax
public final int readUnsignedByte() throws IOException
Returns
the next byte of this input stream, interpreted as an unsigned 8-bit number.
Description
Reads an unsigned 8-bit number from this data input stream. This method reads a byte from this data input stream's underlying input stream and returns that byte. This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream has reached the end.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readUnsignedShort

DataInputStream.readUnsignedShort

Syntax
public final int readUnsignedShort() throws IOException
Returns
the next two bytes of this input stream, interpreted as an unsigned 16-bit integer.
Description
Reads an unsigned 16-bit number from this data input stream. This method reads two bytes from the underlying input stream. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:
    (b1 << 8) | b2

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.
See Also
in


 DataInputStream.readUTF

DataInputStream.readUTF

Syntax 1
public final String readUTF() throws IOException
Returns
a Unicode string.
Description
Reads in a string that has been encoded using a modified UTF-8 format from this data input stream. This method calls readUTF(this). See readUTF(java.io.DataInput) for a more complete description of the format.

This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.
See Also
readUTF

Syntax 2
public static final String readUTF( DataInput in ) throws IOException
Parameters
in
a data input stream.
Returns
a Unicode string.
Description
Reads in a string from the specified data input stream. The string has been encoded using a modified UTF-8 format.

The first two bytes are read as if by readUnsignedShort. This value gives the number of following bytes that are in the encoded string, not the length of the resulting string. The following bytes are then interpreted as bytes encoding characters in the UTF-8 format and are converted into characters.

This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if the input stream reaches the end before all the bytes.
Exceptions
IOException if an I/O error occurs.
Exceptions
UTFDataFormatException if the bytes do not represent a valid UTF-8 encoding of a Unicode string.
See Also
readUnsignedShort


 DataInputStream.skipBytes

DataInputStream.skipBytes

Syntax
public final int skipBytes( int n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the number of bytes skipped, which is always n.
Description
Skips exactly n bytes of input in the underlying input stream. This method blocks until all the bytes are skipped, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this input stream reaches the end before skipping all the bytes.
Exceptions
IOException if an I/O error occurs.


 Interface DataOutput

Interface java.io.DataOutput

Interface Members | This Package | All Packages

public interface DataOutput

The data output interface is implemented by streams that can write primitive Java data types to an output stream in a machine-independent manner.

See Also:
DataInput, DataOutputStream


 DataOutput Members

DataOutput Members

Interface Overview | This Package | All Packages

Methods
Name | Description
write(byte[]) | Writes b.length bytes from the specified byte array to this output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this output stream.
write(int) | Writes the specified byte to this data output stream.
writeBoolean(boolean) | Writes a boolean value to this output stream.
writeByte(int) | Writes an 8-bit value to this output stream.
writeBytes(String) | Writes a string to this output stream.
writeChar(int) | Writes a char value to this output stream.
writeChars(String) | Writes a string to this output stream.
writeDouble(double) | Writes a double value to this output stream.
writeFloat(float) | Writes a float value to this output stream.
writeInt(int) | Writes an int value to this output stream.
writeLong(long) | Writes a long value to this output stream.
writeShort(int) | Writes a 16-bit value to this output stream.
writeUTF(String) | Writes a Unicode string by encoding it using modified UTF-8 format.


 DataOutput.write

DataOutput.write

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to this data output stream.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public abstract void write( byte b[] ) throws IOException
Parameters
b
the data.
Description
Writes b.length bytes from the specified byte array to this output stream.

Exceptions
IOException if an I/O error occurs.

Syntax 3
public abstract void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeBoolean

DataOutput.writeBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeBoolean( boolean v ) throws IOException
Parameters
v
the boolean to be written.
Description
Writes a boolean value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeByte

DataOutput.writeByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeByte( int v ) throws IOException
Parameters
v
the byte value to be written.
Description
Writes an 8-bit value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeBytes

DataOutput.writeBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeBytes( String s ) throws IOException
Parameters
s
the string of bytes to be written.
Description
Writes a string to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeChar

DataOutput.writeChar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeChar( int v ) throws IOException
Parameters
v
the char value to be written.
Description
Writes a char value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeChars

DataOutput.writeChars

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeChars( String s ) throws IOException
Parameters
s
the string value to be written.
Description
Writes a string to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeDouble

DataOutput.writeDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeDouble( double v ) throws IOException
Parameters
v
the double value to be written.
Description
Writes a double value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeFloat

DataOutput.writeFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeFloat( float v ) throws IOException
Parameters
v
the float value to be written.
Description
Writes a float value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeInt

DataOutput.writeInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeInt( int v ) throws IOException
Parameters
v
the int value to be written.
Description
Writes an int value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeLong

DataOutput.writeLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeLong( long v ) throws IOException
Parameters
v
the long value to be written.
Description
Writes a long value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeShort

DataOutput.writeShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeShort( int v ) throws IOException
Parameters
v
the short value to be written.
Description
Writes a 16-bit value to this output stream.

Exceptions
IOException if an I/O error occurs.


 DataOutput.writeUTF

DataOutput.writeUTF

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeUTF( String str ) throws IOException
Parameters
str
the string value to be written.
Description
Writes a Unicode string by encoding it using modified UTF-8 format.

Exceptions
IOException if an I/O error occurs.


 Class DataOutputStream

Class java.io.DataOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.io.DataOutputStream

public class DataOutputStream
extends FilterOutputStream
implements DataOutput

A data input stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

See Also:
DataInputStream


 DataOutputStream Members

DataOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
written | The number of bytes written to the data output stream.

Constructors
Name | Description
DataOutputStream(OutputStream) | Creates a new data output stream to write data to the specified underlying output stream.

Methods
Name | Description
flush() | Flushes this data output stream.
size() | Returns the number of bytes written to this data output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to the underlying output stream.
write(int) | Writes the specified byte to the underlying output stream.
writeBoolean(boolean) | Writes a boolean to the underlying output stream as a 1-byte value.
writeByte(int) | Writes out a byte to the underlying output stream as a 1-byte value.
writeBytes(String) | Writes out the string to the underlying output stream as a sequence of bytes.
writeChar(int) | Writes a char to the underlying output stream as a 2-byte value, high byte first.
writeChars(String) | Writes a string to the underlying output stream as a sequence of characters.
writeDouble(double) | Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
writeFloat(float) | Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.
writeInt(int) | Writes an int to the underlying output stream as four bytes, high byte first.
writeLong(long) | Writes a long to the underlying output stream as eight bytes, high byte first.
writeShort(int) | Writes a short to the underlying output stream as two bytes, high byte first.
writeUTF(String) | Writes a string to the underlying output stream using UTF-8 encoding in a machine-independent manner.


 DataOutputStream.written

DataOutputStream.written

Syntax
protected int written
Description
The number of bytes written to the data output stream.


 DataOutputStream.DataOutputStream

DataOutputStream.DataOutputStream

Syntax
public DataOutputStream( OutputStream out )
Parameters
out
the underlying output stream.
Description
Creates a new data output stream to write data to the specified underlying output stream.

See Also
out


 DataOutputStream.flush

DataOutputStream.flush

Syntax
public void flush() throws IOException
Description
Flushes this data output stream. This forces any buffered output bytes to be written out to the stream.

The flush method of DataOuputStream calls the flush method of its underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
flush in class FilterOutputStream
See Also
out, flush


 DataOutputStream.size

DataOutputStream.size

Syntax
public final int size()
Returns
the value of the written field.
Description
Returns the number of bytes written to this data output stream.

See Also
written


 DataOutputStream.write

DataOutputStream.write

Syntax 1
public synchronized void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to the underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream
See Also
out

Syntax 2
public synchronized void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to the underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream
See Also
out


 DataOutputStream.writeBoolean

DataOutputStream.writeBoolean

Syntax
public final void writeBoolean( boolean v ) throws IOException
Parameters
v
a boolean value to be written.
Description
Writes a boolean to the underlying output stream as a 1-byte value. The value true is written out as the value (byte)1; the value false is written out as the value (byte)0.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeByte

DataOutputStream.writeByte

Syntax
public final void writeByte( int v ) throws IOException
Parameters
v
a byte value to be written.
Description
Writes out a byte to the underlying output stream as a 1-byte value.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeBytes

DataOutputStream.writeBytes

Syntax
public final void writeBytes( String s ) throws IOException
Parameters
s
a string of bytes to be written.
Description
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeChar

DataOutputStream.writeChar

Syntax
public final void writeChar( int v ) throws IOException
Parameters
v
a char value to be written.
Description
Writes a char to the underlying output stream as a 2-byte value, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeChars

DataOutputStream.writeChars

Syntax
public final void writeChars( String s ) throws IOException
Parameters
s
a String value to be written.
Description
Writes a string to the underlying output stream as a sequence of characters. Each character is written to the data output stream as if by the writeChar method.

Exceptions
IOException if an I/O error occurs.
See Also
writeChar, out


 DataOutputStream.writeDouble

DataOutputStream.writeDouble

Syntax
public final void writeDouble( double v ) throws IOException
Parameters
v
a double value to be written.
Description
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out, doubleToLongBits


 DataOutputStream.writeFloat

DataOutputStream.writeFloat

Syntax
public final void writeFloat( float v ) throws IOException
Parameters
v
a float value to be written.
Description
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out, floatToIntBits


 DataOutputStream.writeInt

DataOutputStream.writeInt

Syntax
public final void writeInt( int v ) throws IOException
Parameters
v
an int to be written.
Description
Writes an int to the underlying output stream as four bytes, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeLong

DataOutputStream.writeLong

Syntax
public final void writeLong( long v ) throws IOException
Parameters
v
a long to be written.
Description
Writes a long to the underlying output stream as eight bytes, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeShort

DataOutputStream.writeShort

Syntax
public final void writeShort( int v ) throws IOException
Parameters
v
a short to be written.
Description
Writes a short to the underlying output stream as two bytes, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
out


 DataOutputStream.writeUTF

DataOutputStream.writeUTF

Syntax
public final void writeUTF( String str ) throws IOException
Parameters
str
a string to be written.
Description
Writes a string to the underlying output stream using UTF-8 encoding in a machine-independent manner.

First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the UTF-8 encoding for the character.

Exceptions
IOException if an I/O error occurs.


 Class EOFException

Class java.io.EOFException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.EOFException

public class EOFException
extends IOException

Signals that an end of file or end of stream has been reached unexpectedly during input.

This exception is mainly used by data input streams, which generally expect a binary file in a specific format, and for which an end of stream is an unusual condition. Most other input streams return a special value on end of stream.

See Also:
DataInputStream, IOException


 EOFException Members

EOFException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
EOFException() | Constructs an EOFException with no detail message.
EOFException(String) | Constructs an EOFException with the specified detail message.


 EOFException.EOFException

EOFException.EOFException

Syntax 1
public EOFException()
Description
Constructs an EOFException with no detail message.

Syntax 2
public EOFException( String s )
Parameters
s
the detail message.
Description
Constructs an EOFException with the specified detail message.


 Interface Externalizable

Interface java.io.Externalizable

Interface Members | This Package | All Packages

public interface Externalizable
extends Serializable

Externalization allows a class to specify the methods to be used to write the object's contents to a stream and to read them back. The Externalizable interface's writeExternal and readExternal methods are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state.
Object Serialization uses the Serializable and Externalizable interfaces. Object persistence mechanisms may use them also. Each object to be stored is tested for the Externalizable interface. If the object supports it, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable the object should be saved using ObjectOutputStream.
When an Externalizable object is to be reconstructed, an instance is created using the public no-arg constructor and the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

See Also:
ObjectOutputStream, ObjectInputStream, ObjectOutput, ObjectInput, Serializable


 Externalizable Members

Externalizable Members

Interface Overview | This Package | All Packages

Methods
Name | Description
readExternal(ObjectInput) | The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
writeExternal(ObjectOutput) | The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings and arrays.


 Externalizable.readExternal

Externalizable.readExternal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException
Description
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal.

Exceptions
ClassNotFoundException If the class for an object being restored cannot be found.


 Externalizable.writeExternal

Externalizable.writeExternal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeExternal( ObjectOutput out ) throws IOException
Description
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings and arrays.

Exceptions
IOException Includes any I/O exceptions that may occur


 Class File

Class java.io.File

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.File

public class File
extends Object
implements Serializable

Instances of this class represent the name of a file or directory on the host file system. A file is specified by a pathname, which can either be an absolute pathname or a pathname relative to the current working directory. The pathname must follow the naming conventions of the host platform.

The File class is intended to provide an abstraction that deals with most of the machine dependent complexities of files and pathnames in a machine-independent fashion.

Note that whenever a filename or path is used it is assumed that the host's file naming conventions are used.


 File Members

File Members

Class Overview | This Package | All Packages

Fields
Name | Description
pathSeparator | The system-dependent path separator string.
pathSeparatorChar | The system-dependent path separator character.
separator | The system-dependent path separator character.
separatorChar | The system-dependent path separator string.

Constructors
Name | Description
File(File, String) | Creates a File instance that represents the file with the specified name in the specified directory.
File(String) | Creates a File instance that represents the file whose pathname is the given path argument.
File(String, String) | Creates a File instance whose pathname is the pathname of the specified directory, followed by the separator character, followed by the name argument.

Methods
Name | Description
canRead() | Tests if the application can read from the specified file.
canWrite() | Tests if the application can write to this file.
delete() | Deletes the file specified by this object.
equals(Object) | Compares this object against the specified object.
exists() | Tests if this File exists.
getAbsolutePath() | Returns the absolute pathname of the file represented by this object.
getCanonicalPath() | Returns the canonical form of this File object's pathname.
getName() | Returns the name of the file represented by this object.
getParent() | Returns the parent part of the pathname of this File object, or null if the name has no parent part.
getPath() | Returns the pathname of the file represented by this object.
hashCode() | Computes a hashcode for the file.
isAbsolute() | Tests if the file represented by this File object is an absolute pathname.
isDirectory() | Tests if the file represented by this File object is a directory.
isFile() | Tests if the file represented by this File object is a "normal" file.
lastModified() | Returns the time that the file represented by this File object was last modified.
length() | Returns the length of the file represented by this File object.
list() | Returns a list of the files in the directory specified by this File object.
list(FilenameFilter) | Returns a list of the files in the directory specified by this File that satisfy the specified filter.
mkdir() | Creates a directory whose pathname is specified by this File object.
mkdirs() | Creates a directory whose pathname is specified by this File object, including any necessary parent directories.
renameTo(File) | Renames the file specified by this File object to have the pathname given by the File argument.
toString() | Returns a string representation of this object.


 File.pathSeparator

File.pathSeparator

Syntax
public static final String pathSeparator
Description
The system-dependent path separator string. This field is initialized to contain the value of the system property path.separator.

See Also
getProperty


 File.pathSeparatorChar

File.pathSeparatorChar

Syntax
public static final char pathSeparatorChar
Description
The system-dependent path separator character. This field is initialized to contain the first character of the value of the system property path.separator. This character is often used to separate filenames in a sequence of files given as a "path list".

See Also
getProperty


 File.separator

File.separator

Syntax
public static final String separator
Description
The system-dependent path separator character. This field is initialized to contain the value of the system property file.separator.

See Also
getProperty


 File.separatorChar

File.separatorChar

Syntax
public static final char separatorChar
Description
The system-dependent path separator string. This field is initialized to contain the first character of the value of the system property file.separator. This character separates the directory and file components in a filename.

See Also
getProperty


 File.File

File.File

Syntax 1
public File( String path )
Parameters
path
the file pathname.
Description
Creates a File instance that represents the file whose pathname is the given path argument.

Exceptions
NullPointerException if the file path is equal to null.
See Also
getPath

Syntax 2
public File( String path, String name )
Parameters
path
the directory pathname.
name
the file pathname.
Description
Creates a File instance whose pathname is the pathname of the specified directory, followed by the separator character, followed by the name argument.

See Also
getPath, separator

Syntax 3
public File( File dir, String name )
Parameters
dir
the directory.
name
the file pathname.
Description
Creates a File instance that represents the file with the specified name in the specified directory.

If the directory argument is null, the resulting File instance represents a file in the (system-dependent) current directory whose pathname is the name argument. Otherwise, the File instance represents a file whose pathname is the pathname of the directory, followed by the separator character, followed by the name argument.

See Also
getPath, separator


 File.canRead

File.canRead

Syntax
public boolean canRead()
Returns
true if the file specified by this object exists and the application can read the file; false otherwise.
Description
Tests if the application can read from the specified file.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.canWrite

File.canWrite

Syntax
public boolean canWrite()
Returns
true if the application is allowed to write to a file whose name is specified by this object; false otherwise.
Description
Tests if the application can write to this file.

Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the pathname of this File to see if the application is allowed write access to the file.
See Also
getPath, checkWrite


 File.delete

File.delete

Syntax
public boolean delete()
Returns
true if the file is successfully deleted; false otherwise.
Description
Deletes the file specified by this object. If the target file to be deleted is a directory, it must be empty for deletion to succeed.

Exceptions
SecurityException if a security manager exists, its checkDelete method is called with the pathname of this File to see if the application is allowed to delete the file.
See Also
getPath, checkDelete


 File.equals

File.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object. Returns true if and only if the argument is not null and is a File object whose pathname is equal to the pathname of this object.

Overrides
equals in class Object


 File.exists

File.exists

Syntax
public boolean exists()
Returns
true if the file specified by this object exists; false otherwise.
Description
Tests if this File exists.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.getAbsolutePath

File.getAbsolutePath

Syntax
public String getAbsolutePath()
Returns
a system-dependent absolute pathname for this File.
Description
Returns the absolute pathname of the file represented by this object. If this object represents an absolute pathname, then return the pathname. Otherwise, return a pathname that is a concatenation of the current user directory, the separator character, and the pathname of this file object.

The system property user.dir contains the current user directory.

See Also
getPath, isAbsolute, getProperty


 File.getCanonicalPath

File.getCanonicalPath

Syntax
public String getCanonicalPath() throws IOException
Description
Returns the canonical form of this File object's pathname. The precise definition of canonical form is system-dependent, but it usually specifies an absolute pathname in which all relative references and references to the current user directory have been completely resolved. The canonical form of a pathname of a nonexistent file may not be defined.

Exceptions
IOException If an I/O error occurs, which is possible because the construction of the canonical path may require filesystem queries.


 File.getName

File.getName

Syntax
public String getName()
Returns
the name of the file (without any directory components) represented by this File object.
Description
Returns the name of the file represented by this object. The name is everything in the pathame after the last occurrence of the separator character.

See Also
getPath, separator


 File.getParent

File.getParent

Syntax
public String getParent()
Description
Returns the parent part of the pathname of this File object, or null if the name has no parent part. The parent part is generally everything leading up to the last occurrence of the separator character, although the precise definition is system dependent. On UNIX, for example, the parent part of "/usr/lib" is "/usr", whose parent part is "/", which in turn has no parent. On Windows platforms, the parent part of "c:\java" is "c:\", which in turn has no parent.

See Also
getPath, getCanonicalPath, separator


 File.getPath

File.getPath

Syntax
public String getPath()
Returns
the pathname represented by this File object.
Description
Returns the pathname of the file represented by this object.


 File.hashCode

File.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this File object.
Description
Computes a hashcode for the file.

Overrides
hashCode in class Object


 File.isAbsolute

File.isAbsolute

Syntax
public native boolean isAbsolute()
Returns
true if the pathname indicated by the File object is an absolute pathname; false otherwise.
Description
Tests if the file represented by this File object is an absolute pathname. The definition of an absolute pathname is system dependent. For example, on UNIX, a pathname is absolute if its first character is the separator character. On Windows platforms, a pathname is absolute if its first character is an ASCII '\' or '/', or if it begins with a letter followed by a colon.

See Also
getPath, separator


 File.isDirectory

File.isDirectory

Syntax
public boolean isDirectory()
Returns
true if this File exists and is a directory; false otherwise.
Description
Tests if the file represented by this File object is a directory.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.isFile

File.isFile

Syntax
public boolean isFile()
Returns
true if the file specified by this object exists and is a "normal" file; false otherwise.
Description
Tests if the file represented by this File object is a "normal" file.

A file is "normal" if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

Exceptions
SecurityException If a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.lastModified

File.lastModified

Syntax
public long lastModified()
Returns
the time the file specified by this object was last modified, or 0L if the specified file does not exist.
Description
Returns the time that the file represented by this File object was last modified.

The return value is system dependent and should only be used to compare with other values returned by last modified. It should not be interpreted as an absolute time.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.length

File.length

Syntax
public long length()
Returns
the length, in bytes, of the file specified by this object, or 0L if the specified file does not exist.
Description
Returns the length of the file represented by this File object.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead


 File.list

File.list

Syntax 1
public String[] list()
Returns
an array of file names in the specified directory. This list does not include the current directory or the parent directory ("." and ".." on Unix systems).
Description
Returns a list of the files in the directory specified by this File object.

Exceptions
SecurityException If a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, checkRead

Syntax 2
public String[] list( FilenameFilter filter )
Parameters
filter
a filename filter.
Returns
an array of file names in the specified directory. This list does not include the current directory or the parent directory ("." and ".." on Unix systems).
Description
Returns a list of the files in the directory specified by this File that satisfy the specified filter.

Exceptions
SecurityException If a security manager exists, its checkRead method is called with the pathname of this File to see if the application is allowed read access to the file.
See Also
getPath, FilenameFilter, checkRead


 File.mkdir

File.mkdir

Syntax
public boolean mkdir()
Returns
true if the directory could be created; false otherwise.
Description
Creates a directory whose pathname is specified by this File object.

Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the pathname of this File to see if the application is allowed write access to the file.
See Also
getPath, checkWrite


 File.mkdirs

File.mkdirs

Syntax
public boolean mkdirs()
Returns
true if the directory (or directories) could be created; false otherwise.
Description
Creates a directory whose pathname is specified by this File object, including any necessary parent directories.

Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the pathname of each of the directories that is to be created, before any of the directories are created.
See Also
getPath, checkWrite


 File.renameTo

File.renameTo

Syntax
public boolean renameTo( File dest )
Parameters
dest
the new filename.
Returns
true if the renaming succeeds; false otherwise.
Description
Renames the file specified by this File object to have the pathname given by the File argument.

Exceptions
SecurityException if a security manager exists, its checkWrite method is called both with the pathname of this file object and with the pathname of the destination target object to see if the application is allowed to write to both files.
See Also
getPath, checkWrite


 File.toString

File.toString

Syntax
public String toString()
Returns
a string giving the pathname of this object.
Description
Returns a string representation of this object.

Overrides
toString in class Object
See Also
getPath


 Class FileDescriptor

Class java.io.FileDescriptor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.FileDescriptor

public final class FileDescriptor
extends Object

Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file or an open socket.

Applications should not create their own file descriptors.

See Also:
FileInputStream, FileOutputStream, SocketInputStream, SocketOutputStream


 FileDescriptor Members

FileDescriptor Members

Class Overview | This Package | All Packages

Fields
Name | Description
err | A handle to the standard error stream.
in | A handle to the standard input stream.
out | A handle to the standard output stream.

Constructors
Name | Description
FileDescriptor() |

Methods
Name | Description
sync() | Force all system buffers to synchronize with the underlying device.
valid() | Tests if this file descriptor object is valid.


 FileDescriptor.err

FileDescriptor.err

Syntax
public static final FileDescriptor err
Description
A handle to the standard error stream.


 FileDescriptor.in

FileDescriptor.in

Syntax
public static final FileDescriptor in
Description
A handle to the standard input stream.


 FileDescriptor.out

FileDescriptor.out

Syntax
public static final FileDescriptor out
Description
A handle to the standard output stream.


 FileDescriptor.FileDescriptor

FileDescriptor.FileDescriptor

Syntax
public FileDescriptor()


 FileDescriptor.sync

FileDescriptor.sync

Syntax
public native void sync() throws SyncFailedException
Description
Force all system buffers to synchronize with the underlying device. This method returns after all modified data and attributes of this FileDescriptor have been written to the relevant device(s). In particular, if this FileDescriptor refers to a physical storage medium, such as a file in a file system, sync will not return until all in-memory modified copies of buffers associated with this FileDesecriptor have been written to the physical medium. sync is meant to be used by code that requires physical storage (such as a file) to be in a known state For example, a class that provided a simple transaction facility might use sync to ensure that all changes to a file caused by a given transaction were recorded on a storage medium. sync only affects buffers downstream of this FileDescriptor. If any in-memory buffering is being done by the application (for example, by a BufferedOutputStream object), those buffers must be flushed into the FileDescriptor (for example, by invoking OutputStream.flush) before that data will be affected by sync.

Exceptions
SyncFailedException Thrown when the buffers cannot be flushed, or because the system cannot guarantee that all the buffers have been synchronized with physical media.


 FileDescriptor.valid

FileDescriptor.valid

Syntax
public native boolean valid()
Returns
true if the file descriptor object represents a valid, open file or socket; false otherwise.
Description
Tests if this file descriptor object is valid.


 Class FileInputStream

Class java.io.FileInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FileInputStream

public class FileInputStream
extends InputStream

A file input stream is an input stream for reading data from a File or from a FileDescriptor.

See Also:
File, FileDescriptor, FileOutputStream


 FileInputStream Members

FileInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FileInputStream(File) | Creates an input file stream to read from the specified File object.
FileInputStream(FileDescriptor) | Creates an input file stream to read from the specified file descriptor.
FileInputStream(String) | Creates an input file stream to read from a file with the specified name.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this file input stream without blocking.
close() | Closes this file input stream and releases any system resources associated with the stream.
finalize() | Ensures that the close method of this file input stream is called when there are no more references to it.
getFD() | Returns the opaque file descriptor object associated with this stream.
read() | Reads a byte of data from this input stream.
read(byte[]) | Reads up to b.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
skip(long) | Skips over and discards n bytes of data from the input stream.


 FileInputStream.FileInputStream

FileInputStream.FileInputStream

Syntax 1
public FileInputStream( String name ) throws FileNotFoundException
Parameters
name
the system-dependent file name.
Description
Creates an input file stream to read from a file with the specified name.

Exceptions
FileNotFoundException if the file is not found.
Exceptions
SecurityException if a security manager exists, its checkRead method is called with the name argument to see if the application is allowed read access to the file.
See Also
checkRead

Syntax 2
public FileInputStream( File file ) throws FileNotFoundException
Parameters
file
the file to be opened for reading.
Description
Creates an input file stream to read from the specified File object.

Exceptions
FileNotFoundException if the file is not found.
Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of this File argument to see if the application is allowed read access to the file.
See Also
getPath, checkRead

Syntax 3
public FileInputStream( FileDescriptor fdObj )
Parameters
fdObj
the file descriptor to be opened for reading.
Description
Creates an input file stream to read from the specified file descriptor.

Exceptions
SecurityException if a security manager exists, its checkRead method is called with the file descriptor to see if the application is allowed to read from the specified file descriptor.
See Also
checkRead


 FileInputStream.available

FileInputStream.available

Syntax
public native int available() throws IOException
Returns
the number of bytes that can be read from this file input stream without blocking.
Description
Returns the number of bytes that can be read from this file input stream without blocking.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class InputStream


 FileInputStream.close

FileInputStream.close

Syntax
public native void close() throws IOException
Description
Closes this file input stream and releases any system resources associated with the stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class InputStream


 FileInputStream.finalize

FileInputStream.finalize

Syntax
protected void finalize() throws IOException
Description
Ensures that the close method of this file input stream is called when there are no more references to it.

Exceptions
IOException if an I/O error occurs.
Overrides
finalize in class Object
See Also
close


 FileInputStream.getFD

FileInputStream.getFD

Syntax
public final FileDescriptor getFD() throws IOException
Returns
the file descriptor object associated with this stream.
Description
Returns the opaque file descriptor object associated with this stream.

Exceptions
IOException if an I/O error occurs.
See Also
FileDescriptor


 FileInputStream.read

FileInputStream.read

Syntax 1
public native int read() throws IOException
Returns
the next byte of data, or -1 if the end of the file is reached.
Description
Reads a byte of data from this input stream. This method blocks if no input is yet available.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream

Syntax 2
public int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
Description
Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream

Syntax 3
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream


 FileInputStream.skip

FileInputStream.skip

Syntax
public native long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. The actual number of bytes skipped is returned.

Exceptions
IOException if an I/O error occurs.
Overrides
skip in class InputStream


 Class FileNotFoundException

Class java.io.FileNotFoundException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.FileNotFoundException

public class FileNotFoundException
extends IOException

Signals that a file could not be found.


 FileNotFoundException Members

FileNotFoundException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FileNotFoundException() | Constructs a FileNotFoundException with no detail message.
FileNotFoundException(String) | Constructs a FileNotFoundException with the specified detail message.


 FileNotFoundException.FileNotFoundException

FileNotFoundException.FileNotFoundException

Syntax 1
public FileNotFoundException()
Description
Constructs a FileNotFoundException with no detail message.

Syntax 2
public FileNotFoundException( String s )
Parameters
s
the detail message.
Description
Constructs a FileNotFoundException with the specified detail message.


 Class FileOutputStream

Class java.io.FileOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FileOutputStream

public class FileOutputStream
extends OutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor.

See Also:
File, FileDescriptor, FileInputStream


 FileOutputStream Members

FileOutputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FileOutputStream(File) | Creates a file output stream to write to the specified File object.
FileOutputStream(FileDescriptor) | Creates an output file stream to write to the specified file descriptor.
FileOutputStream(String) | Creates an output file stream to write to the file with the specified name.
FileOutputStream(String, boolean) | Creates an output file with the specified system dependent file name.

Methods
Name | Description
close() | Closes this file output stream and releases any system resources associated with this stream.
finalize() | Ensures that the close method of this file output stream is called when there are no more references to this stream.
getFD() | Returns the file descriptor associated with this stream.
write(byte[]) | Writes b.length bytes from the specified byte array to this file output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this file output stream.
write(int) | Writes the specified byte to this file output stream.


 FileOutputStream.FileOutputStream

FileOutputStream.FileOutputStream

Syntax 1
public FileOutputStream( String name ) throws IOException
Parameters
name
the system-dependent filename.
Description
Creates an output file stream to write to the file with the specified name.

Exceptions
IOException if the file could not be opened for writing.
Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the name argument to see if the application is allowed write access to the file.
See Also
checkWrite

Syntax 2
public FileOutputStream( String name, boolean append ) throws IOException
Parameters
name
the system dependent file name
Description
Creates an output file with the specified system dependent file name.

Exceptions
IOException If the file is not found.

Syntax 3
public FileOutputStream( File file ) throws IOException
Parameters
file
the file to be opened for writing.
Description
Creates a file output stream to write to the specified File object.

Exceptions
IOException if the file could not be opened for writing.
Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the pathname of the File argument to see if the application is allowed write access to the file. This may result in a security exception.
See Also
getPath, SecurityException, checkWrite

Syntax 4
public FileOutputStream( FileDescriptor fdObj )
Parameters
fdObj
the file descriptor to be opened for writing.
Description
Creates an output file stream to write to the specified file descriptor.

Exceptions
SecurityException if a security manager exists, its checkWrite method is called with the file descriptor to see if the application is allowed to write to the specified file descriptor.
See Also
checkWrite


 FileOutputStream.close

FileOutputStream.close

Syntax
public native void close() throws IOException
Description
Closes this file output stream and releases any system resources associated with this stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class OutputStream


 FileOutputStream.finalize

FileOutputStream.finalize

Syntax
protected void finalize() throws IOException
Description
Ensures that the close method of this file output stream is called when there are no more references to this stream.

Exceptions
IOException if an I/O error occurs.
Overrides
finalize in class Object
See Also
close


 FileOutputStream.getFD

FileOutputStream.getFD

Syntax
public final FileDescriptor getFD() throws IOException
Returns
the file descriptor object associated with this stream.
Description
Returns the file descriptor associated with this stream.

Exceptions
IOException if an I/O error occurs.
See Also
FileDescriptor


 FileOutputStream.write

FileOutputStream.write

Syntax 1
public native void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to this file output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream

Syntax 2
public void write( byte b[] ) throws IOException
Parameters
b
the data.
Description
Writes b.length bytes from the specified byte array to this file output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream

Syntax 3
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this file output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream


 Class FileReader

Class java.io.FileReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.InputStreamReader
                   |
                   +----java.io.FileReader

public class FileReader
extends InputStreamReader

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

See Also:
InputStreamReader, FileInputStream


 FileReader Members

FileReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FileReader(File) |
FileReader(FileDescriptor) |
FileReader(String) |


 FileReader.FileReader

FileReader.FileReader

Syntax 1
public FileReader( String fileName ) throws FileNotFoundException

Syntax 2
public FileReader( File file ) throws FileNotFoundException

Syntax 3
public FileReader( FileDescriptor fd )


 Class FileWriter

Class java.io.FileWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.OutputStreamWriter
                   |
                   +----java.io.FileWriter

public class FileWriter
extends OutputStreamWriter

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

See Also:
OutputStreamWriter, FileOutputStream


 FileWriter Members

FileWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FileWriter(File) |
FileWriter(FileDescriptor) |
FileWriter(String) |
FileWriter(String, boolean) |


 FileWriter.FileWriter

FileWriter.FileWriter

Syntax 1
public FileWriter( String fileName ) throws IOException

Syntax 2
public FileWriter( String fileName, boolean append ) throws IOException

Syntax 3
public FileWriter( File file ) throws IOException

Syntax 4
public FileWriter( FileDescriptor fd )


 Interface FilenameFilter

Interface java.io.FilenameFilter

Interface Members | This Package | All Packages

public interface FilenameFilter

Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File, and by the Abstract Window Toolkit's file dialog component.

See Also:
setFilenameFilter, File, list


 FilenameFilter Members

FilenameFilter Members

Interface Overview | This Package | All Packages

Methods
Name | Description
accept(File, String) | Tests if a specified file should be included in a file list.


 FilenameFilter.accept

FilenameFilter.accept

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean accept( File dir, String name )
Parameters
dir
the directory in which the file was found.
name
the name of the file.
Returns
true if the name should be included in the file list; false otherwise.
Description
Tests if a specified file should be included in a file list.


 Class FilterInputStream

Class java.io.FilterInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream

public class FilterInputStream
extends InputStream

This class is the superclass of all classes that filter input streams. These streams sit on top of an already existing input stream (the underlying input stream), but provide additional functionality.

The class FilterInputStream itself simply overrides all methods of InputStream with versions that pass all requests to the underlying input stream. Subclasses of FilterInputStream may further override some of these methods as well as provide additional methods and fields.


 FilterInputStream Members

FilterInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
in | The underlying input stream.

Constructors
Name | Description
FilterInputStream(InputStream) | Creates an input stream filter built on top of the specified input stream.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
close() | Closes this input stream and releases any system resources associated with the stream.
mark(int) | Marks the current position in this input stream.
markSupported() | Tests if this input stream supports the mark and reset methods.
read() | Reads the next byte of data from this input stream.
read(byte[]) | Reads up to byte.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
reset() | Repositions this stream to the position at the time the mark method was last called on this input stream.
skip(long) | Skips over and discards n bytes of data from the input stream.


 FilterInputStream.in

FilterInputStream.in

Syntax
protected InputStream in
Description
The underlying input stream.


 FilterInputStream.FilterInputStream

FilterInputStream.FilterInputStream

Syntax
protected FilterInputStream( InputStream in )
Parameters
in
the underlying input stream.
Description
Creates an input stream filter built on top of the specified input stream.


 FilterInputStream.available

FilterInputStream.available

Syntax
public int available() throws IOException
Returns
the number of bytes that can be read from the input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking.

The available method of FilterInputStream calls the available method of its underlying input stream and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class InputStream
See Also
in


 FilterInputStream.close

FilterInputStream.close

Syntax
public void close() throws IOException
Description
Closes this input stream and releases any system resources associated with the stream. The close method of FilterInputStream calls the close method of its underlying input stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class InputStream
See Also
in


 FilterInputStream.mark

FilterInputStream.mark

Syntax
public synchronized void mark( int readlimit )
Parameters
readlimit
the maximum limit of bytes that can be read before the mark position becomes invalid.
Description
Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes.

The readlimit argument tells this input stream to allow that many bytes to be read before the mark position gets invalidated.

The mark method of FilterInputStream calls the mark method of its underlying input stream with the readlimit argument.

Overrides
mark in class InputStream
See Also
in, reset


 FilterInputStream.markSupported

FilterInputStream.markSupported

Syntax
public boolean markSupported()
Returns
true if this stream type supports the mark and reset method; false otherwise.
Description
Tests if this input stream supports the mark and reset methods. The markSupported method of FilterInputStream calls the markSupported method of its underlying input stream and returns whatever value that method returns.

Overrides
markSupported in class InputStream
See Also
in, mark, reset


 FilterInputStream.read

FilterInputStream.read

Syntax 1
public int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

The read method of FilterInputStream calls the read method of its underlying input stream and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream
See Also
in

Syntax 2
public int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to byte.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

The read method of FilterInputStream calls the read method of three arguments with the arguments b, 0, and b.length, and returns whatever value that method returns.

Note that this method does not call the one-argument read method of its underlying stream with the single argument b. Subclasses of FilterInputStream do not need to override this method if they have overridden the three-argument read method.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream
See Also
read

Syntax 3
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

The read method of FilterInputStream calls the read method of its underlying input stream with the same arguments and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream
See Also
in


 FilterInputStream.reset

FilterInputStream.reset

Syntax
public synchronized void reset() throws IOException
Description
Repositions this stream to the position at the time the mark method was last called on this input stream.

The reset method of FilterInputStream calls the reset method of its underlying input stream.

Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the parse, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it fails. If this happens within readlimit bytes, it allows the outer code to reset the stream and try another parser.

Exceptions
IOException if the stream has not been marked or if the mark has been invalidated.
Overrides
reset in class InputStream
See Also
in, mark


 FilterInputStream.skip

FilterInputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. The actual number of bytes skipped is returned.

The skip method of FilterInputStream calls the skip method of its underlying input stream with the same argument, and returns whatever value that method does.

Exceptions
IOException if an I/O error occurs.
Overrides
skip in class InputStream


 Class FilterOutputStream

Class java.io.FilterOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream

public class FilterOutputStream
extends OutputStream

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream), but provide additional functionality.

The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream. Subclasses of FilterOutputStream may further override some of these methods as well as provide additional methods and fields.


 FilterOutputStream Members

FilterOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
out | The underlying output stream.

Constructors
Name | Description
FilterOutputStream(OutputStream) | Creates an output stream filter built on top of the specified underlying output stream.

Methods
Name | Description
close() | Closes this output stream and releases any system resources associated with the stream.
flush() | Flushes this output stream and forces any buffered output bytes to be written out to the stream.
write(byte[]) | Writes b.length bytes to this output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this output stream.
write(int) | Writes the specified byte to this output stream.


 FilterOutputStream.out

FilterOutputStream.out

Syntax
protected OutputStream out
Description
The underlying output stream.


 FilterOutputStream.FilterOutputStream

FilterOutputStream.FilterOutputStream

Syntax
public FilterOutputStream( OutputStream out )
Parameters
out
the underlying output stream.
Description
Creates an output stream filter built on top of the specified underlying output stream.


 FilterOutputStream.close

FilterOutputStream.close

Syntax
public void close() throws IOException
Description
Closes this output stream and releases any system resources associated with the stream.

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class OutputStream
See Also
flush, out


 FilterOutputStream.flush

FilterOutputStream.flush

Syntax
public void flush() throws IOException
Description
Flushes this output stream and forces any buffered output bytes to be written out to the stream.

The flush method of FilterOutputStream calls the flush method of its underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
flush in class OutputStream
See Also
out


 FilterOutputStream.write

FilterOutputStream.write

Syntax 1
public void write( int b ) throws IOException
Parameters
b
the byte.
Description
Writes the specified byte to this output stream.

The write method of FilterOutputStream calls the write method of its underlying output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream

Syntax 2
public void write( byte b[] ) throws IOException
Parameters
b
the data to be written.
Description
Writes b.length bytes to this output stream.

The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length.

Note that this method does not call the one-argument write method of its underlying stream with the single argument b.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream
See Also
write

Syntax 3
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this output stream.

The write method of FilterOutputStream calls the write method of one argument on each byte to output.

Note that this method does not call the write method of its underlying input stream with the same arguments. Subclasses of FilterOutputStream should provide a more efficient implementation of this method.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream
See Also
write


 Class FilterReader

Class java.io.FilterReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.FilterReader

public abstract class FilterReader
extends Reader

Abstract class for reading filtered character streams.


 FilterReader Members

FilterReader Members

Class Overview | This Package | All Packages

Fields
Name | Description
in | The underlying character-input stream, or null if the stream has been closed

Constructors
Name | Description
FilterReader(Reader) | Create a new filtered reader.

Methods
Name | Description
close() | Close the stream.
mark(int) | Mark the present position in the stream.
markSupported() | Tell whether this stream supports the mark() operation.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.
reset() | Reset the stream.
skip(long) | Skip characters.


 FilterReader.in

FilterReader.in

Syntax
protected Reader in
Description
The underlying character-input stream, or null if the stream has been closed


 FilterReader.FilterReader

FilterReader.FilterReader

Syntax
protected FilterReader( Reader in )
Description
Create a new filtered reader.


 FilterReader.close

FilterReader.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Reader


 FilterReader.mark

FilterReader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Description
Mark the present position in the stream.

Exceptions
IOException If an I/O error occurs
Overrides
mark in class Reader


 FilterReader.markSupported

FilterReader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation.

Overrides
markSupported in class Reader


 FilterReader.read

FilterReader.read

Syntax 1
public int read() throws IOException
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 FilterReader.ready

FilterReader.ready

Syntax
public boolean ready() throws IOException
Description
Tell whether this stream is ready to be read.

Exceptions
IOException If an I/O error occurs
Overrides
ready in class Reader


 FilterReader.reset

FilterReader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream.

Exceptions
IOException If an I/O error occurs
Overrides
reset in class Reader


 FilterReader.skip

FilterReader.skip

Syntax
public long skip( long n ) throws IOException
Description
Skip characters.

Exceptions
IOException If an I/O error occurs
Overrides
skip in class Reader


 Class FilterWriter

Class java.io.FilterWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.FilterWriter

public abstract class FilterWriter
extends Writer

Abstract class for writing filtered character streams.


 FilterWriter Members

FilterWriter Members

Class Overview | This Package | All Packages

Fields
Name | Description
out | The underlying character-output stream.

Constructors
Name | Description
FilterWriter(Writer) | Create a new filtered writer.

Methods
Name | Description
close() | Close the stream.
flush() | Flush the stream.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String, int, int) | Write a portion of a string.


 FilterWriter.out

FilterWriter.out

Syntax
protected Writer out
Description
The underlying character-output stream.


 FilterWriter.FilterWriter

FilterWriter.FilterWriter

Syntax
protected FilterWriter( Writer out )
Description
Create a new filtered writer.


 FilterWriter.close

FilterWriter.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Writer


 FilterWriter.flush

FilterWriter.flush

Syntax
public void flush() throws IOException
Description
Flush the stream.

Exceptions
IOException If an I/O error occurs
Overrides
flush in class Writer


 FilterWriter.write

FilterWriter.write

Syntax 1
public void write( int c ) throws IOException
Description
Write a single character.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 2
public void write( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Buffer of characters to be written
off
Offset from which to start reading characters
len
Number of characters to be written
Description
Write a portion of an array of characters.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 3
public void write( String str, int off, int len ) throws IOException
Parameters
str
String to be written
off
Offset from which to start reading characters
len
Number of characters to be written
Description
Write a portion of a string.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer


 Class IOException

Class java.io.IOException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException

public class IOException
extends Exception

Signals that an I/O exception of some sort has occurred.

See Also:
InputStream, OutputStream


 IOException Members

IOException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IOException() | Constructs an IOException with no detail message.
IOException(String) | Constructs an IOException with the specified detail message.


 IOException.IOException

IOException.IOException

Syntax 1
public IOException()
Description
Constructs an IOException with no detail message.

Syntax 2
public IOException( String s )
Parameters
s
the detail message.
Description
Constructs an IOException with the specified detail message.


 Class InputStream

Class java.io.InputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream

public abstract class InputStream
extends Object

This abstract class is the superclass of all classes representing an input stream of bytes.

Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.

See Also:
BufferedInputStream, ByteArrayInputStream, DataInputStream, FilterInputStream, read, OutputStream, PushbackInputStream


 InputStream Members

InputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InputStream() |

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
close() | Closes this input stream and releases any system resources associated with the stream.
mark(int) | Marks the current position in this input stream.
markSupported() | Tests if this input stream supports the mark and reset methods.
read() | Reads the next byte of data from this input stream.
read(byte[]) | Reads up to b.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
reset() | Repositions this stream to the position at the time the mark method was last called on this input stream.
skip(long) | Skips over and discards n bytes of data from this input stream.


 InputStream.InputStream

InputStream.InputStream

Syntax
public InputStream()


 InputStream.available

InputStream.available

Syntax
public int available() throws IOException
Returns
the number of bytes that can be read from this input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking. The available method of InputStream returns 0. This method should be overridden by subclasses.

Exceptions
IOException if an I/O error occurs.


 InputStream.close

InputStream.close

Syntax
public void close() throws IOException
Description
Closes this input stream and releases any system resources associated with the stream.

The close method of InputStream does nothing.

Exceptions
IOException if an I/O error occurs.


 InputStream.mark

InputStream.mark

Syntax
public synchronized void mark( int readlimit )
Parameters
readlimit
the maximum limit of bytes that can be read before the mark position becomes invalid.
Description
Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes.

The readlimit arguments tells this input stream to allow that many bytes to be read before the mark position gets invalidated.

The mark method of InputStream does nothing.

See Also
reset


 InputStream.markSupported

InputStream.markSupported

Syntax
public boolean markSupported()
Returns
true if this true type supports the mark and reset method; false otherwise.
Description
Tests if this input stream supports the mark and reset methods. The markSupported method of InputStream returns false.

See Also
mark, reset


 InputStream.read

InputStream.read

Syntax 1
public abstract int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Returns
the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached.
Description
Reads up to b.length bytes of data from this input stream into an array of bytes.

The read method of InputStream calls the read method of three arguments with the arguments b, 0, and b.length.

Exceptions
IOException if an I/O error occurs.
See Also
read

Syntax 3
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until some input is available. If the first argument is null, up to len bytes are read and discarded.

The read method of InputStream reads a single byte at a time using the read method of zero arguments to fill in the array. Subclasses are encouraged to provide a more efficient implementation of this method.

Exceptions
IOException if an I/O error occurs.
See Also
read


 InputStream.reset

InputStream.reset

Syntax
public synchronized void reset() throws IOException
Description
Repositions this stream to the position at the time the mark method was last called on this input stream.

The reset method of InputStream throws an IOException, because input streams, by default, do not support mark and reset.

Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the parser, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it fails, which, if it happens within readlimit bytes, allows the outer code to reset the stream and try another parser.

Exceptions
IOException if this stream has not been marked or if the mark has been invalidated.
See Also
mark, IOException


 InputStream.skip

InputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips over and discards n bytes of data from this input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. The actual number of bytes skipped is returned.

The skip method of InputStream creates a byte array of length n and then reads into it until n bytes have been read or the end of the stream has been reached. Subclasses are encouraged to provide a more efficient implementation of this method.

Exceptions
IOException if an I/O error occurs.


 Class InputStreamReader

Class java.io.InputStreamReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.InputStreamReader

public class InputStreamReader
extends Reader

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and translates them into characters according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader; for example,

 BufferedReader in
   = new BufferedReader(new InputStreamReader(System.in));

See Also:
BufferedReader, InputStream


 InputStreamReader Members

InputStreamReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InputStreamReader(InputStream) | Create an InputStreamReader that uses the default character encoding.
InputStreamReader(InputStream, String) | Create an InputStreamReader that uses the named character encoding.

Methods
Name | Description
close() | Close the stream.
getEncoding() | Return the name of the encoding being used by this stream.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.


 InputStreamReader.InputStreamReader

InputStreamReader.InputStreamReader

Syntax 1
public InputStreamReader( InputStream in )
Parameters
in
An InputStream
Description
Create an InputStreamReader that uses the default character encoding.

Syntax 2
public InputStreamReader( InputStream in, String enc ) throws UnsupportedEncodingException
Parameters
in
An InputStream
enc
Name of encoding to be used
Description
Create an InputStreamReader that uses the named character encoding.

Exceptions
UnsupportedEncodingException If the named encoding is not supported


 InputStreamReader.close

InputStreamReader.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Reader


 InputStreamReader.getEncoding

InputStreamReader.getEncoding

Syntax
public String getEncoding()
Description
Return the name of the encoding being used by this stream. May return null if the stream has been closed.


 InputStreamReader.read

InputStreamReader.read

Syntax 1
public int read() throws IOException
Returns
The character read, or -1 if the end of the stream has been reached
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 InputStreamReader.ready

InputStreamReader.ready

Syntax
public boolean ready() throws IOException
Description
Tell whether this stream is ready to be read. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream.

Exceptions
IOException If an I/O error occurs
Overrides
ready in class Reader


 Class InterruptedIOException

Class java.io.InterruptedIOException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.InterruptedIOException

public class InterruptedIOException
extends IOException

Signals that an I/O operation has been interrupted.

See Also:
InputStream, OutputStream, interrupt


 InterruptedIOException Members

InterruptedIOException Members

Class Overview | This Package | All Packages

Fields
Name | Description
bytesTransferred | Reports how many bytes had been transferred as part of the I/O operation before it was interrupted.

Constructors
Name | Description
InterruptedIOException() | Constructs an InterruptedIOException with no detail message.
InterruptedIOException(String) | Constructs an InterruptedIOException with the specified detail message.


 InterruptedIOException.bytesTransferred

InterruptedIOException.bytesTransferred

Syntax
public int bytesTransferred
Description
Reports how many bytes had been transferred as part of the I/O operation before it was interrupted.


 InterruptedIOException.InterruptedIOException

InterruptedIOException.InterruptedIOException

Syntax 1
public InterruptedIOException()
Description
Constructs an InterruptedIOException with no detail message.

Syntax 2
public InterruptedIOException( String s )
Parameters
s
the detail message.
Description
Constructs an InterruptedIOException with the specified detail message.


 Class InvalidClassException

Class java.io.InvalidClassException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.InvalidClassException

public class InvalidClassException
extends ObjectStreamException

Raised when the Serialization runtime detects a problem with a Class. The class may:

  • not match the serial version of the class in the stream
  • the class contains unknown datatypes
  • the class implements only one of writeObject or readObject methods
  • the class is not public
  • the class does not have an accessible no-arg constructor


 InvalidClassException Members

InvalidClassException Members

Class Overview | This Package | All Packages

Fields
Name | Description
classname |

Constructors
Name | Description
InvalidClassException(String) | Report a InvalidClassException for the specified reason.
InvalidClassException(String, String) |

Methods
Name | Description
getMessage() | Produce the message, include the classname if present.


 InvalidClassException.classname

InvalidClassException.classname

Syntax
public String classname


 InvalidClassException.InvalidClassException

InvalidClassException.InvalidClassException

Syntax 1
public InvalidClassException( String reason )
Description
Report a InvalidClassException for the specified reason.

Syntax 2
public InvalidClassException( String cname, String reason )


 InvalidClassException.getMessage

InvalidClassException.getMessage

Syntax
public String getMessage()
Description
Produce the message, include the classname if present.

Overrides
getMessage in class Throwable


 Class InvalidObjectException

Class java.io.InvalidObjectException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.InvalidObjectException

public class InvalidObjectException
extends ObjectStreamException

Indicates that one or more deserialized objects failed validation tests. The argument should be the reason for the failure.

See Also:
ObjectInputValidation


 InvalidObjectException Members

InvalidObjectException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InvalidObjectException(String) | Constructs an InvalidObjectException with a detail message.


 InvalidObjectException.InvalidObjectException

InvalidObjectException.InvalidObjectException

Syntax
public InvalidObjectException( String reason )
Description
Constructs an InvalidObjectException with a detail message. The argument should be the reason why the validation of the object failed.

See Also
ObjectInputValidation


 Class LineNumberInputStream

Class java.io.LineNumberInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.io.LineNumberInputStream

public class LineNumberInputStream
extends FilterInputStream

Note: LineNumberInputStream is deprecated. This class incorrectly assumes that bytes adequately represent characters. As of JDK 1.1, the preferred way to operate on character streams is via the new character-stream classes, which include a class for counting line numbers.

This class is an input stream filter that provides the added functionality of keeping track of the current line number.

A line is a sequence of bytes ending with a carriage return character ('\r'), a newline character ('\n'), or a carriage return character followed immediately by a linefeed character. In all three cases, the line terminating character(s) are returned as a single newline character.

The line number begins at 0, and is incremented by 1 when a read returns a newline character.

See Also:
LineNumberReader


 LineNumberInputStream Members

LineNumberInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
LineNumberInputStream(InputStream) | Constructs a newline number input stream that reads its input from the specified input stream.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
getLineNumber() | Returns the current line number.
mark(int) | Marks the current position in this input stream.
read() | Reads the next byte of data from this input stream.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
reset() | Repositions this stream to the position at the time the mark method was last called on this input stream.
setLineNumber(int) | Sets the line number to the specified argument.
skip(long) | Skips over and discards n bytes of data from the input stream.


 LineNumberInputStream.LineNumberInputStream

LineNumberInputStream.LineNumberInputStream

Syntax
public LineNumberInputStream( InputStream in )
Parameters
in
the underlying input stream.
Description
Constructs a newline number input stream that reads its input from the specified input stream.


 LineNumberInputStream.available

LineNumberInputStream.available

Syntax
public int available() throws IOException
Returns
the number of bytes that can be read from this input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking.

Note that if the underlying input stream is able to supply k input characters without blocking, the LineNumberInputStream can guarantee only to provide k/2 characters without blocking, because the k characters from the underlyhing input stream might consist of k/2 pairs of '\r' and '\n', which are converted to just k/2 '\n' characters.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class FilterInputStream
See Also
in


 LineNumberInputStream.getLineNumber

LineNumberInputStream.getLineNumber

Syntax
public int getLineNumber()
Returns
the current line number.
Description
Returns the current line number.


 LineNumberInputStream.mark

LineNumberInputStream.mark

Syntax
public void mark( int readlimit )
Parameters
readlimit
the maximum limit of bytes that can be read before the mark position becomes invalid.
Description
Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes.

The mark method of LineNumberInputStream remembers the current line number in a private variable, and then calls the mark method of the underlying input stream.

Overrides
mark in class FilterInputStream
See Also
in, reset


 LineNumberInputStream.read

LineNumberInputStream.read

Syntax 1
public int read() throws IOException
Returns
the next byte of data, or -1 if the end of this stream is reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

The read method of LineNumberInputStream calls the read method of the underlying input stream. It checks for carriage returns and newline characters in the input, and modifies the current line number as appropriate. A carriage-return character or a carriage return followed by a newline character are both converted into a single newline character.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
in, getLineNumber

Syntax 2
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of this stream has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

The read method of LineNumberInputStream repeatedly calls the read method of zero arguments to fill in the byte array.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
read


 LineNumberInputStream.reset

LineNumberInputStream.reset

Syntax
public void reset() throws IOException
Description
Repositions this stream to the position at the time the mark method was last called on this input stream.

The reset method of LineNumberInputStream resets the line number to be the line number at the time the mark method was called, and then calls the reset method of the underlying input stream.

Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the parser, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it fails, which, if it happens within readlimit bytes, allows the outer code to reset the stream and try another parser.

Exceptions
IOException if an I/O error occurs.
Overrides
reset in class FilterInputStream
See Also
in, mark


 LineNumberInputStream.setLineNumber

LineNumberInputStream.setLineNumber

Syntax
public void setLineNumber( int lineNumber )
Parameters
lineNumber
the new line number.
Description
Sets the line number to the specified argument.


 LineNumberInputStream.skip

LineNumberInputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0. The actual number of bytes skipped is returned.

The skip method of LineNumberInputStream creates a byte array of length n and then reads into it until n bytes have been read or the end of the stream has been reached.

Exceptions
IOException if an I/O error occurs.
Overrides
skip in class FilterInputStream


 Class LineNumberReader

Class java.io.LineNumberReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.BufferedReader
                   |
                   +----java.io.LineNumberReader

public class LineNumberReader
extends BufferedReader

A buffered character-input stream that keeps track of line numbers. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.


 LineNumberReader Members

LineNumberReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
LineNumberReader(Reader) | Create a new line-numbering reader, using the default input-buffer size.
LineNumberReader(Reader, int) | Create a new line-numbering reader, reading characters into a buffer of the given size.

Methods
Name | Description
getLineNumber() | Get the current line number.
mark(int) | Mark the present position in the stream.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
readLine() | Read a line of text.
reset() | Reset the stream to the most recent mark.
setLineNumber(int) | Set the current line number.
skip(long) | Skip characters.


 LineNumberReader.LineNumberReader

LineNumberReader.LineNumberReader

Syntax 1
public LineNumberReader( Reader in )
Description
Create a new line-numbering reader, using the default input-buffer size.

Syntax 2
public LineNumberReader( Reader in, int sz )
Description
Create a new line-numbering reader, reading characters into a buffer of the given size.


 LineNumberReader.getLineNumber

LineNumberReader.getLineNumber

Syntax
public int getLineNumber()
Description
Get the current line number.


 LineNumberReader.mark

LineNumberReader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Parameters
readAheadLimit
Limit on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail.
Description
Mark the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point, and will also reset the line number appropriately.

Exceptions
IOException If an I/O error occurs
Overrides
mark in class BufferedReader


 LineNumberReader.read

LineNumberReader.read

Syntax 1
public int read() throws IOException
Returns
The character read, or -1 if the end of the stream has been reached
Description
Read a single character. Line terminators are compressed into single newline ('\n') characters.

Exceptions
IOException If an I/O error occurs
Overrides
read in class BufferedReader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The number of bytes read, or -1 if the end of the stream has already been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class BufferedReader


 LineNumberReader.readLine

LineNumberReader.readLine

Syntax
public String readLine() throws IOException
Returns
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Description
Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Exceptions
IOException If an I/O error occurs
Overrides
readLine in class BufferedReader


 LineNumberReader.reset

LineNumberReader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream to the most recent mark.

Exceptions
IOException If the stream has not been marked, or if the mark has been invalidated
Overrides
reset in class BufferedReader


 LineNumberReader.setLineNumber

LineNumberReader.setLineNumber

Syntax
public void setLineNumber( int lineNumber )
Description
Set the current line number.


 LineNumberReader.skip

LineNumberReader.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
The number of characters to skip
Returns
The number of characters actually skipped
Description
Skip characters.

Exceptions
IOException If an I/O error occurs
Overrides
skip in class BufferedReader


 Class NotActiveException

Class java.io.NotActiveException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.NotActiveException

public class NotActiveException
extends ObjectStreamException

The NotActiveException is thrown when serialization or deserialization is not active.


 NotActiveException Members

NotActiveException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NotActiveException() | Constructor to create a new NotActiveException with no reason.
NotActiveException(String) | Constructor to create a new NotActiveException with the reason given.


 NotActiveException.NotActiveException

NotActiveException.NotActiveException

Syntax 1
public NotActiveException( String reason )
Description
Constructor to create a new NotActiveException with the reason given.

Syntax 2
public NotActiveException()
Description
Constructor to create a new NotActiveException with no reason.


 Class NotSerializableException

Class java.io.NotSerializableException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.NotSerializableException

public class NotSerializableException
extends ObjectStreamException

Raised by a class or the serialization runtime when a class may not be serialized. The argument should be the name of the class.


 NotSerializableException Members

NotSerializableException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NotSerializableException() |
NotSerializableException(String) |


 NotSerializableException.NotSerializableException

NotSerializableException.NotSerializableException

Syntax 1
public NotSerializableException( String classname )

Syntax 2
public NotSerializableException()


 Interface ObjectInput

Interface java.io.ObjectInput

Interface Members | This Package | All Packages

public interface ObjectInput
extends DataInput

ObjectInput extends the DataInput interface to include the writing of objects. DataInput includes methods for the input of primitive types, ObjectInput extends that interface to include objects, arrays, and Strings.

See Also:
InputStream, ObjectOutputStream, ObjectInputStream


 ObjectInput Members

ObjectInput Members

Interface Overview | This Package | All Packages

Methods
Name | Description
available() | Returns the number of bytes that can be read without blocking.
close() | Closes the input stream.
read() | Reads a byte of data.
read(byte[]) | Reads into an array of bytes.
read(byte[], int, int) | Reads into an array of bytes.
readObject() | Read and return an object.
skip(long) | Skips n bytes of input.


 ObjectInput.available

ObjectInput.available

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int available() throws IOException
Returns
the number of available bytes.
Description
Returns the number of bytes that can be read without blocking.


 ObjectInput.close

ObjectInput.close

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void close() throws IOException
Description
Closes the input stream. Must be called to release any resources associated with the stream.

Exceptions
IOException If an I/O error has occurred.


 ObjectInput.read

ObjectInput.read

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract int read() throws IOException
Returns
the byte read, or -1 if the end of the stream is reached.
Description
Reads a byte of data. This method will block if no input is available.

Exceptions
IOException If an I/O error has occurred.

Syntax 2
public abstract int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read
Returns
the actual number of bytes read, -1 is returned when the end of the stream is reached.
Description
Reads into an array of bytes. This method will block until some input is available.

Exceptions
IOException If an I/O error has occurred.

Syntax 3
public abstract int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, -1 is returned when the end of the stream is reached.
Description
Reads into an array of bytes. This method will block until some input is available.

Exceptions
IOException If an I/O error has occurred.


 ObjectInput.readObject

ObjectInput.readObject

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object readObject() throws ClassNotFoundException, IOException
Description
Read and return an object. The class that implements this interface defines where the object is "read" from.

Exceptions
ClassNotFoundException If the class of a serialized object cannot be found.
Exceptions
IOException If any of the usual Input/Output related exceptions occur.


 ObjectInput.skip

ObjectInput.skip

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long skip( long n ) throws IOException
Parameters
n
the number of bytes to be skipped
Returns
the actual number of bytes skipped.
Description
Skips n bytes of input.

Exceptions
IOException If an I/O error has occurred.


 Class ObjectInputStream

Class java.io.ObjectInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.ObjectInputStream

public class ObjectInputStream
extends InputStream
implements ObjectInput, ObjectStreamConstants

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.

Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams. The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type.

Primitive data types can be read from the stream using the appropriate method on DataInput.

The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten.

Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specifiec class.

For example to read from a stream as written by the example in ObjectOutputStream:

    FileInputStream istream = new FileInputStream("t.tmp");
    ObjectInputStream p = new ObjectInputStream(istream);
    int i = p.readInt();
    String today = (String)p.readObject();
    Date date = (Date)p.readObject();
    istream.close();
Classes control how they are serialized by implementing either the java.io.Serializable or java.io.Externalizable interfaces.

Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects, saving and restoring entire graphs. Serializable classes that require special handling during the serialization and deserialization process should implement both of these methods:

 private void writeObject(java.io.ObjectOutputStream stream)
     throws IOException;
 private void readObject(java.io.ObjectInputStream stream)
     throws IOException, ClassNotFoundException;

The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput.

Serialization does not read or assign values to the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.

Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading process.

Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.

See Also:
DataInput, ObjectOutputStream, Serializable


 ObjectInputStream Members

ObjectInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ObjectInputStream(InputStream) | Create an ObjectInputStream that reads from the specified InputStream.

Methods
Name | Description
available() | Returns the number of bytes that can be read without blocking.
close() | Closes the input stream.
defaultReadObject() | Read the non-static and non-transient fields of the current class from this stream.
enableResolveObject(boolean) | Enable the stream to allow objects read from the stream to be replaced.
read() | Reads a byte of data.
read(byte[], int, int) | Reads into an array of bytes.
readBoolean() | Reads in a boolean.
readByte() | Reads an 8 bit byte.
readChar() | Reads a 16 bit char.
readDouble() | Reads a 64 bit double.
readFloat() | Reads a 32 bit float.
readFully(byte[]) | Reads bytes, blocking until all bytes are read.
readFully(byte[], int, int) | Reads bytes, blocking until all bytes are read.
readInt() | Reads a 32 bit int.
readLine() | Reads in a line that has been terminated by a \n, \r, \r\n or EOF.
readLong() | Reads a 64 bit long.
readObject() | Read an object from the ObjectInputStream.
readShort() | Reads a 16 bit short.
readStreamHeader() | The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers.
readUnsignedByte() | Reads an unsigned 8 bit byte.
readUnsignedShort() | Reads an unsigned 16 bit short.
readUTF() | Reads a UTF format String.
registerValidation(ObjectInputValidation, int) | Register an object to be validated before the graph is returned.
resolveClass(ObjectStreamClass) | Subclasses may implement this method to allow classes to be fetched from an alternate source.
resolveObject(Object) | This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.
skipBytes(int) | Skips bytes, block until all bytes are skipped.


 ObjectInputStream.ObjectInputStream

ObjectInputStream.ObjectInputStream

Syntax
public ObjectInputStream( InputStream in ) throws IOException, StreamCorruptedException
Description
Create an ObjectInputStream that reads from the specified InputStream. The stream header containing the magic number and version number are read from the stream and verified. This method will block until the corresponding ObjectOutputStream has written and flushed the header.

Exceptions
StreamCorruptedException The version or magic number are incorrect.
Exceptions
IOException An exception occurred in the underlying stream.


 ObjectInputStream.available

ObjectInputStream.available

Syntax
public int available() throws IOException
Returns
the number of available bytes.
Description
Returns the number of bytes that can be read without blocking.

Overrides
available in class InputStream


 ObjectInputStream.close

ObjectInputStream.close

Syntax
public void close() throws IOException
Description
Closes the input stream. Must be called to release any resources associated with the stream.

Exceptions
IOException If an I/O error has occurred.
Overrides
close in class InputStream


 ObjectInputStream.defaultReadObject

ObjectInputStream.defaultReadObject

Syntax
public final void defaultReadObject() throws IOException, ClassNotFoundException, NotActiveException
Description
Read the non-static and non-transient fields of the current class from this stream. This may only be called from the readObject method of the class being deserialized. It will throw the NotActiveException if it is called otherwise.

Exceptions
ClassNotFoundException if the class of a serialized object could not be found.
Exceptions
IOException if an I/O error occurs.
Exceptions
NotActiveException if the stream is not currently reading objects.


 ObjectInputStream.enableResolveObject

ObjectInputStream.enableResolveObject

Syntax
protected final boolean enableResolveObject( boolean enable ) throws SecurityException
Description
Enable the stream to allow objects read from the stream to be replaced. If the stream is a trusted class it is allowed to enable replacment. Trusted classes are those classes with a classLoader equals null.

When enabled the resolveObject method is called for every object being deserialized.

Exceptions
SecurityException The classloader of this stream object is non-null.


 ObjectInputStream.read

ObjectInputStream.read

Syntax 1
public int read() throws IOException
Returns
the byte read, or -1 if the end of the stream is reached.
Description
Reads a byte of data. This method will block if no input is available.

Exceptions
IOException If an I/O error has occurred.
Overrides
read in class InputStream

Syntax 2
public int read( byte data[], int offset, int length ) throws IOException
Parameters
b
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, -1 is returned when the end of the stream is reached.
Description
Reads into an array of bytes. This method will block until some input is available.

Exceptions
IOException If an I/O error has occurred.
Overrides
read in class InputStream


 ObjectInputStream.readBoolean

ObjectInputStream.readBoolean

Syntax
public boolean readBoolean() throws IOException
Returns
the boolean read.
Description
Reads in a boolean.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readByte

ObjectInputStream.readByte

Syntax
public byte readByte() throws IOException
Returns
the 8 bit byte read.
Description
Reads an 8 bit byte.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readChar

ObjectInputStream.readChar

Syntax
public char readChar() throws IOException
Returns
the 16 bit char read.
Description
Reads a 16 bit char.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readDouble

ObjectInputStream.readDouble

Syntax
public double readDouble() throws IOException
Returns
the 64 bit double read.
Description
Reads a 64 bit double.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readFloat

ObjectInputStream.readFloat

Syntax
public float readFloat() throws IOException
Returns
the 32 bit float read.
Description
Reads a 32 bit float.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readFully

ObjectInputStream.readFully

Syntax 1
public void readFully( byte data[] ) throws IOException
Parameters
b
the buffer into which the data is read
Description
Reads bytes, blocking until all bytes are read.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.

Syntax 2
public void readFully( byte data[], int offset, int size ) throws IOException
Parameters
b
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes to read
Description
Reads bytes, blocking until all bytes are read.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readInt

ObjectInputStream.readInt

Syntax
public int readInt() throws IOException
Returns
the 32 bit integer read.
Description
Reads a 32 bit int.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readLine

ObjectInputStream.readLine

Syntax
public String readLine() throws IOException
Returns
a String copy of the line.
Description
Reads in a line that has been terminated by a \n, \r, \r\n or EOF.


 ObjectInputStream.readLong

ObjectInputStream.readLong

Syntax
public long readLong() throws IOException
Returns
the read 64 bit long.
Description
Reads a 64 bit long.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readObject

ObjectInputStream.readObject

Syntax
public final Object readObject() throws OptionalDataException, ClassNotFoundException, IOException
Description
Read an object from the ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read. Default deserializing for a class can be overriden using the writeObject and readObject methods. Objects referenced by this object are read transitively so that a complete equivalent graph of objects is reconstructed by readObject.

The root object is completly restored when all of its fields and the objects it references are completely restored. At this point the object validation callbacks are executed in order based on their registered priorities. The callbacks are registered by objects (in the readObject special methods) as they are individually restored. Exceptions are thrown for problems with the InputStream and for classes that should not be deserialized. All exceptions are fatal to the InputStream and leave it in an indeterminate state; it is up to the caller to ignore or recover the stream state.

Exceptions
ClassNotFoundException Class of a serialized object cannot be found.
Exceptions
InvalidClassException Something is wrong with a class used by serialization.
Exceptions
StreamCorruptedException Control information in the stream is inconsistent.
Exceptions
OptionalDataException Primitive data was found in the stream instead of objects.
Exceptions
IOException Any of the usual Input/Output related exceptions.


 ObjectInputStream.readShort

ObjectInputStream.readShort

Syntax
public short readShort() throws IOException
Returns
the 16 bit short read.
Description
Reads a 16 bit short.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readStreamHeader

ObjectInputStream.readStreamHeader

Syntax
protected void readStreamHeader() throws IOException, StreamCorruptedException
Description
The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers. It reads and verifies the magic number and version number.


 ObjectInputStream.readUnsignedByte

ObjectInputStream.readUnsignedByte

Syntax
public int readUnsignedByte() throws IOException
Returns
the 8 bit byte read.
Description
Reads an unsigned 8 bit byte.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readUnsignedShort

ObjectInputStream.readUnsignedShort

Syntax
public int readUnsignedShort() throws IOException
Returns
the 16 bit short read.
Description
Reads an unsigned 16 bit short.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 ObjectInputStream.readUTF

ObjectInputStream.readUTF

Syntax
public String readUTF() throws IOException
Returns
the String.
Description
Reads a UTF format String.


 ObjectInputStream.registerValidation

ObjectInputStream.registerValidation

Syntax
public synchronized void registerValidation( ObjectInputValidation obj, int prio ) throws NotActiveException, InvalidObjectException
Parameters
obj
the object to receive the validation callback.
prio
controls the order of callbacks;zero is a good default. Use higher numbers to be called back earlier, lower numbers for later callbacks. Within a priority, callbacks are processed in no particular order.
Description
Register an object to be validated before the graph is returned. While similar to resolveObject these validations are called after the entire graph has been reconstituted. Typically, a readObject method will register the object with the stream so that when all of the objects are restored a final set of validations can be performed.

Exceptions
NotActiveException The stream is not currently reading objects so it is invalid to register a callback.
Exceptions
InvalidObjectException The validation object is null.


 ObjectInputStream.resolveClass

ObjectInputStream.resolveClass

Syntax
protected Class resolveClass( ObjectStreamClass v ) throws IOException, ClassNotFoundException
Description
Subclasses may implement this method to allow classes to be fetched from an alternate source. The corresponding method in ObjectOutputStream is annotateClass. This method will be invoked only once for each unique class in the stream. This method can be implemented by subclasses to use an alternate loading mechanism but must return a Class object. Once returned, the serialVersionUID of the class is compared to the serialVersionUID of the serialized class. If there is a mismatch, the deserialization fails and an exception is raised.

By default the class name is resolved relative to the class that called readObject.

Exceptions
ClassNotFoundException If class of a serialized object cannot be found.


 ObjectInputStream.resolveObject

ObjectInputStream.resolveObject

Syntax
protected Object resolveObject( Object obj ) throws IOException
Description
This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization. Replacing objects is disabled until enableResolveObject is called. The enableResolveObject method checks that the stream requesting to resolve object can be trusted. Every reference to serializable objects is passed to resolveObject. To insure that the private state of objects is not unintentionally exposed only trusted streams may use resolveObject.

This method is called after an object has been read but before it is returned from readObject. The default resolveObject method just returns the new object.

When a subclass is replacing objects it must insure that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.

This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object.

Exceptions
IOException Any of the usual Input/Output exceptions.


 ObjectInputStream.skipBytes

ObjectInputStream.skipBytes

Syntax
public int skipBytes( int len ) throws IOException
Parameters
n
the number of bytes to be skipped
Returns
the actual number of bytes skipped.
Description
Skips bytes, block until all bytes are skipped.

Exceptions
EOFException If end of file is reached.
Exceptions
IOException If other I/O error has occurred.


 Interface ObjectInputValidation

Interface java.io.ObjectInputValidation

Interface Members | This Package | All Packages

public interface ObjectInputValidation

Callback interface to allow validation of objects within a graph. Allows an object to be called when a complete graph of objects has been deserialized.

See Also:
ObjectInputStream, registerValidation


 ObjectInputValidation Members

ObjectInputValidation Members

Interface Overview | This Package | All Packages

Methods
Name | Description
validateObject() | Validates the object


 ObjectInputValidation.validateObject

ObjectInputValidation.validateObject

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void validateObject() throws InvalidObjectException
Description
Validates the object

Exceptions
InvalidObjectException If the object cannot validate itself.


 Interface ObjectOutput

Interface java.io.ObjectOutput

Interface Members | This Package | All Packages

public interface ObjectOutput
extends DataOutput

ObjectOutput extends the DataOutput interface to include writing of objects. DataOutput includes methods for output of primitive types, ObjectOutput extends that interface to include objects, arrays, and Strings.

See Also:
InputStream, ObjectOutputStream, ObjectInputStream


 ObjectOutput Members

ObjectOutput Members

Interface Overview | This Package | All Packages

Methods
Name | Description
close() | Closes the stream.
flush() | Flushes the stream.
write(byte[]) | Writes an array of bytes.
write(byte[], int, int) | Writes a sub array of bytes.
write(int) | Writes a byte.
writeObject(Object) | Write an object to the underlying storage or stream.


 ObjectOutput.close

ObjectOutput.close

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void close() throws IOException
Description
Closes the stream. This method must be called to release any resources associated with the stream.

Exceptions
IOException If an I/O error has occurred.


 ObjectOutput.flush

ObjectOutput.flush

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void flush() throws IOException
Description
Flushes the stream. This will write any buffered output bytes.

Exceptions
IOException If an I/O error has occurred.


 ObjectOutput.write

ObjectOutput.write

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void write( int b ) throws IOException
Parameters
b
the byte
Description
Writes a byte. This method will block until the byte is actually written.

Exceptions
IOException If an I/O error has occurred.

Syntax 2
public abstract void write( byte b[] ) throws IOException
Parameters
b
the data to be written
Description
Writes an array of bytes. This method will block until the bytes are actually written.

Exceptions
IOException If an I/O error has occurred.

Syntax 3
public abstract void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data to be written
off
the start offset in the data
len
the number of bytes that are written
Description
Writes a sub array of bytes.

Exceptions
IOException If an I/O error has occurred.


 ObjectOutput.writeObject

ObjectOutput.writeObject

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void writeObject( Object obj ) throws IOException
Description
Write an object to the underlying storage or stream. The class that implements this interface defines how the object is written.

Exceptions
IOException Any of the usual Input/Output related exceptions.


 Class ObjectOutputStream

Class java.io.ObjectOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.ObjectOutputStream

public class ObjectOutputStream
extends OutputStream
implements ObjectOutput, ObjectStreamConstants

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconsituted on another host or in another process.

Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.

The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.

Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.

For example to write an object that can be read by the example in ObjectInputStream:

    FileOutputStream ostream = new FileOutputStream("t.tmp");
    ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeInt(12345);
    p.writeObject("Today");
    p.writeObject(new Date());
    p.flush();
    ostream.close();
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

 private void readObject(java.io.ObjectInputStream stream)
     throws IOException, ClassNotFoundException;
 private void writeObject(java.io.ObjectOutputStream stream)
     throws IOException

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.

Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.

See Also:
DataOutput, ObjectInputStream, Serializable, Externalizable


 ObjectOutputStream Members

ObjectOutputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ObjectOutputStream(OutputStream) | Creates an ObjectOutputStream that writes to the specified OutputStream.

Methods
Name | Description
annotateClass(Class) | Subclasses may implement this method to allow class data to be stored in the stream.
close() | Closes the stream.
defaultWriteObject() | Write the non-static and non-transient fields of the current class to this stream.
drain() | Drain any buffered data in ObjectOutputStream.
enableReplaceObject(boolean) | Enable the stream to do replacement of objects in the stream.
flush() | Flushes the stream.
replaceObject(Object) | This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.
reset() | Reset will disregard the state of any objects already written to the stream.
write(byte[]) | Writes an array of bytes.
write(byte[], int, int) | Writes a sub array of bytes.
write(int) | Writes a byte.
writeBoolean(boolean) | Writes a boolean.
writeByte(int) | Writes an 8 bit byte.
writeBytes(String) | Writes a String as a sequence of bytes.
writeChar(int) | Writes a 16 bit char.
writeChars(String) | Writes a String as a sequence of chars.
writeDouble(double) | Writes a 64 bit double.
writeFloat(float) | Writes a 32 bit float.
writeInt(int) | Writes a 32 bit int.
writeLong(long) | Writes a 64 bit long.
writeObject(Object) | Write the specified object to the ObjectOutputStream.
writeShort(int) | Writes a 16 bit short.
writeStreamHeader() | The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream.
writeUTF(String) | Writes a String in UTF format.


 ObjectOutputStream.ObjectOutputStream

ObjectOutputStream.ObjectOutputStream

Syntax
public ObjectOutputStream( OutputStream out ) throws IOException
Description
Creates an ObjectOutputStream that writes to the specified OutputStream. The stream header is written to the stream. The caller may want to call flush immediately so that the corresponding ObjectInputStream can read the header immediately.

Exceptions
IOException Any exception thrown by the underlying OutputStream.


 ObjectOutputStream.annotateClass

ObjectOutputStream.annotateClass

Syntax
protected void annotateClass( Class cl ) throws IOException
Description
Subclasses may implement this method to allow class data to be stored in the stream. By default this method does nothing. The corresponding method in ObjectInputStream is resolveClass. This method is called exactly once for each unique class in the stream. The class name and signature will have already been written to the stream. This method may make free use of the ObjectOutputStream to save any representation of the class it deems suitable (for example, the bytes of the class file). The resolveClass method in the corresponding subclass of ObjectInputStream must read and use any data or objects written by annotateClass. annotateClass is called only for normal classes. Arrays are not normal classes.

Exceptions
IOException Any exception thrown by the underlying OutputStream.


 ObjectOutputStream.close

ObjectOutputStream.close

Syntax
public void close() throws IOException
Description
Closes the stream. This method must be called to release any resources associated with the stream.

Exceptions
IOException If an I/O error has occurred.
Overrides
close in class OutputStream


 ObjectOutputStream.defaultWriteObject

ObjectOutputStream.defaultWriteObject

Syntax
public final void defaultWriteObject() throws IOException
Description
Write the non-static and non-transient fields of the current class to this stream. This may only be called from the writeObject method of the class being serialized. It will throw the NotActiveException if it is called otherwise.


 ObjectOutputStream.drain

ObjectOutputStream.drain

Syntax
protected void drain() throws IOException
Description
Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to the underlaying stream.


 ObjectOutputStream.enableReplaceObject

ObjectOutputStream.enableReplaceObject

Syntax
protected final boolean enableReplaceObject( boolean enable ) throws SecurityException
Description
Enable the stream to do replacement of objects in the stream. If the stream is a trusted class it is allowed to enable replacement. Trusted classes are those classes with a classLoader equals null.

When enabled the replaceObject method is called for every object being serialized.

Exceptions
SecurityException The classloader of this stream object is non-null.


 ObjectOutputStream.flush

ObjectOutputStream.flush

Syntax
public void flush() throws IOException
Description
Flushes the stream. This will write any buffered output bytes and flush through to the underlying stream.

Exceptions
IOException If an I/O error has occurred.
Overrides
flush in class OutputStream


 ObjectOutputStream.replaceObject

ObjectOutputStream.replaceObject

Syntax
protected Object replaceObject( Object obj ) throws IOException
Description
This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization. Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacment can be trusted. Every reference to serializable objects is passed to replaceObject. To insure that the private state of objects is not unintentionally exposed only trusted streams may use replaceObject.

When a subclass is replacing objects it must insure that either a complementary substitution must be made during deserialization or that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.

This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object. This method should return the object to be substituted or the original object.

Null can be returned as the object to be substituted, but may cause NullReferenceException in classes that contain references to the original object since they may be expecting an object instead of null.

Exceptions
IOException Any exception thrown by the underlying OutputStream.


 ObjectOutputStream.reset

ObjectOutputStream.reset

Syntax
public void reset() throws IOException
Description
Reset will disregard the state of any objects already written to the stream. The state is reset to be the same as a new ObjectOutputStream. The current point in the stream is marked as reset so the corresponding ObjectInputStream will be reset at the same point. Objects previously written to the stream will not be refered to as already being in the stream. They will be written to the stream again.


 ObjectOutputStream.write

ObjectOutputStream.write

Syntax 1
public void write( int data ) throws IOException
Parameters
b
the byte
Description
Writes a byte. This method will block until the byte is actually written.

Exceptions
IOException If an I/O error has occurred.
Overrides
write in class OutputStream

Syntax 2
public void write( byte b[] ) throws IOException
Parameters
b
the data to be written
Description
Writes an array of bytes. This method will block until the bytes are actually written.

Exceptions
IOException If an I/O error has occurred.
Overrides
write in class OutputStream

Syntax 3
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data to be written
off
the start offset in the data
len
the number of bytes that are written
Description
Writes a sub array of bytes.

Exceptions
IOException If an I/O error has occurred.
Overrides
write in class OutputStream


 ObjectOutputStream.writeBoolean

ObjectOutputStream.writeBoolean

Syntax
public void writeBoolean( boolean data ) throws IOException
Parameters
data
the boolean to be written
Description
Writes a boolean.


 ObjectOutputStream.writeByte

ObjectOutputStream.writeByte

Syntax
public void writeByte( int data ) throws IOException
Parameters
data
the byte value to be written
Description
Writes an 8 bit byte.


 ObjectOutputStream.writeBytes

ObjectOutputStream.writeBytes

Syntax
public void writeBytes( String data ) throws IOException
Parameters
s
the String of bytes to be written
Description
Writes a String as a sequence of bytes.


 ObjectOutputStream.writeChar

ObjectOutputStream.writeChar

Syntax
public void writeChar( int data ) throws IOException
Parameters
data
the char value to be written
Description
Writes a 16 bit char.


 ObjectOutputStream.writeChars

ObjectOutputStream.writeChars

Syntax
public void writeChars( String data ) throws IOException
Parameters
s
the String of chars to be written
Description
Writes a String as a sequence of chars.


 ObjectOutputStream.writeDouble

ObjectOutputStream.writeDouble

Syntax
public void writeDouble( double data ) throws IOException
Parameters
data
the double value to be written
Description
Writes a 64 bit double.


 ObjectOutputStream.writeFloat

ObjectOutputStream.writeFloat

Syntax
public void writeFloat( float data ) throws IOException
Parameters
data
the float value to be written
Description
Writes a 32 bit float.


 ObjectOutputStream.writeInt

ObjectOutputStream.writeInt

Syntax
public void writeInt( int data ) throws IOException
Parameters
data
the integer value to be written
Description
Writes a 32 bit int.


 ObjectOutputStream.writeLong

ObjectOutputStream.writeLong

Syntax
public void writeLong( long data ) throws IOException
Parameters
data
the long value to be written
Description
Writes a 64 bit long.


 ObjectOutputStream.writeObject

ObjectOutputStream.writeObject

Syntax
public final void writeObject( Object obj ) throws IOException
Description
Write the specified object to the ObjectOutputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are written. Default serialization for a class can be overridden using the writeObject and the readObject methods. Objects referenced by this object are written transitively so that a complete equivalent graph of objects can be reconstructed by an ObjectInputStream.

Exceptions are thrown for problems with the OutputStream and for classes that should not be serialized. All exceptions are fatal to the OutputStream, which is left in an indeterminate state, and it is up to the caller to ignore or recover the stream state.

Exceptions
InvalidClassException Something is wrong with a class used by serialization.
Exceptions
NotSerializableException Some object to be serialized does not implement the java.io.Serializable interface.
Exceptions
IOException Any exception thrown by the underlying OutputStream.


 ObjectOutputStream.writeShort

ObjectOutputStream.writeShort

Syntax
public void writeShort( int data ) throws IOException
Parameters
data
the short value to be written
Description
Writes a 16 bit short.


 ObjectOutputStream.writeStreamHeader

ObjectOutputStream.writeStreamHeader

Syntax
protected void writeStreamHeader() throws IOException
Description
The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream. It writes the magic number and version to the stream.


 ObjectOutputStream.writeUTF

ObjectOutputStream.writeUTF

Syntax
public void writeUTF( String data ) throws IOException
Parameters
str
the String in UTF format
Description
Writes a String in UTF format.


 Class ObjectStreamClass

Class java.io.ObjectStreamClass

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.ObjectStreamClass

public class ObjectStreamClass
extends Object
implements Serializable

A ObjectStreamClass describes a class that can be serialized to a stream or a class that was serialized to a stream. It contains the name and the serialVersionUID of the class.
The ObjectStreamClass for a specific class loaded in this Java VM can be found using the lookup method.


 ObjectStreamClass Members

ObjectStreamClass Members

Class Overview | This Package | All Packages

Methods
Name | Description
forClass() | Return the class in the local VM that this version is mapped to.
getName() | The name of the class described by this descriptor.
getSerialVersionUID() | Return the serialVersionUID for this class.
lookup(Class) | Find the descriptor for a class that can be serialized.
toString() | Return a string describing this ObjectStreamClass.


 ObjectStreamClass.forClass

ObjectStreamClass.forClass

Syntax
public Class forClass()
Description
Return the class in the local VM that this version is mapped to. Null is returned if there is no corresponding local class.


 ObjectStreamClass.getName

ObjectStreamClass.getName

Syntax
public String getName()
Description
The name of the class described by this descriptor.


 ObjectStreamClass.getSerialVersionUID

ObjectStreamClass.getSerialVersionUID

Syntax
public long getSerialVersionUID()
Description
Return the serialVersionUID for this class. The serialVersionUID defines a set of classes all with the same name that have evolved from a common root class and agree to be serialized and deserialized using a common format.


 ObjectStreamClass.lookup

ObjectStreamClass.lookup

Syntax
public static ObjectStreamClass lookup( Class cl )
Description
Find the descriptor for a class that can be serialized. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable.


 ObjectStreamClass.toString

ObjectStreamClass.toString

Syntax
public String toString()
Description
Return a string describing this ObjectStreamClass.

Overrides
toString in class Object


 Class ObjectStreamException

Class java.io.ObjectStreamException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException

public abstract class ObjectStreamException
extends IOException

Superclass of all exceptions specific to Object Stream classes.


 ObjectStreamException Members

ObjectStreamException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ObjectStreamException() | Create an ObjectStreamException.
ObjectStreamException(String) | Create an ObjectStreamException with the specified argument.


 ObjectStreamException.ObjectStreamException

ObjectStreamException.ObjectStreamException

Syntax 1
protected ObjectStreamException( String classname )
Description
Create an ObjectStreamException with the specified argument.

Syntax 2
protected ObjectStreamException()
Description
Create an ObjectStreamException.


 Class OptionalDataException

Class java.io.OptionalDataException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.OptionalDataException

public class OptionalDataException
extends ObjectStreamException

Unexpected data appeared in an ObjectInputStream trying to read an Object. This exception occurs when the stream contains primitive data instead of the object expected by readObject. The eof flag in the exception is true to indicate that no more primitive data is available. The count field contains the number of bytes available to read.


 OptionalDataException Members

OptionalDataException Members

Class Overview | This Package | All Packages

Fields
Name | Description
eof | True if there is no more data in the buffered part of the stream.
length | The number of bytes of primitive data available to be read in the current buffer.


 OptionalDataException.eof

OptionalDataException.eof

Syntax
public boolean eof
Description
True if there is no more data in the buffered part of the stream.


 OptionalDataException.length

OptionalDataException.length

Syntax
public int length
Description
The number of bytes of primitive data available to be read in the current buffer.


 Class OutputStream

Class java.io.OutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream

public abstract class OutputStream
extends Object

This abstract class is the superclass of all classes representing an output stream of bytes.

Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

See Also:
BufferedOutputStream, ByteArrayOutputStream, DataOutputStream, FilterOutputStream, InputStream, write


 OutputStream Members

OutputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
OutputStream() |

Methods
Name | Description
close() | Closes this output stream and releases any system resources associated with this stream.
flush() | Flushes this output stream and forces any buffered output bytes to be written out.
write(byte[]) | Writes b.length bytes from the specified byte array to this output stream.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this output stream.
write(int) | Writes the specified byte to this output stream.


 OutputStream.OutputStream

OutputStream.OutputStream

Syntax
public OutputStream()


 OutputStream.close

OutputStream.close

Syntax
public void close() throws IOException
Description
Closes this output stream and releases any system resources associated with this stream.

The close method of OutputStream does nothing.

Exceptions
IOException if an I/O error occurs.


 OutputStream.flush

OutputStream.flush

Syntax
public void flush() throws IOException
Description
Flushes this output stream and forces any buffered output bytes to be written out.

The flush method of OutputStream does nothing.

Exceptions
IOException if an I/O error occurs.


 OutputStream.write

OutputStream.write

Syntax 1
public abstract void write( int b ) throws IOException
Parameters
b
the byte.
Description
Writes the specified byte to this output stream.

Subclasses of OutputStream must provide an implementation for this method.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public void write( byte b[] ) throws IOException
Parameters
b
the data.
Description
Writes b.length bytes from the specified byte array to this output stream.

The write method of OutputStream calls the write method of three arguments with the three arguments b, 0, and b.length.

Exceptions
IOException if an I/O error occurs.
See Also
write

Syntax 3
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this output stream.

The write method of OutputStream calls the write method of one argument on each of the bytes to be written out. Subclasses are encouraged to override this method and provide a more efficient implementation.

Exceptions
IOException if an I/O error occurs.


 Class OutputStreamWriter

Class java.io.OutputStreamWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.OutputStreamWriter

public class OutputStreamWriter
extends Writer

Write characters to an output stream, translating characters into bytes according to a specified character encoding. Each OutputStreamWriter incorporates its own CharToByteConverter, and is thus a bridge from character streams to byte streams.

The encoding used by an OutputStreamWriter may be specified by name, by providing a CharToByteConverter, or by accepting the default encoding, which is defined by the system property file.encoding.

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered. For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example,

 Writer out
   = new BufferedWriter(new OutputStreamWriter(System.out));

See Also:
BufferedWriter, OutputStream


 OutputStreamWriter Members

OutputStreamWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
OutputStreamWriter(OutputStream) | Create an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream, String) | Create an OutputStreamWriter that uses the named character encoding.

Methods
Name | Description
close() | Close the stream.
flush() | Flush the stream.
getEncoding() | Return the name of the encoding being used by this stream.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String, int, int) | Write a portion of a string.


 OutputStreamWriter.OutputStreamWriter

OutputStreamWriter.OutputStreamWriter

Syntax 1
public OutputStreamWriter( OutputStream out, String enc ) throws UnsupportedEncodingException
Parameters
out
An OutputStream
enc
Name of the encoding to be used
Description
Create an OutputStreamWriter that uses the named character encoding.

Exceptions
UnsupportedEncodingException If the named encoding is not supported

Syntax 2
public OutputStreamWriter( OutputStream out )
Parameters
out
An OutputStream
Description
Create an OutputStreamWriter that uses the default character encoding.


 OutputStreamWriter.close

OutputStreamWriter.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Writer


 OutputStreamWriter.flush

OutputStreamWriter.flush

Syntax
public void flush() throws IOException
Description
Flush the stream.

Exceptions
IOException If an I/O error occurs
Overrides
flush in class Writer


 OutputStreamWriter.getEncoding

OutputStreamWriter.getEncoding

Syntax
public String getEncoding()
Description
Return the name of the encoding being used by this stream. May return null if the stream has been closed.


 OutputStreamWriter.write

OutputStreamWriter.write

Syntax 1
public void write( int c ) throws IOException
Description
Write a single character.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 2
public void write( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Buffer of characters
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of an array of characters.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer

Syntax 3
public void write( String str, int off, int len ) throws IOException
Parameters
str
A String
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of a string.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer


 Class PipedInputStream

Class java.io.PipedInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.PipedInputStream

public class PipedInputStream
extends InputStream

A piped input stream is the receiving end of a communications pipe. Two threads can communicate by having one thread send data through a piped output stream and having the other thread read the data through a piped input stream.

See Also:
PipedOutputStream


 PipedInputStream Members

PipedInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buffer | The circular buffer into which incoming data is placed.
in |
out |
PIPE_SIZE |

Constructors
Name | Description
PipedInputStream() | Creates a piped input stream that is not yet connected to a piped output stream.
PipedInputStream(PipedOutputStream) | Creates a piped input stream connected to the specified piped output stream.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
close() | Closes this piped input stream and releases any system resources associated with the stream.
connect(PipedOutputStream) | Connects this piped input stream to a sender.
read() | Reads the next byte of data from this piped input stream.
read(byte[], int, int) | Reads up to len bytes of data from this piped input stream into an array of bytes.
receive(int) | Receives a byte of data.


 PipedInputStream.buffer

PipedInputStream.buffer

Syntax
protected byte buffer[]
Description
The circular buffer into which incoming data is placed.


 PipedInputStream.in

PipedInputStream.in

Syntax
protected int in


 PipedInputStream.out

PipedInputStream.out

Syntax
protected int out


 PipedInputStream.PIPE_SIZE

PipedInputStream.PIPE_SIZE

Syntax
protected static final int PIPE_SIZE


 PipedInputStream.PipedInputStream

PipedInputStream.PipedInputStream

Syntax 1
public PipedInputStream( PipedOutputStream src ) throws IOException
Parameters
src
the stream to connect to.
Description
Creates a piped input stream connected to the specified piped output stream.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public PipedInputStream()
Description
Creates a piped input stream that is not yet connected to a piped output stream. It must be connected to a piped output stream, either by the receiver or the sender, before being used.

See Also
connect, connect


 PipedInputStream.available

PipedInputStream.available

Syntax
public synchronized int available() throws IOException
Returns
the number of bytes that can be read from this input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking. This method overrides the available method of the parent class.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class InputStream


 PipedInputStream.close

PipedInputStream.close

Syntax
public void close() throws IOException
Description
Closes this piped input stream and releases any system resources associated with the stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class InputStream


 PipedInputStream.connect

PipedInputStream.connect

Syntax
public void connect( PipedOutputStream src ) throws IOException
Parameters
src
The piped output stream to connect to.
Description
Connects this piped input stream to a sender.

Exceptions
IOException if an I/O error occurs.


 PipedInputStream.read

PipedInputStream.read

Syntax 1
public synchronized int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this piped input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because this end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

Exceptions
IOException if the pipe is broken.
Overrides
read in class InputStream

Syntax 2
public synchronized int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this piped input stream into an array of bytes. This method blocks until at least one byte of input is available.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream


 PipedInputStream.receive

PipedInputStream.receive

Syntax
protected synchronized void receive( int b ) throws IOException
Parameters
b
the byte being received
Description
Receives a byte of data. This method will block if no input is available.

Exceptions
IOException If the pipe is broken.


 Class PipedOutputStream

Class java.io.PipedOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.PipedOutputStream

public class PipedOutputStream
extends OutputStream

A piped output stream is the sending end of a communications pipe. Two threads can communicate by having one thread send data through a piped output stream and having the other thread read the data through a piped input stream.

See Also:
PipedInputStream


 PipedOutputStream Members

PipedOutputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PipedOutputStream() | Creates a piped output stream that is not yet connected to a piped input stream.
PipedOutputStream(PipedInputStream) | Creates a piped output stream connected to the specified piped input stream.

Methods
Name | Description
close() | Closes this piped output stream and releases any system resources associated with this stream.
connect(PipedInputStream) | Connects this piped output stream to a receiver.
flush() | Flushes this output stream and forces any buffered output bytes to be written out.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this piped output stream.
write(int) | Writes the specified byte to the piped output stream.


 PipedOutputStream.PipedOutputStream

PipedOutputStream.PipedOutputStream

Syntax 1
public PipedOutputStream( PipedInputStream snk ) throws IOException
Parameters
snk
The piped input stream to connect to.
Description
Creates a piped output stream connected to the specified piped input stream.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public PipedOutputStream()
Description
Creates a piped output stream that is not yet connected to a piped input stream. It must be connected to a piped input stream, either by the receiver or the sender, before being used.

See Also
connect, connect


 PipedOutputStream.close

PipedOutputStream.close

Syntax
public void close() throws IOException
Description
Closes this piped output stream and releases any system resources associated with this stream.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class OutputStream


 PipedOutputStream.connect

PipedOutputStream.connect

Syntax
public void connect( PipedInputStream snk ) throws IOException
Parameters
snk
the piped output stream to connect to.
Description
Connects this piped output stream to a receiver.

Exceptions
IOException if an I/O error occurs.


 PipedOutputStream.flush

PipedOutputStream.flush

Syntax
public synchronized void flush() throws IOException
Description
Flushes this output stream and forces any buffered output bytes to be written out. This will notify any readers that bytes are waiting in the pipe.

Exceptions
IOException if an I/O error occurs.
Overrides
flush in class OutputStream


 PipedOutputStream.write

PipedOutputStream.write

Syntax 1
public void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to the piped output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream

Syntax 2
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this piped output stream.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class OutputStream


 Class PipedReader

Class java.io.PipedReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.PipedReader

public class PipedReader
extends Reader

Piped character-input streams.


 PipedReader Members

PipedReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PipedReader() | Create a reader that is not yet connected to a piped writer.
PipedReader(PipedWriter) | Create a reader for the specified piped character-output stream.

Methods
Name | Description
close() | Close the stream.
connect(PipedWriter) | Connect the specified piped writer to this reader.
read(char[], int, int) | Read characters into a portion of an array.


 PipedReader.PipedReader

PipedReader.PipedReader

Syntax 1
public PipedReader()
Description
Create a reader that is not yet connected to a piped writer.

Syntax 2
public PipedReader( PipedWriter src ) throws IOException
Description
Create a reader for the specified piped character-output stream.


 PipedReader.close

PipedReader.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Reader


 PipedReader.connect

PipedReader.connect

Syntax
public void connect( PipedWriter src ) throws IOException
Description
Connect the specified piped writer to this reader.

Exceptions
IOException If this reader is already connected


 PipedReader.read

PipedReader.read

Syntax
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 Class PipedWriter

Class java.io.PipedWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.PipedWriter

public class PipedWriter
extends Writer

Piped character-output streams.


 PipedWriter Members

PipedWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PipedWriter() | Create a writer that is not yet connected to a piped reader.
PipedWriter(PipedReader) | Create a writer for the specified piped character-input stream.

Methods
Name | Description
close() | Close the stream.
connect(PipedReader) | Connect the specified piped reader to this writer.
flush() | Flush the stream.
write(char[], int, int) | Write a portion of an array of characters.


 PipedWriter.PipedWriter

PipedWriter.PipedWriter

Syntax 1
public PipedWriter()
Description
Create a writer that is not yet connected to a piped reader.

Syntax 2
public PipedWriter( PipedReader sink ) throws IOException
Description
Create a writer for the specified piped character-input stream.


 PipedWriter.close

PipedWriter.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class Writer


 PipedWriter.connect

PipedWriter.connect

Syntax
public void connect( PipedReader sink ) throws IOException
Description
Connect the specified piped reader to this writer.


 PipedWriter.flush

PipedWriter.flush

Syntax
public void flush() throws IOException
Description
Flush the stream.

Exceptions
IOException If an I/O error occurs
Overrides
flush in class Writer


 PipedWriter.write

PipedWriter.write

Syntax
public void write( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Array of characters
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of an array of characters.

Exceptions
IOException If an I/O error occurs
Overrides
write in class Writer


 Class PrintStream

Class java.io.PrintStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.io.PrintStream

public class PrintStream
extends FilterOutputStream

Print values and objects to an output stream, using the platform's default character encoding to convert characters into bytes.

If automatic flushing is enabled at creation time, then the stream will be flushed each time a line is terminated or a newline character is written.

Methods in this class never throw I/O exceptions. Client code may inquire as to whether any errors have occurred by invoking the checkError method.

Note: This class is provided primarily for use in debugging, and for compatibility with existing code; new code should use the PrintWriter class.

See Also:
PrintWriter


 PrintStream Members

PrintStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PrintStream(OutputStream) | Create a new print stream. Deprecated.
PrintStream(OutputStream, boolean) | Create a new PrintStream. Deprecated.

Methods
Name | Description
checkError() | Flush the stream and check its error state.
close() | Close the stream.
flush() | Flush the stream.
print(boolean) | Print a boolean value.
print(char) | Print a character.
print(char[]) | Print an array of characters.
print(double) | Print a double-precision floating-point number.
print(float) | Print a floating-point number.
print(int) | Print an integer.
print(long) | Print a long integer.
print(Object) | Print an object.
print(String) | Print a string.
println() | Finish the current line by writing a line separator.
println(boolean) | Print a boolean, and then finish the line.
println(char) | Print a character, and then finish the line.
println(char[]) | Print an array of characters, and then finish the line.
println(double) | Print a double, and then finish the line.
println(float) | Print a float, and then finish the line.
println(int) | Print an integer, and then finish the line.
println(long) | Print a long, and then finish the line.
println(Object) | Print an Object, and then finish the line.
println(String) | Print a String, and then finish the line.
setError() | Indicate that an error has occurred.
write(byte[], int, int) | Write a portion of a byte array, blocking if necessary.
write(int) | Write a byte, blocking if necessary.


 PrintStream.PrintStream

PrintStream.PrintStream

Syntax 1
public PrintStream( OutputStream out )
Parameters
out
The output stream to which values and objects will be printed
Description
Note: PrintStream() is deprecated. As of JDK 1.1, the preferred way to print text is via the PrintWriter class. Consider replacing code of the
form PrintStream p = new PrintStream(out);
with PrintWriter p = new PrintWriter(out);

Create a new print stream.

See Also
PrintWriter

Syntax 2
public PrintStream( OutputStream out, boolean autoFlush )
Parameters
out
The output stream to which values and objects will be printed
autoFlush
A boolean; if true, the output buffer will be flushed whenever a line is terminated or a newline character ('\n') is written
Description
Note: PrintStream() is deprecated. As of JDK 1.1, the preferred way to print text is via the PrintWriter class. Consider replacing code of the
form PrintStream p = new PrintStream(out, autoFlush);
with PrintWriter p = new PrintWriter(out, autoFlush);

Create a new PrintStream.

See Also
PrintWriter


 PrintStream.checkError

PrintStream.checkError

Syntax
public boolean checkError()
Returns
True if the print stream has encountered an error, either on the underlying output stream or during a format conversion, otherwise false.
Description
Flush the stream and check its error state. Errors are cumulative; once the stream encounters an error, this routine will continue to return true on all successive calls.


 PrintStream.close

PrintStream.close

Syntax
public void close()
Description
Close the stream. This is done by flushing the stream and then closing the underlying output stream.

Overrides
close in class FilterOutputStream
See Also
close


 PrintStream.flush

PrintStream.flush

Syntax
public void flush()
Description
Flush the stream. This is done by writing any buffered output bytes to the underlying output stream and then flushing that stream.

Overrides
flush in class FilterOutputStream
See Also
flush


 PrintStream.print

PrintStream.print

Syntax 1
public void print( boolean b )
Parameters
b
The boolean to be printed
Description
Print a boolean value. If the given value is true, then the string "true" is written to the underlying output stream; otherwise, the string "false" is written.

Syntax 2
public void print( char c )
Parameters
c
The char to be printed
Description
Print a character. The character is translated into one or more bytes according to the platform's default character encoding.

Syntax 3
public void print( int i )
Parameters
i
The int to be printed
Description
Print an integer. The string printed is the same as that returned by the toString method of the Integer class when invoked on the given int value.

See Also
toString

Syntax 4
public void print( long l )
Parameters
l
The long to be printed
Description
Print a long integer. The string printed is the same as that returned by the toString method of the Long class when invoked on the given long value.

See Also
toString

Syntax 5
public void print( float f )
Parameters
f
The float to be printed
Description
Print a floating-point number. The string printed is the same as that returned by the toString method of the Float class when invoked on the given float value.

See Also
toString

Syntax 6
public void print( double d )
Parameters
d
The double to be printed
Description
Print a double-precision floating-point number. The string printed is the same as that returned by the toString method of the Double class when invoked on the given double value.

See Also
toString

Syntax 7
public void print( char s[] )
Parameters
s
The array of chars to be printed
Description
Print an array of characters. The characters are converted into bytes according to the platform's default character encoding.

Syntax 8
public void print( String s )
Parameters
s
The String to be printed
Description
Print a string. If the argument is null, the string "null" is written to the underlying output stream. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding.

Syntax 9
public void print( Object obj )
Parameters
obj
The Object to be printed
Description
Print an object. The string printed is the same as that returned by the given object's toString method.

See Also
toString


 PrintStream.println

PrintStream.println

Syntax 1
public void println()
Description
Finish the current line by writing a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

Syntax 2
public void println( boolean x )
Description
Print a boolean, and then finish the line.

See Also
print

Syntax 3
public void println( char x )
Description
Print a character, and then finish the line.

See Also
print

Syntax 4
public void println( int x )
Description
Print an integer, and then finish the line.

See Also
print

Syntax 5
public void println( long x )
Description
Print a long, and then finish the line.

See Also
print

Syntax 6
public void println( float x )
Description
Print a float, and then finish the line.

See Also
print

Syntax 7
public void println( double x )
Description
Print a double, and then finish the line.

See Also
print

Syntax 8
public void println( char x[] )
Description
Print an array of characters, and then finish the line.

See Also
print

Syntax 9
public void println( String x )
Description
Print a String, and then finish the line.

See Also
print

Syntax 10
public void println( Object x )
Description
Print an Object, and then finish the line.

See Also
print


 PrintStream.setError

PrintStream.setError

Syntax
protected void setError()
Description
Indicate that an error has occurred.


 PrintStream.write

PrintStream.write

Syntax 1
public void write( int b )
Parameters
b
The byte to be written
Description
Write a byte, blocking if necessary. If the character is a newline and automatic flushing is enabled, the stream's flush method will be called.

Note that the byte is written as given; to write a character that will be translated according to the platform's default character encoding, use the print(char) or println(char) methods.

Overrides
write in class FilterOutputStream
See Also
print, println

Syntax 2
public void write( byte buf[], int off, int len )
Parameters
buf
A byte array
off
Offset from which to start taking bytes
len
Number of bytes to write
Description
Write a portion of a byte array, blocking if necessary.

Overrides
write in class FilterOutputStream


 Class PrintWriter

Class java.io.PrintWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.PrintWriter

public class PrintWriter
extends Writer

Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println() methods is invoked, rather than whenever a newline character happens to be output. The println() methods use the platform's own notion of line separator rather than the newline character.

Methods in this class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError().


 PrintWriter Members

PrintWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PrintWriter(OutputStream) | Create a new PrintWriter, without automatic line flushing, from an existing OutputStream.
PrintWriter(OutputStream, boolean) | Create a new PrintWriter from an existing OutputStream.
PrintWriter(Writer) | Create a new PrintWriter, without automatic line flushing.
PrintWriter(Writer, boolean) | Create a new PrintWriter.

Methods
Name | Description
checkError() | Flush the stream and check its error state.
close() | Close the stream.
flush() | Flush the stream.
print(boolean) | Print a boolean.
print(char) | Print a character.
print(char[]) | Print an array of chracters.
print(double) | Print a double.
print(float) | Print a float.
print(int) | Print an integer.
print(long) | Print a long.
print(Object) | Print an object.
print(String) | Print a String.
println() | Finish the line.
println(boolean) | Print a boolean, and then finish the line.
println(char) | Print a character, and then finish the line.
println(char[]) | Print an array of characters, and then finish the line.
println(double) | Print a double, and then finish the line.
println(float) | Print a float, and then finish the line.
println(int) | Print an integer, and then finish the line.
println(long) | Print a long, and then finish the line.
println(Object) | Print an Object, and then finish the line.
println(String) | Print a String, and then finish the line.
setError() | Indicate that an error has occurred.
write(char[]) | Write an array of characters.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String) | Write a string.
write(String, int, int) | Write a portion of a string.


 PrintWriter.PrintWriter

PrintWriter.PrintWriter

Syntax 1
public PrintWriter( Writer out )
Parameters
out
A character-output stream
Description
Create a new PrintWriter, without automatic line flushing.

Syntax 2
public PrintWriter( Writer out, boolean autoFlush )
Parameters
out
A character-output stream
autoFlush
A boolean; if true, the println() methods will flush the output buffer
Description
Create a new PrintWriter.

Syntax 3
public PrintWriter( OutputStream out )
Parameters
out
An output stream
Description
Create a new PrintWriter, without automatic line flushing, from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

See Also
OutputStreamWriter

Syntax 4
public PrintWriter( OutputStream out, boolean autoFlush )
Parameters
out
An output stream
autoFlush
A boolean; if true, the println() methods will flush the output buffer
Description
Create a new PrintWriter from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

See Also
OutputStreamWriter


 PrintWriter.checkError

PrintWriter.checkError

Syntax
public boolean checkError()
Returns
True if the print stream has encountered an error, either on the underlying output stream or during a format conversion.
Description
Flush the stream and check its error state. Errors are cumulative; once the stream encounters an error, this routine will return true on all successive calls.


 PrintWriter.close

PrintWriter.close

Syntax
public void close()
Description
Close the stream.

Overrides
close in class Writer


 PrintWriter.flush

PrintWriter.flush

Syntax
public void flush()
Description
Flush the stream.

Overrides
flush in class Writer


 PrintWriter.print

PrintWriter.print

Syntax 1
public void print( boolean b )
Description
Print a boolean.

Syntax 2
public void print( char c )
Description
Print a character.

Syntax 3
public void print( int i )
Description
Print an integer.

Syntax 4
public void print( long l )
Description
Print a long.

Syntax 5
public void print( float f )
Description
Print a float.

Syntax 6
public void print( double d )
Description
Print a double.

Syntax 7
public void print( char s[] )
Description
Print an array of chracters.

Syntax 8
public void print( String s )
Description
Print a String.

Syntax 9
public void print( Object obj )
Description
Print an object.


 PrintWriter.println

PrintWriter.println

Syntax 1
public void println()
Description
Finish the line.

Syntax 2
public void println( boolean x )
Description
Print a boolean, and then finish the line.

Syntax 3
public void println( char x )
Description
Print a character, and then finish the line.

Syntax 4
public void println( int x )
Description
Print an integer, and then finish the line.

Syntax 5
public void println( long x )
Description
Print a long, and then finish the line.

Syntax 6
public void println( float x )
Description
Print a float, and then finish the line.

Syntax 7
public void println( double x )
Description
Print a double, and then finish the line.

Syntax 8
public void println( char x[] )
Description
Print an array of characters, and then finish the line.

Syntax 9
public void println( String x )
Description
Print a String, and then finish the line.

Syntax 10
public void println( Object x )
Description
Print an Object, and then finish the line.


 PrintWriter.setError

PrintWriter.setError

Syntax
protected void setError()
Description
Indicate that an error has occurred.


 PrintWriter.write

PrintWriter.write

Syntax 1
public void write( int c )
Description
Write a single character.

Overrides
write in class Writer

Syntax 2
public void write( char buf[], int off, int len )
Description
Write a portion of an array of characters.

Overrides
write in class Writer

Syntax 3
public void write( char buf[] )
Description
Write an array of characters. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.

Overrides
write in class Writer

Syntax 4
public void write( String s, int off, int len )
Description
Write a portion of a string.

Overrides
write in class Writer

Syntax 5
public void write( String s )
Description
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.

Overrides
write in class Writer


 Class PushbackInputStream

Class java.io.PushbackInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.io.PushbackInputStream

public class PushbackInputStream
extends FilterInputStream

This class is an input stream filter that provides a buffer into which data can be "unread." An application may unread data at any time by pushing it back into the buffer, as long as the buffer has sufficient room. Subsequent reads will read all of the pushed-back data in the buffer before reading from the underlying input stream.

This functionality is useful when a fragment of code should read an indefinite number of data bytes that are delimited by particular byte values. After reading the terminating byte the code fragment can push it back, so that the next read operation on the input stream will re-read that byte.


 PushbackInputStream Members

PushbackInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | The pushback buffer.
pos | The position within the pushback buffer from which the next byte will be read.

Constructors
Name | Description
PushbackInputStream(InputStream) | Creates a new pushback input stream with a one-byte pushback buffer.
PushbackInputStream(InputStream, int) | Creates a new pushback input stream with a pushback buffer of the specified size.

Methods
Name | Description
available() | Returns the number of bytes that can be read from this input stream without blocking.
markSupported() | Tests if this input stream supports the mark and reset methods, which it does not.
read() | Reads the next byte of data from this input stream.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
unread(byte[]) | Pushes back an array of bytes by copying it to the front of the pushback buffer.
unread(byte[], int, int) | Pushes back a portion of an array of bytes by copying it to the front of the pushback buffer.
unread(int) | Pushes back a byte by copying it to the front of the pushback buffer.


 PushbackInputStream.buf

PushbackInputStream.buf

Syntax
protected byte buf[]
Description
The pushback buffer.


 PushbackInputStream.pos

PushbackInputStream.pos

Syntax
protected int pos
Description
The position within the pushback buffer from which the next byte will be read. When the buffer is empty, pos is equal to buf.length; when the buffer is full, pos is equal to zero.


 PushbackInputStream.PushbackInputStream

PushbackInputStream.PushbackInputStream

Syntax 1
public PushbackInputStream( InputStream in, int size )
Parameters
in
the input stream from which bytes will be read.
size
the size of the pushback buffer.
Description
Creates a new pushback input stream with a pushback buffer of the specified size.

Syntax 2
public PushbackInputStream( InputStream in )
Parameters
in
the input stream from which bytes will be read.
Description
Creates a new pushback input stream with a one-byte pushback buffer.


 PushbackInputStream.available

PushbackInputStream.available

Syntax
public int available() throws IOException
Returns
the number of bytes that can be read from the input stream without blocking.
Description
Returns the number of bytes that can be read from this input stream without blocking. This method calls the available method of the underlying input stream; it returns that value plus the number of bytes that have been pushed back.

Exceptions
IOException if an I/O error occurs.
Overrides
available in class FilterInputStream
See Also
in


 PushbackInputStream.markSupported

PushbackInputStream.markSupported

Syntax
public boolean markSupported()
Returns
false, since this class does not support the mark and reset methods.
Description
Tests if this input stream supports the mark and reset methods, which it does not.

Overrides
markSupported in class FilterInputStream
See Also
mark, reset


 PushbackInputStream.read

PushbackInputStream.read

Syntax 1
public int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream has been reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

This method returns the most recently pushed-back byte, if there is one, and otherwise calls the read method of its underlying input stream and returns whatever value that method returns.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
read

Syntax 2
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method first reads any pushed-back bytes; after that, if fewer than than len bytes have been read then it reads from the underlying input stream. This method blocks until at least 1 byte of input is available.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream


 PushbackInputStream.unread

PushbackInputStream.unread

Syntax 1
public void unread( int b ) throws IOException
Parameters
b
the int value whose low-order byte is to be pushed back.
Description
Pushes back a byte by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value (byte)b.

Exceptions
IOException If there is not enough room in the pushback buffer for the byte.

Syntax 2
public void unread( byte b[], int off, int len ) throws IOException
Parameters
b
the byte array to push back.
off
the start offset of the data.
len
the number of bytes to push back.
Description
Pushes back a portion of an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[off], the byte after that will have the value b[off+1], and so forth.

Exceptions
IOException If there is not enough room in the pushback buffer for the specified number of bytes.

Syntax 3
public void unread( byte b[] ) throws IOException
Parameters
b
the byte array to push back
Description
Pushes back an array of bytes by copying it to the front of the pushback buffer. After this method returns, the next byte to be read will have the value b[0], the byte after that will have the value b[1], and so forth.

Exceptions
IOException If there is not enough room in the pushback buffer for the specified number of bytes.


 Class PushbackReader

Class java.io.PushbackReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.FilterReader
                   |
                   +----java.io.PushbackReader

public class PushbackReader
extends FilterReader

A character-stream reader that allows characters to be pushed back into the stream.


 PushbackReader Members

PushbackReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PushbackReader(Reader) | Create a new pushback reader with a one-character pushback buffer.
PushbackReader(Reader, int) | Create a new pushback reader with a pushback buffer of the given size.

Methods
Name | Description
close() | Close the stream.
markSupported() | Tell whether this stream supports the mark() operation, which it does not.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.
unread(char[]) | Push back an array of characters by copying it to the front of the pushback buffer.
unread(char[], int, int) | Push back a portion of an array of characters by copying it to the front of the pushback buffer.
unread(int) | Push back a single character.


 PushbackReader.PushbackReader

PushbackReader.PushbackReader

Syntax 1
public PushbackReader( Reader in, int size )
Parameters
in
The reader from which characters will be read
size
The size of the pushback buffer
Description
Create a new pushback reader with a pushback buffer of the given size.

Syntax 2
public PushbackReader( Reader in )
Parameters
in
The reader from which characters will be read
Description
Create a new pushback reader with a one-character pushback buffer.


 PushbackReader.close

PushbackReader.close

Syntax
public void close() throws IOException
Description
Close the stream.

Exceptions
IOException If an I/O error occurs
Overrides
close in class FilterReader


 PushbackReader.markSupported

PushbackReader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation, which it does not.

Overrides
markSupported in class FilterReader


 PushbackReader.read

PushbackReader.read

Syntax 1
public int read() throws IOException
Returns
The character read, or -1 if the end of the stream has been reached
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class FilterReader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start writing characters
len
Maximum number of characters to read
Returns
The number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class FilterReader


 PushbackReader.ready

PushbackReader.ready

Syntax
public boolean ready() throws IOException
Description
Tell whether this stream is ready to be read.

Exceptions
IOException If an I/O error occurs
Overrides
ready in class FilterReader


 PushbackReader.unread

PushbackReader.unread

Syntax 1
public void unread( int c ) throws IOException
Parameters
c
The character to push back
Description
Push back a single character.

Exceptions
IOException If the pushback buffer is full, or if some other I/O error occurs

Syntax 2
public void unread( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Character array
off
Offset of first character to push back
len
Number of characters to push back
Description
Push back a portion of an array of characters by copying it to the front of the pushback buffer. After this method returns, the next character to be read will have the value cbuf[off], the character after that will have the value cbuf[off+1], and so forth.

Exceptions
IOException If there is insufficient room in the pushback buffer, or if some other I/O error occurs

Syntax 3
public void unread( char cbuf[] ) throws IOException
Parameters
cbuf
Character array to push back
Description
Push back an array of characters by copying it to the front of the pushback buffer. After this method returns, the next character to be read will have the value cbuf[0], the character after that will have the value cbuf[1], and so forth.

Exceptions
IOException If there is insufficient room in the pushback buffer, or if some other I/O error occurs


 Class RandomAccessFile

Class java.io.RandomAccessFile

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.RandomAccessFile

public class RandomAccessFile
extends Object
implements DataOutput, DataInput

Instances of this class support both reading and writing to a random access file. An application can modify the position in the file at which the next read or write occurs. This class provides a sense of security by offering methods that allow specified mode accesses of read-only or read-write to files.


 RandomAccessFile Members

RandomAccessFile Members

Class Overview | This Package | All Packages

Constructors
Name | Description
RandomAccessFile(File, String) | Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
RandomAccessFile(String, String) | Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

Methods
Name | Description
close() | Closes this random access file stream and releases any system resources associated with the stream.
getFD() | Returns the opaque file descriptor object associated with this stream.
getFilePointer() | Returns the current offset in this file.
length() | Returns the length of this file.
read() | Reads a byte of data from this file.
read(byte[]) | Reads up to b.length bytes of data from this file into an array of bytes.
read(byte[], int, int) | Reads up to len bytes of data from this file into an array of bytes.
readBoolean() | Reads a boolean from this file.
readByte() | Reads a signed 8-bit value from this file.
readChar() | Reads a Unicode character from this file.
readDouble() | Reads a double from this file.
readFloat() | Reads a float from this file.
readFully(byte[]) | Reads b.length bytes from this file into the byte array.
readFully(byte[], int, int) | Reads exactly len bytes from this file into the byte array.
readInt() | Reads a signed 32-bit integer from this file.
readLine() | Reads the next line of text from this file.
readLong() | Reads a signed 64-bit integer from this file.
readShort() | Reads a signed 16-bit number from this file.
readUnsignedByte() | Reads an unsigned 8-bit number from this file.
readUnsignedShort() | Reads an unsigned 16-bit number from this file.
readUTF() | Reads in a string from this file.
seek(long) | Sets the offset from the beginning of this file at which the next read or write occurs.
skipBytes(int) | Skips exactly n bytes of input.
write(byte[]) | Writes b.length bytes from the specified byte array starting at offset off to this file.
write(byte[], int, int) | Writes len bytes from the specified byte array starting at offset off to this file.
write(int) | Writes the specified byte to this file.
writeBoolean(boolean) | Writes a boolean to the file as a 1-byte value.
writeByte(int) | Writes a byte to the file as a 1-byte value.
writeBytes(String) | Writes the string to the file as a sequence of bytes.
writeChar(int) | Writes a char to the file as a 2-byte value, high byte first.
writeChars(String) | Writes a string to the file as a sequence of characters.
writeDouble(double) | Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an 8-byte quantity, high byte first.
writeFloat(float) | Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a 4-byte quantity, high byte first.
writeInt(int) | Writes an int to the file as four bytes, high byte first.
writeLong(long) | Writes a long to the file as eight bytes, high byte first.
writeShort(int) | Writes a short to the file as two bytes, high byte first.
writeUTF(String) | Writes a string to the file using UTF-8 encoding in a machine-independent manner.


 RandomAccessFile.RandomAccessFile

RandomAccessFile.RandomAccessFile

Syntax 1
public RandomAccessFile( String name, String mode ) throws IOException
Parameters
name
the system-dependent filename.
mode
the access mode.
Description
Creates a random access file stream to read from, and optionally to write to, a file with the specified name.

The mode argument must either be equal to "r" or "rw", indicating either to open the file for input or for both input and output.

Exceptions
IllegalArgumentException if the mode argument is not equal to "r" or to "rw".
Exceptions
IOException if an I/O error occurs.
Exceptions
SecurityException if a security manager exists, its checkRead method is called with the name argument to see if the application is allowed read access to the file. If the mode argument is equal to "rw", its checkWrite method also is called with the name argument to see if the application is allowed write access to the file. Either of these may result in a security exception.
See Also
SecurityException, checkRead

Syntax 2
public RandomAccessFile( File file, String mode ) throws IOException
Parameters
file
the file object.
mode
the access mode.
Description
Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.

The mode argument must either be equal to "r" or to "rw", indicating either to open the file for input, or for both input and output, respectively.

Exceptions
IllegalArgumentException if the mode argument is not equal to "r" or to "rw".
Exceptions
IOException if an I/O error occurs.
Exceptions
SecurityException if a security manager exists, its checkRead method is called with the pathname of the File argument to see if the application is allowed read access to the file. If the mode argument is equal to "rw", its checkWrite method also is called with the pathname to see if the application is allowed write access to the file.
See Also
getPath, checkRead


 RandomAccessFile.close

RandomAccessFile.close

Syntax
public native void close() throws IOException
Description
Closes this random access file stream and releases any system resources associated with the stream.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.getFD

RandomAccessFile.getFD

Syntax
public final FileDescriptor getFD() throws IOException
Returns
the file descriptor object associated with this stream.
Description
Returns the opaque file descriptor object associated with this stream.

Exceptions
IOException if an I/O error occurs.
See Also
FileDescriptor


 RandomAccessFile.getFilePointer

RandomAccessFile.getFilePointer

Syntax
public native long getFilePointer() throws IOException
Returns
the offset from the beginning of the file, in bytes, at which the next read or write occurs.
Description
Returns the current offset in this file.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.length

RandomAccessFile.length

Syntax
public native long length() throws IOException
Returns
the length of this file.
Description
Returns the length of this file.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.read

RandomAccessFile.read

Syntax 1
public native int read() throws IOException
Returns
the next byte of data, or -1 if the end of the file is reached.
Description
Reads a byte of data from this file. This method blocks if no input is yet available.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
Description
Reads up to len bytes of data from this file into an array of bytes. This method blocks until at least one byte of input is available.

Exceptions
IOException if an I/O error occurs.

Syntax 3
public int read( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of this file has been reached.
Description
Reads up to b.length bytes of data from this file into an array of bytes. This method blocks until at least one byte of input is available.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readBoolean

RandomAccessFile.readBoolean

Syntax
public final boolean readBoolean() throws IOException
Returns
the boolean value read.
Description
Reads a boolean from this file. This method reads a single byte from the file. A value of 0 represents false. Any other value represents true. This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file has reached the end.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readByte

RandomAccessFile.readByte

Syntax
public final byte readByte() throws IOException
Returns
the next byte of this file as a signed 8-bit byte.
Description
Reads a signed 8-bit value from this file. This method reads a byte from the file. If the byte read is b, where 0 <= b <= 255, then the result is:
    (byte)(b)

This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file has reached the end.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readChar

RandomAccessFile.readChar

Syntax
public final char readChar() throws IOException
Returns
the next two bytes of this file as a Unicode character.
Description
Reads a Unicode character from this file. This method reads two bytes from the file. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:
    (char)((b1 << 8) | b2)

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readDouble

RandomAccessFile.readDouble

Syntax
public final double readDouble() throws IOException
Returns
the next eight bytes of this file, interpreted as a double.
Description
Reads a double from this file. This method reads a long value as if by the readLong method and then converts that long to a double using the longBitsToDouble method in class Double.

This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading eight bytes.
Exceptions
IOException if an I/O error occurs.
See Also
readLong, longBitsToDouble


 RandomAccessFile.readFloat

RandomAccessFile.readFloat

Syntax
public final float readFloat() throws IOException
Returns
the next four bytes of this file, interpreted as a float.
Description
Reads a float from this file. This method reads an int value as if by the readInt method and then converts that int to a float using the intBitsToFloat method in class Float.

This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading four bytes.
Exceptions
IOException if an I/O error occurs.
See Also
readInt, intBitsToFloat


 RandomAccessFile.readFully

RandomAccessFile.readFully

Syntax 1
public final void readFully( byte b[] ) throws IOException
Parameters
b
the buffer into which the data is read.
Description
Reads b.length bytes from this file into the byte array. This method reads repeatedly from the file until all the bytes are read. This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.

Syntax 2
public final void readFully( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the number of bytes to read.
Description
Reads exactly len bytes from this file into the byte array. This method reads repeatedly from the file until all the bytes are read. This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readInt

RandomAccessFile.readInt

Syntax
public final int readInt() throws IOException
Returns
the next four bytes of this file, interpreted as an int.
Description
Reads a signed 32-bit integer from this file. This method reads 4 bytes from the file. If the bytes read, in order, are b1, b2, b3, and b4, where 0 <= b1, b2, b3, b4 <= 255, then the result is equal to:
    (b1 << 24) | (b2 << 16) + (b3 << 8) + b4

This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading four bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readLine

RandomAccessFile.readLine

Syntax
public final String readLine() throws IOException
Returns
the next line of text from this file.
Description
Reads the next line of text from this file. This method successively reads bytes from the file until it reaches the end of a line of text.

A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the input stream. The line-terminating character(s), if any, are included as part of the string returned.

This method blocks until a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the stream is detected, or an exception is thrown.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readLong

RandomAccessFile.readLong

Syntax
public final long readLong() throws IOException
Returns
the next eight bytes of this file, interpreted as a long.
Description
Reads a signed 64-bit integer from this file. This method reads eight bytes from the file. If the bytes read, in order, are b1, b2, b3, b4, b5, b6, b7, and b8, where:
    0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255,

then the result is equal to:

     ((long)b1 << 56) + ((long)b2 << 48)
     + ((long)b3 << 40) + ((long)b4 << 32)
     + ((long)b5 << 24) + ((long)b6 << 16)
     + ((long)b7 << 8) + b8

This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading eight bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readShort

RandomAccessFile.readShort

Syntax
public final short readShort() throws IOException
Returns
the next two bytes of this file, interpreted as a signed 16-bit number.
Description
Reads a signed 16-bit number from this file. The method reads 2 bytes from this file. If the two bytes read, in order, are b1 and b2, where each of the two values is between 0 and 255, inclusive, then the result is equal to:
    (short)((b1 << 8) | b2)

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readUnsignedByte

RandomAccessFile.readUnsignedByte

Syntax
public final int readUnsignedByte() throws IOException
Returns
the next byte of this file, interpreted as an unsigned 8-bit number.
Description
Reads an unsigned 8-bit number from this file. This method reads a byte from this file and returns that byte.

This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file has reached the end.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readUnsignedShort

RandomAccessFile.readUnsignedShort

Syntax
public final int readUnsignedShort() throws IOException
Returns
the next two bytes of this file, interpreted as an unsigned 16-bit integer.
Description
Reads an unsigned 16-bit number from this file. This method reads two bytes from the file. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:
    (b1 << 8) | b2

This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading two bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.readUTF

RandomAccessFile.readUTF

Syntax
public final String readUTF() throws IOException
Returns
a Unicode string.
Description
Reads in a string from this file. The string has been encoded using a modified UTF-8 format.

The first two bytes are read as if by readUnsignedShort. This value gives the number of following bytes that are in the encoded string, not the length of the resulting string. The following bytes are then interpreted as bytes encoding characters in the UTF-8 format and are converted into characters.

This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before reading all the bytes.
Exceptions
IOException if an I/O error occurs.
Exceptions
UTFDataFormatException if the bytes do not represent valid UTF-8 encoding of a Unicode string.
See Also
readUnsignedShort


 RandomAccessFile.seek

RandomAccessFile.seek

Syntax
public native void seek( long pos ) throws IOException
Parameters
pos
the absolute position.
Description
Sets the offset from the beginning of this file at which the next read or write occurs.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.skipBytes

RandomAccessFile.skipBytes

Syntax
public int skipBytes( int n ) throws IOException
Parameters
n
the number of bytes to be skipped.
Returns
the number of bytes skipped, which is always n.
Description
Skips exactly n bytes of input.

This method blocks until all the bytes are skipped, the end of the stream is detected, or an exception is thrown.

Exceptions
EOFException if this file reaches the end before skipping all the bytes.
Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.write

RandomAccessFile.write

Syntax 1
public native void write( int b ) throws IOException
Parameters
b
the byte to be written.
Description
Writes the specified byte to this file.

Exceptions
IOException if an I/O error occurs.

Syntax 2
public void write( byte b[] ) throws IOException
Parameters
b
the data.
Description
Writes b.length bytes from the specified byte array starting at offset off to this file.

Exceptions
IOException if an I/O error occurs.

Syntax 3
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data.
off
the start offset in the data.
len
the number of bytes to write.
Description
Writes len bytes from the specified byte array starting at offset off to this file.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeBoolean

RandomAccessFile.writeBoolean

Syntax
public final void writeBoolean( boolean v ) throws IOException
Parameters
v
a boolean value to be written.
Description
Writes a boolean to the file as a 1-byte value. The value true is written out as the value (byte)1; the value false is written out as the value (byte)0.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeByte

RandomAccessFile.writeByte

Syntax
public final void writeByte( int v ) throws IOException
Parameters
v
a byte value to be written.
Description
Writes a byte to the file as a 1-byte value.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeBytes

RandomAccessFile.writeBytes

Syntax
public final void writeBytes( String s ) throws IOException
Parameters
s
a string of bytes to be written.
Description
Writes the string to the file as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeChar

RandomAccessFile.writeChar

Syntax
public final void writeChar( int v ) throws IOException
Parameters
v
a char value to be written.
Description
Writes a char to the file as a 2-byte value, high byte first.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeChars

RandomAccessFile.writeChars

Syntax
public final void writeChars( String s ) throws IOException
Parameters
s
a String value to be written.
Description
Writes a string to the file as a sequence of characters. Each character is written to the data output stream as if by the writeChar method.

Exceptions
IOException if an I/O error occurs.
See Also
writeChar


 RandomAccessFile.writeDouble

RandomAccessFile.writeDouble

Syntax
public final void writeDouble( double v ) throws IOException
Parameters
v
a double value to be written.
Description
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an 8-byte quantity, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
doubleToLongBits


 RandomAccessFile.writeFloat

RandomAccessFile.writeFloat

Syntax
public final void writeFloat( float v ) throws IOException
Parameters
v
a float value to be written.
Description
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a 4-byte quantity, high byte first.

Exceptions
IOException if an I/O error occurs.
See Also
floatToIntBits


 RandomAccessFile.writeInt

RandomAccessFile.writeInt

Syntax
public final void writeInt( int v ) throws IOException
Parameters
v
an int to be written.
Description
Writes an int to the file as four bytes, high byte first.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeLong

RandomAccessFile.writeLong

Syntax
public final void writeLong( long v ) throws IOException
Parameters
v
a long to be written.
Description
Writes a long to the file as eight bytes, high byte first.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeShort

RandomAccessFile.writeShort

Syntax
public final void writeShort( int v ) throws IOException
Parameters
v
a short to be written.
Description
Writes a short to the file as two bytes, high byte first.

Exceptions
IOException if an I/O error occurs.


 RandomAccessFile.writeUTF

RandomAccessFile.writeUTF

Syntax
public final void writeUTF( String str ) throws IOException
Parameters
str
a string to be written.
Description
Writes a string to the file using UTF-8 encoding in a machine-independent manner.

First, two bytes are written to the file as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the UTF-8 encoding for each character.

Exceptions
IOException if an I/O error occurs.


 Class Reader

Class java.io.Reader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader

public abstract class Reader
extends Object

Abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

See Also:
BufferedReader, LineNumberReader, CharArrayReader, InputStreamReader, FileReader, FilterReader, PushbackReader, PipedReader, StringReader, Writer


 Reader Members

Reader Members

Class Overview | This Package | All Packages

Fields
Name | Description
lock | The object used to synchronize operations on this stream.

Constructors
Name | Description
Reader() | Create a new character-stream reader whose critical sections will synchronize on the reader itself.
Reader(Object) | Create a new character-stream reader whose critical sections will synchronize on the given object.

Methods
Name | Description
close() | Close the stream.
mark(int) | Mark the present position in the stream.
markSupported() | Tell whether this stream supports the mark() operation.
read() | Read a single character.
read(char[]) | Read characters into an array.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.
reset() | Reset the stream.
skip(long) | Skip characters.


 Reader.lock

Reader.lock

Syntax
protected Object lock
Description
The object used to synchronize operations on this stream. For efficiency, a character-stream object may use an object other than itself to protect critical sections. A subclass should therefore use the object in this field rather than this or a synchronized method.


 Reader.Reader

Reader.Reader

Syntax 1
protected Reader()
Description
Create a new character-stream reader whose critical sections will synchronize on the reader itself.

Syntax 2
protected Reader( Object lock )
Description
Create a new character-stream reader whose critical sections will synchronize on the given object.


 Reader.close

Reader.close

Syntax
public abstract void close() throws IOException
Description
Close the stream. Once a stream has been closed, further read(), ready(), mark(), or reset() invocations will throw an IOException. Closing a previously-closed stream, however, has no effect.

Exceptions
IOException If an I/O error occurs


 Reader.mark

Reader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Parameters
readAheadLimit
Limit on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail.
Description
Mark the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point. Not all character-input streams support the mark() operation.

Exceptions
IOException If the stream does not support mark(), or if some other I/O error occurs


 Reader.markSupported

Reader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation.


 Reader.read

Reader.read

Syntax 1
public int read() throws IOException
Returns
The character read, as an integer in the range 0 to 16383 (0x00-0xffff), or -1 if the end of the stream has been reached
Description
Read a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.

Subclasses that intend to support efficient single-character input should override this method.

Exceptions
IOException If an I/O error occurs

Syntax 2
public int read( char cbuf[] ) throws IOException
Parameters
cbuf
Destination buffer
Returns
The number of bytes read, or -1 if the end of the stream has been reached
Description
Read characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Exceptions
IOException If an I/O error occurs

Syntax 3
public abstract int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start storing characters
len
Maximum number of characters to read
Returns
The number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Exceptions
IOException If an I/O error occurs


 Reader.ready

Reader.ready

Syntax
public boolean ready() throws IOException
Returns
True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.
Description
Tell whether this stream is ready to be read.

Exceptions
IOException If an I/O error occurs


 Reader.reset

Reader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point. Not all character-input streams support the reset() operation, and some support reset() without supporting mark().

Exceptions
IOException If the stream has not been marked, or if the mark has been invalidated, or if the stream does not support reset(), or if some other I/O error occurs


 Reader.skip

Reader.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
The number of characters to skip
Returns
The number of characters actually skipped
Description
Skip characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.

Exceptions
IOException If an I/O error occurs


 Class SequenceInputStream

Class java.io.SequenceInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.SequenceInputStream

public class SequenceInputStream
extends InputStream

The sequence input stream class allows an application to combine several input streams serially and make them appear as if they were a single input stream. Each input stream is read from, in turn, until it reaches the end of the stream. The sequence input stream class then closes that stream and automatically switches to the next input stream.


 SequenceInputStream Members

SequenceInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SequenceInputStream(Enumeration) | Constructs a new sequence input stream initialized to the specified enumeration of input streams.
SequenceInputStream(InputStream, InputStream) | Constructs a new sequence input stream initialized to read first from the input stream s1, and then from the input stream s2.

Methods
Name | Description
available() | Returns the number of bytes available on the current stream.
close() | Closes this input stream and releases any system resources associated with the stream.
read() | Reads the next byte of data from this input stream.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.


 SequenceInputStream.SequenceInputStream

SequenceInputStream.SequenceInputStream

Syntax 1
public SequenceInputStream( Enumeration e )
Parameters
e
an enumeration of input streams.
Description
Constructs a new sequence input stream initialized to the specified enumeration of input streams. Each object in the enumeration must be an InputStream.

See Also
Enumeration

Syntax 2
public SequenceInputStream( InputStream s1, InputStream s2 )
Parameters
s1
the first input stream to read.
s2
the second input stream to read.
Description
Constructs a new sequence input stream initialized to read first from the input stream s1, and then from the input stream s2.


 SequenceInputStream.available

SequenceInputStream.available

Syntax
public int available() throws IOException
Description
Returns the number of bytes available on the current stream.

Overrides
available in class InputStream


 SequenceInputStream.close

SequenceInputStream.close

Syntax
public void close() throws IOException
Description
Closes this input stream and releases any system resources associated with the stream.

The close method of SequenceInputStream calls the close method of both the substream from which it is currently reading and the close method of all the substreams that it has not yet begun to read from.

Exceptions
IOException if an I/O error occurs.
Overrides
close in class InputStream


 SequenceInputStream.read

SequenceInputStream.read

Syntax 1
public int read() throws IOException
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this input stream. The byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

The read method of SequenceInputStream tries to read one character from the current substream. If it reaches the end of the stream, it calls the close method of the current substream and begins reading from the next substream.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream

Syntax 2
public int read( byte buf[], int pos, int len ) throws IOException
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Description
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until at least 1 byte of input is available. If the first argument is null, up to len bytes are read and discarded.

The read method of SequenceInputStream tries to read the data from the current substream. If it fails to read any characters because the substream has reached the end of the stream, it calls the close method of the current substream and begins reading from the next substream.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class InputStream


 Interface Serializable

Interface java.io.Serializable

This Package | All Packages

public interface Serializable

Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable in this case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object's fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

See Also:
ObjectOutputStream, ObjectInputStream, ObjectOutput, ObjectInput, Externalizable


 Class StreamCorruptedException

Class java.io.StreamCorruptedException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.StreamCorruptedException

public class StreamCorruptedException
extends ObjectStreamException

Raised when control information read from an object stream violates internal consistency checks.


 StreamCorruptedException Members

StreamCorruptedException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StreamCorruptedException() | Create a StreamCorruptedException with no reason.
StreamCorruptedException(String) | Create a StreamCorruptedException with a reason.


 StreamCorruptedException.StreamCorruptedException

StreamCorruptedException.StreamCorruptedException

Syntax 1
public StreamCorruptedException( String reason )
Description
Create a StreamCorruptedException with a reason.

Syntax 2
public StreamCorruptedException()
Description
Create a StreamCorruptedException with no reason.


 Class StreamTokenizer

Class java.io.StreamTokenizer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.StreamTokenizer

public class StreamTokenizer
extends Object

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these attributes.

In addition, an instance has four flags. These flags indicate:

  • Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens.
  • Whether C-style comments are to be recognized and skipped.
  • Whether C++-style comments are to be recognized and skipped.
  • Whether the characters of identifiers are converted to lowercase.

A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF.

See Also:
nextToken, TT_EOF


 StreamTokenizer Members

StreamTokenizer Members

Class Overview | This Package | All Packages

Fields
Name | Description
nval | If the current token is a number, this field contains the value of that number.
sval | If the current token is a word token, this field contains a string giving the characters of the word token.
TT_EOF | A constant indicating that the end of the stream has been read.
TT_EOL | A constant indicating that the end of the line has been read.
TT_NUMBER | A constant indicating that a number token has been read.
TT_WORD | A constant indicating that a word token has been read.
ttype | After a call to the nextToken method, this field contains the type of the token just read.

Constructors
Name | Description
StreamTokenizer(InputStream) | Creates a stream tokenizer that parses the specified input stream. Deprecated.
StreamTokenizer(Reader) | Create a tokenizer that parses the given character stream.

Methods
Name | Description
commentChar(int) | Specified that the character argument starts a single-line comment.
eolIsSignificant(boolean) | Determines whether or not ends of line are treated as tokens.
lineno() | Return the current line number.
lowerCaseMode(boolean) | Determines whether or not word token are automatically lowercased.
nextToken() | Parses the next token from the input stream of this tokenizer.
ordinaryChar(int) | Specifies that the character argument is "ordinary" in this tokenizer.
ordinaryChars(int, int) | Specifies that all characters c in the range low <= c <= high are "ordinary" in this tokenizer.
parseNumbers() | Specifies that numbers should be parsed by this tokenizer.
pushBack() | Causes the next call to the nextToken method of this tokenizer to return the current value in the ttype field, and not to modify the value in the nval or sval field.
quoteChar(int) | Specifies that matching pairs of this character delimit string constants in this tokenizer.
resetSyntax() | Resets this tokenizer's syntax table so that all characters are "ordinary." See the ordinaryChar method for more information on a character being ordinary.
slashSlashComments(boolean) | Determines whether or not the tokenizer recognizes C++-style comments.
slashStarComments(boolean) | Determines whether or not the tokenizer recognizes C-style comments.
toString() | Returns the string representation of the current stream token.
whitespaceChars(int, int) | Specifies that all characters c in the range low <= c <= high are white space characters.
wordChars(int, int) | Specifies that all characters c in the range low <= c <= high are word constituents.


 StreamTokenizer.nval

StreamTokenizer.nval

Syntax
public double nval
Description
If the current token is a number, this field contains the value of that number. The current token is a number when the value of the ttype field is TT_NUMBER.

See Also
TT_NUMBER, ttype


 StreamTokenizer.sval

StreamTokenizer.sval

Syntax
public String sval
Description
If the current token is a word token, this field contains a string giving the characters of the word token. When the current token is a quoted string token, this field contains the body of the string.

The current token is a word when the value of the ttype field is TT_WORD. The current token is a quoted string token when the value of the ttype field is a quote character.

See Also
quoteChar, TT_WORD, ttype


 StreamTokenizer.TT_EOF

StreamTokenizer.TT_EOF

Syntax
public static final int TT_EOF
Description
A constant indicating that the end of the stream has been read.


 StreamTokenizer.TT_EOL

StreamTokenizer.TT_EOL

Syntax
public static final int TT_EOL
Description
A constant indicating that the end of the line has been read.


 StreamTokenizer.TT_NUMBER

StreamTokenizer.TT_NUMBER

Syntax
public static final int TT_NUMBER
Description
A constant indicating that a number token has been read.


 StreamTokenizer.TT_WORD

StreamTokenizer.TT_WORD

Syntax
public static final int TT_WORD
Description
A constant indicating that a word token has been read.


 StreamTokenizer.ttype

StreamTokenizer.ttype

Syntax
public int ttype
Description
After a call to the nextToken method, this field contains the type of the token just read. For a single character token, its value is the single character, converted to an integer. For a quoted string token (see , its value is the quote character. Otherwise, its value is one of the following:
  • TT_WORD indicates that the token is a word.
  • TT_NUMBER indicates that the token is a number.
  • TT_EOL indicates that the end of line has been read. The field can only have this value if the eolIsSignificant method has been called with the argument true.
  • TT_EOF indicates that the end of the input stream has been reached.

See Also
eolIsSignificant, nextToken, quoteChar, TT_EOF, TT_EOL, TT_NUMBER, TT_WORD


 StreamTokenizer.StreamTokenizer

StreamTokenizer.StreamTokenizer

Syntax 1
public StreamTokenizer( InputStream is )
Parameters
is
an input stream.
Description
Note: StreamTokenizer() is deprecated. As of JDK version 1.1, the preferred way to tokenize an input stream is to convert it into a character stream, for example:

   Reader r = new BufferedReader(new InputStreamReader(is));
   StreamTokenizer st = new StreamTokenizer(r);

Creates a stream tokenizer that parses the specified input stream. The stream tokenizer is initialized to the following default state:

  • All byte values 'A' through 'Z', 'a' through 'z', and '\u00A0' through '\u00FF' are considered to be alphabetic.
  • All byte values '\u0000' through '\u0020' are considered to be white space.
  • '/' is a comment character.
  • Single quote '\'' and double quote '"' are string quote characters.
  • Numbers are parsed.
  • Ends of lines are treated as white space, not as separate tokens.
  • C-style and C++-style comments are not recognized.

See Also
BufferedReader, InputStreamReader, StreamTokenizer

Syntax 2
public StreamTokenizer( Reader r )
Description
Create a tokenizer that parses the given character stream.


 StreamTokenizer.commentChar

StreamTokenizer.commentChar

Syntax
public void commentChar( int ch )
Parameters
ch
the character.
Description
Specified that the character argument starts a single-line comment. All characters from the comment character to the end of the line are ignored by this stream tokenizer.


 StreamTokenizer.eolIsSignificant

StreamTokenizer.eolIsSignificant

Syntax
public void eolIsSignificant( boolean flag )
Parameters
flag
true indicates that end-of-line characters are separate tokens; false indicates that end-of-line characters are white space.
Description
Determines whether or not ends of line are treated as tokens. If the flag argument is true, this tokenizer treats end of lines as tokens; the nextToken method returns TT_EOL and also sets the ttype field to this value when an end of line is read.

A line is a sequence of characters ending with either a carriage-return character ('\r') or a newline character ('\n'). In addition, a carriage-return character followed immediately by a newline character is treated as a single end-of-line token.

If the flag is false, end-of-line characters are treated as white space and serve only to separate tokens.

See Also
nextToken, ttype, TT_EOL


 StreamTokenizer.lineno

StreamTokenizer.lineno

Syntax
public int lineno()
Returns
the current line number of this stream tokenizer.
Description
Return the current line number.


 StreamTokenizer.lowerCaseMode

StreamTokenizer.lowerCaseMode

Syntax
public void lowerCaseMode( boolean fl )
Parameters
fl
true indicates that all word tokens should be lowercased.
Description
Determines whether or not word token are automatically lowercased. If the flag argument is true, then the value in the sval field is lowercased whenever a word token is returned (the ttype field has the value TT_WORD by the nextToken method of this tokenizer.

If the flag argument is false, then the sval field is not modified.

See Also
nextToken, ttype, TT_WORD


 StreamTokenizer.nextToken

StreamTokenizer.nextToken

Syntax
public int nextToken() throws IOException
Returns
the value of the ttype field.
Description
Parses the next token from the input stream of this tokenizer. The type of the next token is returned in the ttype field. Additional information about the token may be in the nval field or the sval field of this tokenizer.

Typical clients of this class first set up the syntax tables and then sit in a loop calling nextToken to parse successive tokens until TT_EOF is returned.

Exceptions
IOException if an I/O error occurs.
See Also
nval, sval, ttype


 StreamTokenizer.ordinaryChar

StreamTokenizer.ordinaryChar

Syntax
public void ordinaryChar( int ch )
Parameters
ch
the character.
Description
Specifies that the character argument is "ordinary" in this tokenizer. It removes any special significance the character has as a comment character, word component, string delimiter, white space, or number character. When such a character is encountered by the parser, the parser treates it as a single-character token and sets ttype field to the character value.

See Also
ttype


 StreamTokenizer.ordinaryChars

StreamTokenizer.ordinaryChars

Syntax
public void ordinaryChars( int low, int hi )
Parameters
low
the low end of the range.
hi
the high end of the range.
Description
Specifies that all characters c in the range low <= c <= high are "ordinary" in this tokenizer. See the ordinaryChar method for more information on a character being ordinary.

See Also
ordinaryChar


 StreamTokenizer.parseNumbers

StreamTokenizer.parseNumbers

Syntax
public void parseNumbers()
Description
Specifies that numbers should be parsed by this tokenizer. The syntax table of this tokenizer is modified so that each of the twelve characters:
    0 1 2 3 4 5 6 7 8 9 . -

has the "numeric" attribute.

When the parser encounters a word token that has the format of a double precision floating-point number, it treats the token as a number rather than a word, by setting the the ttype field to the value TT_NUMBER and putting the numeric value of the token into the nval field.

See Also
nval, TT_NUMBER, ttype


 StreamTokenizer.pushBack

StreamTokenizer.pushBack

Syntax
public void pushBack()
Description
Causes the next call to the nextToken method of this tokenizer to return the current value in the ttype field, and not to modify the value in the nval or sval field.

See Also
nextToken, nval, sval, ttype


 StreamTokenizer.quoteChar

StreamTokenizer.quoteChar

Syntax
public void quoteChar( int ch )
Parameters
ch
the character.
Description
Specifies that matching pairs of this character delimit string constants in this tokenizer.

When the nextToken method encounters a string constant, the ttype field is set to the string delimiter and the sval field is set to the body of the string.

If a string quote character is encountered, then a string is recognized, consisting of all characters after (but not including) the string quote character, up to (but not including) the next occurrence of that same string quote character, or a line terminator, or end of file. The usual escape sequences such as "\n" and "\t" are recognized and converted to single characters as the string is parsed.

See Also
nextToken, sval, ttype


 StreamTokenizer.resetSyntax

StreamTokenizer.resetSyntax

Syntax
public void resetSyntax()
Description
Resets this tokenizer's syntax table so that all characters are "ordinary." See the ordinaryChar method for more information on a character being ordinary.

See Also
ordinaryChar


 StreamTokenizer.slashSlashComments

StreamTokenizer.slashSlashComments

Syntax
public void slashSlashComments( boolean flag )
Parameters
flag
true indicates to recognize and ignore C++-style comments.
Description
Determines whether or not the tokenizer recognizes C++-style comments. If the flag argument is true, this stream tokenizer recognizes C++-style comments. Any occurrence of two consecutive slash characters ('/') is treated as the beginning of a comment that extends to the end of the line.

If the flag argument is false, then C++-style comments are not treated specially.


 StreamTokenizer.slashStarComments

StreamTokenizer.slashStarComments

Syntax
public void slashStarComments( boolean flag )
Parameters
flag
true indicates to recognize and ignore C-style comments.
Description
Determines whether or not the tokenizer recognizes C-style comments. If the flag argument is true, this stream tokenizer recognizes C-style comments. All text between successive occurrences of /* and */ are discarded.

If the flag argument is false, then C-style comments are not treated specially.


 StreamTokenizer.toString

StreamTokenizer.toString

Syntax
public String toString()
Returns
a string representation of the token specified by the ttype, nval, and sval fields.
Description
Returns the string representation of the current stream token.

Overrides
toString in class Object
See Also
nval, sval, ttype


 StreamTokenizer.whitespaceChars

StreamTokenizer.whitespaceChars

Syntax
public void whitespaceChars( int low, int hi )
Parameters
low
the low end of the range.
hi
the high end of the range.
Description
Specifies that all characters c in the range low <= c <= high are white space characters. White space characters serve only to separate tokens in the input stream.


 StreamTokenizer.wordChars

StreamTokenizer.wordChars

Syntax
public void wordChars( int low, int hi )
Parameters
low
the low end of the range.
hi
the high end of the range.
Description
Specifies that all characters c in the range low <= c <= high are word constituents. A word token consists of a word constituent followed by zero or more word constituents or number constituents.


 Class StringBufferInputStream

Class java.io.StringBufferInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.StringBufferInputStream

public class StringBufferInputStream
extends InputStream

Note: StringBufferInputStream is deprecated. This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.

This class allows an application to create an input stream in which the bytes read are supplied by the contents of a string. Applications can also read bytes from a byte array by using a ByteArrayInputStream.

Only the low eight bits of each character in the string are used by this class.

See Also:
ByteArrayInputStream, StringReader


 StringBufferInputStream Members

StringBufferInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buffer | The string from which bytes are read.
count | The number of valid characters in the input stream buffer.
pos | The index of the next character to read from the input stream buffer.

Constructors
Name | Description
StringBufferInputStream(String) | Creates a string input stream to read data from the specified string.

Methods
Name | Description
available() | Returns the number of bytes that can be read from the input stream without blocking.
read() | Reads the next byte of data from this input stream.
read(byte[], int, int) | Reads up to len bytes of data from this input stream into an array of bytes.
reset() | Resets the input stream to begin reading from the first character of this input stream's underlying buffer.
skip(long) | Skips n bytes of input from this input stream.


 StringBufferInputStream.buffer

StringBufferInputStream.buffer

Syntax
protected String buffer
Description
The string from which bytes are read.


 StringBufferInputStream.count

StringBufferInputStream.count

Syntax
protected int count
Description
The number of valid characters in the input stream buffer.

See Also
buffer


 StringBufferInputStream.pos

StringBufferInputStream.pos

Syntax
protected int pos
Description
The index of the next character to read from the input stream buffer.

See Also
buffer


 StringBufferInputStream.StringBufferInputStream

StringBufferInputStream.StringBufferInputStream

Syntax
public StringBufferInputStream( String s )
Parameters
s
the underlying input buffer.
Description
Creates a string input stream to read data from the specified string.


 StringBufferInputStream.available

StringBufferInputStream.available

Syntax
public synchronized int available()
Returns
the value of count - pos, which is the number of bytes remaining to be read from the input buffer.
Description
Returns the number of bytes that can be read from the input stream without blocking.

Overrides
available in class InputStream


 StringBufferInputStream.read

StringBufferInputStream.read

Syntax 1
public synchronized int read()
Returns
the next byte of data, or -1 if the end of the stream is reached.
Description
Reads the next byte of data from this input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.

The read method of StringBufferInputStream cannot block. It returns the low eight bits of the next character in this input stream's buffer.

Overrides
read in class InputStream

Syntax 2
public synchronized int read( byte b[], int off, int len )
Parameters
b
the buffer into which the data is read.
off
the start offset of the data.
len
the maximum number of bytes read.
Returns
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Description
Reads up to len bytes of data from this input stream into an array of bytes.

The read method of StringBufferInputStream cannot block. It copies the low eight bits from the characters in this input stream's buffer into the byte array argument.

Overrides
read in class InputStream


 StringBufferInputStream.reset

StringBufferInputStream.reset

Syntax
public synchronized void reset()
Description
Resets the input stream to begin reading from the first character of this input stream's underlying buffer.

Overrides
reset in class InputStream


 StringBufferInputStream.skip

StringBufferInputStream.skip

Syntax
public synchronized long skip( long n )
Parameters
n
the number of bytes to be skipped.
Returns
the actual number of bytes skipped.
Description
Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached.

Overrides
skip in class InputStream


 Class StringReader

Class java.io.StringReader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Reader
           |
           +----java.io.StringReader

public class StringReader
extends Reader

A character stream whose source is a string.


 StringReader Members

StringReader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringReader(String) | Create a new string reader.

Methods
Name | Description
close() | Close the stream.
mark(int) | Mark the present position in the stream.
markSupported() | Tell whether this stream supports the mark() operation, which it does.
read() | Read a single character.
read(char[], int, int) | Read characters into a portion of an array.
ready() | Tell whether this stream is ready to be read.
reset() | Reset the stream to the most recent mark, or to the beginning of the string if it has never been marked.
skip(long) | Skip characters.


 StringReader.StringReader

StringReader.StringReader

Syntax
public StringReader( String s )
Description
Create a new string reader.


 StringReader.close

StringReader.close

Syntax
public void close()
Description
Close the stream.

Overrides
close in class Reader


 StringReader.mark

StringReader.mark

Syntax
public void mark( int readAheadLimit ) throws IOException
Parameters
readAheadLimit
Limit on the number of characters that may be read while still preserving the mark. Because the stream's input comes from a string, there is no actual limit, so this argument is ignored.
Description
Mark the present position in the stream. Subsequent calls to reset() will reposition the stream to this point.

Exceptions
IOException If an I/O error occurs
Overrides
mark in class Reader


 StringReader.markSupported

StringReader.markSupported

Syntax
public boolean markSupported()
Description
Tell whether this stream supports the mark() operation, which it does.

Overrides
markSupported in class Reader


 StringReader.read

StringReader.read

Syntax 1
public int read() throws IOException
Returns
The character read, or -1 if the end of the stream has been reached
Description
Read a single character.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader

Syntax 2
public int read( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Destination buffer
off
Offset at which to start writing characters
len
Maximum number of characters to read
Returns
The number of characters read, or -1 if the end of the stream has been reached
Description
Read characters into a portion of an array.

Exceptions
IOException If an I/O error occurs
Overrides
read in class Reader


 StringReader.ready

StringReader.ready

Syntax
public boolean ready()
Description
Tell whether this stream is ready to be read. String readers are always ready to be read.

Overrides
ready in class Reader


 StringReader.reset

StringReader.reset

Syntax
public void reset() throws IOException
Description
Reset the stream to the most recent mark, or to the beginning of the string if it has never been marked.

Exceptions
IOException If an I/O error occurs
Overrides
reset in class Reader


 StringReader.skip

StringReader.skip

Syntax
public long skip( long ns ) throws IOException
Description
Skip characters.

Exceptions
IOException If an I/O error occurs
Overrides
skip in class Reader


 Class StringWriter

Class java.io.StringWriter

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer
           |
           +----java.io.StringWriter

public class StringWriter
extends Writer

A character stream that collects its output in a string buffer, which can then be used to construct a string.


 StringWriter Members

StringWriter Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringWriter() | Create a new string writer, using the default initial string-buffer size.
StringWriter(int) | Create a new string writer, using the specified initial string-buffer size.

Methods
Name | Description
close() | Close the stream.
flush() | Flush the stream.
getBuffer() | Return the string buffer itself.
toString() | Return the buffer's current value as a string.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String) | Write a string.
write(String, int, int) | Write a portion of a string.


 StringWriter.StringWriter

StringWriter.StringWriter

Syntax 1
public StringWriter()
Description
Create a new string writer, using the default initial string-buffer size.

Syntax 2
protected StringWriter( int initialSize )
Description
Create a new string writer, using the specified initial string-buffer size.


 StringWriter.close

StringWriter.close

Syntax
public void close()
Description
Close the stream. This method does not release the buffer, since its contents might still be required.

Overrides
close in class Writer


 StringWriter.flush

StringWriter.flush

Syntax
public void flush()
Description
Flush the stream.

Overrides
flush in class Writer


 StringWriter.getBuffer

StringWriter.getBuffer

Syntax
public StringBuffer getBuffer()
Description
Return the string buffer itself.


 StringWriter.toString

StringWriter.toString

Syntax
public String toString()
Description
Return the buffer's current value as a string.

Overrides
toString in class Object


 StringWriter.write

StringWriter.write

Syntax 1
public void write( int c )
Description
Write a single character.

Overrides
write in class Writer

Syntax 2
public void write( char cbuf[], int off, int len )
Parameters
cbuf
Array of characters
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of an array of characters.

Overrides
write in class Writer

Syntax 3
public void write( String str )
Description
Write a string.

Overrides
write in class Writer

Syntax 4
public void write( String str, int off, int len )
Parameters
str
String to be written
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of a string.

Overrides
write in class Writer


 Class SyncFailedException

Class java.io.SyncFailedException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.SyncFailedException

public class SyncFailedException
extends IOException


 SyncFailedException Members

SyncFailedException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SyncFailedException(String) | Constructs an SyncFailedException with a detail message.


 SyncFailedException.SyncFailedException

SyncFailedException.SyncFailedException

Syntax
public SyncFailedException( String desc )
Description
Constructs an SyncFailedException with a detail message. A detail message is a String that describes this particular exception.


 Class UTFDataFormatException

Class java.io.UTFDataFormatException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.UTFDataFormatException

public class UTFDataFormatException
extends IOException

Signals that a malformed UTF-8 string has been read in a data input stream or by any class that implements the data input interface. See the writeUTF method for the format in which UTF-8 strings are read and written.

See Also:
DataInput, readUTF, IOException


 UTFDataFormatException Members

UTFDataFormatException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UTFDataFormatException() | Constructs a UTFDataFormatException with no detail message.
UTFDataFormatException(String) | Constructs a UTFDataFormatException with the specified detail message.


 UTFDataFormatException.UTFDataFormatException

UTFDataFormatException.UTFDataFormatException

Syntax 1
public UTFDataFormatException()
Description
Constructs a UTFDataFormatException with no detail message.

Syntax 2
public UTFDataFormatException( String s )
Parameters
s
the detail message.
Description
Constructs a UTFDataFormatException with the specified detail message.


 Class UnsupportedEncodingException

Class java.io.UnsupportedEncodingException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.UnsupportedEncodingException

public class UnsupportedEncodingException
extends IOException

The Character Encoding is not supported


 UnsupportedEncodingException Members

UnsupportedEncodingException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnsupportedEncodingException() | no detailed message
UnsupportedEncodingException(String) | detailed message


 UnsupportedEncodingException.UnsupportedEncodingException

UnsupportedEncodingException.UnsupportedEncodingException

Syntax 1
public UnsupportedEncodingException()
Description
no detailed message

Syntax 2
public UnsupportedEncodingException( String s )
Parameters
s
- detailed message
Description
detailed message


 Class WriteAbortedException

Class java.io.WriteAbortedException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.io.ObjectStreamException
                                   |
                                   +----java.io.WriteAbortedException

public class WriteAbortedException
extends ObjectStreamException


 WriteAbortedException Members

WriteAbortedException Members

Class Overview | This Package | All Packages

Fields
Name | Description
detail |

Constructors
Name | Description
WriteAbortedException(String, Exception) | A WriteAbortedException is thrown during a read when one of the ObjectStreamExceptions was thrown during writing.

Methods
Name | Description
getMessage() | Produce the message, include the message from the nested exception if there is one.


 WriteAbortedException.detail

WriteAbortedException.detail

Syntax
public Exception detail


 WriteAbortedException.WriteAbortedException

WriteAbortedException.WriteAbortedException

Syntax
public WriteAbortedException( String s, Exception ex )
Description
A WriteAbortedException is thrown during a read when one of the ObjectStreamExceptions was thrown during writing. The exception that terminated the write can be found in the detail field. The stream is reset to it's initial state, all references to objects already deserialized are discarded.


 WriteAbortedException.getMessage

WriteAbortedException.getMessage

Syntax
public String getMessage()
Description
Produce the message, include the message from the nested exception if there is one.

Overrides
getMessage in class Throwable


 Class Writer

Class java.io.Writer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.Writer

public abstract class Writer
extends Object

Abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

See Also:
Writer, BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, FileWriter, PipedWriter, PrintWriter, StringWriter, Reader


 Writer Members

Writer Members

Class Overview | This Package | All Packages

Fields
Name | Description
lock | The object used to synchronize operations on this stream.

Constructors
Name | Description
Writer() | Create a new character-stream writer whose critical sections will synchronize on the writer itself.
Writer(Object) | Create a new character-stream writer whose critical sections will synchronize on the given object.

Methods
Name | Description
close() | Close the stream, flushing it first.
flush() | Flush the stream.
write(char[]) | Write an array of characters.
write(char[], int, int) | Write a portion of an array of characters.
write(int) | Write a single character.
write(String) | Write a string.
write(String, int, int) | Write a portion of a string.


 Writer.lock

Writer.lock

Syntax
protected Object lock
Description
The object used to synchronize operations on this stream. For efficiency, a character-stream object may use an object other than itself to protect critical sections. A subclass should therefore use the object in this field rather than this or a synchronized method.


 Writer.Writer

Writer.Writer

Syntax 1
protected Writer()
Description
Create a new character-stream writer whose critical sections will synchronize on the writer itself.

Syntax 2
protected Writer( Object lock )
Description
Create a new character-stream writer whose critical sections will synchronize on the given object.


 Writer.close

Writer.close

Syntax
public abstract void close() throws IOException
Description
Close the stream, flushing it first. Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.

Exceptions
IOException If an I/O error occurs


 Writer.flush

Writer.flush

Syntax
public abstract void flush() throws IOException
Description
Flush the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.

Exceptions
IOException If an I/O error occurs


 Writer.write

Writer.write

Syntax 1
public void write( int c ) throws IOException
Description
Write a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

Subclasses that intend to support efficient single-character output should override this method.

Exceptions
IOException If an I/O error occurs

Syntax 2
public void write( char cbuf[] ) throws IOException
Parameters
cbuf
Array of characters to be written
Description
Write an array of characters.

Exceptions
IOException If an I/O error occurs

Syntax 3
public abstract void write( char cbuf[], int off, int len ) throws IOException
Parameters
cbuf
Array of characters
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of an array of characters.

Exceptions
IOException If an I/O error occurs

Syntax 4
public void write( String str ) throws IOException
Parameters
str
String to be written
Description
Write a string.

Exceptions
IOException If an I/O error occurs

Syntax 5
public void write( String str, int off, int len ) throws IOException
Parameters
str
A String
off
Offset from which to start writing characters
len
Number of characters to write
Description
Write a portion of a string.

Exceptions
IOException If an I/O error occurs


 Package java.lang

Package java.lang

All Packages

Interfaces

  • Cloneable
  • Runnable

    • Classes

  • Boolean
  • Byte
  • Character
  • Class
  • ClassLoader
  • Compiler
  • Double
  • Float
  • Integer
  • Long
  • Math
  • Number
  • Object
  • Process
  • Runtime
  • SecurityManager
  • Short
  • String
  • StringBuffer
  • System
  • Thread
  • ThreadGroup
  • Throwable
  • Void

    • Exceptions

  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • ArrayStoreException
  • ClassCastException
  • ClassNotFoundException
  • CloneNotSupportedException
  • Exception
  • IllegalAccessException
  • IllegalArgumentException
  • IllegalMonitorStateException
  • IllegalStateException
  • IllegalThreadStateException
  • IndexOutOfBoundsException
  • InstantiationException
  • InterruptedException
  • NegativeArraySizeException
  • NoSuchFieldException
  • NoSuchMethodException
  • NullPointerException
  • NumberFormatException
  • RuntimeException
  • SecurityException
  • StringIndexOutOfBoundsException

    • Errors

  • AbstractMethodError
  • ClassCircularityError
  • ClassFormatError
  • Error
  • ExceptionInInitializerError
  • IllegalAccessError
  • IncompatibleClassChangeError
  • InstantiationError
  • InternalError
  • LinkageError
  • NoClassDefFoundError
  • NoSuchFieldError
  • NoSuchMethodError
  • OutOfMemoryError
  • StackOverflowError
  • ThreadDeath
  • UnknownError
  • UnsatisfiedLinkError
  • VerifyError
  • VirtualMachineError


 Class AbstractMethodError

Class java.lang.AbstractMethodError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError
                                   |
                                   +----java.lang.AbstractMethodError

public class AbstractMethodError
extends IncompatibleClassChangeError

Thrown when an application tries to call an abstract method. Normally, this error is caught by the compiler; this error can only occur at run time if the definition of some class has incompatibly changed since the currently executing method was last compiled.


 AbstractMethodError Members

AbstractMethodError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
AbstractMethodError() | Constructs an AbstractMethodError with no detail message.
AbstractMethodError(String) | Constructs an AbstractMethodError with the specified detail message.


 AbstractMethodError.AbstractMethodError

AbstractMethodError.AbstractMethodError

Syntax 1
public AbstractMethodError()
Description
Constructs an AbstractMethodError with no detail message.

Syntax 2
public AbstractMethodError( String s )
Parameters
s
the detail message.
Description
Constructs an AbstractMethodError with the specified detail message.


 Class ArithmeticException

Class java.lang.ArithmeticException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.ArithmeticException

public class ArithmeticException
extends RuntimeException

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.


 ArithmeticException Members

ArithmeticException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ArithmeticException() | Constructs an ArithmeticException with no detail message.
ArithmeticException(String) | Constructs an ArithmeticException with the specified detail message.


 ArithmeticException.ArithmeticException

ArithmeticException.ArithmeticException

Syntax 1
public ArithmeticException()
Description
Constructs an ArithmeticException with no detail message.

Syntax 2
public ArithmeticException( String s )
Parameters
s
the detail message.
Description
Constructs an ArithmeticException with the specified detail message.


 Class ArrayIndexOutOfBoundsException

Class java.lang.ArrayIndexOutOfBoundsException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IndexOutOfBoundsException
                                   |
                                   +----java.lang.ArrayIndexOutOfBoundsException

public class ArrayIndexOutOfBoundsException
extends IndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.


 ArrayIndexOutOfBoundsException Members

ArrayIndexOutOfBoundsException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ArrayIndexOutOfBoundsException() | Constructs an ArrayIndexOutOfBoundsException with no detail message.
ArrayIndexOutOfBoundsException(int) | Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.
ArrayIndexOutOfBoundsException(String) | Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.


 ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException

Class Overview | Class Members | This Package | All Packages

Syntax 1
public ArrayIndexOutOfBoundsException()
Description
Constructs an ArrayIndexOutOfBoundsException with no detail message.

Syntax 2
public ArrayIndexOutOfBoundsException( int index )
Parameters
index
the illegal index.
Description
Constructs a new ArrayIndexOutOfBoundsException class with an argument indicating the illegal index.

Syntax 3
public ArrayIndexOutOfBoundsException( String s )
Parameters
s
the detail message.
Description
Constructs an ArrayIndexOutOfBoundsException class with the specified detail message.


 Class ArrayStoreException

Class java.lang.ArrayStoreException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.ArrayStoreException

public class ArrayStoreException
extends RuntimeException

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

     Object x[] = new String[3];
     x[0] = new Integer(0);


 ArrayStoreException Members

ArrayStoreException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ArrayStoreException() | Constructs an ArrayStoreException with no detail message.
ArrayStoreException(String) | Constructs an ArrayStoreException with the specified detail message.


 ArrayStoreException.ArrayStoreException

ArrayStoreException.ArrayStoreException

Syntax 1
public ArrayStoreException()
Description
Constructs an ArrayStoreException with no detail message.

Syntax 2
public ArrayStoreException( String s )
Parameters
s
the detail message.
Description
Constructs an ArrayStoreException with the specified detail message.


 Class Boolean

Class java.lang.Boolean

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Boolean

public final class Boolean
extends Object
implements Serializable

The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

In addition, this class provides many methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean.


 Boolean Members

Boolean Members

Class Overview | This Package | All Packages

Fields
Name | Description
FALSE | The Boolean object corresponding to the primitive value false.
TRUE | The Boolean object corresponding to the primitive value true.
TYPE | The Class object representing the primitive type boolean.

Constructors
Name | Description
Boolean(boolean) | Allocates a Boolean object representing the value argument.
Boolean(String) | Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Methods
Name | Description
booleanValue() | Returns the value of this Boolean object as a boolean.
equals(Object) | Returns true if and only if the argument is not null and is a Boolean object that contains the same boolean value as this object.
getBoolean(String) | Returns is true if and only if the system property named by the argument exists and is equal to the string "true".
hashCode() | Returns a hash code for this Boolean.
toString() | Returns a String object representing this Boolean's value.
valueOf(String) | Returns the boolean value represented by the specified String.


 Boolean.FALSE

Boolean.FALSE

Syntax
public static final Boolean FALSE
Description
The Boolean object corresponding to the primitive value false.


 Boolean.TRUE

Boolean.TRUE

Syntax
public static final Boolean TRUE
Description
The Boolean object corresponding to the primitive value true.


 Boolean.TYPE

Boolean.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type boolean.


 Boolean.Boolean

Boolean.Boolean

Syntax 1
public Boolean( boolean value )
Parameters
value
the value of the Boolean.
Description
Allocates a Boolean object representing the value argument.

Syntax 2
public Boolean( String s )
Parameters
s
the string to be converted to a Boolean.
Description
Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false.


 Boolean.booleanValue

Boolean.booleanValue

Syntax
public boolean booleanValue()
Returns
the primitive boolean value of this object.
Description
Returns the value of this Boolean object as a boolean.


 Boolean.equals

Boolean.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Returns true if and only if the argument is not null and is a Boolean object that contains the same boolean value as this object.

Overrides
equals in class Object


 Boolean.getBoolean

Boolean.getBoolean

Syntax
public static boolean getBoolean( String name )
Parameters
name
the system property name.
Returns
the boolean value of the system property.
Description
Returns is true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with Java 1.0.2, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class.

See Also
getProperty, getProperty


 Boolean.hashCode

Boolean.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hash code for this Boolean.

Overrides
hashCode in class Object


 Boolean.toString

Boolean.toString

Syntax
public String toString()
Returns
a string representation of this object.
Description
Returns a String object representing this Boolean's value. If this object contains the value true, a string equal to "true" is returned. Otherwise, a string equal to "false" is returned.

Overrides
toString in class Object


 Boolean.valueOf

Boolean.valueOf

Syntax
public static Boolean valueOf( String s )
Parameters
s
a string.
Returns
the Boolean value represented by the string.
Description
Returns the boolean value represented by the specified String. A new Boolean object is constructed. This Boolean contains the value true if the string argument is not null and is equal, ignoring case, to the string "true".


 Class Byte

Class java.lang.Byte

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Byte

public final class Byte
extends Number

The Byte class is the standard wrapper for byte values.

See Also:
Number


 Byte Members

Byte Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The maximum value a Byte can have.
MIN_VALUE | The minimum value a Byte can have.
TYPE | The Class object representing the primitive type byte.

Constructors
Name | Description
Byte(byte) | Constructs a Byte object initialized to the specified byte value.
Byte(String) | Constructs a Byte object initialized to the value specified by the String parameter.

Methods
Name | Description
byteValue() | Returns the value of this Byte as a byte.
decode(String) | Decodes a String into a Byte.
doubleValue() | Returns the value of this Byte as a double.
equals(Object) | Compares this object to the specified object.
floatValue() | Returns the value of this Byte as a float.
hashCode() | Returns a hashcode for this Byte.
intValue() | Returns the value of this Byte as an int.
longValue() | Returns the value of this Byte as a long.
parseByte(String) | Assuming the specified String represents a byte, returns that byte's value.
parseByte(String, int) | Assuming the specified String represents a byte, returns that byte's value.
shortValue() | Returns the value of this Byte as a short.
toString() | Returns a String object representing this Byte's value.
toString(byte) | Returns a new String object representing the specified Byte.
valueOf(String) | Assuming the specified String represents a byte, returns a new Byte object initialized to that value.
valueOf(String, int) | Assuming the specified String represents a byte, returns a new Byte object initialized to that value.


 Byte.MAX_VALUE

Byte.MAX_VALUE

Syntax
public static final byte MAX_VALUE
Description
The maximum value a Byte can have.


 Byte.MIN_VALUE

Byte.MIN_VALUE

Syntax
public static final byte MIN_VALUE
Description
The minimum value a Byte can have.


 Byte.TYPE

Byte.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type byte.


 Byte.Byte

Byte.Byte

Syntax 1
public Byte( byte value )
Parameters
value
the initial value of the Byte
Description
Constructs a Byte object initialized to the specified byte value.

Syntax 2
public Byte( String s ) throws NumberFormatException
Parameters
s
the String to be converted to a Byte
Description
Constructs a Byte object initialized to the value specified by the String parameter. The radix is assumed to be 10.

Exceptions
NumberFormatException If the String does not contain a parsable byte.


 Byte.byteValue

Byte.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Byte as a byte.

Overrides
byteValue in class Number


 Byte.decode

Byte.decode

Syntax
public static Byte decode( String nm ) throws NumberFormatException
Parameters
nm
the string to decode
Description
Decodes a String into a Byte. The String may represent decimal, hexadecimal, and octal numbers.


 Byte.doubleValue

Byte.doubleValue

Syntax
public double doubleValue()
Description
Returns the value of this Byte as a double.

Overrides
doubleValue in class Number


 Byte.equals

Byte.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with
Returns
true if the objects are the same; false otherwise.
Description
Compares this object to the specified object.

Overrides
equals in class Object


 Byte.floatValue

Byte.floatValue

Syntax
public float floatValue()
Description
Returns the value of this Byte as a float.

Overrides
floatValue in class Number


 Byte.hashCode

Byte.hashCode

Syntax
public int hashCode()
Description
Returns a hashcode for this Byte.

Overrides
hashCode in class Object


 Byte.intValue

Byte.intValue

Syntax
public int intValue()
Description
Returns the value of this Byte as an int.

Overrides
intValue in class Number


 Byte.longValue

Byte.longValue

Syntax
public long longValue()
Description
Returns the value of this Byte as a long.

Overrides
longValue in class Number


 Byte.parseByte

Byte.parseByte

Syntax 1
public static byte parseByte( String s ) throws NumberFormatException
Parameters
s
the String containing the byte
Description
Assuming the specified String represents a byte, returns that byte's value. Throws an exception if the String cannot be parsed as a byte. The radix is assumed to be 10.

Exceptions
NumberFormatException If the string does not contain a parsable byte.

Syntax 2
public static byte parseByte( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the byte
radix
the radix to be used
Description
Assuming the specified String represents a byte, returns that byte's value. Throws an exception if the String cannot be parsed as a byte.

Exceptions
NumberFormatException If the String does not contain a parsable byte.


 Byte.shortValue

Byte.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Byte as a short.

Overrides
shortValue in class Number


 Byte.toString

Byte.toString

Syntax
public static String toString( byte b )
Parameters
b
the byte to be converted
Description
Returns a new String object representing the specified Byte. The radix is assumed to be 10.


 Byte.toString

Byte.toString

Syntax
public String toString()
Description
Returns a String object representing this Byte's value.

Overrides
toString in class Object


 Byte.valueOf

Byte.valueOf

Syntax 1
public static Byte valueOf( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the integer
radix
the radix to be used
Description
Assuming the specified String represents a byte, returns a new Byte object initialized to that value. Throws an exception if the String cannot be parsed as a byte.

Exceptions
NumberFormatException If the String does not contain a parsable byte.

Syntax 2
public static Byte valueOf( String s ) throws NumberFormatException
Parameters
s
the String containing the integer
Description
Assuming the specified String represents a byte, returns a new Byte object initialized to that value. Throws an exception if the String cannot be parsed as a byte. The radix is assumed to be 10.

Exceptions
NumberFormatException If the String does not contain a parsable byte.


 Class Character

Class java.lang.Character

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Character

public final class Character
extends Object
implements Serializable

The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char.

In addition, this class provides several methods for determining the type of a character and converting characters from uppercase to lowercase and vice versa.

Many of the methods of class Character are defined in terms of a "Unicode attribute table" that specifies a name for every defined Unicode code point. The table also includes other attributes, such as a decimal value, an uppercase equivalent, a lowercase equivalent, and/or a titlecase equivalent. The Unicode attribute table is available on the World Wide Web as the file:

    ftp://unicode.org/pub/MappingTables/UnicodeData1.1.5.txt

For a more detailed specification of the Character class, one that encompasses the exact behavior of methods such as isDigit, isLetter, isLowerCase, and isUpperCase over the full range of Unicode values, see Gosling, Joy, and Steele, The Java Language Specification.


 Character Members

Character Members

Class Overview | This Package | All Packages

Fields
Name | Description
COMBINING_SPACING_MARK |
CONNECTOR_PUNCTUATION |
CONTROL |
CURRENCY_SYMBOL |
DASH_PUNCTUATION |
DECIMAL_DIGIT_NUMBER |
ENCLOSING_MARK |
END_PUNCTUATION |
FORMAT |
LETTER_NUMBER |
LINE_SEPARATOR |
LOWERCASE_LETTER |
MATH_SYMBOL |
MAX_RADIX | The maximum radix available for conversion to and from Strings.
MAX_VALUE | The constant value of this field is the largest value of type char.
MIN_RADIX | The minimum radix available for conversion to and from Strings.
MIN_VALUE | The constant value of this field is the smallest value of type char.
MODIFIER_LETTER |
MODIFIER_SYMBOL |
NON_SPACING_MARK |
OTHER_LETTER |
OTHER_NUMBER |
OTHER_PUNCTUATION |
OTHER_SYMBOL |
PARAGRAPH_SEPARATOR |
PRIVATE_USE |
SPACE_SEPARATOR |
START_PUNCTUATION |
SURROGATE |
TITLECASE_LETTER |
TYPE | The Class object representing the primitive type char.
UNASSIGNED |
UPPERCASE_LETTER |

Constructors
Name | Description
Character(char) | Constructs a Character object and initializes it so that it represents the primitive value argument.

Methods
Name | Description
charValue() | Returns the value of this Character object.
digit(char, int) | Returns the numeric value of the character ch in the specified radix.
equals(Object) | Compares this object against the specified object.
forDigit(int, int) | Determines the character representation for a specific digit in the specified radix.
getNumericValue(char) | Returns the Unicode numeric value of the character as a nonnegative integer.
getType(char) | Returns a value indicating a character category.
hashCode() | Returns a hash code for this Character.
isDefined(char) | Determines if a character has a defined meaning in Unicode.
isDigit(char) | Determines if the specified character is a digit.
isIdentifierIgnorable(char) | Determines if the specified character should be regarded as an ignorable character in a Java identifier or a Unicode identifier.
isISOControl(char) | Determines if the specified character is an ISO control character.
isJavaIdentifierPart(char) | Determines if the specified character may be part of a Java identifier as other than the first character.
isJavaIdentifierStart(char) | Determines if the specified character is permissible as the first character in a Java identifier.
isJavaLetter(char) | Determines if the specified character is a "Java" letter, that is, the character is permissible as the first character in an identifier in the Java language. Deprecated.
isJavaLetterOrDigit(char) | Determines if the specified character is a "Java" letter or digit, that is, the character is permissible as a non-initial character in an identifier in the Java language. Deprecated.
isLetter(char) | Determines if the specified character is a letter.
isLetterOrDigit(char) | Determines if the specified character is a letter or digit.
isLowerCase(char) | Determines if the specified character is a lowercase character.
isSpace(char) | Determines if the specified character is ISO-LATIN-1 white space. Deprecated.
isSpaceChar(char) | Determines if the specified character is a Unicode space character.
isTitleCase(char) | Determines if the specified character is a titlecase character.
isUnicodeIdentifierPart(char) | Determines if the specified character may be part of a Unicode identifier as other than the first character.
isUnicodeIdentifierStart(char) | Determines if the specified character is permissible as the first character in a Unicode identifier.
isUpperCase(char) | Determines if the specified character is an uppercase character.
isWhitespace(char) | Determines if the specified character is white space according to Java.
toLowerCase(char) | The given character is mapped to its lowercase equivalent; if the character has no lowercase equivalent, the character itself is returned.
toString() | Returns a String object representing this character's value.
toTitleCase(char) | Converts the character argument to titlecase.
toUpperCase(char) | Converts the character argument to uppercase.


 Character.COMBINING_SPACING_MARK

Character.COMBINING_SPACING_MARK

Syntax
public static final byte COMBINING_SPACING_MARK


 Character.CONNECTOR_PUNCTUATION

Character.CONNECTOR_PUNCTUATION

Syntax
public static final byte CONNECTOR_PUNCTUATION


 Character.CONTROL

Character.CONTROL

Syntax
public static final byte CONTROL


 Character.CURRENCY_SYMBOL

Character.CURRENCY_SYMBOL

Syntax
public static final byte CURRENCY_SYMBOL


 Character.DASH_PUNCTUATION

Character.DASH_PUNCTUATION

Syntax
public static final byte DASH_PUNCTUATION


 Character.DECIMAL_DIGIT_NUMBER

Character.DECIMAL_DIGIT_NUMBER

Syntax
public static final byte DECIMAL_DIGIT_NUMBER


 Character.ENCLOSING_MARK

Character.ENCLOSING_MARK

Syntax
public static final byte ENCLOSING_MARK


 Character.END_PUNCTUATION

Character.END_PUNCTUATION

Syntax
public static final byte END_PUNCTUATION


 Character.FORMAT

Character.FORMAT

Syntax
public static final byte FORMAT


 Character.LETTER_NUMBER

Character.LETTER_NUMBER

Syntax
public static final byte LETTER_NUMBER


 Character.LINE_SEPARATOR

Character.LINE_SEPARATOR

Syntax
public static final byte LINE_SEPARATOR


 Character.LOWERCASE_LETTER

Character.LOWERCASE_LETTER

Syntax
public static final byte LOWERCASE_LETTER


 Character.MATH_SYMBOL

Character.MATH_SYMBOL

Syntax
public static final byte MATH_SYMBOL


 Character.MAX_RADIX

Character.MAX_RADIX

Syntax
public static final int MAX_RADIX
Description
The maximum radix available for conversion to and from Strings. The constant value of this field is the largest value permitted for the radix argument in radix-conversion methods such as the digit method, the forDigit method, and the toString method of class Integer.

See Also
digit, forDigit, toString, valueOf


 Character.MAX_VALUE

Character.MAX_VALUE

Syntax
public static final char MAX_VALUE
Description
The constant value of this field is the largest value of type char.


 Character.MIN_RADIX

Character.MIN_RADIX

Syntax
public static final int MIN_RADIX
Description
The minimum radix available for conversion to and from Strings. The constant value of this field is the smallest value permitted for the radix argument in radix-conversion methods such as the digit method, the forDigit method, and the toString method of class Integer.

See Also
digit, forDigit, toString, valueOf


 Character.MIN_VALUE

Character.MIN_VALUE

Syntax
public static final char MIN_VALUE
Description
The constant value of this field is the smallest value of type char.


 Character.MODIFIER_LETTER

Character.MODIFIER_LETTER

Syntax
public static final byte MODIFIER_LETTER


 Character.MODIFIER_SYMBOL

Character.MODIFIER_SYMBOL

Syntax
public static final byte MODIFIER_SYMBOL


 Character.NON_SPACING_MARK

Character.NON_SPACING_MARK

Syntax
public static final byte NON_SPACING_MARK


 Character.OTHER_LETTER

Character.OTHER_LETTER

Syntax
public static final byte OTHER_LETTER


 Character.OTHER_NUMBER

Character.OTHER_NUMBER

Syntax
public static final byte OTHER_NUMBER


 Character.OTHER_PUNCTUATION

Character.OTHER_PUNCTUATION

Syntax
public static final byte OTHER_PUNCTUATION


 Character.OTHER_SYMBOL

Character.OTHER_SYMBOL

Syntax
public static final byte OTHER_SYMBOL


 Character.PARAGRAPH_SEPARATOR

Character.PARAGRAPH_SEPARATOR

Syntax
public static final byte PARAGRAPH_SEPARATOR


 Character.PRIVATE_USE

Character.PRIVATE_USE

Syntax
public static final byte PRIVATE_USE


 Character.SPACE_SEPARATOR

Character.SPACE_SEPARATOR

Syntax
public static final byte SPACE_SEPARATOR


 Character.START_PUNCTUATION

Character.START_PUNCTUATION

Syntax
public static final byte START_PUNCTUATION


 Character.SURROGATE

Character.SURROGATE

Syntax
public static final byte SURROGATE


 Character.TITLECASE_LETTER

Character.TITLECASE_LETTER

Syntax
public static final byte TITLECASE_LETTER


 Character.TYPE

Character.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type char.


 Character.UNASSIGNED

Character.UNASSIGNED

Syntax
public static final byte UNASSIGNED


 Character.UPPERCASE_LETTER

Character.UPPERCASE_LETTER

Syntax
public static final byte UPPERCASE_LETTER


 Character.Character

Character.Character

Syntax
public Character( char value )
Parameters
value
value for the new Character object.
Description
Constructs a Character object and initializes it so that it represents the primitive value argument.


 Character.charValue

Character.charValue

Syntax
public char charValue()
Returns
the primitive char value represented by this object.
Description
Returns the value of this Character object.


 Character.digit

Character.digit

Syntax
public static int digit( char ch, int radix )
Parameters
ch
the character to be converted.
radix
the radix.
Returns
the numeric value represented by the character in the specified radix.
Description
Returns the numeric value of the character ch in the specified radix.

If the radix is not in the range MIN_RADIX <= radix <= MAX_RADIX or if the value of ch is not a valid digit in the specified radix, -1 is returned. A character is a valid digit if at least one of the following is true:

  • The method isDigit is true of the character and the Unicode decimal digit value of the character (or its single-character decomposition) is less than the specified radix. In this case the decimal digit value is returned.
  • The character is one of the uppercase Latin letters 'A' through 'Z' and its code is less than radix + 'A' - 10. In this case, ch - 'A' + 10 is returned.
  • The character is one of the lowercase Latin letters 'a' through 'z' and its code is less than radix + 'a' - 10. In this case, ch - 'a' + 10 is returned.

See Also
forDigit, isDigit


 Character.equals

Character.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object. The result is true if and only if the argument is not null and is a Character object that represents the same char value as this object.

Overrides
equals in class Object


 Character.forDigit

Character.forDigit

Syntax
public static char forDigit( int digit, int radix )
Parameters
digit
the number to convert to a character.
radix
the radix.
Returns
the char representation of the specified digit in the specified radix.
Description
Determines the character representation for a specific digit in the specified radix. If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character ('\u0000') is returned.

The radix argument is valid if it is greater than or equal to MIN_RADIX and less than or equal to MAX_RADIX. The digit argument is valid if 0 <= digit <= radix.

If the digit is less than 10, then '0' + digit is returned. Otherwise, the value 'a' + digit - 10 is returned.

See Also
MIN_RADIX, MAX_RADIX, digit


 Character.getNumericValue

Character.getNumericValue

Syntax
public static int getNumericValue( char ch )
Parameters
ch
the character to be converted.
radix
the radix.
Returns
the numeric value of the character, as a nonnegative int value; -2 if the character has a numeric value that is not a nonnegative integer; -1 if the character has no numeric value.
Description
Returns the Unicode numeric value of the character as a nonnegative integer. If the character does not have a numeric value, then -1 is returned. If the character has a numeric value that cannot be represented as a nonnegative integer (for example, a fractional value), then -2 is returned.

See Also
forDigit, isDigit


 Character.getType

Character.getType

Syntax
public static int getType( char ch )
Parameters
ch
the character to be tested.
Returns
a value of type int, the character category.
Description
Returns a value indicating a character category.

See Also
COMBINING_SPACING_MARK, CONNECTOR_PUNCTUATION, CONTROL, CURRENCY_SYMBOL, DASH_PUNCTUATION, DECIMAL_DIGIT_NUMBER, ENCLOSING_MARK, END_PUNCTUATION, FORMAT, LETTER_NUMBER, LINE_SEPARATOR, LOWERCASE_LETTER, MATH_SYMBOL, MODIFIER_LETTER, MODIFIER_SYMBOL, NON_SPACING_MARK, OTHER_LETTER, OTHER_NUMBER, OTHER_PUNCTUATION, OTHER_SYMBOL, PARAGRAPH_SEPARATOR, PRIVATE_USE, SPACE_SEPARATOR, START_PUNCTUATION, SURROGATE, TITLECASE_LETTER, UNASSIGNED, UPPERCASE_LETTER


 Character.hashCode

Character.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hash code for this Character.

Overrides
hashCode in class Object


 Character.isDefined

Character.isDefined

Syntax
public static boolean isDefined( char ch )
Parameters
ch
the character to be tested
Returns
true if the character has a defined meaning in Unicode; false otherwise.
Description
Determines if a character has a defined meaning in Unicode. A character is defined if at least one of the following is true:
  • It has an entry in the Unicode attribute table.
  • Its value is in the range '\u3040' <= ch <= '\u9FA5'.
  • Its value is in the range '\uF900' <= ch <= '\uFA2D'.

See Also
isDigit, isLetter, isLetterOrDigit, isLowerCase, isTitleCase, isUpperCase


 Character.isDigit

Character.isDigit

Syntax
public static boolean isDigit( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a digit; false otherwise.
Description
Determines if the specified character is a digit. A character is considered to be a digit if it is not in the range '\u2000' <= ch <= '\u2FFF' and its Unicode name contains the word "DIGIT". For a more complete specification that encompasses all Unicode characters that are defined as digits, see Gosling, Joy, and Steele, The Java Language Specification.

These are the ranges of Unicode characters that are considered digits:
0x0030 through 0x0039 | ISO-LATIN-1 digits ('0' through '9')
0x0660 through 0x0669 | Arabic-Indic digits
0x06F0 through 0x06F9 | Extended Arabic-Indic digits
0x0966 through 0x096F | Devanagari digits
0x09E6 through 0x09EF | Bengali digits
0x0A66 through 0x0A6F | Gurmukhi digits
0x0AE6 through 0x0AEF | Gujarati digits
0x0B66 through 0x0B6F | Oriya digits
0x0BE7 through 0x0BEF | Tamil digits
0x0C66 through 0x0C6F | Telugu digits
0x0CE6 through 0x0CEF | Kannada digits
0x0D66 through 0x0D6F | Malayalam digits
0x0E50 through 0x0E59 | Thai digits
0x0ED0 through 0x0ED9 | Lao digits
0x0F20 through 0x0F29 | Tibetan digits
0xFF10 through 0xFF19 | Fullwidth digits

See Also
digit, forDigit


 Character.isIdentifierIgnorable

Character.isIdentifierIgnorable

Syntax
public static boolean isIdentifierIgnorable( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character may be part of a Unicode identifier; false otherwise.
Description
Determines if the specified character should be regarded as an ignorable character in a Java identifier or a Unicode identifier. The following Unicode characters are ignorable in a Java identifier or a Unicode identifier:
0x0000 through 0x0008, | ISO control characters that
0x000E through 0x001B, | are not whitespace
and 0x007F through 0x009F
0x200C through 0x200F | join controls
0x200A through 0x200E | bidirectional controls
0x206A through 0x206F | format controls
0xFEFF | zero-width no-break space

See Also
isJavaIdentifierPart, isUnicodeIdentifierPart


 Character.isISOControl

Character.isISOControl

Syntax
public static boolean isISOControl( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is an ISO control character; false otherwise.
Description
Determines if the specified character is an ISO control character. A character is considered to be an ISO control character if its code is in the range \u0000 through \u001F or in the range \u007F through \u009F.

See Also
isSpaceChar, isWhitespace


 Character.isJavaIdentifierPart

Character.isJavaIdentifierPart

Syntax
public static boolean isJavaIdentifierPart( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character may be part of a Unicode identifier; false otherwise.
Description
Determines if the specified character may be part of a Java identifier as other than the first character. A character may be part of a Java identifier if and only if it is one of the following:
  • a letter
  • a currency symbol (such as "$")
  • a connecting punctuation character (such as "_").
  • a digit
  • a numeric letter (such as a Roman numeral character)
  • a combining mark
  • a non-spacing mark
  • an ignorable control character

See Also
isIdentifierIgnorable, isJavaIdentifierStart, isLetterOrDigit, isUnicodeIdentifierPart


 Character.isJavaIdentifierStart

Character.isJavaIdentifierStart

Syntax
public static boolean isJavaIdentifierStart( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character may start a Java identifier; false otherwise.
Description
Determines if the specified character is permissible as the first character in a Java identifier. A character may start a Java identifier if and only if it is one of the following:
  • a letter
  • a currency symbol (such as "$")
  • a connecting punctuation character (such as "_").

See Also
isJavaIdentifierPart, isLetter, isUnicodeIdentifierStart


 Character.isJavaLetter

Character.isJavaLetter

Syntax
public static boolean isJavaLetter( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a Java letter; false otherwise.
Description
Note: isJavaLetter() is deprecated. Replaced by isJavaIdentifierStart(char).

Determines if the specified character is a "Java" letter, that is, the character is permissible as the first character in an identifier in the Java language.

A character is considered to be a Java letter if and only if it is a letter, the ASCII dollar sign character '$', or the underscore character '_'.

See Also
isJavaIdentifierStart, isJavaLetterOrDigit, isLetter, isLetterOrDigit, isUnicodeIdentifierStart


 Character.isJavaLetterOrDigit

Character.isJavaLetterOrDigit

Syntax
public static boolean isJavaLetterOrDigit( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a Java letter or digit; false otherwise.
Description
Note: isJavaLetterOrDigit() is deprecated. Replaced by isJavaIdentifierPart(char).

Determines if the specified character is a "Java" letter or digit, that is, the character is permissible as a non-initial character in an identifier in the Java language.

A character is considered to be a Java letter or digit if and only if it is a letter, a digit, the ASCII dollar sign character '$', or the underscore character '_'.

See Also
isJavaIdentifierPart, isJavaLetter, isLetter, isLetterOrDigit, isUnicodeIdentifierPart


 Character.isLetter

Character.isLetter

Syntax
public static boolean isLetter( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a letter; false otherwise.
Description
Determines if the specified character is a letter. For a more complete specification that encompasses all Unicode characters, see Gosling, Joy, and Steele, The Java Language Specification.

A character is considered to be a letter if and only if it is specified to be a letter by the Unicode 2.0 standard (category "Lu", "Ll", "Lt", "Lm", or "Lo" in the Unicode specification data file).

Note that most ideographic characters are considered to be letters (category "Lo") for this purpose.

Note also that not all letters have case: many Unicode characters are letters but are neither uppercase nor lowercase nor titlecase.

See Also
isDigit, isJavaIdentifierStart, isJavaLetter, isJavaLetterOrDigit, isLetterOrDigit, isLowerCase, isTitleCase, isUnicodeIdentifierStart, isUpperCase


 Character.isLetterOrDigit

Character.isLetterOrDigit

Syntax
public static boolean isLetterOrDigit( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a letter or digit; false otherwise.
Description
Determines if the specified character is a letter or digit. For a more complete specification that encompasses all Unicode characters, see Gosling, Joy, and Steele, The Java Language Specification.

A character is considered to be a letter if and only if it is specified to be a letter or a digit by the Unicode 2.0 standard (category "Lu", "Ll", "Lt", "Lm", "Lo", or "Nd" in the Unicode specification data file). In other words, isLetterOrDigit is true of a character if and only if either isLetter is true of the character or isDigit is true of the character.

See Also
isDigit, isJavaIdentifierPart, isJavaLetter, isJavaLetterOrDigit, isLetter, isUnicodeIdentifierPart


 Character.isLowerCase

Character.isLowerCase

Syntax
public static boolean isLowerCase( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is lowercase; false otherwise.
Description
Determines if the specified character is a lowercase character. A character is lowercase if it is not in the range '\u2000' through '\u2FFF', the Unicode attribute table does not specify a mapping to lowercase for the character, and at least one of the following is true:
  • The attribute table specifies a mapping to uppercase for the character.
  • The name for the character contains the words "SMALL LETTER".
  • The name for the character contains the words "SMALL LIGATURE".

A character is considered to be lowercase if and only if it is specified to be lowercase by the Unicode 2.0 standard (category "Ll" in the Unicode specification data file).

Of the ISO-LATIN-1 characters (character codes 0x0000 through 0x00FF), the following are lowercase:

 a b c d e f g h i j k l m n o p q r s t u v w x y z
 \u00DF \u00E0 \u00E1 \u00E2 \u00E3 \u00E4 \u00E5 \u00E6 \u00E7
 \u00E8 \u00E9 \u00EA \u00EB \u00EC \u00ED \u00EE \u00EF \u00F0
 \u00F1 \u00F2 \u00F3 \u00F4 \u00F5 \u00F6 \u00F8 \u00F9 \u00FA
 \u00FB \u00FC \u00FD \u00FE \u00FF

Many other Unicode characters are lowercase, too.

See Also
isLowerCase, isTitleCase, toLowerCase


 Character.isSpace

Character.isSpace

Syntax
public static boolean isSpace( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is ISO-LATIN-1 white space; false otherwise.
Description
Note: isSpace() is deprecated. Replaced by isWhitespace(char).

Determines if the specified character is ISO-LATIN-1 white space. This method returns true for the following five characters only:
'\t' | \u0009 | HORIZONTAL TABULATION
'\n' | \u000A | NEW LINE
'\f' | \u000C | FORM FEED
'\r' | \u000D | CARRIAGE RETURN
' ' | \u0020 | SPACE

See Also
isSpaceChar, isWhitespace


 Character.isSpaceChar

Character.isSpaceChar

Syntax
public static boolean isSpaceChar( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a space character; false otherwise.
Description
Determines if the specified character is a Unicode space character. A character is considered to be a space character if and only if it is specified to be a space character by the Unicode 2.0 standard (category "Zs", "Zl, or "Zp" in the Unicode specification data file).

See Also
isWhitespace


 Character.isTitleCase

Character.isTitleCase

Syntax
public static boolean isTitleCase( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is titlecase; false otherwise.
Description
Determines if the specified character is a titlecase character. A character is considered to be titlecase if and only if it is specified to be titlecase by the Unicode 2.0 standard (category "Lt" in the Unicode specification data file).

The printed representations of four Unicode characters look like pairs of Latin letters. For example, there is an uppercase letter that looks like "LJ" and has a corresponding lowercase letter that looks like "lj". A third form, which looks like "Lj", is the appropriate form to use when rendering a word in lowercase with initial capitals, as for a book title.

These are the Unicode characters for which this method returns true:

  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON
  • LATIN CAPITAL LETTER L WITH SMALL LETTER J
  • LATIN CAPITAL LETTER N WITH SMALL LETTER J
  • LATIN CAPITAL LETTER D WITH SMALL LETTER Z

See Also
isLowerCase, isUpperCase, toTitleCase


 Character.isUnicodeIdentifierPart

Character.isUnicodeIdentifierPart

Syntax
public static boolean isUnicodeIdentifierPart( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character may be part of a Unicode identifier; false otherwise.
Description
Determines if the specified character may be part of a Unicode identifier as other than the first character. A character may be part of a Unicode identifier if and only if it is one of the following:
  • a letter
  • a connecting punctuation character (such as "_").
  • a digit
  • a numeric letter (such as a Roman numeral character)
  • a combining mark
  • a non-spacing mark
  • an ignorable control character

See Also
isIdentifierIgnorable, isJavaIdentifierPart, isLetterOrDigit, isUnicodeIdentifierStart


 Character.isUnicodeIdentifierStart

Character.isUnicodeIdentifierStart

Syntax
public static boolean isUnicodeIdentifierStart( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character may start a Unicode identifier; false otherwise.
Description
Determines if the specified character is permissible as the first character in a Unicode identifier. A character may start a Unicode identifier if and only if it is a letter.

See Also
isJavaIdentifierStart, isLetter, isUnicodeIdentifierPart


 Character.isUpperCase

Character.isUpperCase

Syntax
public static boolean isUpperCase( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is uppercase; false otherwise.
Description
Determines if the specified character is an uppercase character. A character is uppercase if it is not in the range '\u2000' through '\u2FFF', the Unicode attribute table does not specify a mapping to uppercase for the character, and at least one of the following is true:
  • The attribute table specifies a mapping to lowercase for the character.
  • The name for the character contains the words "CAPITAL LETTER".
  • The name for the character contains the words "CAPITAL LIGATURE".

Of the ISO-LATIN-1 characters (character codes 0x0000 through 0x00FF), the following are uppercase:

 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
 \u00C0 \u00C1 \u00C2 \u00C3 \u00C4 \u00C5 \u00C6 \u00C7
 \u00C8 \u00C9 \u00CA \u00CB \u00CC \u00CD \u00CE \u00CF \u00D0
 \u00D1 \u00D2 \u00D3 \u00D4 \u00D5 \u00D6 \u00D8 \u00D9 \u00DA
 \u00DB \u00DC \u00DD \u00DE

Many other Unicode characters are uppercase, too.

See Also
isLowerCase, isTitleCase, toUpperCase


 Character.isWhitespace

Character.isWhitespace

Syntax
public static boolean isWhitespace( char ch )
Parameters
ch
the character to be tested.
Returns
true if the character is a Java whitespace character; false otherwise.
Description
Determines if the specified character is white space according to Java. A character is considered to be a Java whitespace character if and only if it satisfies one of the following criteria:
  • It is a Unicode space separator (category "Zs"), but is not a no-break space (\u00A0 or \uFEFF).
  • It is a Unicode line separator (category "Zl").
  • It is a Unicode paragraph separator (category "Zp").
  • It is \u0009, HORIZONTAL TABULATION.
  • It is \u000A, LINE FEED.
  • It is \u000B, VERTICAL TABULATION.
  • It is \u000C, FORM FEED.
  • It is \u000D, CARRIAGE RETURN.
  • It is \u001C, FILE SEPARATOR.
  • It is \u001D, GROUP SEPARATOR.
  • It is \u001E, RECORD SEPARATOR.
  • It is \u001F, UNIT SEPARATOR.

See Also
isSpaceChar


 Character.toLowerCase

Character.toLowerCase

Syntax
public static char toLowerCase( char ch )
Parameters
ch
the character to be converted.
Returns
the lowercase equivalent of the character, if any; otherwise the character itself.
Description
The given character is mapped to its lowercase equivalent; if the character has no lowercase equivalent, the character itself is returned.

A character has a lowercase equivalent if and only if a lowercase mapping is specified for the character in the Unicode attribute table.

Note that some Unicode characters in the range '\u2000' to '\u2FFF' have lowercase mappings; this method does map such characters to their lowercase equivalents even though the method isUpperCase does not return true for such characters.

See Also
isLowerCase, isUpperCase, toTitleCase, toUpperCase


 Character.toString

Character.toString

Syntax
public String toString()
Returns
a string representation of this object.
Description
Returns a String object representing this character's value. Converts this Character object to a string. The result is a string whose length is 1. The string's sole component is the primitive char value represented by this object.

Overrides
toString in class Object


 Character.toTitleCase

Character.toTitleCase

Syntax
public static char toTitleCase( char ch )
Parameters
ch
the character to be converted.
Returns
the titlecase equivalent of the character, if any; otherwise the character itself.
Description
Converts the character argument to titlecase. A character has a titlecase equivalent if and only if a titlecase mapping is specified for the character in the Unicode attribute table.

Note that some Unicode characters in the range '\u2000' through '\u2FFF' have titlecase mappings; this method does map such characters to their titlecase equivalents even though the method isTitleCase does not return true for such characters.

There are only four Unicode characters that are truly titlecase forms that are distinct from uppercase forms. As a rule, if a character has no true titlecase equivalent but does have an uppercase mapping, then the Unicode 2.0 attribute table specifies a titlecase mapping that is the same as the uppercase mapping.

See Also
isTitleCase, toLowerCase, toUpperCase


 Character.toUpperCase

Character.toUpperCase

Syntax
public static char toUpperCase( char ch )
Parameters
ch
the character to be converted.
Returns
the uppercase equivalent of the character, if any; otherwise the character itself.
Description
Converts the character argument to uppercase. A character has an uppercase equivalent if and only if an uppercase mapping is specified for the character in the Unicode attribute table.

Note that some Unicode characters in the range '\u2000' to '\u2000FFF' have uppercase mappings; this method does map such characters to their titlecase equivalents even though the method isLowerCase does not return true for such characters.

See Also
isLowerCase, isUpperCase, toLowerCase, toTitleCase


 Class Class

Class java.lang.Class

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Class

public final class Class
extends Object
implements Serializable

Instances of the class Class represent classes and interfaces in a running Java application. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. Finally, the either primitive Java types (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as Class objects.

There is no public constructor for the class Class. Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

The following example uses a Class object to print the Class name of an object:

     void printClassName(Object obj) {
         System.out.println("The class of " + obj +
                            " is " + obj.getClass().getName());
     }

See Also:
defineClass


 Class Members

Class Members

Class Overview | This Package | All Packages

Methods
Name | Description
forName(String) | Returns the Class object associated with the class with the given string name.
getClasses() | Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.
getClassLoader() | Determines the class loader for the class.
getComponentType() | If this class represents an array type, returns the Class object representing the component type of the array; otherwise returns null.
getConstructor(Class[]) | Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
getConstructors() | Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
getDeclaredClasses() | Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.
getDeclaredConstructor(Class[]) | Returns a Constructor object that reflects the specified declared constructor of the class or interface represented by this Class object.
getDeclaredConstructors() | Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
getDeclaredField(String) | Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
getDeclaredFields() | Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.
getDeclaredMethod(String, Class[]) | Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
getDeclaredMethods() | Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.
getDeclaringClass() | If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class of which it is a member (its declaring class).
getField(String) | Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
getFields() | Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
getInterfaces() | Determines the interfaces implemented by the class or interface represented by this object.
getMethod(String, Class[]) | Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
getMethods() | Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces.
getModifiers() | Returns the Java language modifiers for this class or interface, encoded in an integer.
getName() | Returns the fully-qualified name of the type (class, interface, array, or primitive) represented by this Class object, as a String.
getResource(String) |
getResourceAsStream(String) | Find a resource with a given name.
getSigners() | Get the signers of this class.
getSuperclass() | If this object represents any class other than the class Object, then the object that represents the superclass of that class is returned.
isArray() | If this Class object represents an array type, returns true, otherwise returns false.
isAssignableFrom(Class) | Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
isInstance(Object) | This method is the dynamic equivalent of the Java language instanceof operator.
isInterface() | Determines if the specified Class object represents an interface type.
isPrimitive() | Determines if the specified Class object represents a primitive Java type.
newInstance() | Creates a new instance of a class.
toString() | Converts the object to a string.


 Class.forName

Class.forName

Syntax
public static native Class forName( String className ) throws ClassNotFoundException
Parameters
className
the fully qualified name of the desired class.
Returns
the Class descriptor for the class with the specified name.
Description
Returns the Class object associated with the class with the given string name. Given the fully-qualified name for a class or interface, this method attempts to locate, load and link the class. If it succeeds, returns the Class object representing the class. If it fails, the method throws a ClassNotFoundException.

For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:

    Class t = Class.forName("java.lang.Thread")

Exceptions
ClassNotFoundException if the class could not be found.


 Class.getClasses

Class.getClasses

Syntax
public Class[] getClasses()
Description
Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. This includes public class and interface members inherited from superclasses and public class and interface members declared by the class. Returns an array of length 0 if the class has no public member classes or interfaces, or if this Class object represents a primitive type.


 Class.getClassLoader

Class.getClassLoader

Syntax
public native ClassLoader getClassLoader()
Returns
the class loader that created the class or interface represented by this object, or null if the class was not created by a class loader.
Description
Determines the class loader for the class.

See Also
ClassLoader


 Class.getComponentType

Class.getComponentType

Syntax
public native Class getComponentType()
Description
If this class represents an array type, returns the Class object representing the component type of the array; otherwise returns null.

See Also
Array


 Class.getConstructor

Class.getConstructor

Syntax
public Constructor getConstructor( Class parameterTypes[] ) throws NoSuchMethodException, SecurityException
Description
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order.

The constructor to reflect is located by searching all the constructors of the class represented by this Class object for a public constructor with the exactly the same formal parameter types.

Exceptions
NoSuchMethodException if a matching method is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Constructor


 Class.getConstructors

Class.getConstructors

Syntax
public Constructor[] getConstructors() throws SecurityException
Description
Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. An array of length 0 is returned if the class has no public constructors.

Exceptions
SecurityException if access to the information is denied.
See Also
Constructor


 Class.getDeclaredClasses

Class.getDeclaredClasses

Syntax
public Class[] getDeclaredClasses() throws SecurityException
Description
Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. This includes public, protected, default (package) access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces. Returns an array of length 0 if the class declares no classes or interfaces as members, or if this Class object represents a primitive type.

Exceptions
SecurityException if access to the information is denied.


 Class.getDeclaredConstructor

Class.getDeclaredConstructor

Syntax
public Constructor getDeclaredConstructor( Class parameterTypes[] ) throws NoSuchMethodException, SecurityException
Description
Returns a Constructor object that reflects the specified declared constructor of the class or interface represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order.

Exceptions
NoSuchMethodException if a matching method is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Constructor


 Class.getDeclaredConstructors

Class.getDeclaredConstructors

Syntax
public Constructor[] getDeclaredConstructors() throws SecurityException
Description
Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. Returns an array of length 0 if this Class object represents an interface or a primitive type.

See The Java Language Specification, section 8.2.

Exceptions
SecurityException if access to the information is denied.
See Also
Constructor


 Class.getDeclaredField

Class.getDeclaredField

Syntax
public Field getDeclaredField( String name ) throws NoSuchFieldException, SecurityException
Description
Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field.

Exceptions
NoSuchFieldException if a field with the specified name is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Field


 Class.getDeclaredFields

Class.getDeclaredFields

Syntax
public Field[] getDeclaredFields() throws SecurityException
Description
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields. Returns an array of length 0 if the class or interface declares no fields, or if this Class object represents a primitive type. See The Java Language Specification, sections 8.2 and 8.3.

Exceptions
SecurityException if access to the information is denied.
See Also
Field


 Class.getDeclaredMethod

Class.getDeclaredMethod

Syntax
public Method getDeclaredMethod( String name, Class parameterTypes[] ) throws NoSuchMethodException, SecurityException
Description
Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired method, and the parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order.

Exceptions
NoSuchMethodException if a matching method is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Method


 Class.getDeclaredMethods

Class.getDeclaredMethods

Syntax
public Method[] getDeclaredMethods() throws SecurityException
Description
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods. Returns an array of length 0 if the class or interface declares no methods, or if this Class object represents a primitive type.

See The Java Language Specification, section 8.2.

Exceptions
SecurityException if access to the information is denied.
See Also
Method


 Class.getDeclaringClass

Class.getDeclaringClass

Syntax
public Class getDeclaringClass()
Description
If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class of which it is a member (its declaring class). Returns null if this class or interface is not a member of any other class.


 Class.getField

Class.getField

Syntax
public Field getField( String name ) throws NoSuchFieldException, SecurityException
Description
Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.

The field to be reflected is located by searching all the member fields of the class or interface represented by this Class object for a public field with the specified name.

See The Java Language Specification, sections 8.2 and 8.3.

Exceptions
NoSuchFieldException if a field with the specified name is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Field


 Class.getFields

Class.getFields

Syntax
public Field[] getFields() throws SecurityException
Description
Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. Returns an array of length 0 if the class or interface has no accessible public fields, or if it represents an array type or a primitive type.

Specifically, if this Class object represents a class, returns the public fields of this class and of all its superclasses. If this Class object represents an interface, returns the fields of this interface and of all its superinterfaces. If this Class object represents an array type or a primitive type, returns an array of length 0.

The implicit length field for array types is not reflected by this method. User code should use the methods of class Array to manipulate arrays.

See The Java Language Specification, sections 8.2 and 8.3.

Exceptions
SecurityException if access to the information is denied.
See Also
Field


 Class.getInterfaces

Class.getInterfaces

Syntax
public native Class[] getInterfaces()
Returns
an array of interfaces implemented by this class.
Description
Determines the interfaces implemented by the class or interface represented by this object.

If this object represents a class, the return value is an array containing objects representing all interfaces implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this object.

If this object represents an interface, the array contains objects representing all interfaces extended by the interface. The order of the interface objects in the array corresponds to the order of the interface names in the extends clause of the declaration of the interface represented by this object.

If the class or interface implements no interfaces, the method returns an array of length 0.


 Class.getMethod

Class.getMethod

Syntax
public Method getMethod( String name, Class parameterTypes[] ) throws NoSuchMethodException, SecurityException
Description
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name the desired method, and the parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order.

The method to reflect is located by searching all the member methods of the class or interface represented by this Class object for a public method with the specified name and exactly the same formal parameter types.

See The Java Language Specification, sections 8.2 and 8.4.

Exceptions
NoSuchMethodException if a matching method is not found.
Exceptions
SecurityException if access to the information is denied.
See Also
Method


 Class.getMethods

Class.getMethods

Syntax
public Method[] getMethods() throws SecurityException
Description
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. Returns an array of length 0 if the class or interface has no public member methods.

See The Java Language Specification, sections 8.2 and 8.4.

Exceptions
SecurityException if access to the information is denied.
See Also
Method


 Class.getModifiers

Class.getModifiers

Syntax
public native int getModifiers()
Description
Returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, and interface; they should be decoded using the methods of class Modifier.

The modifier encodings are defined in The Java Virtual Machine Specification, table 4.1.

See Also
Modifier


 Class.getName

Class.getName

Syntax
public native String getName()
Returns
the fully qualified name of the class or interface represented by this object.
Description
Returns the fully-qualified name of the type (class, interface, array, or primitive) represented by this Class object, as a String.


 Class.getResource

Class.getResource

Syntax
public URL getResource( String name )


 Class.getResourceAsStream

Class.getResourceAsStream

Syntax
public InputStream getResourceAsStream( String name )
Description
Find a resource with a given name. Will return null if no resource with this name is found. The rules for searching a resources associated with a given class are implemented by the ClassLoader of the class.

The Class methods delegate to ClassLoader methods, after applying a naming convention: if the resource name starts with "/", it is used as is. Otherwise, the name of the package is prepended, after converting "." to "/".

See Also
ClassLoader


 Class.getSigners

Class.getSigners

Syntax
public native Object[] getSigners()
Description
Get the signers of this class.


 Class.getSuperclass

Class.getSuperclass

Syntax
public native Class getSuperclass()
Returns
the superclass of the class represented by this object.
Description
If this object represents any class other than the class Object, then the object that represents the superclass of that class is returned.

If this object is the one that represents the class Object or this object represents an interface, null is returned.


 Class.isArray

Class.isArray

Syntax
public native boolean isArray()
Description
If this Class object represents an array type, returns true, otherwise returns false.


 Class.isAssignableFrom

Class.isAssignableFrom

Syntax
public native boolean isAssignableFrom( Class cls )
Description
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so, false otherwise. If this Class object represents a primitive type, returns true if the specified Class parameter is exactly this Class object, false otherwise.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

Exceptions
NullPointerException if the specified Class parameter is null.


 Class.isInstance

Class.isInstance

Syntax
public native boolean isInstance( Object obj )
Parameters
obj
The object to check
Description
This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

Specifically, if this Class object represents a declared class, returns true if the specified Object argument is an instance of the represented class (or of any of its subclasses); false otherwise. If this Class object represents an array class, returns true if the specified Object argument can be converted to an object of the array type by an identity conversion or by a widening reference conversion; false otherwise. If this Class object represents an interface, returns true if the class or any superclass of the specified Object argument implements this interface; false otherwise. If this Class object represents a primitive type, returns false.


 Class.isInterface

Class.isInterface

Syntax
public native boolean isInterface()
Returns
true if this object represents an interface; false otherwise.
Description
Determines if the specified Class object represents an interface type.


 Class.isPrimitive

Class.isPrimitive

Syntax
public native boolean isPrimitive()
Description
Determines if the specified Class object represents a primitive Java type.

There are nine predefined Class objects to represent the eight primitive Java types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double, and void.

These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.

See Also
TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE, TYPE


 Class.newInstance

Class.newInstance

Syntax
public native Object newInstance() throws InstantiationException, IllegalAccessException
Returns
a newly allocated instance of the class represented by this object. This is done exactly as if by a new expression with an empty argument list.
Description
Creates a new instance of a class.

Exceptions
IllegalAccessException if the class or initializer is not accessible.
Exceptions
InstantiationException if an application tries to instantiate an abstract class or an interface, or if the instantiation fails for some other reason.


 Class.toString

Class.toString

Syntax
public String toString()
Returns
a string representation of this class object.
Description
Converts the object to a string. The string representation is the string "class" or "interface" followed by a space and then the fully qualified name of the class. If this Class object represents a primitive type, returns the name of the primitive type.

Overrides
toString in class Object


 Class ClassCastException

Class java.lang.ClassCastException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.ClassCastException

public class ClassCastException
extends RuntimeException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

     Object x = new Integer(0);
     System.out.println((String)x);


 ClassCastException Members

ClassCastException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ClassCastException() | Constructs a ClassCastException with no detail message.
ClassCastException(String) | Constructs a ClassCastException with the specified detail message.


 ClassCastException.ClassCastException

ClassCastException.ClassCastException

Syntax 1
public ClassCastException()
Description
Constructs a ClassCastException with no detail message.

Syntax 2
public ClassCastException( String s )
Parameters
s
the detail message.
Description
Constructs a ClassCastException with the specified detail message.


 Class ClassCircularityError

Class java.lang.ClassCircularityError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.ClassCircularityError

public class ClassCircularityError
extends LinkageError

Thrown when a circularity has been detected while initializing a class.


 ClassCircularityError Members

ClassCircularityError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ClassCircularityError() | Constructs a ClassCircularityError with no detail message.
ClassCircularityError(String) | Constructs a ClassCircularityError with the specified detail message.


 ClassCircularityError.ClassCircularityError

ClassCircularityError.ClassCircularityError

Syntax 1
public ClassCircularityError()
Description
Constructs a ClassCircularityError with no detail message.

Syntax 2
public ClassCircularityError( String s )
Parameters
s
the detail message.
Description
Constructs a ClassCircularityError with the specified detail message.


 Class ClassFormatError

Class java.lang.ClassFormatError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.ClassFormatError

public class ClassFormatError
extends LinkageError

Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.


 ClassFormatError Members

ClassFormatError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ClassFormatError() | Constructs a ClassFormatError with no detail message.
ClassFormatError(String) | Constructs a ClassFormatError with the specified detail message.


 ClassFormatError.ClassFormatError

ClassFormatError.ClassFormatError

Syntax 1
public ClassFormatError()
Description
Constructs a ClassFormatError with no detail message.

Syntax 2
public ClassFormatError( String s )
Parameters
s
the detail message.
Description
Constructs a ClassFormatError with the specified detail message.


 Class ClassLoader

Class java.lang.ClassLoader

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.ClassLoader

public abstract class ClassLoader
extends Object

The class ClassLoader is an abstract class. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java Virtual Machine dynamically loads classes.

Normally, the Java Virtual Machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the Virtual Machine loads classes from the directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using the newInstance method in class Class.

The methods and constructors of objects created by a class loader may reference other classes. To determine the class(es) referred to, the Java Virtual Machine calls the loadClass method of the class loader that originally created the class. If the Java Virtual Machine only needs to determine if the class exists and if it does exist to know its superclass, the resolve flag is set to false. However, if an instance of the class is being created or any of its methods are being called, the class must also be resolved. In this case the resolve flag is set to true, and the resolveClass method should be called.

For example, an application could create a network class loader to download class files from a server. Sample code might look like:

    ClassLoader loader = new NetworkClassLoader(host, port);
    Object main = loader.loadClass("Main", true).newInstance();
    . . .

The network class loader subclass must define the method loadClass to load a class from the network. Once it has downloaded the bytes that make up the class, it should use the method defineClass to create a class instance. A sample implementation is:

     class NetworkClassLoader {
         String host;
         int port;
         Hashtable cache = new Hashtable();
         private byte loadClassData(String name)[] {
         // load the class data from the connection
          . . .
         }
         public synchronized Class loadClass(String name,
                                             boolean resolve) {
             Class c = cache.get(name);
             if (c == null) {
                 byte data[] = loadClassData(name);
                 c = defineClass(data, 0, data.length);
                 cache.put(name, c);
             }
             if (resolve)
                 resolveClass(c);
             return c;
         }
     }

See Also:
Class, newInstance, defineClass, loadClass, resolveClass


 ClassLoader Members

ClassLoader Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ClassLoader() | Constructs a new class loader and initializes it.

Methods
Name | Description
defineClass(byte[], int, int) | Converts an array of bytes into an instance of class Class. Deprecated.
defineClass(String, byte[], int, int) | Converts an array of bytes to an instance of class Class.
findLoadedClass(String) |
findSystemClass(String) | Finds the system class with the specified name, loading it in if necessary.
getResource(String) | Find a resource with a given name.
getResourceAsStream(String) | Get an InputStream on a given resource.
getSystemResource(String) | Find a resource with a given name.
getSystemResourceAsStream(String) | Get an InputStream on a given resource..
loadClass(String) | Requests the class loader to load a class with the specified name.
loadClass(String, boolean) | Resolves the specified name to a Class.
resolveClass(Class) | Resolves the class so that an instance of the class can be created, or so that one of its methods can be called.
setSigners(Class, Object[]) | Sets the signers of a class.


 ClassLoader.ClassLoader

ClassLoader.ClassLoader

Syntax
protected ClassLoader()
Description
Constructs a new class loader and initializes it.

If there is a security manager, its checkCreateClassLoader method is called. This may result in a security exception.

Exceptions
SecurityException if the current thread does not have permission to create a new class loader.
See Also
SecurityException, checkCreateClassLoader


 ClassLoader.defineClass

ClassLoader.defineClass

Syntax 1
protected final Class defineClass( byte data[], int offset, int length )
Parameters
data
the bytes that make up the Class.
offset
the start offset of the Class data.
length
the length of the Class data.
Returns
the Class object that was created from the data.
Description
Note: defineClass() is deprecated. Replaced by defineClass(java.lang.String, byte[], int, int).

Converts an array of bytes into an instance of class Class. Before the Class can be used it must be resolved. This method is deprecated in favor of the version that takes a "name" as a first argument, and is more secure.

Exceptions
ClassFormatError if the data does not contain a valid Class.
See Also
loadClass, resolveClass

Syntax 2
protected final Class defineClass( String name, byte data[], int offset, int length )
Parameters
name
the expected name of the class; null if unknown; using '.' and not '/' as separator, and without a trailing ".class" suffix.
data
the bytes that make up the Class.
offset
the start offset of the Class data.
length
the length of the Class data.
Returns
the Class object that was created from the data.
Description
Converts an array of bytes to an instance of class Class. Before the Class can be used it must be resolved.

Exceptions
ClassFormatError if the data does not contain a valid Class.
See Also
loadClass, resolveClass


 ClassLoader.findLoadedClass

ClassLoader.findLoadedClass

Syntax
protected final Class findLoadedClass( String name )


 ClassLoader.findSystemClass

ClassLoader.findSystemClass

Syntax
protected final Class findSystemClass( String name ) throws ClassNotFoundException
Parameters
name
the name of the system class.
Returns
a system class with the given name.
Description
Finds the system class with the specified name, loading it in if necessary.

A system class is a class loaded from the local file system in a platform- dependent way. It has no class loader.

Exceptions
ClassNotFoundException if it could not find a definition for the class.
Exceptions
NoClassDefFoundError if the class is not found.


 ClassLoader.getResource

ClassLoader.getResource

Syntax
public URL getResource( String name )
Parameters
name
the name of the resource, to be used as is.
Returns
an InputStream on the resource, or null if not found.
Description
Find a resource with a given name. The return is a URL to the resource. Doing a getContent() on the URL may return an Image, an AudioClip, or an InputStream.

The class loader can choose what to do to locate the resource.


 ClassLoader.getResourceAsStream

ClassLoader.getResourceAsStream

Syntax
public InputStream getResourceAsStream( String name )
Parameters
name
the name of the resource, to be used as is.
Returns
an InputStream on the resource, or null if not found.
Description
Get an InputStream on a given resource. Will return null if no resource with this name is found.

The class loader can choose what to do to locate the resource.


 ClassLoader.getSystemResource

ClassLoader.getSystemResource

Syntax
public static final URL getSystemResource( String name )
Parameters
name
the name of the resource, to be used as is.
Returns
the URL on the resource, or null if not found.
Description
Find a resource with a given name. The return is a URL to the resource Doing a getContent() on the URL may return an Image, an AudioClip, or an InputStream.

The resource name may be any system resource (e.g. follows CLASSPATH order).


 ClassLoader.getSystemResourceAsStream

ClassLoader.getSystemResourceAsStream

Syntax
public static final InputStream getSystemResourceAsStream( String name )
Parameters
name
the name of the resource, to be used as is.
Returns
an InputStream on the resource, or null if not found.
Description
Get an InputStream on a given resource.. Will return null if no resource with this name is found.

The resource name may be any system resource (e.g. follows CLASSPATH order).


 ClassLoader.loadClass

ClassLoader.loadClass

Syntax 1
public Class loadClass( String name ) throws ClassNotFoundException
Parameters
name
the name of the desired Class.
resolve
true if the Class must be resolved.
Returns
the resulting Class, or null if it was not found.
Description
Requests the class loader to load a class with the specified name. The loadClass method is called by the Java Virtual Machine when a class loaded by a class loader first references another class. Every subclass of class ClassLoader must define this method.

If the resolve flag is true, the method should call the resolveClass method on the resulting class object.

Class loaders should use a hashtable or other cache to avoid defining classes with the same name multiple times.

Exceptions
ClassNotFoundException if the class loader cannot find a definition for the class.

Syntax 2
protected abstract Class loadClass( String name, boolean resolve ) throws ClassNotFoundException
Parameters
name
the name of the desired Class.
resolve
true if the Class needs to be resolved.
Returns
the resulting Class, or null if it was not found.
Description
Resolves the specified name to a Class. The method loadClass() is called by the virtual machine. As an abstract method, loadClass() must be defined in a subclass of ClassLoader. By using a Hashtable, you can avoid loading the same Class more than once.

Exceptions
ClassNotFoundException if the class loader cannot find a definition for the class.
See Also
Hashtable


 ClassLoader.resolveClass

ClassLoader.resolveClass

Syntax
protected final void resolveClass( Class c )
Parameters
c
the Class instance to be resolved.
Description
Resolves the class so that an instance of the class can be created, or so that one of its methods can be called. This method should be called by loadClass if the resolve flag is true.

See Also
defineClass


 ClassLoader.setSigners

ClassLoader.setSigners

Syntax
protected final void setSigners( Class cl, Object signers[] )
Description
Sets the signers of a class. This is called after defining a class, by signature-aware class loading code.


 Class ClassNotFoundException

Class java.lang.ClassNotFoundException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.ClassNotFoundException

public class ClassNotFoundException
extends Exception

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.

but no definition for the class with the specifed name could be found.

See Also:
forName, findSystemClass, loadClass


 ClassNotFoundException Members

ClassNotFoundException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ClassNotFoundException() | Constructs a ClassNotFoundException with no detail message.
ClassNotFoundException(String) | Constructs a ClassNotFoundException with the specified detail message.


 ClassNotFoundException.ClassNotFoundException

ClassNotFoundException.ClassNotFoundException

Syntax 1
public ClassNotFoundException()
Description
Constructs a ClassNotFoundException with no detail message.

Syntax 2
public ClassNotFoundException( String s )
Parameters
s
the detail message.
Description
Constructs a ClassNotFoundException with the specified detail message.


 Class CloneNotSupportedException

Class java.lang.CloneNotSupportedException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.CloneNotSupportedException

public class CloneNotSupportedException
extends Exception

Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.

Applications that override the clone method can also throw this exception to indicate that an object could not or should not be cloned.

See Also:
Cloneable, clone


 CloneNotSupportedException Members

CloneNotSupportedException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CloneNotSupportedException() | Constructs a CloneNotSupportedException with no detail message.
CloneNotSupportedException(String) | Constructs a CloneNotSupportedException with the specified detail message.


 CloneNotSupportedException.CloneNotSupportedException

CloneNotSupportedException.CloneNotSupportedException

Syntax 1
public CloneNotSupportedException()
Description
Constructs a CloneNotSupportedException with no detail message.

Syntax 2
public CloneNotSupportedException( String s )
Parameters
s
the detail message.
Description
Constructs a CloneNotSupportedException with the specified detail message.


 Interface Cloneable

Interface java.lang.Cloneable

This Package | All Packages

public interface Cloneable

A class implements the Cloneable interface to indicate to the clone method in class Object that it is legal for that method to make a field-for-field copy of instances of that class.

Attempts to clone instances that do not implement the Cloneable interface result in the exception CloneNotSupportedException being thrown.

See Also:
CloneNotSupportedException


 Class Compiler

Class java.lang.Compiler

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Compiler

public final class Compiler
extends Object

The Compiler class is provided to support Java-to-native-code compilers and related services. By design, the Compiler class does nothing; it serves as a placeholder for a JIT compiler implementation.

When the Java Virtual Machine first starts, it determines if the system property java.compiler exists. (System properties are accessible through getProperty and , a method defined by the System class.) If so, it is assumed to be the name of a library (with a platform-dependent exact location and type); the loadLibrary method in class System is called to load that library. If this loading succeeds, the function named java_lang_Compiler_start() in that library is called.

If no compiler is available, these methods do nothing.

See Also:
getProperty, getProperty, loadLibrary


 Compiler Members

Compiler Members

Class Overview | This Package | All Packages

Methods
Name | Description
command(Object) | Examines the argument type and its fields and perform some documented operation.
compileClass(Class) | Compiles the specified class.
compileClasses(String) | Compiles all classes whose name matches the specified string.
disable() | Cause the Compiler to cease operation.
enable() | Cause the Compiler to resume operation.


 Compiler.command

Compiler.command

Syntax
public static native Object command( Object any )
Parameters
any
an argument.
Returns
a compiler-specific value, or null if no compiler is available.
Description
Examines the argument type and its fields and perform some documented operation. No specific operations are required.


 Compiler.compileClass

Compiler.compileClass

Syntax
public static native boolean compileClass( Class clazz )
Parameters
clazz
a class.
Returns
true if the compilation succeeded; false if the compilation failed or no compiler is available.
Description
Compiles the specified class.


 Compiler.compileClasses

Compiler.compileClasses

Syntax
public static native boolean compileClasses( String string )
Parameters
string
the name of the classes to compile.
Returns
true if the compilation succeeded; false if the compilation failed or no compiler is available.
Description
Compiles all classes whose name matches the specified string.


 Compiler.disable

Compiler.disable

Syntax
public static native void disable()
Description
Cause the Compiler to cease operation.


 Compiler.enable

Compiler.enable

Syntax
public static native void enable()
Description
Cause the Compiler to resume operation.


 Class Double

Class java.lang.Double

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Double

public final class Double
extends Number

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.


 Double Members

Double Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The largest positive value of type double.
MIN_VALUE | The smallest positive value of type double.
NaN | A NaN value of type double.
NEGATIVE_INFINITY | The negative infinity of type double.
POSITIVE_INFINITY | The positive infinity of type double.
TYPE | The Class object representing the primitive type double.

Constructors
Name | Description
Double(double) | Constructs a newly allocated Double object that represents the primitive double argument.
Double(String) | Constructs a newly allocated Double object that represents the floating- point value of type double represented by the string.

Methods
Name | Description
byteValue() | Returns the value of this Double as a byte (by casting to a byte).
doubleToLongBits(double) | Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout.
doubleValue() | Returns the double value of this Double.
equals(Object) | Compares this object against the specified object.
floatValue() | Returns the float value of this Double.
hashCode() | Returns a hashcode for this Double.
intValue() | Returns the integer value of this Double (by casting to an int).
isInfinite() | Returns true if this Double value is infinitely large in magnitude.
isInfinite(double) | Returns true if the specified number is infinitely large in magnitude.
isNaN() | Returns true if this Double value is the special Not-a-Number (NaN) value.
isNaN(double) | Returns true if the specified number is the special Not-a-Number (NaN) value.
longBitsToDouble(long) | Returns the double-float corresponding to a given bit represention.
longValue() | Returns the long value of this Double (by casting to a long).
shortValue() | Returns the value of this Double as a short (by casting to a short).
toString() | Returns a String representation of this Double object.
toString(double) | Creates a string representation of the double argument.
valueOf(String) | Returns a new Double value initialized to the value represented by the specified String.


 Double.MAX_VALUE

Double.MAX_VALUE

Syntax
public static final double MAX_VALUE
Description
The largest positive value of type double.


 Double.MIN_VALUE

Double.MIN_VALUE

Syntax
public static final double MIN_VALUE
Description
The smallest positive value of type double.


 Double.NaN

Double.NaN

Syntax
public static final double NaN
Description
A NaN value of type double.


 Double.NEGATIVE_INFINITY

Double.NEGATIVE_INFINITY

Syntax
public static final double NEGATIVE_INFINITY
Description
The negative infinity of type double.


 Double.POSITIVE_INFINITY

Double.POSITIVE_INFINITY

Syntax
public static final double POSITIVE_INFINITY
Description
The positive infinity of type double.


 Double.TYPE

Double.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type double.


 Double.Double

Double.Double

Syntax 1
public Double( double value )
Parameters
value
the value to be represented by the Double.
Description
Constructs a newly allocated Double object that represents the primitive double argument.

Syntax 2
public Double( String s ) throws NumberFormatException
Parameters
s
a string to be converted to a Double.
Description
Constructs a newly allocated Double object that represents the floating- point value of type double represented by the string. The string is converted to a double value as if by the valueOf method.

Exceptions
NumberFormatException if the string does not contain a parsable number.
See Also
valueOf


 Double.byteValue

Double.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Double as a byte (by casting to a byte).

Overrides
byteValue in class Number


 Double.doubleToLongBits

Double.doubleToLongBits

Syntax
public static native long doubleToLongBits( double value )
Parameters
value
a double precision floating-point number.
Returns
the bits that represent the floating-point number.
Description
Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout.

Bit 63 represents the sign of the floating-point number. Bits 62-52 represent the exponent. Bits 51-0 represent the significand (sometimes called the mantissa) of the floating-point number.

If the argument is positive infinity, the result is 0x7ff0000000000000L.

If the argument is negative infinity, the result is 0xfff0000000000000L.

If the argument is NaN, the result is 0x7ff8000000000000L.


 Double.doubleValue

Double.doubleValue

Syntax
public double doubleValue()
Returns
the double value represented by this object.
Description
Returns the double value of this Double.

Overrides
doubleValue in class Number


 Double.equals

Double.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object. The result is true if and only if the argument is not null and is a Double object that represents a double that has the identical bit pattern to the bit pattern of the double represented by this object.

Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

    d1.doubleValue() == d2.doubleValue()

also has the value true. However, there are two exceptions:

  • If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false.
  • If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true.

Overrides
equals in class Object


 Double.floatValue

Double.floatValue

Syntax
public float floatValue()
Returns
the double value represented by this object is converted to type float and the result of the conversion is returned.
Description
Returns the float value of this Double.

Overrides
floatValue in class Number


 Double.hashCode

Double.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hashcode for this Double.

Overrides
hashCode in class Object


 Double.intValue

Double.intValue

Syntax
public int intValue()
Returns
the double value represented by this object is converted to type int and the result of the conversion is returned.
Description
Returns the integer value of this Double (by casting to an int).

Overrides
intValue in class Number


 Double.isInfinite

Double.isInfinite

Syntax
public static boolean isInfinite( double v )
Parameters
v
the value to be tested.
Returns
true if the value of the argument is positive infinity or negative infinity; false otherwise.
Description
Returns true if the specified number is infinitely large in magnitude.


 Double.isInfinite

Double.isInfinite

Syntax
public boolean isInfinite()
Returns
true if the value represented by this object is positive infinity or negative infinity; false otherwise.
Description
Returns true if this Double value is infinitely large in magnitude.


 Double.isNaN

Double.isNaN

Syntax
public static boolean isNaN( double v )
Parameters
v
the value to be tested.
Returns
true if the value of the argument is NaN; false otherwise.
Description
Returns true if the specified number is the special Not-a-Number (NaN) value.


 Double.isNaN

Double.isNaN

Syntax
public boolean isNaN()
Returns
true if the value represented by this object is NaN; false otherwise.
Description
Returns true if this Double value is the special Not-a-Number (NaN) value.


 Double.longBitsToDouble

Double.longBitsToDouble

Syntax
public static native double longBitsToDouble( long bits )
Parameters
bits
any long integer.
Returns
the double floating-point value with the same bit pattern.
Description
Returns the double-float corresponding to a given bit represention. The argument is considered to be a representation of a floating-point value according to the IEEE 754 floating-point "double precision" bit layout. That floating-point value is returned as the result.

If the argument is 0x7f80000000000000L, the result is positive infinity.

If the argument is 0xff80000000000000L, the result is negative infinity.

If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result is NaN. All IEEE 754 NaN values are, in effect, lumped together by the Java language into a single value.


 Double.longValue

Double.longValue

Syntax
public long longValue()
Returns
the double value represented by this object is converted to type long and the result of the conversion is returned.
Description
Returns the long value of this Double (by casting to a long).

Overrides
longValue in class Number


 Double.shortValue

Double.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Double as a short (by casting to a short).

Overrides
shortValue in class Number


 Double.toString

Double.toString

Syntax
public static String toString( double d )
Parameters
d
the double to be converted.
Returns
a string representation of the argument.
Description
Creates a string representation of the double argument.

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.

If d is in the range 10-3 <= |d| <=107, then it is converted to a string in the style [-]ddd.ddd. Otherwise, it is converted to a string in the style [-]m.ddddE±xx.

There is always a minimum of one digit after the decimal point. The number of digits is the minimum needed to uniquely distinguish the argument value from adjacent values of type double.


 Double.toString

Double.toString

Syntax
public String toString()
Returns
a String representation of this object.
Description
Returns a String representation of this Double object. The primitive double value represented by this object is converted to a string exactly as if by the method toString of one argument.

Overrides
toString in class Object
See Also
toString


 Double.valueOf

Double.valueOf

Syntax
public static Double valueOf( String s ) throws NumberFormatException
Parameters
s
the string to be parsed.
Returns
a newly constructed Double initialized to the value represented by the string argument.
Description
Returns a new Double value initialized to the value represented by the specified String.

Exceptions
NumberFormatException if the string does not contain a parsable number.


 Class Error

Class java.lang.Error

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error

public class Error
extends Throwable

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

See Also:
ThreadDeath


 Error Members

Error Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Error() | Constructs an Error with no specified detail message.
Error(String) | Constructs an Error with the specified detail message.


 Error.Error

Error.Error

Syntax 1
public Error()
Description
Constructs an Error with no specified detail message.

Syntax 2
public Error( String s )
Parameters
s
the detail message.
Description
Constructs an Error with the specified detail message.


 Class Exception

Class java.lang.Exception

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception

public class Exception
extends Throwable

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

See Also:
Error


 Exception Members

Exception Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Exception() | Constructs an Exception with no specified detail message.
Exception(String) | Constructs an Exception with the specified detail message.


 Exception.Exception

Exception.Exception

Syntax 1
public Exception()
Description
Constructs an Exception with no specified detail message.

Syntax 2
public Exception( String s )
Parameters
s
the detail message.
Description
Constructs an Exception with the specified detail message.


 Class ExceptionInInitializerError

Class java.lang.ExceptionInInitializerError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.ExceptionInInitializerError

public class ExceptionInInitializerError
extends LinkageError

Signals that an unexpected exception has occurred in a static initializer.


 ExceptionInInitializerError Members

ExceptionInInitializerError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ExceptionInInitializerError() | Constructs an ExceptionInInitializerError with no detail message.
ExceptionInInitializerError(String) | Constructs a ExceptionInInitializerError with the specified detail message.
ExceptionInInitializerError(Throwable) | Constructs a new ExceptionInInitializerError class initialized to the specific throwable

Methods
Name | Description
getException() | Returns the exception that occurred during a static initialization that caused this Error to be created.


 ExceptionInInitializerError.ExceptionInInitializerError

ExceptionInInitializerError.ExceptionInInitializerError

Syntax 1
public ExceptionInInitializerError()
Description
Constructs an ExceptionInInitializerError with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public ExceptionInInitializerError( Throwable thrown )
Parameters
thrown
The exception thrown
Description
Constructs a new ExceptionInInitializerError class initialized to the specific throwable

Syntax 3
public ExceptionInInitializerError( String s )
Parameters
s
the detail message
Description
Constructs a ExceptionInInitializerError with the specified detail message. A detail message is a String that describes this particular exception.


 ExceptionInInitializerError.getException

ExceptionInInitializerError.getException

Syntax
public Throwable getException()
Description
Returns the exception that occurred during a static initialization that caused this Error to be created.


 Class Float

Class java.lang.Float

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Float

public final class Float
extends Number

The Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.

In addition, this class provides several methods for converting a float to a String and a String to a float, as well as other constants and methods useful when dealing with a float.


 Float Members

Float Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The largest positive value of type float.
MIN_VALUE | The smallest positive value of type float.
NaN | The NaN value of type float.
NEGATIVE_INFINITY | The negative infinity of type float.
POSITIVE_INFINITY | The positive infinity of type float.
TYPE | The Class object representing the primitive type float.

Constructors
Name | Description
Float(double) | Constructs a newly allocated Floatobject that represents the argument converted to type float.
Float(float) | Constructs a newly allocated Float object that represents the primitive float argument.
Float(String) | Constructs a newly allocated Float object that represents the floating- point value of type float represented by the string.

Methods
Name | Description
byteValue() | Returns the value of this Float as a byte (by casting to a byte).
doubleValue() | Returns the double value of this Float.
equals(Object) | Compares this object against some other object.
floatToIntBits(float) | Returns the bit represention of a single-float value.
floatValue() | Returns the float value of this Float object.
hashCode() | Returns a hashcode for this Float.
intBitsToFloat(int) | Returns the single-float corresponding to a given bit represention.
intValue() | Returns the integer value of this Float (by casting to an int).
isInfinite() | Returns true if this Float value is infinitely large in magnitude.
isInfinite(float) | Returns true if the specified number is infinitely large in magnitude.
isNaN() | Returns true if this Float value is Not-a-Number (NaN).
isNaN(float) | Returns true if the specified number is the special Not-a-Number (NaN) value.
longValue() | Returns the long value of this Float (by casting to a long).
shortValue() | Returns the value of this Float as a short (by casting to a short).
toString() | Returns a String representation of this Float object.
toString(float) | Returns a String representation for the specified float value.
valueOf(String) | Returns the floating point value represented by the specified String.


 Float.MAX_VALUE

Float.MAX_VALUE

Syntax
public static final float MAX_VALUE
Description
The largest positive value of type float.


 Float.MIN_VALUE

Float.MIN_VALUE

Syntax
public static final float MIN_VALUE
Description
The smallest positive value of type float.


 Float.NaN

Float.NaN

Syntax
public static final float NaN
Description
The NaN value of type float.


 Float.NEGATIVE_INFINITY

Float.NEGATIVE_INFINITY

Syntax
public static final float NEGATIVE_INFINITY
Description
The negative infinity of type float.


 Float.POSITIVE_INFINITY

Float.POSITIVE_INFINITY

Syntax
public static final float POSITIVE_INFINITY
Description
The positive infinity of type float.


 Float.TYPE

Float.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type float.


 Float.Float

Float.Float

Syntax 1
public Float( float value )
Parameters
value
the value to be represented by the Float.
Description
Constructs a newly allocated Float object that represents the primitive float argument.

Syntax 2
public Float( double value )
Parameters
value
the value to be represented by the Float.
Description
Constructs a newly allocated Floatobject that represents the argument converted to type float.

Syntax 3
public Float( String s ) throws NumberFormatException
Parameters
s
a string to be converted to a Float.
Description
Constructs a newly allocated Float object that represents the floating- point value of type float represented by the string. The string is converted to a float value as if by the valueOf method.

Exceptions
NumberFormatException if the string does not contain a parsable number.
See Also
valueOf


 Float.byteValue

Float.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Float as a byte (by casting to a byte).

Overrides
byteValue in class Number


 Float.doubleValue

Float.doubleValue

Syntax
public double doubleValue()
Description
Returns the double value of this Float.

Overrides
doubleValue in class Number


 Float.equals

Float.equals

Syntax
public boolean equals( Object obj )
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against some other object. The result is true if and only if the argument is not null and is a Float object that represents a float that has the identical bit pattern to the bit pattern of the float represented by this object.

Note that in most cases, for two instances of class Float, f1 and f2, the value of f1.equals(f2) is true if and only if

    f1.floatValue() == f2.floatValue()

also has the value true. However, there are two exceptions:

  • If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false.
  • If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true.

Overrides
equals in class Object
See Also
floatToIntBits


 Float.floatToIntBits

Float.floatToIntBits

Syntax
public static native int floatToIntBits( float value )
Parameters
value
a floating-point number.
Returns
the bits that represent the floating-point number.
Description
Returns the bit represention of a single-float value. The result is a representation of the floating-point argument according to the IEEE 754 floating-point "single precision" bit layout.

Bit 31 represents the sign of the floating-point number. Bits 30-23 represent the exponent. Bits 22-0 represent the significand (sometimes called the mantissa) of the floating-point number.

If the argument is positive infinity, the result is 0x7f800000.

If the argument is negative infinity, the result is 0xff800000.

If the argument is NaN, the result is 0x7fc00000.


 Float.floatValue

Float.floatValue

Syntax
public float floatValue()
Returns
the float value represented by this object.
Description
Returns the float value of this Float object.

Overrides
floatValue in class Number


 Float.hashCode

Float.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hashcode for this Float.

Overrides
hashCode in class Object


 Float.intBitsToFloat

Float.intBitsToFloat

Syntax
public static native float intBitsToFloat( int bits )
Parameters
bits
an integer.
Returns
the single-format floating-point value with the same bit pattern.
Description
Returns the single-float corresponding to a given bit represention. The argument is considered to be a representation of a floating-point value according to the IEEE 754 floating-point "single precision" bit layout.

If the argument is 0x7f800000, the result is positive infinity.

If the argument is 0xff800000, the result is negative infinity.

If the argument is any value in the range 0x7f800001 through 0x7f8fffff or in the range 0xff800001 through 0xff8fffff, the result is NaN. All IEEE 754 NaN values are, in effect, lumped together by the Java language into a single value.


 Float.intValue

Float.intValue

Syntax
public int intValue()
Returns
the float value represented by this object converted to type int and the result of the conversion is returned.
Description
Returns the integer value of this Float (by casting to an int).

Overrides
intValue in class Number


 Float.isInfinite

Float.isInfinite

Syntax
public static boolean isInfinite( float v )
Parameters
v
the value to be tested.
Returns
true if the argument is positive infinity or negative infinity; false otherwise.
Description
Returns true if the specified number is infinitely large in magnitude.


 Float.isInfinite

Float.isInfinite

Syntax
public boolean isInfinite()
Returns
true if the value represented by this object is positive infinity or negative infinity; false otherwise.
Description
Returns true if this Float value is infinitely large in magnitude.


 Float.isNaN

Float.isNaN

Syntax
public static boolean isNaN( float v )
Parameters
v
the value to be tested.
Returns
true if the argument is NaN; false otherwise.
Description
Returns true if the specified number is the special Not-a-Number (NaN) value.


 Float.isNaN

Float.isNaN

Syntax
public boolean isNaN()
Returns
true if the value represented by this object is NaN; false otherwise.
Description
Returns true if this Float value is Not-a-Number (NaN).


 Float.longValue

Float.longValue

Syntax
public long longValue()
Returns
the float value represented by this object is converted to type long and the result of the conversion is returned.
Description
Returns the long value of this Float (by casting to a long).

Overrides
longValue in class Number


 Float.shortValue

Float.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Float as a short (by casting to a short).

Overrides
shortValue in class Number


 Float.toString

Float.toString

Syntax
public static String toString( float f )
Parameters
d
the float to be converted.
Returns
a string representation of the argument.
Description
Returns a String representation for the specified 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.

If d is in the range 10-3 <= |d| <= 107, then it is converted to a String in the style [-]ddd.ddd. Otherwise, it is converted to a string in the style [-]m.ddddE±xx.

There is always a minimum of 1 digit after the decimal point. The number of digits is the minimum needed to uniquely distinguish the argument value from adjacent values of type float.


 Float.toString

Float.toString

Syntax
public String toString()
Returns
a String representation of this object.
Description
Returns a String representation of this Float object. The primitive float value represented by this object is converted to a String exactly as if by the method toString of one argument.

Overrides
toString in class Object
See Also
toString


 Float.valueOf

Float.valueOf

Syntax
public static Float valueOf( String s ) throws NumberFormatException
Parameters
s
the string to be parsed.
Returns
a newly constructed Float initialized to the value represented by the String argument.
Description
Returns the floating point value represented by the specified String.

Exceptions
NumberFormatException if the string does not contain a parsable number.


 Class IllegalAccessError

Class java.lang.IllegalAccessError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError
                                   |
                                   +----java.lang.IllegalAccessError

public class IllegalAccessError
extends IncompatibleClassChangeError

Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.


 IllegalAccessError Members

IllegalAccessError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalAccessError() | Constructs an IllegalAccessError with no detail message.
IllegalAccessError(String) | Constructs an IllegalAccessError with the specified detail message.


 IllegalAccessError.IllegalAccessError

IllegalAccessError.IllegalAccessError

Syntax 1
public IllegalAccessError()
Description
Constructs an IllegalAccessError with no detail message.

Syntax 2
public IllegalAccessError( String s )
Parameters
s
the detail message.
Description
Constructs an IllegalAccessError with the specified detail message.


 Class IllegalAccessException

Class java.lang.IllegalAccessException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.IllegalAccessException

public class IllegalAccessException
extends Exception

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but the currently executing method does not have access to the definition of the specified class, because the class is not public and in another package.

An instance of this class can also be thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the current method does not have access to the appropriate zero-argument constructor.

See Also:
forName, newInstance, findSystemClass, loadClass


 IllegalAccessException Members

IllegalAccessException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalAccessException() | Constructs an IllegalAccessException without a detail message.
IllegalAccessException(String) | Constructs an IllegalAccessException with a detail message.


 IllegalAccessException.IllegalAccessException

IllegalAccessException.IllegalAccessException

Syntax 1
public IllegalAccessException()
Description
Constructs an IllegalAccessException without a detail message.

Syntax 2
public IllegalAccessException( String s )
Parameters
s
the detail message.
Description
Constructs an IllegalAccessException with a detail message.


 Class IllegalArgumentException

Class java.lang.IllegalArgumentException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalArgumentException

public class IllegalArgumentException
extends RuntimeException

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

See Also:
setPriority


 IllegalArgumentException Members

IllegalArgumentException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalArgumentException() | Constructs an IllegalArgumentException with no detail message.
IllegalArgumentException(String) | Constructs an IllegalArgumentException with the specified detail message.


 IllegalArgumentException.IllegalArgumentException

IllegalArgumentException.IllegalArgumentException

Syntax 1
public IllegalArgumentException()
Description
Constructs an IllegalArgumentException with no detail message.

Syntax 2
public IllegalArgumentException( String s )
Parameters
s
the detail message.
Description
Constructs an IllegalArgumentException with the specified detail message.


 Class IllegalMonitorStateException

Class java.lang.IllegalMonitorStateException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalMonitorStateException

public class IllegalMonitorStateException
extends RuntimeException

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

See Also:
notify, notifyAll, wait, wait, wait


 IllegalMonitorStateException Members

IllegalMonitorStateException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalMonitorStateException() | Constructs an IllegalMonitorStateException with no detail message.
IllegalMonitorStateException(String) | Constructs an IllegalMonitorStateException with the specified detail message.


 IllegalMonitorStateException.IllegalMonitorStateException

IllegalMonitorStateException.IllegalMonitorStateException

Syntax 1
public IllegalMonitorStateException()
Description
Constructs an IllegalMonitorStateException with no detail message.

Syntax 2
public IllegalMonitorStateException( String s )
Parameters
s
the detail message.
Description
Constructs an IllegalMonitorStateException with the specified detail message.


 Class IllegalStateException

Class java.lang.IllegalStateException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalStateException

public class IllegalStateException
extends RuntimeException

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.


 IllegalStateException Members

IllegalStateException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalStateException() | Constructs an IllegalStateException with no detail message.
IllegalStateException(String) | Constructs an IllegalStateException with the specified detail message.


 IllegalStateException.IllegalStateException

IllegalStateException.IllegalStateException

Syntax 1
public IllegalStateException()
Description
Constructs an IllegalStateException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public IllegalStateException( String s )
Parameters
s
the String that contains a detailed message
Description
Constructs an IllegalStateException with the specified detail message. A detail message is a String that describes this particular exception.


 Class IllegalThreadStateException

Class java.lang.IllegalThreadStateException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalArgumentException
                                   |
                                   +----java.lang.IllegalThreadStateException

public class IllegalThreadStateException
extends IllegalArgumentException

Thrown to indicate that a thread is not in an appropriate state for the requested operation. See, for example, the suspend and resume methods in class Thread.

See Also:
resume, suspend


 IllegalThreadStateException Members

IllegalThreadStateException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IllegalThreadStateException() | Constructs an IllegalThreadStateException with no detail message.
IllegalThreadStateException(String) | Constructs an IllegalThreadStateException with the specified detail message.


 IllegalThreadStateException.IllegalThreadStateException

IllegalThreadStateException.IllegalThreadStateException

Syntax 1
public IllegalThreadStateException()
Description
Constructs an IllegalThreadStateException with no detail message.

Syntax 2
public IllegalThreadStateException( String s )
Parameters
s
the detail message.
Description
Constructs an IllegalThreadStateException with the specified detail message.


 Class IncompatibleClassChangeError

Class java.lang.IncompatibleClassChangeError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError

public class IncompatibleClassChangeError
extends LinkageError

Thrown when an incompatible class change has occurred to some class definition. The definition of some class, on which the currently executing method depends, has since changed.


 IncompatibleClassChangeError Members

IncompatibleClassChangeError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IncompatibleClassChangeError() | Constructs an IncompatibleClassChangeError with no detail message.
IncompatibleClassChangeError(String) | Constructs an IncompatibleClassChangeError with the specified detail message.


 IncompatibleClassChangeError.IncompatibleClassChangeError

IncompatibleClassChangeError.IncompatibleClassChangeError

Syntax 1
public IncompatibleClassChangeError()
Description
Constructs an IncompatibleClassChangeError with no detail message.

Syntax 2
public IncompatibleClassChangeError( String s )
Parameters
s
the detail message.
Description
Constructs an IncompatibleClassChangeError with the specified detail message.


 Class IndexOutOfBoundsException

Class java.lang.IndexOutOfBoundsException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IndexOutOfBoundsException

public class IndexOutOfBoundsException
extends RuntimeException

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

Applications can subclass this class to indicate similar exceptions.


 IndexOutOfBoundsException Members

IndexOutOfBoundsException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IndexOutOfBoundsException() | Constructs an IndexOutOfBoundsException with no detail message.
IndexOutOfBoundsException(String) | Constructs an IndexOutOfBoundsException with the specified detail message.


 IndexOutOfBoundsException.IndexOutOfBoundsException

IndexOutOfBoundsException.IndexOutOfBoundsException

Syntax 1
public IndexOutOfBoundsException()
Description
Constructs an IndexOutOfBoundsException with no detail message.

Syntax 2
public IndexOutOfBoundsException( String s )
Parameters
s
the detail message.
Description
Constructs an IndexOutOfBoundsException with the specified detail message.


 Class InstantiationError

Class java.lang.InstantiationError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError
                                   |
                                   +----java.lang.InstantiationError

public class InstantiationError
extends IncompatibleClassChangeError

Thrown when an application tries to use the Java new construct to instantiate an abstract class or an interface.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.


 InstantiationError Members

InstantiationError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InstantiationError() | Constructs an InstantiationError with no detail message.
InstantiationError(String) | Constructs an InstantiationError with the specified detail message.


 InstantiationError.InstantiationError

InstantiationError.InstantiationError

Syntax 1
public InstantiationError()
Description
Constructs an InstantiationError with no detail message.

Syntax 2
public InstantiationError( String s )
Parameters
s
the detail message.
Description
Constructs an InstantiationError with the specified detail message.


 Class InstantiationException

Class java.lang.InstantiationException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.InstantiationException

public class InstantiationException
extends Exception

Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.

See Also:
newInstance


 InstantiationException Members

InstantiationException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InstantiationException() | Constructs an InstantiationException with no detail message.
InstantiationException(String) | Constructs an InstantiationException with the specified detail message.


 InstantiationException.InstantiationException

InstantiationException.InstantiationException

Syntax 1
public InstantiationException()
Description
Constructs an InstantiationException with no detail message.

Syntax 2
public InstantiationException( String s )
Parameters
s
the detail message.
Description
Constructs an InstantiationException with the specified detail message.


 Class Integer

Class java.lang.Integer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Integer

public final class Integer
extends Number

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.


 Integer Members

Integer Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The largest value of type int.
MIN_VALUE | The smallest value of type int.
TYPE | The Class object representing the primitive type int.

Constructors
Name | Description
Integer(int) | Constructs a newly allocated Integer object that represents the primitive int argument.
Integer(String) | Constructs a newly allocated Integer object that represents the value represented by the string.

Methods
Name | Description
byteValue() | Returns the value of this Integer as a byte.
decode(String) | Decodes a string into an Integer.
doubleValue() | Returns the value of this Integer as a double.
equals(Object) | Compares this object to the specified object.
floatValue() | Returns the value of this Integer as a float.
getInteger(String) | Determines the integer value of the system property with the specified name.
getInteger(String, int) | Determines the integer value of the system property with the specified name.
getInteger(String, Integer) | Determines the integer value of the system property with the specified name.
hashCode() | Returns a hashcode for this Integer.
intValue() | Returns the value of this Integer as an int.
longValue() | Returns the value of this Integer as a long.
parseInt(String) | Parses the string argument as a signed decimal integer.
parseInt(String, int) | Parses the string argument as a signed integer in the radix specified by the second argument.
shortValue() | Returns the value of this Integer as a short.
toBinaryString(int) | Creates a string representation of the integer argument as an unsigned integer in base 2.
toHexString(int) | Creates a string representation of the integer argument as an unsigned integer in base 16.
toOctalString(int) | Creates a string representation of the integer argument as an unsigned integer in base 8.
toString() | Returns a String object representing this Integer's value.
toString(int) | Returns a new String object representing the specified integer.
toString(int, int) | Creates a string representation of the first argument in the radix specified by the second argument.
valueOf(String) | Returns a new Integer object initialized to the value of the specified String.
valueOf(String, int) | Returns a new Integer object initialized to the value of the specified String.


 Integer.MAX_VALUE

Integer.MAX_VALUE

Syntax
public static final int MAX_VALUE
Description
The largest value of type int.


 Integer.MIN_VALUE

Integer.MIN_VALUE

Syntax
public static final int MIN_VALUE
Description
The smallest value of type int.


 Integer.TYPE

Integer.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type int.


 Integer.Integer

Integer.Integer

Syntax 1
public Integer( int value )
Parameters
value
the value to be represented by the Integer.
Description
Constructs a newly allocated Integer object that represents the primitive int argument.

Syntax 2
public Integer( String s ) throws NumberFormatException
Parameters
s
the String to be converted to an Integer.
Description
Constructs a newly allocated Integer object that represents the value represented by the string. The string is converted to an int value as if by the valueOf method.

Exceptions
NumberFormatException if the String does not contain a parsable integer.
See Also
valueOf


 Integer.byteValue

Integer.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Integer as a byte.

Overrides
byteValue in class Number


 Integer.decode

Integer.decode

Syntax
public static Integer decode( String nm ) throws NumberFormatException
Parameters
nm
the string to decode
Description
Decodes a string into an Integer. Deals with decimal, hexadecimal, and octal numbers.


 Integer.doubleValue

Integer.doubleValue

Syntax
public double doubleValue()
Returns
the int value represented by this object is converted to type double and the result of the conversion is returned.
Description
Returns the value of this Integer as a double.

Overrides
doubleValue in class Number


 Integer.equals

Integer.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

Overrides
equals in class Object


 Integer.floatValue

Integer.floatValue

Syntax
public float floatValue()
Returns
the int value represented by this object is converted to type float and the result of the conversion is returned.
Description
Returns the value of this Integer as a float.

Overrides
floatValue in class Number


 Integer.getInteger

Integer.getInteger

Syntax 1
public static Integer getInteger( String nm )
Parameters
nm
property name.
Returns
the Integer value of the property.
Description
Determines the integer value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.

If there is no property with the specified name, or if the property does not have the correct numeric format, then null is returned.

See Also
getProperty, getProperty

Syntax 2
public static Integer getInteger( String nm, int val )
Parameters
nm
property name.
val
default value.
Returns
the Integer value of the property.
Description
Determines the integer value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.

If there is no property with the specified name, or if the property does not have the correct numeric format, then an Integer object that represents the value of the second argument is returned.

See Also
getProperty, getProperty

Syntax 3
public static Integer getInteger( String nm, Integer val )
Parameters
nm
property name.
val
default value.
Returns
the Integer value of the property.
Description
Determines the integer value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned.

If the property value begins with "0x" or "#", not followed by a minus sign, the rest of it is parsed as a hexadecimal integer exactly as for the method Integer.valueOf with radix 16.

If the property value begins with "0" then it is parsed as an octal integer exactly as for the method Integer.valueOf with radix 8.

Otherwise the property value is parsed as a decimal integer exactly as for the method Integer.valueOf with radix 10.

The second argument is the default value. If there is no property of the specified name, or if the property does not have the correct numeric format, then the second argument is returned.

See Also
getProperty, getProperty


 Integer.hashCode

Integer.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hashcode for this Integer.

Overrides
hashCode in class Object


 Integer.intValue

Integer.intValue

Syntax
public int intValue()
Returns
the int value represented by this object.
Description
Returns the value of this Integer as an int.

Overrides
intValue in class Number


 Integer.longValue

Integer.longValue

Syntax
public long longValue()
Returns
the int value represented by this object that is converted to type long and the result of the conversion is returned.
Description
Returns the value of this Integer as a long.

Overrides
longValue in class Number


 Integer.parseInt

Integer.parseInt

Syntax 1
public static int parseInt( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the integer.
radix
the radix to be used.
Returns
the integer represented by the string argument in the specified radix.
Description
Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit returns a nonnegative value), except that the first character may be an ASCII minus sign '-' to indicate a negative value. The resulting integer value is returned.

Exceptions
NumberFormatException if the string does not contain a parsable integer.

Syntax 2
public static int parseInt( String s ) throws NumberFormatException
Parameters
s
a string.
Returns
the integer represented by the argument in decimal.
Description
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' to indicate a negative value.

Exceptions
NumberFormatException if the string does not contain a parsable integer.


 Integer.shortValue

Integer.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Integer as a short.

Overrides
shortValue in class Number


 Integer.toBinaryString

Integer.toBinaryString

Syntax
public static String toBinaryString( int i )
Parameters
i
an integer.
Returns
the string representation of the unsigned integer value represented by the argument in binary (base 2).
Description
Creates a string representation of the integer argument as an unsigned integer in base 2.

The unsigned integer value is the argument plus 232if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.


 Integer.toHexString

Integer.toHexString

Syntax
public static String toHexString( int i )
Parameters
i
an integer.
Returns
the string representation of the unsigned integer value represented by the argument in hexadecimal (base 16).
Description
Creates a string representation of the integer argument as an unsigned integer in base 16.

The unsigned integer value is the argument plus 232 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s.


 Integer.toOctalString

Integer.toOctalString

Syntax
public static String toOctalString( int i )
Parameters
i
an integer
Returns
the string representation of the unsigned integer value represented by the argument in octal (base&mnsp;8).
Description
Creates a string representation of the integer argument as an unsigned integer in base 8.

The unsigned integer value is the argument plus 232 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0s.


 Integer.toString

Integer.toString

Syntax
public static String toString( int i, int radix )
Parameters
i
an integer.
radix
the radix.
Returns
a string representation of the argument in the specified radix.
Description
Creates a string representation of the first argument in the radix specified by the second argument.

If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.

If the first argument is negative, the first element of the result is the ASCII minus character '-'. If the first argument is not negative, no sign character appears in the result. The following ASCII characters are used as digits:

    0123456789abcdefghijklmnopqrstuvwxyz

See Also
MAX_RADIX, MIN_RADIX


 Integer.toString

Integer.toString

Syntax
public static String toString( int i )
Parameters
i
an integer to be converted.
Returns
a string representation of the argument in base 10.
Description
Returns a new String object representing the specified integer. The radix is assumed to be 10.


 Integer.toString

Integer.toString

Syntax
public String toString()
Returns
a string representation of the value of this object in base 10.
Description
Returns a String object representing this Integer's value.

Overrides
toString in class Object


 Integer.valueOf

Integer.valueOf

Syntax 1
public static Integer valueOf( String s, int radix ) throws NumberFormatException
Parameters
s
the string to be parsed.
Returns
a newly constructed Integer initialized to the value represented by the string argument in the specified radix.
Description
Returns a new Integer object initialized to the value of the specified String. Throws an exception if the String cannot be parsed as an int.

Exceptions
NumberFormatException if the String does not contain a parsable integer.

Syntax 2
public static Integer valueOf( String s ) throws NumberFormatException
Parameters
s
the string to be parsed.
Returns
a newly constructed Integer initialized to the value represented by the string argument.
Description
Returns a new Integer object initialized to the value of the specified String. Throws an exception if the String cannot be parsed as an int. The radix is assumed to be 10.

Exceptions
NumberFormatException if the string does not contain a parsable integer.


 Class InternalError

Class java.lang.InternalError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.VirtualMachineError
                           |
                           +----java.lang.InternalError

public class InternalError
extends VirtualMachineError

Thrown to indicate some unexpected internal error has occurred in the Java Virtual Machine.


 InternalError Members

InternalError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InternalError() | Constructs an InternalError with no detail message.
InternalError(String) | Constructs an InternalError with the specified detail message.


 InternalError.InternalError

InternalError.InternalError

Syntax 1
public InternalError()
Description
Constructs an InternalError with no detail message.

Syntax 2
public InternalError( String s )
Parameters
s
the detail message.
Description
Constructs an InternalError with the specified detail message.


 Class InterruptedException

Class java.lang.InterruptedException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.InterruptedException

public class InterruptedException
extends Exception

Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

See Also:
wait, wait, wait, sleep, interrupt, interrupted


 InterruptedException Members

InterruptedException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InterruptedException() | Constructs an InterruptedException with no detail message.
InterruptedException(String) | Constructs an InterruptedException with the specified detail message.


 InterruptedException.InterruptedException

InterruptedException.InterruptedException

Syntax 1
public InterruptedException()
Description
Constructs an InterruptedException with no detail message.

Syntax 2
public InterruptedException( String s )
Parameters
s
the detail message.
Description
Constructs an InterruptedException with the specified detail message.


 Class LinkageError

Class java.lang.LinkageError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError

public class LinkageError
extends Error

Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.


 LinkageError Members

LinkageError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
LinkageError() | Constructs a LinkageError with no detail message.
LinkageError(String) | Constructs a LinkageError with the specified detail message.


 LinkageError.LinkageError

LinkageError.LinkageError

Syntax 1
public LinkageError()
Description
Constructs a LinkageError with no detail message.

Syntax 2
public LinkageError( String s )
Parameters
s
the detail message.
Description
Constructs a LinkageError with the specified detail message.


 Class Long

Class java.lang.Long

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Long

public final class Long
extends Number

The Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long.

In addition, this class provides several methods for converting a long to a String and a String to a long, as well as other constants and methods useful when dealing with a long.


 Long Members

Long Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The largest value of type long.
MIN_VALUE | The smallest value of type long.
TYPE | The Class object representing the primitive type long.

Constructors
Name | Description
Long(long) | Constructs a newly allocated Long object that represents the primitive long argument.
Long(String) | Constructs a newly allocated Long object that represents the value represented by the string.

Methods
Name | Description
byteValue() | Returns the value of this Long as a byte.
doubleValue() | Returns the value of this Long as a double.
equals(Object) | Compares this object against the specified object.
floatValue() | Returns the value of this Long as a float.
getLong(String) | Determines the long value of the system property with the specified name.
getLong(String, Long) | Determines the long value of the system property with the specified name.
getLong(String, long) | Determines the long value of the system property with the specified name.
hashCode() | Computes a hashcode for this Long.
intValue() | Returns the value of this Long as an int.
longValue() | Returns the value of this Long as a long.
parseLong(String) | Parses the string argument as a signed decimal long.
parseLong(String, int) | Parses the string argument as a signed long in the radix specified by the second argument.
shortValue() | Returns the value of this Long as a short.
toBinaryString(long) | Creates a string representation of the long argument as an unsigned integer in base 2.
toHexString(long) | Creates a string representation of the long argument as an unsigned integer in base 16.
toOctalString(long) | Creates a string representation of the long argument as an unsigned integer in base 8.
toString() | Returns a String object representing this Long's value.
toString(long) | Returns a new String object representing the specified integer.
toString(long, int) | Creates a string representation of the first argument in the radix specified by the second argument.
valueOf(String) | Returns a new long object initialized to the value of the specified String.
valueOf(String, int) | Returns a new long object initialized to the value of the specified String.


 Long.MAX_VALUE

Long.MAX_VALUE

Syntax
public static final long MAX_VALUE
Description
The largest value of type long.


 Long.MIN_VALUE

Long.MIN_VALUE

Syntax
public static final long MIN_VALUE
Description
The smallest value of type long.


 Long.TYPE

Long.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type long.


 Long.Long

Long.Long

Syntax 1
public Long( long value )
Parameters
value
the value to be represented by the Long.
Description
Constructs a newly allocated Long object that represents the primitive long argument.

Syntax 2
public Long( String s ) throws NumberFormatException
Parameters
s
the string to be converted to a Long.
Description
Constructs a newly allocated Long object that represents the value represented by the string. The string is converted to an long value as if by the valueOf method.

Exceptions
NumberFormatException if the String does not contain a parsable long integer.
See Also
valueOf


 Long.byteValue

Long.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Long as a byte.

Overrides
byteValue in class Number


 Long.doubleValue

Long.doubleValue

Syntax
public double doubleValue()
Returns
the long value represented by this object that is converted to type double and the result of the conversion is returned.
Description
Returns the value of this Long as a double.

Overrides
doubleValue in class Number


 Long.equals

Long.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object.

Overrides
equals in class Object


 Long.floatValue

Long.floatValue

Syntax
public float floatValue()
Returns
the long value represented by this object is converted to type float and the result of the conversion is returned.
Description
Returns the value of this Long as a float.

Overrides
floatValue in class Number


 Long.getLong

Long.getLong

Syntax 1
public static Long getLong( String nm )
Parameters
nm
property name.
Returns
the Long value of the property.
Description
Determines the long value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as a long value and a Long object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.

If there is no property with the specified name, or if the property does not have the correct numeric format, then null is returned.

See Also
getProperty, getProperty

Syntax 2
public static Long getLong( String nm, long val )
Parameters
nm
property name.
val
default value.
Returns
the Long value of the property.
Description
Determines the long value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as a long value and a Long object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.

If there is no property with the specified name, or if the property does not have the correct numeric format, then a Long object that represents the value of the second argument is returned.

See Also
getProperty, getProperty

Syntax 3
public static Long getLong( String nm, Long val )
Parameters
nm
the property name.
val
the default Long value.
Returns
the long value of the property.
Description
Determines the long value of the system property with the specified name.

The first argument is treated as the name of a system property. System properties are accessible through getProperty and , a method defined by the System class. The string value of this property is then interpreted as a long value and a Long object representing this value is returned.

If the property value begins with "0x" or "#", not followed by a minus sign, the rest of it is parsed as a hexadecimal integer exactly as for the method Long.valueOf with radix 16.

If the property value begins with "0", then it is parsed as an octal integer exactly as for the method Long.valueOf with radix 8.

Otherwise the property value is parsed as a decimal integer exactly as for the method Long.valueOf with radix 10.

Note that, in every case, neither L nor l is permitted to appear at the end of the string.

The second argument is the default value. If there is no property of the specified name, or if the property does not have the correct numeric format, then the second argument is returned.

See Also
valueOf, getProperty, getProperty


 Long.hashCode

Long.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Computes a hashcode for this Long.

Overrides
hashCode in class Object


 Long.intValue

Long.intValue

Syntax
public int intValue()
Returns
the long value represented by this object is converted to type int and the result of the conversion is returned.
Description
Returns the value of this Long as an int.

Overrides
intValue in class Number


 Long.longValue

Long.longValue

Syntax
public long longValue()
Returns
the long value represented by this object.
Description
Returns the value of this Long as a long.

Overrides
longValue in class Number


 Long.parseLong

Long.parseLong

Syntax 1
public static long parseLong( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the long.
radix
the radix to be used.
Returns
the long represented by the string argument in the specified radix.
Description
Parses the string argument as a signed long in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit returns a nonnegative value), except that the first character may be an ASCII minus sign '-' to indicate a negative value. The resulting long value is returned.

Exceptions
NumberFormatException if the string does not contain a parsable integer.

Syntax 2
public static long parseLong( String s ) throws NumberFormatException
Parameters
s
a string.
Returns
the long represented by the argument in decimal.
Description
Parses the string argument as a signed decimal long. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' to indicate a negative value.

Exceptions
NumberFormatException if the string does not contain a parsable long.


 Long.shortValue

Long.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Long as a short.

Overrides
shortValue in class Number


 Long.toBinaryString

Long.toBinaryString

Syntax
public static String toBinaryString( long i )
Parameters
i
a long.
Returns
the string representation of the unsigned long value represented by the argument in binary (base 2).
Description
Creates a string representation of the long argument as an unsigned integer in base 2.

The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.


 Long.toHexString

Long.toHexString

Syntax
public static String toHexString( long i )
Parameters
i
a long.
Returns
the string representation of the unsigned long value represented by the argument in hexadecimal (base 16).
Description
Creates a string representation of the long argument as an unsigned integer in base 16.

The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s.


 Long.toOctalString

Long.toOctalString

Syntax
public static String toOctalString( long i )
Parameters
i
a long.
Returns
the string representation of the unsigned long value represented by the argument in octal (base 8).
Description
Creates a string representation of the long argument as an unsigned integer in base 8.

The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0s.


 Long.toString

Long.toString

Syntax
public static String toString( long i, int radix )
Parameters
i
a long.
radix
the radix.
Returns
a string representation of the argument in the specified radix.
Description
Creates a string representation of the first argument in the radix specified by the second argument.

If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the radix 10 is used instead.

If the first argument is negative, the first element of the result is the ASCII minus sign '-'. If the first argument is not negative, no sign character appears in the result. The following ASCII characters are used as digits:

    0123456789abcdefghijklmnopqrstuvwxyz

See Also
MAX_RADIX, MIN_RADIX


 Long.toString

Long.toString

Syntax
public static String toString( long i )
Parameters
i
a long to be converted.
Returns
a string representation of the argument in base 10.
Description
Returns a new String object representing the specified integer. The radix is assumed to be 10.


 Long.toString

Long.toString

Syntax
public String toString()
Returns
a string representation of this object in base 10.
Description
Returns a String object representing this Long's value.

Overrides
toString in class Object


 Long.valueOf

Long.valueOf

Syntax 1
public static Long valueOf( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the long.
radix
the radix to be used.
Returns
a newly constructed Long initialized to the value represented by the string argument in the specified radix.
Description
Returns a new long object initialized to the value of the specified String. Throws an exception if the String cannot be parsed as a long.

Exceptions
NumberFormatException If the String does not contain a parsable long.

Syntax 2
public static Long valueOf( String s ) throws NumberFormatException
Parameters
s
the string to be parsed.
Returns
a newly constructed Long initialized to the value represented by the string argument.
Description
Returns a new long object initialized to the value of the specified String. Throws an exception if the String cannot be parsed as a long. The radix is assumed to be 10.

Exceptions
NumberFormatException If the String does not contain a parsable long.


 Class Math

Class java.lang.Math

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Math

public final class Math
extends Object

The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

To help ensure portability of Java programs, the definitions of many of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library" (fdlibm). These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic.

The network library may be found on the World Wide Web at

    http://netlib.att.com/

then perform a keyword search for "fdlibm".

The Java math library is defined with respect to the version of fdlibm dated January 4, 1995. Where fdlibm provides more than one definition for a function (such as acos), use the "IEEE 754 core function" version (residing in a file whose name begins with the letter e).


 Math Members

Math Members

Class Overview | This Package | All Packages

Fields
Name | Description
E | The double value that is closer than any other to e, the base of the natural logarithms.
PI | The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

Methods
Name | Description
abs(double) | Returns the absolute value of a double value.
abs(float) | Returns the absolute value of a float value.
abs(int) | Returns the absolute value of an int value.
abs(long) | Returns the absolute value of a long value.
acos(double) | Returns the arc cosine of an angle, in the range of 0.0 through pi.
asin(double) | Returns the arc sine of an angle, in the range of -pi/2 through pi/2.
atan(double) | Returns the arc tangent of an angle, in the range of -pi/2 through pi/2.
atan2(double, double) | Converts rectangular coordinates (b, a) to polar (r, theta).
ceil(double) | Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.
cos(double) | Returns the trigonometric cosine of an angle.
exp(double) | Returns the exponential number e (i.e., 2.718...) raised to the power of a double value.
floor(double) | Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.
IEEEremainder(double, double) | Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.
log(double) | Returns the natural logarithm (base e) of a double value.
max(double, double) | Returns the greater of two double values.
max(float, float) | Returns the greater of two float values.
max(int, int) | Returns the greater of two int values.
max(long, long) | Returns the greater of two long values.
min(double, double) | Returns the smaller of two double values.
min(float, float) | Returns the smaller of two float values.
min(int, int) | Returns the smaller of two int values.
min(long, long) | Returns the smaller of two long values.
pow(double, double) | Returns of value of the first argument raised to the power of the second argument.
random() | Returns a random number between 0.0 and 1.0.
rint(double) | returns the closest integer to the argument.
round(double) | Returns the closest long to the argument.
round(float) | Returns the closest int to the argument.
sin(double) | Returns the trigonometric sine of an angle.
sqrt(double) | Returns the square root of a double value.
tan(double) | Returns the trigonometric tangent of an angle.


 Math.E

Math.E

Syntax
public static final double E
Description
The double value that is closer than any other to e, the base of the natural logarithms.


 Math.PI

Math.PI

Syntax
public static final double PI
Description
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.


 Math.abs

Math.abs

Syntax 1
public static int abs( int a )
Parameters
a
an int value.
Returns
the absolute value of the argument.
Description
Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

See Also
MIN_VALUE

Syntax 2
public static long abs( long a )
Parameters
a
a long value.
Returns
the absolute value of the argument.
Description
Returns the absolute value of a long value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Note that if the argument is equal to the value of Long.MIN_VALUE, the most negative representable long value, the result is that same value, which is negative.

See Also
MIN_VALUE

Syntax 3
public static float abs( float a )
Parameters
a
a float value.
Returns
the absolute value of the argument.
Description
Returns the absolute value of a float value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Syntax 4
public static double abs( double a )
Parameters
a
a double value.
Returns
the absolute value of the argument.
Description
Returns the absolute value of a double value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.


 Math.acos

Math.acos

Syntax
public static native double acos( double a )
Parameters
a
an angle, in radians.
Returns
the arc cosine of the argument.
Description
Returns the arc cosine of an angle, in the range of 0.0 through pi.


 Math.asin

Math.asin

Syntax
public static native double asin( double a )
Parameters
a
an angle, in radians.
Returns
the arc sine of the argument.
Description
Returns the arc sine of an angle, in the range of -pi/2 through pi/2.


 Math.atan

Math.atan

Syntax
public static native double atan( double a )
Parameters
a
an angle, in radians.
Returns
the arc tangent of the argument.
Description
Returns the arc tangent of an angle, in the range of -pi/2 through pi/2.


 Math.atan2

Math.atan2

Syntax
public static native double atan2( double a, double b )
Parameters
a
a double value.
b
a double value.
Returns
the theta component of the point (r, theta) in polar coordinates that corresponds to the point (b, a) in Cartesian coordinates.
Description
Converts rectangular coordinates (b, a) to polar (r, theta). This method computes the phase theta by computing an arc tangent of b/a in the range of -pi to pi.


 Math.ceil

Math.ceil

Syntax
public static native double ceil( double a )
Parameters
a
a double value.
Returns
the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.
Description
Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.


 Math.cos

Math.cos

Syntax
public static native double cos( double a )
Parameters
a
an angle, in radians.
Returns
the cosine of the argument.
Description
Returns the trigonometric cosine of an angle.


 Math.exp

Math.exp

Syntax
public static native double exp( double a )
Parameters
a
a double value.
Returns
the value ea, where e is the base of the natural logarithms.
Description
Returns the exponential number e (i.e., 2.718...) raised to the power of a double value.


 Math.floor

Math.floor

Syntax
public static native double floor( double a )
Parameters
a
a double value.
a
an assigned value.
Returns
the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.
Description
Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.


 Math.IEEEremainder

Math.IEEEremainder

Syntax
public static native double IEEEremainder( double f1, double f2 )
Parameters
f1
the dividend.
f2
the divisor.
Returns
the remainder when f1 is divided by f2.
Description
Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard. The remainder value is mathematically equal to f1 - f2 × n, where n is the mathematical integer closest to the exact mathematical value of the quotient f1/f2, and if two mathematical integers are equally close to f1/f2, then n is the integer that is even. If the remainder is zero, its sign is the same as the sign of the first argument.


 Math.log

Math.log

Syntax
public static native double log( double a )
Parameters
a
a number greater than 0.0.
Returns
the value ln a, the natural logarithm of a.
Description
Returns the natural logarithm (base e) of a double value.


 Math.max

Math.max

Syntax 1
public static int max( int a, int b )
Parameters
a
an int value.
b
an int value.
Returns
the larger of a and b.
Description
Returns the greater of two int values.

Syntax 2
public static long max( long a, long b )
Parameters
a
a long value.
b
a long value.
Returns
the larger of a and b.
Description
Returns the greater of two long values.

Syntax 3
public static float max( float a, float b )
Parameters
a
a float value.
b
a float value.
Returns
the larger of a and b.
Description
Returns the greater of two float values. If either value is NaN, then the result is NaN. Unlike the the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.

Syntax 4
public static double max( double a, double b )
Parameters
a
a double value.
b
a double value.
Returns
the larger of a and b.
Description
Returns the greater of two double values. If either value is NaN, then the result is NaN. Unlike the the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.


 Math.min

Math.min

Syntax 1
public static int min( int a, int b )
Parameters
a
an int value.
b
an int value.
Returns
the smaller of a and b.
Description
Returns the smaller of two int values.

Syntax 2
public static long min( long a, long b )
Parameters
a
a long value.
b
a long value.
Returns
the smaller of a and b.
Description
Returns the smaller of two long values.

Syntax 3
public static float min( float a, float b )
Parameters
a
a float value.
b
a float value.
Returns
the smaller of a and b.
Description
Returns the smaller of two float values. If either value is NaN, then the result is NaN. Unlike the the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.

Syntax 4
public static double min( double a, double b )
Parameters
a
a double value.
b
a double value.
Returns
the smaller of a and b.
Description
Returns the smaller of two double values. If either value is NaN, then the result is NaN. Unlike the the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.


 Math.pow

Math.pow

Syntax
public static native double pow( double a, double b )
Parameters
a
a double value.
b
a double value.
Returns
the value ab.
Description
Returns of value of the first argument raised to the power of the second argument.

If (a == 0.0), then b must be greater than 0.0; otherwise an exception is thrown. An exception also will occur if (a <= 0.0) and b is not equal to a whole number.

Exceptions
ArithmeticException if (a == 0.0) and (b <= 0.0), or if (a <= 0.0) and b is not equal to a whole number.


 Math.random

Math.random

Syntax
public static synchronized double random()
Returns
a pseudorandom double between 0.0 and 1.0.
Description
Returns a random number between 0.0 and 1.0. Random number generators are often referred to as pseudorandom number generators because the numbers produced tend to repeat themselves after a period of time.

See Also
nextDouble


 Math.rint

Math.rint

Syntax
public static native double rint( double a )
Parameters
a
a double value.
Returns
the closest double value to a that is equal to a mathematical integer. If two double values that are mathematical integers are equally close to the value of the argument, the result is the integer value that is even.
Description
returns the closest integer to the argument.


 Math.round

Math.round

Syntax 1
public static int round( float a )
Parameters
a
a float value.
Returns
the value of the argument rounded to the nearest int value.
Description
Returns the closest int to the argument.

If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.

If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

See Also
MAX_VALUE, MIN_VALUE

Syntax 2
public static long round( double a )
Parameters
a
a double value.
Returns
the value of the argument rounded to the nearest long value.
Description
Returns the closest long to the argument.

If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.

If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

See Also
MAX_VALUE, MIN_VALUE


 Math.sin

Math.sin

Syntax
public static native double sin( double a )
Parameters
a
an angle, in radians.
Returns
the sine of the argument.
Description
Returns the trigonometric sine of an angle.


 Math.sqrt

Math.sqrt

Syntax
public static native double sqrt( double a )
Parameters
a
a double value.
Returns
the square root of a. If the argument is NaN or less than zero, the result is NaN.
Description
Returns the square root of a double value.


 Math.tan

Math.tan

Syntax
public static native double tan( double a )
Parameters
a
an angle, in radians.
Returns
the tangent of the argument.
Description
Returns the trigonometric tangent of an angle.


 Class NegativeArraySizeException

Class java.lang.NegativeArraySizeException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.NegativeArraySizeException

public class NegativeArraySizeException
extends RuntimeException

Thrown if an application tries to create an array with negative size.


 NegativeArraySizeException Members

NegativeArraySizeException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NegativeArraySizeException() | Constructs a NegativeArraySizeException with no detail message.
NegativeArraySizeException(String) | Constructs a NegativeArraySizeException with the specified detail message.


 NegativeArraySizeException.NegativeArraySizeException

NegativeArraySizeException.NegativeArraySizeException

Syntax 1
public NegativeArraySizeException()
Description
Constructs a NegativeArraySizeException with no detail message.

Syntax 2
public NegativeArraySizeException( String s )
Parameters
s
the detail message.
Description
Constructs a NegativeArraySizeException with the specified detail message.


 Class NoClassDefFoundError

Class java.lang.NoClassDefFoundError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.NoClassDefFoundError

public class NoClassDefFoundError
extends LinkageError

Thrown if the Java Virtual Machine or a classloader tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.


 NoClassDefFoundError Members

NoClassDefFoundError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoClassDefFoundError() | Constructs a NoClassDefFoundError with no detail message.
NoClassDefFoundError(String) | Constructs a NoClassDefFoundError with the specified detail message.


 NoClassDefFoundError.NoClassDefFoundError

NoClassDefFoundError.NoClassDefFoundError

Syntax 1
public NoClassDefFoundError()
Description
Constructs a NoClassDefFoundError with no detail message.

Syntax 2
public NoClassDefFoundError( String s )
Parameters
s
the detail message.
Description
Constructs a NoClassDefFoundError with the specified detail message.


 Class NoSuchFieldError

Class java.lang.NoSuchFieldError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError
                                   |
                                   +----java.lang.NoSuchFieldError

public class NoSuchFieldError
extends IncompatibleClassChangeError

Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.


 NoSuchFieldError Members

NoSuchFieldError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchFieldError() | Constructs a NoSuchFieldException with no detail message.
NoSuchFieldError(String) | Constructs a NoSuchFieldException with the specified detail message.


 NoSuchFieldError.NoSuchFieldError

NoSuchFieldError.NoSuchFieldError

Syntax 1
public NoSuchFieldError()
Description
Constructs a NoSuchFieldException with no detail message.

Syntax 2
public NoSuchFieldError( String s )
Parameters
s
the detail message.
Description
Constructs a NoSuchFieldException with the specified detail message.


 Class NoSuchFieldException

Class java.lang.NoSuchFieldException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.NoSuchFieldException

public class NoSuchFieldException
extends Exception

Signals that the class doesn't have a field of a specified name.


 NoSuchFieldException Members

NoSuchFieldException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchFieldException() | Constructor.
NoSuchFieldException(String) | Constructor with a detail message.


 NoSuchFieldException.NoSuchFieldException

NoSuchFieldException.NoSuchFieldException

Syntax 1
public NoSuchFieldException()
Description
Constructor.

Syntax 2
public NoSuchFieldException( String s )
Description
Constructor with a detail message.


 Class NoSuchMethodError

Class java.lang.NoSuchMethodError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.IncompatibleClassChangeError
                                   |
                                   +----java.lang.NoSuchMethodError

public class NoSuchMethodError
extends IncompatibleClassChangeError

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.


 NoSuchMethodError Members

NoSuchMethodError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchMethodError() |
NoSuchMethodError(String) | Constructs a NoSuchMethodException with the specified detail message.


 NoSuchMethodError.NoSuchMethodError

NoSuchMethodError.NoSuchMethodError

Syntax 1
public NoSuchMethodError()

Syntax 2
public NoSuchMethodError( String s )
Parameters
s
the detail message.
Description
Constructs a NoSuchMethodException with the specified detail message.


 Class NoSuchMethodException

Class java.lang.NoSuchMethodException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.NoSuchMethodException

public class NoSuchMethodException
extends Exception

Thrown when a particular method cannot be found.


 NoSuchMethodException Members

NoSuchMethodException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchMethodException() | Constructs a NoSuchMethodException without a detail message.
NoSuchMethodException(String) | Constructs a NoSuchMethodException with a detail message.


 NoSuchMethodException.NoSuchMethodException

NoSuchMethodException.NoSuchMethodException

Syntax 1
public NoSuchMethodException()
Description
Constructs a NoSuchMethodException without a detail message.

Syntax 2
public NoSuchMethodException( String s )
Parameters
s
the detail message.
Description
Constructs a NoSuchMethodException with a detail message.


 Class NullPointerException

Class java.lang.NullPointerException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.NullPointerException

public class NullPointerException
extends RuntimeException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.


 NullPointerException Members

NullPointerException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NullPointerException() | Constructs a NullPointerException with no detail message.
NullPointerException(String) | Constructs a NullPointerException with the specified detail message.


 NullPointerException.NullPointerException

NullPointerException.NullPointerException

Syntax 1
public NullPointerException()
Description
Constructs a NullPointerException with no detail message.

Syntax 2
public NullPointerException( String s )
Parameters
s
the detail message.
Description
Constructs a NullPointerException with the specified detail message.


 Class Number

Class java.lang.Number

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number

public abstract class Number
extends Object
implements Serializable

The abstract class Number is the superclass of classes Byte, Double, Float, Integer, Long, and Short.

Subclasses of Number must provide methods to convert the represented numeric value to byte, double, float, int, long, and short.

See Also:
Byte, Double, Float, Integer, Long, Short


 Number Members

Number Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Number() |

Methods
Name | Description
byteValue() | Returns the value of the specified number as a byte.
doubleValue() | Returns the value of the specified number as a double.
floatValue() | Returns the value of the specified number as a float.
intValue() | Returns the value of the specified number as an int.
longValue() | Returns the value of the specified number as a long.
shortValue() | Returns the value of the specified number as a short.


 Number.Number

Number.Number

Syntax
public Number()


 Number.byteValue

Number.byteValue

Syntax
public byte byteValue()
Returns
the numeric value represented by this object after conversion to type byte.
Description
Returns the value of the specified number as a byte. This may involve rounding or truncation.


 Number.doubleValue

Number.doubleValue

Syntax
public abstract double doubleValue()
Returns
the numeric value represented by this object after conversion to type double.
Description
Returns the value of the specified number as a double. This may involve rounding.


 Number.floatValue

Number.floatValue

Syntax
public abstract float floatValue()
Returns
the numeric value represented by this object after conversion to type float.
Description
Returns the value of the specified number as a float. This may involve rounding.


 Number.intValue

Number.intValue

Syntax
public abstract int intValue()
Returns
the numeric value represented by this object after conversion to type int.
Description
Returns the value of the specified number as an int. This may involve rounding.


 Number.longValue

Number.longValue

Syntax
public abstract long longValue()
Returns
the numeric value represented by this object after conversion to type long.
Description
Returns the value of the specified number as a long. This may involve rounding.


 Number.shortValue

Number.shortValue

Syntax
public short shortValue()
Returns
the numeric value represented by this object after conversion to type short.
Description
Returns the value of the specified number as a short. This may involve rounding or truncation.


 Class NumberFormatException

Class java.lang.NumberFormatException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalArgumentException
                                   |
                                   +----java.lang.NumberFormatException

public class NumberFormatException
extends IllegalArgumentException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

See Also:
toString


 NumberFormatException Members

NumberFormatException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NumberFormatException() | Constructs a NumberFormatException with no detail message.
NumberFormatException(String) | Constructs a NumberFormatException with the specified detail message.


 NumberFormatException.NumberFormatException

NumberFormatException.NumberFormatException

Syntax 1
public NumberFormatException()
Description
Constructs a NumberFormatException with no detail message.

Syntax 2
public NumberFormatException( String s )
Parameters
s
the detail message.
Description
Constructs a NumberFormatException with the specified detail message.


 Class Object

Class java.lang.Object

Class Members | This Package | All Packages
java.lang.Object

public class Object

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

See Also:
Class


 Object Members

Object Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Object() |

Methods
Name | Description
clone() | Creates a new object of the same class as this object.
equals(Object) | Compares two Objects for equality.
finalize() | Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
getClass() | Returns the runtime class of an object.
hashCode() | Returns a hash code value for the object.
notify() | Wakes up a single thread that is waiting on this object's monitor.
notifyAll() | Wakes up all threads that are waiting on this object's monitor.
toString() | Returns a string representation of the object.
wait() | Waits to be notified by another thread of a change in this object.
wait(long) | Waits to be notified by another thread of a change in this object.
wait(long, int) | Waits to be notified by another thread of a change in this object.


 Object.Object

Object.Object

Syntax
public Object()


 Object.clone

Object.clone

Syntax
protected native Object clone() throws CloneNotSupportedException
Returns
a clone of this instance.
Description
Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.

The clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface.

Exceptions
CloneNotSupportedException if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.
Exceptions
OutOfMemoryError if there is not enough memory.
See Also
Cloneable


 Object.equals

Object.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the reference object with which to compare.
Returns
true if this object is the same as the obj argument; false otherwise.
Description
Compares two Objects for equality.

The equals method implements an equivalence relation:

  • It is reflexive: for any reference value x, x.equals(x) should return true.
  • It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any reference values x,
     y, and z, if x.equals(y)
     returns  true and y.equals(z) returns
     true, then x.equals(z) should return
     true.
  • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false.
  • For any reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

See Also
hashCode, Hashtable


 Object.finalize

Object.finalize

Syntax
protected void finalize() throws Throwable
Description
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

The finalize method in Object does nothing.

Exceptions
Throwable [Need description!]


 Object.getClass

Object.getClass

Syntax
public final native Class getClass()
Returns
the object of type Class that represents the runtime class of the object.
Description
Returns the runtime class of an object.


 Object.hashCode

Object.hashCode

Syntax
public native int hashCode()
Returns
a hash code value for this object.
Description
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.

See Also
equals, Hashtable


 Object.notify

Object.notify

Syntax
public final native void notify()
Description
Wakes up a single thread that is waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Exceptions
IllegalMonitorStateException if the current thread is not the owner of this object's monitor.
See Also
notifyAll, wait


 Object.notifyAll

Object.notifyAll

Syntax
public final native void notifyAll()
Description
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Exceptions
IllegalMonitorStateException if the current thread is not the owner of this object's monitor.
See Also
notify, wait


 Object.toString

Object.toString

Syntax
public String toString()
Returns
a string representation of the object.
Description
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommendedthat all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.


 Object.wait

Object.wait

Syntax 1
public final native void wait( long timeout ) throws InterruptedException
Parameters
timeout
the maximum time to wait in milliseconds.
Description
Waits to be notified by another thread of a change in this object.

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by the timeout argument in milliseconds, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Exceptions
IllegalArgumentException if the value of timeout is negative.
Exceptions
IllegalMonitorStateException if the current thread is not the owner of the object's monitor.
Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
notify, notifyAll

Syntax 2
public final void wait( long timeout, int nanos ) throws InterruptedException
Parameters
timeout
the maximum time to wait in milliseconds.
nano
additional time, in nanoseconds range 0-999999.
Description
Waits to be notified by another thread of a change in this object.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up.

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Exceptions
IllegalArgumentException if the value of timeout is negative or the value of nanos is not in the range 0-999999.
Exceptions
IllegalMonitorStateException if the current thread is not the owner of this object's monitor.
Exceptions
InterruptedException if another thread has interrupted this thread.

Syntax 3
public final void wait() throws InterruptedException
Description
Waits to be notified by another thread of a change in this object.

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Exceptions
IllegalMonitorStateException if the current thread is not the owner of the object's monitor.
Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
notify, notifyAll


 Class OutOfMemoryError

Class java.lang.OutOfMemoryError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.VirtualMachineError
                           |
                           +----java.lang.OutOfMemoryError

public class OutOfMemoryError
extends VirtualMachineError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.


 OutOfMemoryError Members

OutOfMemoryError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
OutOfMemoryError() | Constructs an OutOfMemoryError with no detail message.
OutOfMemoryError(String) | Constructs an OutOfMemoryError with the specified detail message.


 OutOfMemoryError.OutOfMemoryError

OutOfMemoryError.OutOfMemoryError

Syntax 1
public OutOfMemoryError()
Description
Constructs an OutOfMemoryError with no detail message.

Syntax 2
public OutOfMemoryError( String s )
Parameters
s
the detail message.
Description
Constructs an OutOfMemoryError with the specified detail message.


 Class Process

Class java.lang.Process

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Process

public abstract class Process
extends Object

The exec methods return an instance of a subclass of Process that can be used to control the process and obtain information about it.

The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously.

See Also:
exec, exec, exec, exec


 Process Members

Process Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Process() |

Methods
Name | Description
destroy() | Kills the subprocess.
exitValue() | Returns the exit value for the subprocess.
getErrorStream() | Gets the error stream of the subprocess.
getInputStream() | Gets the input stream of the subprocess.
getOutputStream() | Gets the output stream of the subprocess.
waitFor() | Waits for the subprocess to complete.


 Process.Process

Process.Process

Syntax
public Process()


 Process.destroy

Process.destroy

Syntax
public abstract void destroy()
Description
Kills the subprocess.


 Process.exitValue

Process.exitValue

Syntax
public abstract int exitValue()
Returns
the exit value of the subprocess.
Description
Returns the exit value for the subprocess.

Exceptions
IllegalThreadStateException if the subprocess has not yet terminated.


 Process.getErrorStream

Process.getErrorStream

Syntax
public abstract InputStream getErrorStream()
Returns
the input stream connected to the error stream of the subprocess.
Description
Gets the error stream of the subprocess. This stream is usually unbuffered.


 Process.getInputStream

Process.getInputStream

Syntax
public abstract InputStream getInputStream()
Returns
the input stream connected to the normal output of the subprocess.
Description
Gets the input stream of the subprocess. This stream is usually buffered.


 Process.getOutputStream

Process.getOutputStream

Syntax
public abstract OutputStream getOutputStream()
Returns
the output stream connected to the normal input of the subprocess.
Description
Gets the output stream of the subprocess. This stream is usually buffered.


 Process.waitFor

Process.waitFor

Syntax
public abstract int waitFor() throws InterruptedException
Returns
the exit value of the process.
Description
Waits for the subprocess to complete. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

Exceptions
InterruptedException if the waitFor was interrupted.


 Interface Runnable

Interface java.lang.Runnable

Interface Members | This Package | All Packages

public interface Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.

In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a ,code>Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

See Also:
Thread


 Runnable Members

Runnable Members

Interface Overview | This Package | All Packages

Methods
Name | Description
run() | When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.


 Runnable.run

Runnable.run

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void run()
Description
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

See Also
run


 Class Runtime

Class java.lang.Runtime

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Runtime

public class Runtime
extends Object


 Runtime Members

Runtime Members

Class Overview | This Package | All Packages

Methods
Name | Description
exec(String) | Executes the specified string command in a separate process.
exec(String, String[]) | Executes the specified string command in a separate process with the specified environment.
exec(String[]) | Executes the specified command and arguments in a separate process.
exec(String[], String[]) | Executes the specified command and arguments in a separate process with the specified environment.
exit(int) | Terminates the currently running Java Virtual Machine.
freeMemory() | Returns the amount of free memory in the system.
gc() | Runs the garbage collector.
getLocalizedInputStream(InputStream) | Creates a localized version of an input stream. Deprecated.
getLocalizedOutputStream(OutputStream) | Creates a localized version of an output stream. Deprecated.
getRuntime() | Returns the runtime object associated with the current Java application.
load(String) | Loads the specified filename as a dynamic library.
loadLibrary(String) | Loads the dynamic library with the specified library name.
runFinalization() | Runs the finalization methods of any objects pending finalization.
runFinalizersOnExit(boolean) | Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits.
totalMemory() | Returns the total amount of memory in the Java Virtual Machine.
traceInstructions(boolean) | Enables/Disables tracing of instructions.
traceMethodCalls(boolean) | Enables/Disables tracing of method calls.


 Runtime.exec

Runtime.exec

Syntax 1
public Process exec( String command ) throws IOException
Parameters
command
a specified system command.
Returns
a Process object for managing the subprocess.
Description
Executes the specified string command in a separate process.

The command argument is parsed into tokens and then executed as a command in a separate process. This method has exactly the same effect as exec(command, null).

Exceptions
SecurityException if the current thread cannot create a subprocess.
See Also
exec

Syntax 2
public Process exec( String command, String envp[] ) throws IOException
Parameters
command
a specified system command.
envp
array containing environment in format name=value
Returns
a Process object for managing the subprocess.
Description
Executes the specified string command in a separate process with the specified environment.

This method breaks the command string into tokens and creates a new array cmdarray containing the tokens; it then performs the call exec(cmdarray, envp).

Exceptions
SecurityException if the current thread cannot create a subprocess.
See Also
exec

Syntax 3
public Process exec( String cmdarray[] ) throws IOException
Parameters
cmdarray
array containing the command to call and its arguments.
Returns
a Process object for managing the subprocess.
Description
Executes the specified command and arguments in a separate process.

The command specified by the tokens in cmdarray is executed as a command in a separate process. This has exactly the same effect as exec(cmdarray, null).

Exceptions
SecurityException if the current thread cannot create a subprocess.
See Also
exec

Syntax 4
public Process exec( String cmdarray[], String envp[] ) throws IOException
Parameters
cmdarray
array containing the command to call and its arguments.
envp
array containing environment in format name=value.
Returns
a Process object for managing the subprocess.
Description
Executes the specified command and arguments in a separate process with the specified environment.

If there is a security manager, its checkExec method is called with the first component of the array cmdarray as its argument. This may result in a security exception.

Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing an "environment" that defines system properties, this method creates a new process in which to execute the specified command.

Exceptions
SecurityException if the current thread cannot create a subprocess.
See Also
SecurityException, checkExec


 Runtime.exit

Runtime.exit

Syntax
public void exit( int status )
Parameters
status
exit status.
Description
Terminates the currently running Java Virtual Machine. This method never returns normally.

If there is a security manager, its checkExit method is called with the status as its argument. This may result in a security exception.

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

Exceptions
SecurityException if the current thread cannot exit with the specified status.
See Also
SecurityException, checkExit


 Runtime.freeMemory

Runtime.freeMemory

Syntax
public native long freeMemory()
Returns
an approximation to the total amount of memory currently available for future allocated objects, measured in bytes.
Description
Returns the amount of free memory in the system. The value returned by this method is always less than the value returned by the totalMemory method. Calling the gc method may result in increasing the value returned by freeMemory.


 Runtime.gc

Runtime.gc

Syntax
public native void gc()
Description
Runs the garbage collector. Calling this method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made its best effort to recycle all unused objects.

The name gc stands for "garbage collector". The Java Virtual Machine performs this recycling process automatically as needed even if the gc method is not invoked explicitly.


 Runtime.getLocalizedInputStream

Runtime.getLocalizedInputStream

Syntax
public InputStream getLocalizedInputStream( InputStream in )
Returns
a localized input stream.
Description
Note: getLocalizedInputStream() is deprecated. As of JDK 1.1, the preferred way translate a byte stream in the local encoding into a character stream in Unicode is via the InputStreamReader and BufferedReader classes.

Creates a localized version of an input stream. This method takes an InputStream and returns an InputStream equivalent to the argument in all respects except that it is localized: as characters in the local character set are read from the stream, they are automatically converted from the local character set to Unicode.

If the argument is already a localized stream, it may be returned as the result.

See Also
InputStream, BufferedReader, InputStreamReader


 Runtime.getLocalizedOutputStream

Runtime.getLocalizedOutputStream

Syntax
public OutputStream getLocalizedOutputStream( OutputStream out )
Returns
a localized output stream.
Description
Note: getLocalizedOutputStream() is deprecated. As of JDK 1.1, the preferred way to translate a Unicode character stream into a byte stream in the local encoding is via the OutputStreamWriter, BufferedWriter, and PrintWriter classes.

Creates a localized version of an output stream. This method takes an OutputStream and returns an OutputStream equivalent to the argument in all respects except that it is localized: as Unicode characters are written to the stream, they are automatically converted to the local character set.

If the argument is already a localized stream, it may be returned as the result.

See Also
OutputStream, BufferedWriter, OutputStreamWriter, PrintWriter


 Runtime.getRuntime

Runtime.getRuntime

Syntax
public static Runtime getRuntime()
Returns
the Runtime object associated with the current Java application.
Description
Returns the runtime object associated with the current Java application.


 Runtime.load

Runtime.load

Syntax
public synchronized void load( String filename )
Parameters
filename
the file to load.
Description
Loads the specified filename as a dynamic library. The filename argument must be a complete pathname. From java_g it will automagically insert "_g" before the ".so" (for example Runtime.getRuntime().load("/home/avh/lib/libX11.so");).

If there is a security manager, its checkLink method is called with the filename as its argument. This may result in a security exception.

Exceptions
SecurityException if the current thread cannot load the specified dynamic library.
Exceptions
UnsatisfiedLinkError if the file does not exist.
See Also
getRuntime, SecurityException, checkLink


 Runtime.loadLibrary

Runtime.loadLibrary

Syntax
public synchronized void loadLibrary( String libname )
Parameters
libname
the name of the library.
Description
Loads the dynamic library with the specified library name. The mapping from a library name to a specific filename is done in a system-specific manner.

First, if there is a security manager, its checkLink method is called with the filename as its argument. This may result in a security exception.

If this method is called more than once with the same library name, the second and subsequent calls are ignored.

Exceptions
SecurityException if the current thread cannot load the specified dynamic library.
Exceptions
UnsatisfiedLinkError if the library does not exist.
See Also
SecurityException, checkLink


 Runtime.runFinalization

Runtime.runFinalization

Syntax
public native void runFinalization()
Description
Runs the finalization methods of any objects pending finalization. Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

The Java Virtual Machine performs the finalization process automatically as needed if the runFinalization method is not invoked explicitly.

See Also
finalize


 Runtime.runFinalizersOnExit

Runtime.runFinalizersOnExit

Syntax
public static void runFinalizersOnExit( boolean value )
Description
Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits. By default, finalization on exit is disabled. An invocation of the runFinalizersOnExit method is permitted only if the caller is allowed to exit, and is otherwise rejected by the security manager.

See Also
gc, exit


 Runtime.totalMemory

Runtime.totalMemory

Syntax
public native long totalMemory()
Returns
the total amount of memory currently available for allocating objects, measured in bytes.
Description
Returns the total amount of memory in the Java Virtual Machine.


 Runtime.traceInstructions

Runtime.traceInstructions

Syntax
public native void traceInstructions( boolean on )
Parameters
on
true to enable instruction tracing; false to disable this feature.
Description
Enables/Disables tracing of instructions. If the boolean argument is true, this method asks the Java Virtual Machine to print out a detailed trace of each instruction in the Java Virtual Machine as it is executed. The virtual machine may ignore this request if it does not support this feature. The destination of the trace output is system dependent.

If the boolean argument is false, this method causes the Java Virtual Machine to stop performing the detailed instruction trace it is performing.


 Runtime.traceMethodCalls

Runtime.traceMethodCalls

Syntax
public native void traceMethodCalls( boolean on )
Parameters
on
true to enable instruction tracing; false to disable this feature.
Description
Enables/Disables tracing of method calls. If the boolean argument is true, this method asks the Java Virtual Machine to print out a detailed trace of each method in the Java Virtual Machine as it is called. The virtual machine may ignore this request if it does not support this feature. The destination of the trace output is system dependent.

If the boolean argument is false, this method causes the Java Virtual Machine to stop performing the detailed method trace it is performing.


 Class RuntimeException

Class java.lang.RuntimeException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException

public class RuntimeException
extends Exception

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.


 RuntimeException Members

RuntimeException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
RuntimeException() | Constructs a RuntimeException with no detail message.
RuntimeException(String) | Constructs a RuntimeException with the specified detail message.


 RuntimeException.RuntimeException

RuntimeException.RuntimeException

Syntax 1
public RuntimeException()
Description
Constructs a RuntimeException with no detail message.

Syntax 2
public RuntimeException( String s )
Parameters
s
the detail message.
Description
Constructs a RuntimeException with the specified detail message.


 Class SecurityException

Class java.lang.SecurityException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.SecurityException

public class SecurityException
extends RuntimeException

Thrown by the security manager to indicate a security violation.

See Also:
SecurityManager


 SecurityException Members

SecurityException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SecurityException() | Constructs a SecurityException with no detail message.
SecurityException(String) | Constructs a SecurityException with the specified detail message.


 SecurityException.SecurityException

SecurityException.SecurityException

Syntax 1
public SecurityException()
Description
Constructs a SecurityException with no detail message.

Syntax 2
public SecurityException( String s )
Parameters
s
the detail message.
Description
Constructs a SecurityException with the specified detail message.


 Class SecurityManager

Class java.lang.SecurityManager

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.SecurityManager

public abstract class SecurityManager
extends Object

The security manager is an abstract class that allows applications to implement a security policy. It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether the operation is being performed by a class created via a class loader rather than installed locally. Classes loaded via a class loader (especially if they have been downloaded over a network) may be less trustworthy than classes from files installed locally. The application can allow or disallow the operation.

The SecurityManager class contains many methods with names that begin with the word check. These methods are called by various methods in the Java libraries before those methods perform certain potentially sensitive operations. The invocation of such a check method typically looks like this:

     SecurityManager security = System.getSecurityManager();
     if (security != null) {
         security.checkXXX(argument,  . . . );
     }

The security manager is thereby given an opportunity to prevent completion of the operation by throwing an exception. A security manager routine simply returns if the operation is permitted, but throws a SecurityException if the operation is not permitted. The only exception to this convention is checkTopLevelWindow, which returns a boolean value.

The current security manager is set by the setSecurityManager method in class System. The current security manager is obtained by the getSecurityManager method.

The default implementation of each of the check XXX methods is to assume that the caller does not have permission to perform the requested operation.

See Also:
ClassLoader, SecurityException, checkTopLevelWindow, getSecurityManager, setSecurityManager


 SecurityManager Members

SecurityManager Members

Class Overview | This Package | All Packages

Fields
Name | Description
inCheck | This field is true if there is a security check in progress; false otherwise.

Constructors
Name | Description
SecurityManager() | Constructs a new SecurityManager.

Methods
Name | Description
checkAccept(String, int) | Throws a SecurityException if the calling thread is not permitted to accept a socket connection from the specified host and port number.
checkAccess(Thread) | Throws a SecurityException if the calling thread is not allowed to modify the thread argument.
checkAccess(ThreadGroup) | Throws a SecurityException if the calling thread is not allowed to modify the thread group argument.
checkAwtEventQueueAccess() | Tests if a client can get access to the AWT event queue.
checkConnect(String, int) | Throws a SecurityException if the calling thread is not allowed to open a socket connection to the specified host and port number.
checkConnect(String, int, Object) | Throws a SecurityException if the specified security context is not allowed to open a socket connection to the specified host and port number.
checkCreateClassLoader() | Throws a SecurityException if the calling thread is not allowed to create a new class loader.
checkDelete(String) | Throws a SecurityException if the calling thread is not allowed to delete the specified file.
checkExec(String) | Throws a SecurityException if the calling thread is not allowed to create a subprocss.
checkExit(int) | Throws a SecurityException if the calling thread is not allowed to cause the Java Virtual Machine to halt with the specified status code.
checkLink(String) | Throws a SecurityException if the calling thread is not allowed to dynamic link the library code specified by the string argument file.
checkListen(int) | Throws a SecurityException if the calling thread is not allowed to wait for a connection request on the specified local port number.
checkMemberAccess(Class, int) | Tests if a client is allowed to access members.
checkMulticast(InetAddress) | Tests if current execution context is allowed to use (join/leave/send/receive) IP multicast.
checkMulticast(InetAddress, byte) | Tests to see if current execution context is allowed to use (join/leave/send/receive) IP multicast.
checkPackageAccess(String) | Throws a SecurityException if the calling thread is not allowed to access the package specified by the argument.
checkPackageDefinition(String) | Throws a SecurityException if the calling thread is not allowed to define classes in the package specified by the argument.
checkPrintJobAccess() | Tests if a client can initiate a print job request.
checkPropertiesAccess() | Throws a SecurityException if the calling thread is not allowed to access or modify the system properties.
checkPropertyAccess(String) | Throws a SecurityException if the calling thread is not allowed to access the system property with the specified key name.
checkRead(FileDescriptor) | Throws a SecurityException if the calling thread is not allowed to read from the specified file descriptor.
checkRead(String) | Throws a SecurityException if the calling thread is not allowed to read the file specified by the string argument.
checkRead(String, Object) | Throws a SecurityException if the specified security context is not allowed to read the file specified by the string argument.
checkSecurityAccess(String) | Tests access to certain operations for a security API action.
checkSetFactory() | Throws a SecurityException if the calling thread is not allowed to set the socket factory used by ServerSocket or Socket, or the stream handler factory used by URL.
checkSystemClipboardAccess() | Tests if a client can get access to the system clipboard.
checkTopLevelWindow(Object) | Returns false if the calling thread is not trusted to bring up the top-level window indicated by the window argument.
checkWrite(FileDescriptor) | Throws a SecurityException if the calling thread is not allowed to write to the specified file descriptor.
checkWrite(String) | Throws a SecurityException if the calling thread is not allowed to write to the file specified by the string argument.
classDepth(String) | Returns the stack depth of the specified class.
classLoaderDepth() | Returns the stack depth of the most recently executing method from a class defined using a class loader.
currentClassLoader() | Returns an object describing the most recent class loader executing on the stack.
currentLoadedClass() | Returns the current Class with a ClassLoader on the execution stack.
getClassContext() | Returns the current execution stack as an array of classes.
getInCheck() | Tests if there is a security check in progress.
getSecurityContext() | Creates an object that encapsulates the current execution environment.
getThreadGroup() | Returns the thread group into which to instantiate any new thread being created at the time this is being called.
inClass(String) | Tests if the specified String is in this Class.
inClassLoader() | Tests if the current ClassLoader is equal to null.


 SecurityManager.inCheck

SecurityManager.inCheck

Syntax
protected boolean inCheck
Description
This field is true if there is a security check in progress; false otherwise.


 SecurityManager.SecurityManager

SecurityManager.SecurityManager

Syntax
protected SecurityManager()
Description
Constructs a new SecurityManager. An application is not allowed to create a new security manager if there is already a current security manager.

Exceptions
SecurityException if a security manager already exists.
See Also
getSecurityManager


 SecurityManager.checkAccept

SecurityManager.checkAccept

Syntax
public void checkAccept( String host, int port )
Parameters
host
the host name of the socket connection.
port
the port number of the socket connection.
Description
Throws a SecurityException if the calling thread is not permitted to accept a socket connection from the specified host and port number.

This method is invoked for the current security manager by the accept method of class ServerSocket.

The checkAccept method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to accept the connection.
See Also
getSecurityManager, accept


 SecurityManager.checkAccess

SecurityManager.checkAccess

Syntax 1
public void checkAccess( Thread g )
Parameters
g
the thread to be checked.
Description
Throws a SecurityException if the calling thread is not allowed to modify the thread argument.

This method is invoked for the current security manager by the stop, suspend, resume, setPriority, setName, and setDaemon methods of class Thread.

The checkAccess method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to modify the thread.
See Also
getSecurityManager, resume, setDaemon, setName, setPriority, stop, suspend

Syntax 2
public void checkAccess( ThreadGroup g )
Parameters
g
the thread group to be checked.
Description
Throws a SecurityException if the calling thread is not allowed to modify the thread group argument.

This method is invoked for the current security manager when a new child thread or child thread group is created, and by the setDaemon, setMaxPriority, stop, suspend, resume, and destroy methods of class ThreadGroup.

The checkAccess method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to modify the thread group.
See Also
getSecurityManager, destroy, resume, setDaemon, setMaxPriority, stop, suspend


 SecurityManager.checkAwtEventQueueAccess

SecurityManager.checkAwtEventQueueAccess

Syntax
public void checkAwtEventQueueAccess()
Description
Tests if a client can get access to the AWT event queue.


 SecurityManager.checkConnect

SecurityManager.checkConnect

Syntax 1
public void checkConnect( String host, int port )
Parameters
host
the host name port to connect to.
port
the protocol port to connect to.
Description
Throws a SecurityException if the calling thread is not allowed to open a socket connection to the specified host and port number.

A port number of -1 indicates that the calling method is attempting to determine the IP address of the specified host name.

The checkConnect method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to open a socket connection to the specified host and port.

Syntax 2
public void checkConnect( String host, int port, Object context )
Parameters
host
the host name port to connect to.
port
the protocol port to connect to.
context
a system-dependent security context.
Description
Throws a SecurityException if the specified security context is not allowed to open a socket connection to the specified host and port number.

A port number of -1 indicates that the calling method is attempting to determine the IP address of the specified host name.

The checkConnect method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the specified security context does not have permission to open a socket connection to the specified host and port.
See Also
getSecurityContext


 SecurityManager.checkCreateClassLoader

SecurityManager.checkCreateClassLoader

Syntax
public void checkCreateClassLoader()
Description
Throws a SecurityException if the calling thread is not allowed to create a new class loader.

The checkCreateClassLoader method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to create a new class loader.
See Also
ClassLoader


 SecurityManager.checkDelete

SecurityManager.checkDelete

Syntax
public void checkDelete( String file )
Parameters
file
the system-dependent filename.
Description
Throws a SecurityException if the calling thread is not allowed to delete the specified file.

This method is invoked for the current security manager by the delete method of class File.

The checkDelete method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to delete the file.
See Also
delete, getSecurityManager


 SecurityManager.checkExec

SecurityManager.checkExec

Syntax
public void checkExec( String cmd )
Parameters
cmd
the specified system command.
Description
Throws a SecurityException if the calling thread is not allowed to create a subprocss.

This method is invoked for the current security manager by the exec methods of class Runtime.

The checkExec method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to create a subprocess.
See Also
exec, exec, exec, exec, getSecurityManager


 SecurityManager.checkExit

SecurityManager.checkExit

Syntax
public void checkExit( int status )
Parameters
status
the exit status.
Description
Throws a SecurityException if the calling thread is not allowed to cause the Java Virtual Machine to halt with the specified status code.

This method is invoked for the current security manager by the exit method of class Runtime. A status of 0 indicates success; other values indicate various errors.

The checkExit method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to halt the Java Virtual Machine with the specified status.
See Also
exit, getSecurityManager


 SecurityManager.checkLink

SecurityManager.checkLink

Syntax
public void checkLink( String lib )
Parameters
lib
the name of the library.
Description
Throws a SecurityException if the calling thread is not allowed to dynamic link the library code specified by the string argument file. The argument is either a simple library name or a complete filename.

This method is invoked for the current security manager by methods load and loadLibrary of class Runtime.

The checkLink method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to dynamically link the library.
See Also
load, loadLibrary, getSecurityManager


 SecurityManager.checkListen

SecurityManager.checkListen

Syntax
public void checkListen( int port )
Parameters
port
the local port.
Description
Throws a SecurityException if the calling thread is not allowed to wait for a connection request on the specified local port number.

The checkListen method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to listen on the specified port.


 SecurityManager.checkMemberAccess

SecurityManager.checkMemberAccess

Syntax
public void checkMemberAccess( Class clazz, int which )
Description
Tests if a client is allowed to access members. If access is denied, throw a SecurityException. The default policy is to deny all accesses.


 SecurityManager.checkMulticast

SecurityManager.checkMulticast

Syntax 1
public void checkMulticast( InetAddress maddr )
Parameters
multicast
Internet group address to be used.
Description
Tests if current execution context is allowed to use (join/leave/send/receive) IP multicast.

Exceptions
SecurityException if a security error has occurred.

Syntax 2
public void checkMulticast( InetAddress maddr, byte ttl )
Parameters
multicast
Internet group address to be used.
ttl
value in use, if it is multicast send.
Description
Tests to see if current execution context is allowed to use (join/leave/send/receive) IP multicast.

Exceptions
SecurityException if a security error has occurred.


 SecurityManager.checkPackageAccess

SecurityManager.checkPackageAccess

Syntax
public void checkPackageAccess( String pkg )
Parameters
pkg
the package name.
Description
Throws a SecurityException if the calling thread is not allowed to access the package specified by the argument.

This method is used by the loadClass method of class loaders.

The checkPackageAccess method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified package.
See Also
loadClass


 SecurityManager.checkPackageDefinition

SecurityManager.checkPackageDefinition

Syntax
public void checkPackageDefinition( String pkg )
Parameters
pkg
the package name.
Description
Throws a SecurityException if the calling thread is not allowed to define classes in the package specified by the argument.

This method is used by the loadClass method of some class loaders.

The checkPackageDefinition method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to define classes in the specified package.
See Also
loadClass


 SecurityManager.checkPrintJobAccess

SecurityManager.checkPrintJobAccess

Syntax
public void checkPrintJobAccess()
Description
Tests if a client can initiate a print job request.


 SecurityManager.checkPropertiesAccess

SecurityManager.checkPropertiesAccess

Syntax
public void checkPropertiesAccess()
Description
Throws a SecurityException if the calling thread is not allowed to access or modify the system properties.

This method is used by the getProperties and setProperties methods of class System.

The checkPropertiesAccess method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access or modify the system properties.
See Also
getProperties, setProperties


 SecurityManager.checkPropertyAccess

SecurityManager.checkPropertyAccess

Syntax
public void checkPropertyAccess( String key )
Parameters
key
a system property key.
Description
Throws a SecurityException if the calling thread is not allowed to access the system property with the specified key name.

This method is used by the getProperty method of class System.

The checkPropertiesAccess method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified system property.
See Also
getProperty


 SecurityManager.checkRead

SecurityManager.checkRead

Syntax 1
public void checkRead( FileDescriptor fd )
Parameters
fd
the system-dependent file descriptor.
Description
Throws a SecurityException if the calling thread is not allowed to read from the specified file descriptor.

The checkRead method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified file descriptor.
See Also
FileDescriptor

Syntax 2
public void checkRead( String file )
Parameters
file
the system-dependent file name.
Description
Throws a SecurityException if the calling thread is not allowed to read the file specified by the string argument.

The checkRead method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified file.

Syntax 3
public void checkRead( String file, Object context )
Parameters
file
the system-dependent filename.
context
a system-dependent security context.
Description
Throws a SecurityException if the specified security context is not allowed to read the file specified by the string argument. The context must be a security context returned by a previous call to getSecurityContext.

The checkRead method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the specified security context does not have permission to read the specified file.
See Also
getSecurityContext


 SecurityManager.checkSecurityAccess

SecurityManager.checkSecurityAccess

Syntax
public void checkSecurityAccess( String action )
Description
Tests access to certain operations for a security API action.


 SecurityManager.checkSetFactory

SecurityManager.checkSetFactory

Syntax
public void checkSetFactory()
Description
Throws a SecurityException if the calling thread is not allowed to set the socket factory used by ServerSocket or Socket, or the stream handler factory used by URL.

The checkSetFactory method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to specify a socket factory or a stream handler factory.
See Also
setSocketFactory, setSocketImplFactory, setURLStreamHandlerFactory


 SecurityManager.checkSystemClipboardAccess

SecurityManager.checkSystemClipboardAccess

Syntax
public void checkSystemClipboardAccess()
Description
Tests if a client can get access to the system clipboard.


 SecurityManager.checkTopLevelWindow

SecurityManager.checkTopLevelWindow

Syntax
public boolean checkTopLevelWindow( Object window )
Parameters
window
the new window that is being created.
Returns
true if the caller is trusted to put up top-level windows; false otherwise.
Description
Returns false if the calling thread is not trusted to bring up the top-level window indicated by the window argument. In this case, the caller can still decide to show the window, but the window should include some sort of visual warning. If the method returns true, then the window can be shown without any special restrictions.

See class Window for more information on trusted and untrusted windows.

The checkSetFactory method for class SecurityManager always returns false.

Exceptions
SecurityException if creation is disallowed entirely.
See Also
Window


 SecurityManager.checkWrite

SecurityManager.checkWrite

Syntax 1
public void checkWrite( FileDescriptor fd )
Parameters
fd
the system-dependent file descriptor.
Description
Throws a SecurityException if the calling thread is not allowed to write to the specified file descriptor.

The checkWrite method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified file descriptor.
See Also
FileDescriptor

Syntax 2
public void checkWrite( String file )
Parameters
file
the system-dependent filename.
Description
Throws a SecurityException if the calling thread is not allowed to write to the file specified by the string argument.

The checkWrite method for class SecurityManager always throws a SecurityException.

Exceptions
SecurityException if the caller does not have permission to access the specified file.


 SecurityManager.classDepth

SecurityManager.classDepth

Syntax
protected native int classDepth( String name )
Parameters
name
the fully qualified name of the class to search for.
Returns
the depth on the stack frame of the first occurrence of a method from a class with the specified name; -1 if such a frame cannot be found.
Description
Returns the stack depth of the specified class.


 SecurityManager.classLoaderDepth

SecurityManager.classLoaderDepth

Syntax
protected native int classLoaderDepth()
Returns
the depth on the stack frame of the most recent occurrence of a method from a class defined using a class loader; returns -1 if there is no occurrence of a method from a class defined using a class loader.
Description
Returns the stack depth of the most recently executing method from a class defined using a class loader.


 SecurityManager.currentClassLoader

SecurityManager.currentClassLoader

Syntax
protected native ClassLoader currentClassLoader()
Returns
the class loader of the most recent occurrence on the stack of a method from a class defined using a class loader; returns null if there is no occurrence on the stack of a method from a class defined using a class loader.
Description
Returns an object describing the most recent class loader executing on the stack.


 SecurityManager.currentLoadedClass

SecurityManager.currentLoadedClass

Syntax
protected Class currentLoadedClass()
Description
Returns the current Class with a ClassLoader on the execution stack.


 SecurityManager.getClassContext

SecurityManager.getClassContext

Syntax
protected native Class[] getClassContext()
Returns
the execution stack.
Description
Returns the current execution stack as an array of classes.

The length of the array is the number of methods on the execution stack. The element at index 0 is the class of the currently executing method, the element at index 1 is the class of that method's caller, and so on.


 SecurityManager.getInCheck

SecurityManager.getInCheck

Syntax
public boolean getInCheck()
Returns
the value of the inCheck field. This field should contain true if a security check is in progress; false otherwise.
Description
Tests if there is a security check in progress.

See Also
inCheck


 SecurityManager.getSecurityContext

SecurityManager.getSecurityContext

Syntax
public Object getSecurityContext()
Returns
an implementation-dependent object that encapsulates sufficient information about the current execution environment to perform some security checks later.
Description
Creates an object that encapsulates the current execution environment. The result of this method is used by the three-argument checkConnect method and by the two-argument checkRead method.

These methods are needed because a trusted method may be called on to read a file or open a socket on behalf of another method. The trusted method needs to determine if the other (possibly untrusted) method would be allowed to perform the operation on its own.

See Also
checkConnect, checkRead


 SecurityManager.getThreadGroup

SecurityManager.getThreadGroup

Syntax
public ThreadGroup getThreadGroup()
Description
Returns the thread group into which to instantiate any new thread being created at the time this is being called. By default, it returns the thread group of the current thread. This should be overriden by specific security manager to return the appropriate thread group.


 SecurityManager.inClass

SecurityManager.inClass

Syntax
protected boolean inClass( String name )
Parameters
name
the fully qualified name of the class.
Returns
true if a method from a class with the specified name is on the execution stack; false otherwise.
Description
Tests if the specified String is in this Class.


 SecurityManager.inClassLoader

SecurityManager.inClassLoader

Syntax
protected boolean inClassLoader()
Returns
true if a method from a class defined using a class loader is on the execution stack.
Description
Tests if the current ClassLoader is equal to null.


 Class Short

Class java.lang.Short

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.lang.Short

public final class Short
extends Number

The Short class is the standard wrapper for short values.

See Also:
Number


 Short Members

Short Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_VALUE | The maximum value a Short can have.
MIN_VALUE | The minimum value a Short can have.
TYPE | The Class object representing the primitive type short.

Constructors
Name | Description
Short(short) | Constructs a Short object initialized to the specified short value.
Short(String) | Constructs a Short object initialized to the value specified by the String parameter.

Methods
Name | Description
byteValue() | Returns the value of this Short as a byte.
decode(String) | Decodes a String into a Short.
doubleValue() | Returns the value of this Short as a double.
equals(Object) | Compares this object to the specified object.
floatValue() | Returns the value of this Short as a float.
hashCode() | Returns a hashcode for this Short.
intValue() | Returns the value of this Short as an int.
longValue() | Returns the value of this Short as a long.
parseShort(String) | Assuming the specified String represents a short, returns that short's value.
parseShort(String, int) | Assuming the specified String represents a short, returns that short's value.
shortValue() | Returns the value of this Short as a short.
toString() | Returns a String object representing this Short's value.
toString(short) | Returns a new String object representing the specified Short.
valueOf(String) | Assuming the specified String represents a short, returns a new Short object initialized to that value.
valueOf(String, int) | Assuming the specified String represents a short, returns a new Short object initialized to that value.


 Short.MAX_VALUE

Short.MAX_VALUE

Syntax
public static final short MAX_VALUE
Description
The maximum value a Short can have.


 Short.MIN_VALUE

Short.MIN_VALUE

Syntax
public static final short MIN_VALUE
Description
The minimum value a Short can have.


 Short.TYPE

Short.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive type short.


 Short.Short

Short.Short

Syntax 1
public Short( short value )
Parameters
value
the initial value of the Short
Description
Constructs a Short object initialized to the specified short value.

Syntax 2
public Short( String s ) throws NumberFormatException
Parameters
s
the String to be converted to a Short
Description
Constructs a Short object initialized to the value specified by the String parameter. The radix is assumed to be 10.

Exceptions
NumberFormatException If the String does not contain a parsable short.


 Short.byteValue

Short.byteValue

Syntax
public byte byteValue()
Description
Returns the value of this Short as a byte.

Overrides
byteValue in class Number


 Short.decode

Short.decode

Syntax
public static Short decode( String nm ) throws NumberFormatException
Parameters
nm
the string to decode
Description
Decodes a String into a Short. The String may represent decimal, hexadecimal, and octal numbers.


 Short.doubleValue

Short.doubleValue

Syntax
public double doubleValue()
Description
Returns the value of this Short as a double.

Overrides
doubleValue in class Number


 Short.equals

Short.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with
Returns
true if the objects are the same; false otherwise.
Description
Compares this object to the specified object.

Overrides
equals in class Object


 Short.floatValue

Short.floatValue

Syntax
public float floatValue()
Description
Returns the value of this Short as a float.

Overrides
floatValue in class Number


 Short.hashCode

Short.hashCode

Syntax
public int hashCode()
Description
Returns a hashcode for this Short.

Overrides
hashCode in class Object


 Short.intValue

Short.intValue

Syntax
public int intValue()
Description
Returns the value of this Short as an int.

Overrides
intValue in class Number


 Short.longValue

Short.longValue

Syntax
public long longValue()
Description
Returns the value of this Short as a long.

Overrides
longValue in class Number


 Short.parseShort

Short.parseShort

Syntax 1
public static short parseShort( String s ) throws NumberFormatException
Parameters
s
the String containing the short
Description
Assuming the specified String represents a short, returns that short's value. Throws an exception if the String cannot be parsed as a short. The radix is assumed to be 10.

Exceptions
NumberFormatException If the string does not contain a parsable short.

Syntax 2
public static short parseShort( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the short
radix
the radix to be used
Description
Assuming the specified String represents a short, returns that short's value. Throws an exception if the String cannot be parsed as a short.

Exceptions
NumberFormatException If the String does not contain a parsable short.


 Short.shortValue

Short.shortValue

Syntax
public short shortValue()
Description
Returns the value of this Short as a short.

Overrides
shortValue in class Number


 Short.toString

Short.toString

Syntax
public static String toString( short s )
Parameters
s
the short to be converted
Description
Returns a new String object representing the specified Short. The radix is assumed to be 10.


 Short.toString

Short.toString

Syntax
public String toString()
Description
Returns a String object representing this Short's value.

Overrides
toString in class Object


 Short.valueOf

Short.valueOf

Syntax 1
public static Short valueOf( String s, int radix ) throws NumberFormatException
Parameters
s
the String containing the integer
radix
the radix to be used
Description
Assuming the specified String represents a short, returns a new Short object initialized to that value. Throws an exception if the String cannot be parsed as a short.

Exceptions
NumberFormatException If the String does not contain a parsable short.

Syntax 2
public static Short valueOf( String s ) throws NumberFormatException
Parameters
s
the String containing the integer
Description
Assuming the specified String represents a short, returns a new Short object initialized to that value. Throws an exception if the String cannot be parsed as a short.

Exceptions
NumberFormatException If the String does not contain a parsable short.


 Class StackOverflowError

Class java.lang.StackOverflowError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.VirtualMachineError
                           |
                           +----java.lang.StackOverflowError

public class StackOverflowError
extends VirtualMachineError

Thrown when a stack overflow occurs because an application recurses too deeply.


 StackOverflowError Members

StackOverflowError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StackOverflowError() | Constructs a StackOverflowError with no detail message.
StackOverflowError(String) | Constructs a StackOverflowError with the specified detail message.


 StackOverflowError.StackOverflowError

StackOverflowError.StackOverflowError

Syntax 1
public StackOverflowError()
Description
Constructs a StackOverflowError with no detail message.

Syntax 2
public StackOverflowError( String s )
Parameters
s
the detail message.
Description
Constructs a StackOverflowError with the specified detail message.


 Class String

Class java.lang.String

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.String

public final class String
extends Object
implements Serializable

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2,3);
     String d = cde.substring(1, 2);

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase.

The Java language provides special support for the string concatentation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuffer class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

See Also:
toString, StringBuffer, append, append, append, append, append, append, append, append, append, append


 String Members

String Members

Class Overview | This Package | All Packages

Constructors
Name | Description
String() | Allocates a new String containing no characters.
String(byte[]) | Construct a new String by converting the specified array of bytes using the platform's default character encoding.
String(byte[], int) | Allocates a new String containing characters constructed from an array of 8-bit integer values. Deprecated.
String(byte[], int, int) | Construct a new String by converting the specified subarray of bytes using the platform's default character encoding.
String(byte[], int, int, int) | Allocates a new String constructed from a subarray of an array of 8-bit integer values. Deprecated.
String(byte[], int, int, String) | Construct a new String by converting the specified subarray of bytes using the specified character encoding.
String(byte[], String) | Construct a new String by converting the specified array of bytes using the specified character encoding.
String(char[]) | Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
String(char[], int, int) | Allocates a new String that contains characters from a subarray of the character array argument.
String(String) | Allocates a new string that contains the same sequence of characters as the string argument.
String(StringBuffer) | Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.

Methods
Name | Description
charAt(int) | Returns the character at the specified index.
compareTo(String) | Compares two strings lexicographically.
concat(String) | Concatenates the specified string to the end of this string.
copyValueOf(char[]) | Returns a String that is equivalent to the specified character array.
copyValueOf(char[], int, int) | Returns a String that is equivalent to the specified character array.
endsWith(String) | Tests if this string ends with the specified suffix.
equals(Object) | Compares this string to the specified object.
equalsIgnoreCase(String) | Compares this String to another object.
getBytes() | Convert this String into bytes according to the platform's default character encoding, storing the result into a new byte array.
getBytes(int, int, byte[], int) | Copies characters from this string into the destination byte array. Deprecated.
getBytes(String) | Convert this String into bytes according to the specified character encoding, storing the result into a new byte array.
getChars(int, int, char[], int) | Copies characters from this string into the destination character array.
hashCode() | Returns a hashcode for this string.
indexOf(int) | Returns the index within this string of the first occurrence of the specified character.
indexOf(int, int) | Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
indexOf(String) | Returns the index within this string of the first occurrence of the specified substring.
indexOf(String, int) | Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
intern() | Returns a canonical representation for the string object.
lastIndexOf(int) | Returns the index within this string of the last occurrence of the specified character.
lastIndexOf(int, int) | Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
lastIndexOf(String) | Returns the index within this string of the rightmost occurrence of the specified substring.
lastIndexOf(String, int) | Returns the index within this string of the last occurrence of the specified substring.
length() | Returns the length of this string.
regionMatches(boolean, int, String, int, int) | Tests if two string regions are equal.
regionMatches(int, String, int, int) | Tests if two string regions are equal.
replace(char, char) | Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
startsWith(String) | Tests if this string starts with the specified prefix.
startsWith(String, int) | Tests if this string starts with the specified prefix.
substring(int) | Returns a new string that is a substring of this string.
substring(int, int) | Returns a new string that is a substring of this string.
toCharArray() | Converts this string to a new character array.
toLowerCase() | Converts this String to lowercase.
toLowerCase(Locale) | Converts all of the characters in this String to lower case using the rules of the given locale.
toString() | This object (which is already a string!) is itself returned.
toUpperCase() | Converts this string to uppercase.
toUpperCase(Locale) | Converts all of the characters in this String to upper case using the rules of the given locale.
trim() | Removes white space from both ends of this string.
valueOf(boolean) | Returns the string representation of the boolean argument.
valueOf(char) | Returns the string representation of the char * argument.
valueOf(char[]) | Returns the string representation of the char array argument.
valueOf(char[], int, int) | Returns the string representation of a specific subarray of the char array argument.
valueOf(double) | Returns the string representation of the double argument.
valueOf(float) | Returns the string representation of the float argument.
valueOf(int) | Returns the string representation of the int argument.
valueOf(long) | Returns the string representation of the long argument.
valueOf(Object) | Returns the string representation of the Object argument.


 String.String

String.String

Syntax 1
public String()
Description
Allocates a new String containing no characters.

Syntax 2
public String( String value )
Parameters
value
a String.
Description
Allocates a new string that contains the same sequence of characters as the string argument.

Syntax 3
public String( char value[] )
Parameters
value
the initial value of the string.
Description
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

Syntax 4
public String( char value[], int offset, int count )
Parameters
value
array that is the source of characters.
offset
the initial offset.
count
the length.
Description
Allocates a new String that contains characters from a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray.

Exceptions
StringIndexOutOfBoundsException if the offset and count arguments index characters outside the bounds of the value array.

Syntax 5
public String( byte ascii[], int hibyte, int offset, int count )
Parameters
ascii
the bytes to be converted to characters.
hibyte
the top 8 bits of each 16-bit Unicode character.
offset
the initial offset.
count
the length.
Description
Note: String() is deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a character-encoding name or that use the platform's default encoding.

Allocates a new String constructed from a subarray of an array of 8-bit integer values.

The offset argument is the index of the first byte of the subarray, and the count argument specifies the length of the subarray.

Each byte in the subarray is converted to a char as specified in the method above.

Exceptions
StringIndexOutOfBoundsException if the offset or count argument is invalid.
See Also
String, String, String, String, String

Syntax 6
public String( byte ascii[], int hibyte )
Parameters
ascii
the bytes to be converted to characters.
hibyte
the top 8 bits of each 16-bit Unicode character.
Description
Note: String() is deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a character-encoding name or that use the platform's default encoding.

Allocates a new String containing characters constructed from an array of 8-bit integer values. Each character cin the resulting string is constructed from the corresponding component b in the byte array such that:

     c == (char)(((hibyte & 0xff) << 8)
                         | (b & 0xff))

See Also
String, String, String, String

Syntax 7
public String( byte bytes[], int offset, int length, String enc ) throws UnsupportedEncodingException
Parameters
bytes
The bytes to be converted into characters
offset
Index of the first byte to convert
length
Number of bytes to convert
enc
The name of a character encoding
Description
Construct a new String by converting the specified subarray of bytes using the specified character encoding. The length of the new String is a function of the encoding, and hence may not be equal to the length of the subarray.

Exceptions
UnsupportedEncodingException If the named encoding is not supported

Syntax 8
public String( byte bytes[], String enc ) throws UnsupportedEncodingException
Parameters
bytes
The bytes to be converted into characters
enc
A character-encoding name
Description
Construct a new String by converting the specified array of bytes using the specified character encoding. The length of the new String is a function of the encoding, and hence may not be equal to the length of the byte array.

Exceptions
UnsupportedEncodingException If the named encoding is not supported

Syntax 9
public String( byte bytes[], int offset, int length )
Parameters
bytes
The bytes to be converted into characters
offset
Index of the first byte to convert
length
Number of bytes to convert
Description
Construct a new String by converting the specified subarray of bytes using the platform's default character encoding. The length of the new String is a function of the encoding, and hence may not be equal to the length of the subarray.

Syntax 10
public String( byte bytes[] )
Parameters
bytes
The bytes to be converted into characters
Description
Construct a new String by converting the specified array of bytes using the platform's default character encoding. The length of the new String is a function of the encoding, and hence may not be equal to the length of the byte array.

Syntax 11
public String( StringBuffer buffer )
Parameters
buffer
a StringBuffer.
Description
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.


 String.charAt

String.charAt

Syntax
public char charAt( int index )
Parameters
index
the index of the character.
Returns
the character at the specified index of this string. The first character is at index 0.
Description
Returns the character at the specified index. An index ranges from 0 to length() - 1.

Exceptions
StringIndexOutOfBoundsException if the index is out of range.


 String.compareTo

String.compareTo

Syntax
public int compareTo( String anotherString )
Parameters
anotherString
the String to be compared.
Returns
the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
Description
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.


 String.concat

String.concat

Syntax
public String concat( String str )
Parameters
str
the String that is concatenated to the end of this String.
Returns
a string that represents the concatenation of this object's characters followed by the string argument's characters.
Description
Concatenates the specified string to the end of this string.

If the length of the argument string is 0, then this object is returned.


 String.copyValueOf

String.copyValueOf

Syntax 1
public static String copyValueOf( char data[], int offset, int count )
Parameters
data
the character array.
offset
initial offset of the subarray.
count
length of the subarray.
Returns
a String that contains the characters of the specified subarray of the character array.
Description
Returns a String that is equivalent to the specified character array. It creates a new array and copies the characters into it.

Syntax 2
public static String copyValueOf( char data[] )
Parameters
data
the character array.
Returns
a String that contains the characters of the character array.
Description
Returns a String that is equivalent to the specified character array. It creates a new array and copies the characters into it.


 String.endsWith

String.endsWith

Syntax
public boolean endsWith( String suffix )
Parameters
suffix
the suffix.
Returns
true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise.
Description
Tests if this string ends with the specified suffix.


 String.equals

String.equals

Syntax
public boolean equals( Object anObject )
Parameters
anObject
the object to compare this String against.
Returns
true if the String are equal; false otherwise.
Description
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Overrides
equals in class Object
See Also
compareTo, equalsIgnoreCase


 String.equalsIgnoreCase

String.equalsIgnoreCase

Syntax
public boolean equalsIgnoreCase( String anotherString )
Parameters
anotherString
the String to compare this String against.
Returns
true if the Strings are equal, ignoring case; false otherwise.
Description
Compares this String to another object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object, where case is ignored.

Two characters are considered the same, ignoring case, if at least one of the following is true:

  • The two characters are the same (as compared by the == operator).
  • Applying the method Character.toUppercase to each character produces the same result.
  • Applying the method Character.toLowercase to each character produces the same result.

Two sequences of characters are the same, ignoring case, if the sequences have the same length and corresponding characters are the same, ignoring case.

See Also
toLowerCase, toUpperCase


 String.getBytes

String.getBytes

Syntax 1
public void getBytes( int srcBegin, int srcEnd, byte dst[], int dstBegin )
Parameters
srcBegin
index of the first character in the string to copy.
srcEnd
index after the last character in the string to copy.
dst
the destination array.
dstBegin
the start offset in the destination array.
Description
Note: getBytes() is deprecated. This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes(String enc) method, which takes a character-encoding name, or the getBytes() method, which uses the platform's default encoding.

Copies characters from this string into the destination byte array. Each byte receives the 8 low-order bits of the corresponding character.

The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1. The total number of characters to be copied is srcEnd-srcBegin. The characters, converted to bytes, are copied into the subarray of dst starting at index dstBegin and ending at index:

     dstbegin + (srcEnd-srcBegin) - 1

Exceptions
StringIndexOutOfBoundsException if srcBegin or srcEnd is out of range, or if srcBegin is greater than srcEnd.

Syntax 2
public byte[] getBytes( String enc ) throws UnsupportedEncodingException
Parameters
enc
A character-encoding name
Returns
The resultant byte array
Description
Convert this String into bytes according to the specified character encoding, storing the result into a new byte array.

Exceptions
UnsupportedEncodingException If the named encoding is not supported

Syntax 3
public byte[] getBytes()
Returns
the resultant byte array.
Description
Convert this String into bytes according to the platform's default character encoding, storing the result into a new byte array.


 String.getChars

String.getChars

Syntax
public void getChars( int srcBegin, int srcEnd, char dst[], int dstBegin )
Parameters
srcBegin
index of the first character in the string to copy.
srcEnd
index after the last character in the string to copy.
dst
the destination array.
dstBegin
the start offset in the destination array.
Description
Copies characters from this string into the destination character array.

The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

     dstbegin + (srcEnd-srcBegin) - 1

Exceptions
StringIndexOutOfBoundsException If srcBegin or srcEnd is out of range, or if srcBegin is greater than the srcEnd.


 String.hashCode

String.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hashcode for this string.

Overrides
hashCode in class Object


 String.indexOf

String.indexOf

Syntax 1
public int indexOf( int ch )
Parameters
ch
a character.
Returns
the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
Description
Returns the index within this string of the first occurrence of the specified character.

Syntax 2
public int indexOf( int ch, int fromIndex )
Parameters
ch
a character.
fromIndex
the index to start the search from.
Returns
the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.
Description
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.


 String.indexOf

String.indexOf

Syntax 1
public int indexOf( String str )
Parameters
str
any string.
Returns
if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
Description
Returns the index within this string of the first occurrence of the specified substring.

Syntax 2
public int indexOf( String str, int fromIndex )
Parameters
str
the substring to search for.
fromIndex
the index to start the search from.
Returns
If the string argument occurs as a substring within this object at a starting index no smaller than fromIndex, then the index of the first character of the first such substring is returned. If it does not occur as a substring starting at fromIndex or beyond, -1 is returned.
Description
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.


 String.intern

String.intern

Syntax
public native String intern()
Returns
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
Description
Returns a canonical representation for the string object.

If s and t are strings such that s.equals(t), it is guaranteed that
s.intern() == t.intern().


 String.lastIndexOf

String.lastIndexOf

Syntax 1
public int lastIndexOf( int ch )
Parameters
ch
a character.
Returns
the index of the last occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
Description
Returns the index within this string of the last occurrence of the specified character. The String is searched backwards starting at the last character.

Syntax 2
public int lastIndexOf( int ch, int fromIndex )
Parameters
ch
a character.
fromIndex
the index to start the search from.
Returns
the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.
Description
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.


 String.lastIndexOf

String.lastIndexOf

Syntax 1
public int lastIndexOf( String str )
Parameters
str
the substring to search for.
Returns
if the string argument occurs one or more times as a substring within this object, then the index of the first character of the last such substring is returned. If it does not occur as a substring, -1 is returned.
Description
Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string "" is considered to occur at the index value this.length().

Syntax 2
public int lastIndexOf( String str, int fromIndex )
Parameters
str
the substring to search for.
fromIndex
the index to start the search from.
Returns
If the string argument occurs one or more times as a substring within this object at a starting index no greater than fromIndex, then the index of the first character of the last such substring is returned. If it does not occur as a substring starting at fromIndex or earlier, -1 is returned.
Description
Returns the index within this string of the last occurrence of the specified substring. The returned index indicates the start of the substring, and it must be equal to or less than fromIndex.


 String.length

String.length

Syntax
public int length()
Returns
the length of the sequence of characters represented by this object.
Description
Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.


 String.regionMatches

String.regionMatches

Syntax 1
public boolean regionMatches( int toffset, String other, int ooffset, int len )
Parameters
toffset
the starting offset of the subregion in this string.
other
the string argument.
ooffset
the starting offset of the subregion in the string argument.
len
the number of characters to compare.
Returns
true if the specified subregion of this string exactly matches the specified subregion of the string argument; false otherwise.
Description
Tests if two string regions are equal.

If toffset or ooffset is negative, or if toffset+length is greater than the length of this string, or if ooffset+length is greater than the length of the string argument, then this method returns false.

Syntax 2
public boolean regionMatches( boolean ignoreCase, int toffset, String other, int ooffset, int len )
Parameters
ignoreCase
if true, ignore case when comparing characters.
toffset
the starting offset of the subregion in this string.
other
the string argument.
ooffset
the starting offset of the subregion in the string argument.
len
the number of characters to compare.
Returns
true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
Description
Tests if two string regions are equal.

If toffset or ooffset is negative, or if toffset+length is greater than the length of this string, or if ooffset+length is greater than the length of the string argument, then this method returns false.


 String.replace

String.replace

Syntax
public String replace( char oldChar, char newChar )
Parameters
oldChar
the old character.
newChar
the new character.
Returns
a string derived from this string by replacing every occurrence of oldChar with newChar.
Description
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

If the character oldChar does not occur in the character sequence represented by this object, then this string is returned.


 String.startsWith

String.startsWith

Syntax 1
public boolean startsWith( String prefix, int toffset )
Parameters
prefix
the prefix.
toffset
where to begin looking in the string.
Returns
true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset; false otherwise.
Description
Tests if this string starts with the specified prefix.

Syntax 2
public boolean startsWith( String prefix )
Parameters
prefix
the prefix.
Returns
true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.
Description
Tests if this string starts with the specified prefix.


 String.substring

String.substring

Syntax 1
public String substring( int beginIndex )
Parameters
beginIndex
the beginning index, inclusive.
Returns
the specified substring.
Description
Returns a new string that is a substring of this string. The substring begins at the specified index and extends to the end of this string.

Exceptions
StringIndexOutOfBoundsException if the beginIndex is out of range.

Syntax 2
public String substring( int beginIndex, int endIndex )
Parameters
beginIndex
the beginning index, inclusive.
endIndex
the ending index, exclusive.
Returns
the specified substring.
Description
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.

Exceptions
StringIndexOutOfBoundsException if the beginIndex or the endIndex is out of range.


 String.toCharArray

String.toCharArray

Syntax
public char[] toCharArray()
Returns
a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
Description
Converts this string to a new character array.


 String.toLowerCase

String.toLowerCase

Syntax 1
public String toLowerCase( Locale locale )
Parameters
locale
use the case transformation rules for this locale
Returns
the String, converted to lowercase.
Description
Converts all of the characters in this String to lower case using the rules of the given locale.

See Also
toLowerCase, toUpperCase

Syntax 2
public String toLowerCase()
Returns
the string, converted to lowercase.
Description
Converts this String to lowercase.

If no character in the string has a different lowercase version, based on calling the toLowerCase method defined by Character, then the original string is returned.

Otherwise, a new string is allocated, whose length is identical to this string, and such that each character that has a different lowercase version is mapped to this lowercase equivalent.

See Also
toLowerCase, toUpperCase


 String.toString

String.toString

Syntax
public String toString()
Returns
the string itself.
Description
This object (which is already a string!) is itself returned.

Overrides
toString in class Object


 String.toUpperCase

String.toUpperCase

Syntax 1
public String toUpperCase( Locale locale )
Parameters
locale
use the case transformation rules for this locale
Returns
the String, converted to uppercase.
Description
Converts all of the characters in this String to upper case using the rules of the given locale.

See Also
toUpperCase, toLowerCase

Syntax 2
public String toUpperCase()
Returns
the string, converted to uppercase.
Description
Converts this string to uppercase.

If no character in this string has a different uppercase version, based on calling the toUpperCase method defined by Character, then the original string is returned.

Otherwise, a new string is allocated, whose length is identical to this string, and such that each character that has a different uppercase version is mapped to this uppercase equivalent.

See Also
toUpperCase, toLowerCase


 String.trim

String.trim

Syntax
public String trim()
Returns
this string, with white space removed from the front and end.
Description
Removes white space from both ends of this string.

All characters that have codes less than or equal to '\u0020' (the space character) are considered to be white space.


 String.valueOf

String.valueOf

Syntax 1
public static String valueOf( Object obj )
Parameters
obj
an Object.
Returns
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Description
Returns the string representation of the Object argument.

See Also
toString

Syntax 2
public static String valueOf( char data[] )
Parameters
data
a char array.
Returns
a newly allocated string representing the same sequence of characters contained in the character array argument.
Description
Returns the string representation of the char array argument.

Syntax 3
public static String valueOf( char data[], int offset, int count )
Parameters
data
the character array.
offset
the initial offset into the value of the String.
count
the length of the value of the String.
Returns
a newly allocated string representing the sequence of characters contained in the subarray of the character array argument.
Description
Returns the string representation of a specific subarray of the char array argument.

The offset argument is the index of the first character of the subarray. The count argument specifies the length of the subarray.


 String.valueOf

String.valueOf

Syntax 1
public static String valueOf( boolean b )
Parameters
b
a boolean.
Returns
if the argument is true, a string equal to "true" is returned; otherwise, a string equal to "false" is returned.
Description
Returns the string representation of the boolean argument.

Syntax 2
public static String valueOf( char c )
Parameters
c
a char.
Returns
a newly allocated string of length 1 containing as its single character the argument c.
Description
Returns the string representation of the char * argument.

Syntax 3
public static String valueOf( int i )
Parameters
i
an int.
Returns
a newly allocated string containing a string representation of the int argument.
Description
Returns the string representation of the int argument.

The representation is exactly the one returned by the Integer.toString method of one argument.

See Also
toString

Syntax 4
public static String valueOf( long l )
Parameters
l
a long.
Returns
a newly allocated string containing a string representation of the long argument.
Description
Returns the string representation of the long argument.

The representation is exactly the one returned by the Long.toString method of one argument.

See Also
toString

Syntax 5
public static String valueOf( float f )
Parameters
f
a float.
Returns
a newly allocated string containing a string representation of the float argument.
Description
Returns the string representation of the float argument.

The representation is exactly the one returned by the Float.toString method of one argument.

See Also
toString

Syntax 6
public static String valueOf( double d )
Parameters
d
a double.
Returns
a newly allocated string containing a string representation of the double argument.
Description
Returns the string representation of the double argument.

The representation is exactly the one returned by the Double.toString method of one argument.

See Also
toString


 Class StringBuffer

Class java.lang.StringBuffer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.StringBuffer

public final class StringBuffer
extends Object
implements Serializable

A string buffer implements a mutable sequence of characters.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order.

String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

     x = "a" + 4 + "c"

is compiled to the equivalent of:

     x = new StringBuffer().append("a").append(4).append("c")
                           .toString()

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

See Also:
ByteArrayOutputStream, String


 StringBuffer Members

StringBuffer Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringBuffer() | Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(int) | Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.
StringBuffer(String) | Constructs a string buffer so that it represents the same sequence of characters as the string argument.

Methods
Name | Description
append(boolean) | Appends the string representation of the boolean argument to the string buffer.
append(char) | Appends the string representation of the char argument to this string buffer.
append(char[]) | Appends the string representation of the char array argument to this string buffer.
append(char[], int, int) | Appends the string representation of a subarray of the char array argument to this string buffer.
append(double) | Appends the string representation of the double argument to this string buffer.
append(float) | Appends the string representation of the float argument to this string buffer.
append(int) | Appends the string representation of the int argument to this string buffer.
append(long) | Appends the string representation of the long argument to this string buffer.
append(Object) | Appends the string representation of the Object argument to this string buffer.
append(String) | Appends the string to this string buffer.
capacity() | Returns the current capacity of the String buffer.
charAt(int) | Returns the character at a specific index in this string buffer.
ensureCapacity(int) | Ensures that the capacity of the buffer is at least equal to the specified minimum.
getChars(int, int, char[], int) | Characters are copied from this string buffer into the destination character array dst.
insert(int, boolean) | Inserts the string representation of the boolean argument into this string buffer.
insert(int, char) | Inserts the string representation of the char argument into this string buffer.
insert(int, char[]) | Inserts the string representation of the char array argument into this string buffer.
insert(int, double) | Inserts the string representation of the double argument into this string buffer.
insert(int, float) | Inserts the string representation of the float argument into this string buffer.
insert(int, int) | Inserts the string representation of the second int argument into this string buffer.
insert(int, long) | Inserts the string representation of the long argument into this string buffer.
insert(int, Object) | Inserts the string representation of the Object argument into this string buffer.
insert(int, String) | Inserts the string into this string buffer.
length() | Returns the length (character count) of this string buffer.
reverse() | The character sequence contained in this string buffer is replaced by the reverse of the sequence.
setCharAt(int, char) | The character at the specified index of this string buffer is set to ch.
setLength(int) | Sets the length of this String buffer.
toString() | Converts to a string representing the data in this string buffer.


 StringBuffer.StringBuffer

StringBuffer.StringBuffer

Syntax 1
public StringBuffer()
Description
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

Syntax 2
public StringBuffer( int length )
Parameters
length
the initial capacity.
Description
Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.

Exceptions
NegativeArraySizeException if the length argument is less than 0.

Syntax 3
public StringBuffer( String str )
Parameters
str
the initial contents of the buffer.
Description
Constructs a string buffer so that it represents the same sequence of characters as the string argument. The initial capacity of the string buffer is 16 plus the length of the string argument.


 StringBuffer.append

StringBuffer.append

Syntax 1
public synchronized StringBuffer append( Object obj )
Parameters
obj
an Object.
Returns
this string buffer.
Description
Appends the string representation of the Object argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append

Syntax 2
public synchronized StringBuffer append( String str )
Parameters
str
a string.
Returns
this string buffer.
Description
Appends the string to this string buffer.

The characters of the String argument are appended, in order, to the contents of this string buffer, increasing the length of this string buffer by the length of the argument.

Syntax 3
public synchronized StringBuffer append( char str[] )
Parameters
str
the characters to be appended.
Returns
this string buffer.
Description
Appends the string representation of the char array argument to this string buffer.

The characters of the array argument are appended, in order, to the contents of this string buffer. The length of this string buffer increases by the length of the argument.

Syntax 4
public synchronized StringBuffer append( char str[], int offset, int len )
Parameters
str
the characters to be appended.
offset
the index of the first character to append.
len
the number of characters to append.
Returns
this string buffer.
Description
Appends the string representation of a subarray of the char array argument to this string buffer.

Characters of the character array str, starting at index offset, are appended, in order, to the contents of this string buffer. The length of this string buffer increases by the value of len.

Syntax 5
public StringBuffer append( boolean b )
Parameters
b
a boolean.
Returns
this string buffer.
Description
Appends the string representation of the boolean argument to the string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append

Syntax 6
public synchronized StringBuffer append( char c )
Parameters
ch
a char.
Returns
this string buffer.
Description
Appends the string representation of the char argument to this string buffer.

The argument is appended to the contents of this string buffer. The length of this string buffer increases by 1.

Syntax 7
public StringBuffer append( int i )
Parameters
i
an int.
Returns
this string buffer.
Description
Appends the string representation of the int argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append

Syntax 8
public StringBuffer append( long l )
Parameters
l
a long.
Returns
this string buffer.
Description
Appends the string representation of the long argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append

Syntax 9
public StringBuffer append( float f )
Parameters
f
a float.
Returns
this string buffer.
Description
Appends the string representation of the float argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append

Syntax 10
public StringBuffer append( double d )
Parameters
d
a double.
Returns
this string buffer.
Description
Appends the string representation of the double argument to this string buffer.

The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.

See Also
valueOf, append


 StringBuffer.capacity

StringBuffer.capacity

Syntax
public int capacity()
Returns
the current capacity of this string buffer.
Description
Returns the current capacity of the String buffer. The capacity is the amount of storage available for newly inserted characters; beyond which an allocation will occur.


 StringBuffer.charAt

StringBuffer.charAt

Syntax
public synchronized char charAt( int index )
Parameters
index
the index of the desired character.
Returns
the character at the specified index of this string buffer.
Description
Returns the character at a specific index in this string buffer.

The first character of a string buffer is at index 0, the next at index 1, and so on, for array indexing.

The index argument must be greater than or equal to 0, and less than the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the index is invalid.
See Also
length


 StringBuffer.ensureCapacity

StringBuffer.ensureCapacity

Syntax
public synchronized void ensureCapacity( int minimumCapacity )
Parameters
minimumCapacity
the minimum desired capacity.
Description
Ensures that the capacity of the buffer is at least equal to the specified minimum. If the current capacity of this string buffer is less than the argument, then a new internal buffer is allocated with greater capacity. The new capacity is the larger of:
  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.
If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.


 StringBuffer.getChars

StringBuffer.getChars

Syntax
public synchronized void getChars( int srcBegin, int srcEnd, char dst[], int dstBegin )
Parameters
srcBegin
start copying at this offset in the string buffer.
srcEnd
stop copying at this offset in the string buffer.
dst
the array to copy the data into.
dstBegin
offset into dst.
Description
Characters are copied from this string buffer into the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1. The total number of characters to be copied is srcEnd-srcBegin. The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

     dstbegin + (srcEnd-srcBegin) - 1

Exceptions
StringIndexOutOfBoundsException if there is an invalid index into the buffer.


 StringBuffer.insert

StringBuffer.insert

Syntax 1
public synchronized StringBuffer insert( int offset, Object obj )
Parameters
offset
the offset.
b
an Object.
Returns
this string buffer.
Description
Inserts the string representation of the Object argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length

Syntax 2
public synchronized StringBuffer insert( int offset, String str )
Parameters
offset
the offset.
str
a string.
Returns
this string buffer.
Description
Inserts the string into this string buffer.

The characters of the String argument are inserted, in order, into this string buffer at the indicated offset. The length of this string buffer is increased by the length of the argument.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
length

Syntax 3
public synchronized StringBuffer insert( int offset, char str[] )
Parameters
offset
the offset.
ch
a character array.
Returns
this string buffer.
Description
Inserts the string representation of the char array argument into this string buffer.

The characters of the array argument are inserted into the contents of this string buffer at the position indicated by offset. The length of this string buffer increases by the length of the argument.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.

Syntax 4
public StringBuffer insert( int offset, boolean b )
Parameters
offset
the offset.
b
a boolean.
Returns
this string buffer.
Description
Inserts the string representation of the boolean argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length

Syntax 5
public synchronized StringBuffer insert( int offset, char c )
Parameters
offset
the offset.
ch
a char.
Returns
this string buffer.
Description
Inserts the string representation of the char argument into this string buffer.

The second argument is inserted into the contents of this string buffer at the position indicated by offset. The length of this string buffer increases by one.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
length

Syntax 6
public StringBuffer insert( int offset, int i )
Parameters
offset
the offset.
b
an int.
Returns
this string buffer.
Description
Inserts the string representation of the second int argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length

Syntax 7
public StringBuffer insert( int offset, long l )
Parameters
offset
the offset.
b
a long.
Returns
this string buffer.
Description
Inserts the string representation of the long argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length

Syntax 8
public StringBuffer insert( int offset, float f )
Parameters
offset
the offset.
b
a float.
Returns
this string buffer.
Description
Inserts the string representation of the float argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length

Syntax 9
public StringBuffer insert( int offset, double d )
Parameters
offset
the offset.
b
a double.
Returns
this string buffer.
Description
Inserts the string representation of the double argument into this string buffer.

The second argument is converted to a string as if by the method String.valueOf, and the characters of that string are then inserted into this string buffer at the indicated offset.

The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the offset is invalid.
See Also
valueOf, insert, length


 StringBuffer.length

StringBuffer.length

Syntax
public int length()
Returns
the number of characters in this string buffer.
Description
Returns the length (character count) of this string buffer.


 StringBuffer.reverse

StringBuffer.reverse

Syntax
public synchronized StringBuffer reverse()
Returns
this string buffer.
Description
The character sequence contained in this string buffer is replaced by the reverse of the sequence.


 StringBuffer.setCharAt

StringBuffer.setCharAt

Syntax
public synchronized void setCharAt( int index, char ch )
Parameters
index
the index of the character to modify.
ch
the new character.
Description
The character at the specified index of this string buffer is set to ch.

The offset argument must be greater than or equal to 0, and less than the length of this string buffer.

Exceptions
StringIndexOutOfBoundsException if the index is invalid.
See Also
length


 StringBuffer.setLength

StringBuffer.setLength

Syntax
public synchronized void setLength( int newLength )
Parameters
newLength
the new length of the buffer.
Description
Sets the length of this String buffer. If the newLength argument is less than the current length of the string buffer, the string buffer is truncated to contain exactly the number of characters given by the newLength argument.

If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended to the string buffer so that length becomes the newLength argument.

The newLength argument must be greater than or equal to 0.

Exceptions
StringIndexOutOfBoundsException if the newLength argument is invalid.
See Also
length


 StringBuffer.toString

StringBuffer.toString

Syntax
public String toString()
Returns
a string representation of the string buffer.
Description
Converts to a string representing the data in this string buffer. A new String object is allocated and initialized to contain the character sequence currently represented by this string buffer. This String is then returned. Subsequent changes to the string buffer do not affect the contents of the String.

Overrides
toString in class Object


 Class StringIndexOutOfBoundsException

Class java.lang.StringIndexOutOfBoundsException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IndexOutOfBoundsException
                                   |
                                   +----java.lang.StringIndexOutOfBoundsException

public class StringIndexOutOfBoundsException
extends IndexOutOfBoundsException

Thrown by the charAt method in class String and by other String methods to indicate that an index is either negative or greater than or equal to the size of the string.

See Also:
charAt


 StringIndexOutOfBoundsException Members

StringIndexOutOfBoundsException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringIndexOutOfBoundsException() | Constructs a StringIndexOutOfBoundsException with no detail message.
StringIndexOutOfBoundsException(int) | Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index.
StringIndexOutOfBoundsException(String) | Constructs a StringIndexOutOfBoundsException with the specified detail message.


 StringIndexOutOfBoundsException.StringIndexOutOfBoundsException

StringIndexOutOfBoundsException.StringIndexOutOfBoundsException

Class Overview | Class Members | This Package | All Packages

Syntax 1
public StringIndexOutOfBoundsException()
Description
Constructs a StringIndexOutOfBoundsException with no detail message.

Syntax 2
public StringIndexOutOfBoundsException( String s )
Parameters
s
the detail message.
Description
Constructs a StringIndexOutOfBoundsException with the specified detail message.

Syntax 3
public StringIndexOutOfBoundsException( int index )
Parameters
index
the illegal index.
Description
Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index.


 Class System

Class java.lang.System

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.System

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties"; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.


 System Members

System Members

Class Overview | This Package | All Packages

Fields
Name | Description
err | The "standard" error output stream.
in | The "standard" input stream.
out | The "standard" output stream.

Methods
Name | Description
arraycopy(Object, int, Object, int, int) | Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
currentTimeMillis() | Returns the current time in milliseconds.
exit(int) | Terminates the currently running Java Virtual Machine.
gc() | Runs the garbage collector.
getenv(String) | Gets an environment variable. Deprecated.
getProperties() | Determines the current system properties.
getProperty(String) | Gets the system property indicated by the specified key.
getProperty(String, String) | Gets the system property indicated by the specified key.
getSecurityManager() | Gets the system security interface.
identityHashCode(Object) | Returns the same hashcode for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().
load(String) | Loads the specified filename as a dynamic library.
loadLibrary(String) | Loads the system library specified by the libname argument.
runFinalization() | Runs the finalization methods of any objects pending finalization.
runFinalizersOnExit(boolean) | Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits.
setErr(PrintStream) | Reassigns the "standard" error output stream.
setIn(InputStream) | Reassigns the "standard" input stream.
setOut(PrintStream) | Reassigns the "standard" output stream.
setProperties(Properties) | Sets the system properties to the Properties argument.
setSecurityManager(SecurityManager) | Sets the System security.


 System.err

System.err

Syntax
public static final PrintStream err
Description
The "standard" error output stream. This stream is already open and ready to accept output data.

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored.


 System.in

System.in

Syntax
public static final InputStream in
Description
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.


 System.out

System.out

Syntax
public static final PrintStream out
Description
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.

For simple stand-alone Java applications, a typical way to write a line of output data is:

    System.out.println(data)

See the println methods in class PrintStream.

See Also
println, println, println, println, println, println, println, println, println, println


 System.arraycopy

System.arraycopy

Syntax
public static native void arraycopy( Object src, int src_position, Object dst, int dst_position, int length )
Parameters
src:
the source array.
srcpos
start position in the source array.
dest
the destination array.
destpos
start position in the destination data.
length
the number of array elements to be copied.
Description
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dst. The number of components copied is equal to the length argument. The components at positions srcOffset through srcOffset+length-1 in the source array are copied into positions dstOffset through dstOffset+length-1, respectively, of the destination array.

If the src and dst arguments refer to the same array object, then the copying is performed as if the components at positions srcOffset through srcOffset+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions dstOffset through dstOffset+length-1 of the argument array.

If any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

  • The src argument refers to an object that is not an array.
  • The dst argument refers to an object that is not an array.
  • The src argument and dst argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dst argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dst argument refers to an array with a primitive component type.

Otherwise, if any of the following is true, an ArrayIndexOutOfBoundsException is thrown and the destination is not modified:

  • The srcOffset argument is negative.
  • The dstOffset argument is negative.
  • The length argument is negative.
  • srcOffset+length is greater than src.length, the length of the source array.
  • dstOffset+length is greater than dst.length, the length of the destination array.

Otherwise, if any actual component of the source array from position srcOffset through srcOffset+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcOffset+k] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcOffset through srcOffset+k-1 will already have been copied to destination array positions dstOffset through dstOffset+k-1 and no other positions of the destination array will have been modified.

Exceptions
ArrayIndexOutOfBoundsException if copying would cause access of data outside array bounds.
Exceptions
ArrayStoreException if an element in the src array could not be stored into the dest array because of a type mismatch.


 System.currentTimeMillis

System.currentTimeMillis

Syntax
public static native long currentTimeMillis()
Returns
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
Description
Returns the current time in milliseconds.

See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

See Also
Date


 System.exit

System.exit

Syntax
public static void exit( int status )
Parameters
status
exit status.
Description
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method calls the exit method in class Runtime. This method never returns normally.

Exceptions
SecurityException if the current thread cannot exit with the specified status.
See Also
exit


 System.gc

System.gc

Syntax
public static void gc()
Description
Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all unused objects.

See Also
gc


 System.getenv

System.getenv

Syntax
public static String getenv( String name )
Parameters
the
name of the environment variable.
Returns
the value of the variable, or null if the variable is not defined.
Description
Note: getenv() is deprecated.

Gets an environment variable. An environment variable is a system dependent external variable that has a string value.


 System.getProperties

System.getProperties

Syntax
public static Properties getProperties()
Description
Determines the current system properties.

If there is a security manager, its checkPropertiesAccess method is called with no arguments. This may result in a security exception.

The current set of system properties is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized.

This set of system properties always includes values for the following keys:
Key | Description of Associated Value
java.version | Java version number
java.vendor | Java vendor-specific string
java.vendor.url | Java vendor URL
java.home | Java installation directory
java.class.version | Java class format version number
java.class.path | Java class path
os.name | Operating system name
os.arch | Operating system architecture
os.version | Operating system version
file.separator | File separator ("/" on UNIX)
path.separator | Path separator (":" on UNIX)
line.separator | Line separator ("\n" on UNIX)
user.name | User's account name
user.home | User's home directory
user.dir | User's current working directory

Exceptions
SecurityException if the current thread cannot access the system properties.
See Also
SecurityException, checkPropertiesAccess, Properties


 System.getProperty

System.getProperty

Syntax 1
public static String getProperty( String key )
Parameters
key
the name of the system property.
Returns
the string value of the system property, or null if there is no property with that key.
Description
Gets the system property indicated by the specified key.

First, if there is a security manager, its checkPropertyAccess method is called with the key as its argument. This may result in a system exception.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

Exceptions
SecurityException if the current thread cannot access the system properties or the specified property.
See Also
SecurityException, checkPropertyAccess, getProperties

Syntax 2
public static String getProperty( String key, String def )
Parameters
key
the name of the system property.
def
a default value.
Returns
the string value of the system property, or the default value if there is no property with that key.
Description
Gets the system property indicated by the specified key.

First, if there is a security manager, its checkPropertyAccess method is called with the key as its argument.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

Exceptions
SecurityException if the current thread cannot access the system properties or the specified property.
See Also
checkPropertyAccess, getProperties


 System.getSecurityManager

System.getSecurityManager

Syntax
public static SecurityManager getSecurityManager()
Returns
if a security manager has already been established for the current application, then that security manager is returned; otherwise, null is returned.
Description
Gets the system security interface.


 System.identityHashCode

System.identityHashCode

Syntax
public static native int identityHashCode( Object x )
Description
Returns the same hashcode for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hashcode for the null reference is zero.


 System.load

System.load

Syntax
public static void load( String filename )
Parameters
filename
the file to load.
Description
Loads the specified filename as a dynamic library. The filename argument must be a complete pathname.

This method calls the load method in class Runtime.

Exceptions
SecurityException if the current thread cannot load the specified dynamic library.
Exceptions
UnsatisfiedLinkError if the file does not exist.
See Also
load


 System.loadLibrary

System.loadLibrary

Syntax
public static void loadLibrary( String libname )
Parameters
libname
the name of the library.
Description
Loads the system library specified by the libname argument. The manner in which a library name is mapped to the actual system library is system dependent.

Exceptions
SecurityException if the current thread cannot load the specified dynamic library.
Exceptions
UnsatisfiedLinkError if the library does not exist.
See Also
loadLibrary


 System.runFinalization

System.runFinalization

Syntax
public static void runFinalization()
Description
Runs the finalization methods of any objects pending finalization.

Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

See Also
runFinalization


 System.runFinalizersOnExit

System.runFinalizersOnExit

Syntax
public static void runFinalizersOnExit( boolean value )
Description
Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits. By default, finalization on exit is disabled.

See Also
exit, gc


 System.setErr

System.setErr

Syntax
public static void setErr( PrintStream err )
Description
Reassigns the "standard" error output stream.


 System.setIn

System.setIn

Syntax
public static void setIn( InputStream in )
Description
Reassigns the "standard" input stream.


 System.setOut

System.setOut

Syntax
public static void setOut( PrintStream out )
Description
Reassigns the "standard" output stream.


 System.setProperties

System.setProperties

Syntax
public static void setProperties( Properties props )
Parameters
props
the new system properties.
Description
Sets the system properties to the Properties argument.

First, if there is a security manager, its checkPropertiesAccess method is called with no arguments. This may result in a security exception.

The argument becomes the current set of system properties for use by the getProperty method. If the argument is null, then the current set of system properties is forgotten.

Exceptions
SecurityException if the current thread cannot set the system properties.
See Also
SecurityException, checkPropertiesAccess


 System.setSecurityManager

System.setSecurityManager

Syntax
public static void setSecurityManager( SecurityManager s )
Parameters
s
the security manager.
Description
Sets the System security. If a security manager has already been established for the currently running Java application, a SecurityException is thrown. Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

Exceptions
SecurityException if the security manager has already been set.


 Class Thread

Class java.lang.Thread

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Thread

public class Thread
extends Object
implements Runnable

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by performing the stop method.

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows:

     class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }
         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

The following code would then create a thread and start it running:

     PrimeThread p = new PrimeThread(143);
     p.start();

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following:

     class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }
         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }

The following code would then create a thread and start it running:

     PrimeRun p = new PrimeRun(143);
     new Thread(p).start();

Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

See Also:
Runnable, exit, run, stop


 Thread Members

Thread Members

Class Overview | This Package | All Packages

Fields
Name | Description
MAX_PRIORITY | The maximum priority that a thread can have.
MIN_PRIORITY | The minimum priority that a thread can have.
NORM_PRIORITY | The default priority that is assigned to a thread.

Constructors
Name | Description
Thread() | Allocates a new Thread object.
Thread(Runnable) | Allocates a new Thread object.
Thread(Runnable, String) | Allocates a new Thread object.
Thread(String) | Allocates a new Thread object.
Thread(ThreadGroup, Runnable) | Allocates a new Thread object.
Thread(ThreadGroup, Runnable, String) | Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
Thread(ThreadGroup, String) | Allocates a new Thread object.

Methods
Name | Description
activeCount() | Returns the current number of active threads in this thread group.
checkAccess() | Determines if the currently running thread has permission to modify this thread.
countStackFrames() | Counts the number of stack frames in this thread.
currentThread() | Returns a reference to the currently executing thread object.
destroy() | Destroys this thread, without any cleanup.
dumpStack() | Prints a stack trace of the current thread.
enumerate(Thread[]) | Copies into the specified array every active thread in this thread group and its subgroups.
getName() | Returns this thread's name.
getPriority() | Returns this thread's priority.
getThreadGroup() | Returns this thread's thread group.
interrupt() | Interrupts this thread.
interrupted() | Tests if the current thread has been interrupted.
isAlive() | Tests if this thread is alive.
isDaemon() | Tests if this thread is a daemon thread.
isInterrupted() | Tests if the current thread has been interrupted.
join() | Waits for this thread to die.
join(long) | Waits at most millis milliseconds for this thread to die.
join(long, int) | Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
resume() | Resumes a suspended thread.
run() | If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
setDaemon(boolean) | Marks this thread as either a daemon thread or a user thread.
setName(String) | Changes the name of this thread to be equal to the argument name.
setPriority(int) | Changes the priority of this thread.
sleep(long) | Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
sleep(long, int) | Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds.
start() | Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
stop() | Forces the thread to stop executing.
stop(Throwable) | Forces the thread to stop executing.
suspend() | Suspends this thread.
toString() | Returns a string representation of this thread, including the thread's name, priority, and thread group.
yield() | Causes the currently executing thread object to temporarily pause and allow other threads to execute.


 Thread.MAX_PRIORITY

Thread.MAX_PRIORITY

Syntax
public static final int MAX_PRIORITY
Description
The maximum priority that a thread can have.


 Thread.MIN_PRIORITY

Thread.MIN_PRIORITY

Syntax
public static final int MIN_PRIORITY
Description
The minimum priority that a thread can have.


 Thread.NORM_PRIORITY

Thread.NORM_PRIORITY

Syntax
public static final int NORM_PRIORITY
Description
The default priority that is assigned to a thread.


 Thread.Thread

Thread.Thread

Syntax 1
public Thread()
Description
Allocates a new Thread object. This constructor has the same effect as Thread(null, null, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.

Threads created this way must have overridden their run() method to actually do anything. An example illustrating this method being used follows:

     import java.lang.*;
     class plain01 implements Runnable {
         String name;
         plain01() {
             name = null;
         }
         plain01(String s) {
             name = s;
         }
         public void run() {
             if (name == null)
                 System.out.println("A new thread created");
             else
                 System.out.println("A new thread with name " + name +
                                    " created");
         }
     }
     class threadtest01 {
         public static void main(String args[] ) {
             int failed = 0 ;
             Thread t1 = new Thread();
             if (t1 != null)
                 System.out.println("new Thread() succeed");
             else {
                 System.out.println("new Thread() failed");
                 failed++;
             }
         }
     }

See Also
Thread

Syntax 2
public Thread( Runnable target )
Parameters
target
the object whose run method is called.
Description
Allocates a new Thread object. This constructor has the same effect as Thread(null, target, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.

See Also
Thread

Syntax 3
public Thread( ThreadGroup group, Runnable target )
Parameters
group
the thread group.
target
the object whose run method is called.
Description
Allocates a new Thread object. This constructor has the same effect as Thread(group, target, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.

Exceptions
SecurityException if the current thread cannot create a thread in the specified thread group.
See Also
Thread

Syntax 4
public Thread( String name )
Parameters
name
the name of the new thread.
Description
Allocates a new Thread object. This constructor has the same effect as Thread(null, null, name).

See Also
Thread

Syntax 5
public Thread( ThreadGroup group, String name )
Parameters
group
the thread group.
name
the name of the new thread.
Description
Allocates a new Thread object. This constructor has the same effect as Thread(group, null, name)

Exceptions
SecurityException if the current thread cannot create a thread in the specified thread group.
See Also
Thread

Syntax 6
public Thread( Runnable target, String name )
Parameters
target
the object whose run method is called.
name
the name of the new thread.
Description
Allocates a new Thread object. This constructor has the same effect as Thread(null, target, name).

See Also
Thread

Syntax 7
public Thread( ThreadGroup group, Runnable target, String name )
Parameters
group
the thread group.
target
the object whose run method is called.
name
the name of the new thread.
Description
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

If group is not null, the checkAccess method of that thread group is called with no arguments; this may result in throwing a SecurityException; if group is null, the new process belongs to the same group as the thread that is creating the new thread.

If the target argument is not null, the run method of the target is called when this thread is started. If the target argument is null, this thread's run method is called when this thread is started.

The priority of the newly created thread is set equal to the priority of the thread creating it, that is, the currently running thread. The method setPriority may be used to change the priority to a new value.

The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.

Exceptions
SecurityException if the current thread cannot create a thread in the specified thread group.
See Also
run, run, setDaemon, setPriority, checkAccess


 Thread.activeCount

Thread.activeCount

Syntax
public static int activeCount()
Returns
the current number of threads in this thread's thread group.
Description
Returns the current number of active threads in this thread group.


 Thread.checkAccess

Thread.checkAccess

Syntax
public void checkAccess()
Description
Determines if the currently running thread has permission to modify this thread.

If there is a security manager, its checkAccess method is called with this thread as its argument. This may result in throwing a SecurityException.

Exceptions
SecurityException if the current thread is not allowed to access this thread.
See Also
checkAccess


 Thread.countStackFrames

Thread.countStackFrames

Syntax
public native int countStackFrames()
Returns
the number of stack frames in this thread.
Description
Counts the number of stack frames in this thread. The thread must be suspended.

Exceptions
IllegalThreadStateException if this thread is not suspended.


 Thread.currentThread

Thread.currentThread

Syntax
public static native Thread currentThread()
Returns
the currently executing thread.
Description
Returns a reference to the currently executing thread object.


 Thread.destroy

Thread.destroy

Syntax
public void destroy()
Description
Destroys this thread, without any cleanup. Any monitors it has locked remain locked. (This method is not implemented in Java 1.0.2.)


 Thread.dumpStack

Thread.dumpStack

Syntax
public static void dumpStack()
Description
Prints a stack trace of the current thread. This method is used only for debugging.

See Also
printStackTrace


 Thread.enumerate

Thread.enumerate

Syntax
public static int enumerate( Thread tarray[] )
Returns
the number of threads put into the array.
Description
Copies into the specified array every active thread in this thread group and its subgroups. This method simply calls the enumerate method of this thread's thread group with the array argument.

See Also
enumerate


 Thread.getName

Thread.getName

Syntax
public final String getName()
Returns
this thread's name.
Description
Returns this thread's name.

See Also
setName


 Thread.getPriority

Thread.getPriority

Syntax
public final int getPriority()
Returns
this thread's name.
Description
Returns this thread's priority.

See Also
setPriority


 Thread.getThreadGroup

Thread.getThreadGroup

Syntax
public final ThreadGroup getThreadGroup()
Returns
this thread's thread group.
Description
Returns this thread's thread group.


 Thread.interrupt

Thread.interrupt

Syntax
public void interrupt()
Description
Interrupts this thread.


 Thread.interrupted

Thread.interrupted

Syntax
public static boolean interrupted()
Returns
true if the current thread has been interrupted; false otherwise.
Description
Tests if the current thread has been interrupted. Note that interrupted is a static method, while isInterrupted is called on the current Thread instance.

See Also
isInterrupted


 Thread.isAlive

Thread.isAlive

Syntax
public final native boolean isAlive()
Returns
true if this thread is alive; false otherwise.
Description
Tests if this thread is alive. A thread is alive if it has been started and has not yet died.


 Thread.isDaemon

Thread.isDaemon

Syntax
public final boolean isDaemon()
Returns
true if this thread is a daemon thread; false otherwise.
Description
Tests if this thread is a daemon thread.

See Also
setDaemon


 Thread.isInterrupted

Thread.isInterrupted

Syntax
public boolean isInterrupted()
Returns
true if this thread has been interrupted; false otherwise.
Description
Tests if the current thread has been interrupted. Note that isInterrupted is called on the current Thread instance; by contrast, interrupted is a static method.

See Also
interrupted


 Thread.join

Thread.join

Syntax 1
public final synchronized void join( long millis ) throws InterruptedException
Parameters
millis
the time to wait in milliseconds.
Description
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

Exceptions
InterruptedException if another thread has interrupted the current thread.

Syntax 2
public final synchronized void join( long millis, int nanos ) throws InterruptedException
Parameters
millis
the time to wait in milliseconds.
nanos
0-999999 additional nanoseconds to wait.
Description
Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Exceptions
IllegalArgumentException if the value of millis is negative the value of nanos is not in the range 0-999999.
Exceptions
InterruptedException if another thread has interrupted the current thread.

Syntax 3
public final void join() throws InterruptedException
Description
Waits for this thread to die.

Exceptions
InterruptedException if another thread has interrupted the current thread.


 Thread.resume

Thread.resume

Syntax
public final void resume()
Description
Resumes a suspended thread.

First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException(in the current thread).

If the thread is alive but suspended, it is resumed and is permitted to make progress in its execution.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, isAlive


 Thread.run

Thread.run

Syntax
public void run()
Description
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.

Subclasses of Thread should override this method.

See Also
start, stop, Thread, run


 Thread.setDaemon

Thread.setDaemon

Syntax
public final void setDaemon( boolean on )
Parameters
on
if true, marks this thread as a daemon thread.
Description
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

This method must be called before the thread is started.

Exceptions
IllegalThreadStateException if this thread is active.
See Also
isDaemon


 Thread.setName

Thread.setName

Syntax
public final void setName( String name )
Parameters
name
the new name for this thread.
Description
Changes the name of this thread to be equal to the argument name.

First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, getName


 Thread.setPriority

Thread.setPriority

Syntax
public final void setPriority( int newPriority )
Description
Changes the priority of this thread.

First the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException.

Otherwise, the priority of this thread is set to the smaller of the specified newPriority and the maximum permitted priority of the thread's thread group.

Exceptions
IllegalArgumentException If the priority is not in the range MIN_PRIORITY to MAX_PRIORITY.
Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, getPriority, getThreadGroup, MAX_PRIORITY, MIN_PRIORITY, getMaxPriority


 Thread.sleep

Thread.sleep

Syntax 1
public static native void sleep( long millis ) throws InterruptedException
Parameters
millis
the length of time to sleep in milliseconds.
Description
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.

Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
notify

Syntax 2
public static void sleep( long millis, int nanos ) throws InterruptedException
Parameters
millis
the length of time to sleep in milliseconds.
nanos
0-999999 additional nanoseconds to sleep.
Description
Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds. The thread does not lose ownership of any monitors.

Exceptions
IllegalArgumentException if the value of millis is negative or the value of nanos is not in the range 0-999999.
Exceptions
InterruptedException if another thread has interrupted this thread.
See Also
notify


 Thread.start

Thread.start

Syntax
public native synchronized void start()
Description
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

Exceptions
IllegalThreadStateException if the thread was already started.
See Also
run, stop


 Thread.stop

Thread.stop

Syntax 1
public final void stop()
Description
Forces the thread to stop executing.

First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread).

The thread represented by this thread is forced to stop whatever it is doing abnormally and to throw a newly created ThreadDeath object as an exception.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it immediately terminates.

An application should not normally try to catch ThreadDeath unless it must do some extraordinary cleanup operation (note that the throwing of ThreadDeath causes finally clauses of try statements to be executed before the thread officially dies). If a catch clause catches a ThreadDeath object, it is important to rethrow the object so that the thread actually dies.

The top-level error handler that reacts to otherwise uncaught exceptions does not print out a message or otherwise notify the application if the uncaught exception is an instance of ThreadDeath.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, run, start, ThreadDeath, uncaughtException

Syntax 2
public final synchronized void stop( Throwable o )
Parameters
obj
the Throwable object to be thrown.
Description
Forces the thread to stop executing.

First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the argument obj is null, a NullPointerException is thrown (in the current thread).

The thread represented by this thread is forced to complete whatever it is doing abnormally and to throw the Throwable object obj as an exception. This is an unusual action to take; normally, the stop method that takes no arguments should be used.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it immediately terminates.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, run, start, stop


 Thread.suspend

Thread.suspend

Syntax
public final void suspend()
Description
Suspends this thread.

First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the thread is alive, it is suspended and makes no further progress unless and until it is resumed.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
checkAccess, isAlive


 Thread.toString

Thread.toString

Syntax
public String toString()
Returns
a string representation of this thread.
Description
Returns a string representation of this thread, including the thread's name, priority, and thread group.

Overrides
toString in class Object


 Thread.yield

Thread.yield

Syntax
public static native void yield()
Description
Causes the currently executing thread object to temporarily pause and allow other threads to execute.


 Class ThreadDeath

Class java.lang.ThreadDeath

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.ThreadDeath

public class ThreadDeath
extends Error

An instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called.

An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

The top-level error handler does not print out a message if ThreadDeath is never caught.

The class ThreadDeath is specifically a subclass of Error rather than Exception, even though it is a "normal occurrence", because many applications catch all occurrences of Exception and then discard the exception.

See Also:
stop


 ThreadDeath Members

ThreadDeath Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ThreadDeath() |


 ThreadDeath.ThreadDeath

ThreadDeath.ThreadDeath

Syntax
public ThreadDeath()


 Class ThreadGroup

Class java.lang.ThreadGroup

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.ThreadGroup

public class ThreadGroup
extends Object

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.

A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group or any other thread groups.


 ThreadGroup Members

ThreadGroup Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ThreadGroup(String) | Constructs a new thread group.
ThreadGroup(ThreadGroup, String) | Creates a new thread group.

Methods
Name | Description
activeCount() | Returns an estimate of the number of active threads in this thread group.
activeGroupCount() | Returns an estimate of the number of active groups in this thread group.
allowThreadSuspension(boolean) | Used by VM to control lowmem implicit suspension.
checkAccess() | Determines if the currently running thread has permission to modify this thread group.
destroy() | Destroys this thread group and all of its subgroups.
enumerate(Thread[]) | Copies into the specified array every active thread in this thread group and its subgroups.
enumerate(Thread[], boolean) | Copies into the specified array every active thread in this thread group.
enumerate(ThreadGroup[]) | Copies into the specified array references to every active subgroup in this thread group.
enumerate(ThreadGroup[], boolean) | Copies into the specified array references to every active subgroup in this thread group.
getMaxPriority() | Returns the maximum priority of this thread group.
getName() | Returns the name of this thread group.
getParent() | Returns the parent of this thread group.
isDaemon() | Tests if this thread group is a daemon thread group.
isDestroyed() | Tests if this thread group has been destroyed.
list() | Prints information about this thread group to the standard output.
parentOf(ThreadGroup) | Tests if this thread group is either the thread group argument or one of its ancestor thread groups.
resume() | Resumes all processes in this thread group.
setDaemon(boolean) | Changes the daemon status of this thread group.
setMaxPriority(int) | Sets the maximum priority of the group.
stop() | Stops all processes in this thread group.
suspend() | Suspends all processes in this thread group.
toString() | Returns a string representation of this Thread group.
uncaughtException(Thread, Throwable) | Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception.


 ThreadGroup.ThreadGroup

ThreadGroup.ThreadGroup

Syntax 1
public ThreadGroup( String name )
Parameters
name
the name of the new thread group.
Description
Constructs a new thread group. The parent of this new group is the thread group of the currently running thread.

Syntax 2
public ThreadGroup( ThreadGroup parent, String name )
Parameters
parent
the parent thread group.
name
the name of the new thread group.
Description
Creates a new thread group. The parent of this new group is the specified thread group.

The checkAccess method of the parent thread group is called with no arguments; this may result in a security exception.

Exceptions
NullPointerException if the thread group argument is null.
Exceptions
SecurityException if the current thread cannot create a thread in the specified thread group.
See Also
SecurityException, checkAccess


 ThreadGroup.activeCount

ThreadGroup.activeCount

Syntax
public int activeCount()
Returns
the number of active threads in this thread group and in any other thread group that has this thread group as an ancestor.
Description
Returns an estimate of the number of active threads in this thread group.


 ThreadGroup.activeGroupCount

ThreadGroup.activeGroupCount

Syntax
public int activeGroupCount()
Returns
the number of active thread groups with this thread group as an ancestor.
Description
Returns an estimate of the number of active groups in this thread group.


 ThreadGroup.allowThreadSuspension

ThreadGroup.allowThreadSuspension

Syntax
public boolean allowThreadSuspension( boolean b )
Description
Used by VM to control lowmem implicit suspension.


 ThreadGroup.checkAccess

ThreadGroup.checkAccess

Syntax
public final void checkAccess()
Description
Determines if the currently running thread has permission to modify this thread group.

If there is a security manager, its checkAccess method is called with this thread group as its argument. This may result in throwing a SecurityException.

Exceptions
SecurityException if the current thread is not allowed to access this thread group.
See Also
checkAccess


 ThreadGroup.destroy

ThreadGroup.destroy

Syntax
public final void destroy()
Description
Destroys this thread group and all of its subgroups. This thread group must be empty, indicating that all threads that had been in this thread group have since stopped.

Exceptions
IllegalThreadStateException if the thread group is not empty or if the thread group has already been destroyed.
Exceptions
SecurityException if the current thread cannot modify this thread group.


 ThreadGroup.enumerate

ThreadGroup.enumerate

Syntax 1
public int enumerate( Thread list[] )
Parameters
list
an array into which to place the list of threads.
Returns
the number of threads put into the array.
Description
Copies into the specified array every active thread in this thread group and its subgroups.

An application should use the activeCount method to get an estimate of how big the array should be. If the array is too short to hold all the threads, the extra threads are silently ignored.

See Also
activeCount

Syntax 2
public int enumerate( Thread list[], boolean recurse )
Parameters
list
an array into which to place the list of threads.
recurse
a flag indicating whether also to include threads in thread groups that are subgroups of this thread group.
Returns
the number of threads placed into the array.
Description
Copies into the specified array every active thread in this thread group. If the recurse flag is true, references to every active thread in this thread's subgroups are also included. If the array is too short to hold all the threads, the extra threads are silently ignored.

An application should use the activeCount method to get an estimate of how big the array should be.

See Also
activeCount


 ThreadGroup.enumerate

ThreadGroup.enumerate

Syntax
public int enumerate( ThreadGroup list[] )
Parameters
list
an array into which to place the list of thread groups.
Returns
the number of thread groups put into the array.
Description
Copies into the specified array references to every active subgroup in this thread group.

An application should use the activeGroupCount method to get an estimate of how big the array should be. If the array is too short to hold all the thread groups, the extra thread groups are silently ignored.

See Also
activeGroupCount


 ThreadGroup.enumerate

ThreadGroup.enumerate

Syntax
public int enumerate( ThreadGroup list[], boolean recurse )
Parameters
list
an array into which to place the list of threads.
recurse
a flag indicating whether to recursively enumerate all included thread groups.
Returns
the number of thread groups put into the array.
Description
Copies into the specified array references to every active subgroup in this thread group. If the recurse flag is true, references to all active subgroups of the subgroups and so forth are also included.

An application should use the activeGroupCount method to get an estimate of how big the array should be.

See Also
activeGroupCount


 ThreadGroup.getMaxPriority

ThreadGroup.getMaxPriority

Syntax
public final int getMaxPriority()
Returns
the maximum priority that a thread in this thread group can have.
Description
Returns the maximum priority of this thread group. Threads that are part of this group cannot have a higher priority than the maximum priority.


 ThreadGroup.getName

ThreadGroup.getName

Syntax
public final String getName()
Returns
the name of this thread group.
Description
Returns the name of this thread group.


 ThreadGroup.getParent

ThreadGroup.getParent

Syntax
public final ThreadGroup getParent()
Returns
the parent of this thread group. The top-level thread group is the only thread group whose parent is null.
Description
Returns the parent of this thread group.


 ThreadGroup.isDaemon

ThreadGroup.isDaemon

Syntax
public final boolean isDaemon()
Returns
true if this thread group is a daemon thread group; false otherwise.
Description
Tests if this thread group is a daemon thread group. A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.


 ThreadGroup.isDestroyed

ThreadGroup.isDestroyed

Syntax
public synchronized boolean isDestroyed()
Description
Tests if this thread group has been destroyed.


 ThreadGroup.list

ThreadGroup.list

Syntax
public void list()
Description
Prints information about this thread group to the standard output. This method is useful only for debugging.


 ThreadGroup.parentOf

ThreadGroup.parentOf

Syntax
public final boolean parentOf( ThreadGroup g )
Parameters
g
a thread group.
Returns
true if this thread group is the thread group argument or one of its ancestor thread groups; false otherwise.
Description
Tests if this thread group is either the thread group argument or one of its ancestor thread groups.


 ThreadGroup.resume

ThreadGroup.resume

Syntax
public final void resume()
Description
Resumes all processes in this thread group.

First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.

This method then calls the resume method on all the threads in this thread group and in all of its sub groups.

Exceptions
SecurityException if the current thread is not allowed to access this thread group or any of the threads in the thread group.
See Also
SecurityException, resume, checkAccess


 ThreadGroup.setDaemon

ThreadGroup.setDaemon

Syntax
public final void setDaemon( boolean daemon )
Parameters
daemon
if true, marks this thread group as a daemon thread group; otherwise, marks this thread group as normal.
Description
Changes the daemon status of this thread group.

First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.

A daemon thread group is automatically destroyed when its last thread is stopped or its last thread group is destroyed.

Exceptions
SecurityException if the current thread cannot modify this thread.
See Also
SecurityException, checkAccess


 ThreadGroup.setMaxPriority

ThreadGroup.setMaxPriority

Syntax
public final void setMaxPriority( int pri )
Parameters
pri
the new priority of the thread group.
Description
Sets the maximum priority of the group.

First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.

Threads in the thread group that already have a higher priority are not affected.

Exceptions
SecurityException if the current thread cannot modify this thread group.
See Also
SecurityException, checkAccess


 ThreadGroup.stop

ThreadGroup.stop

Syntax
public final void stop()
Description
Stops all processes in this thread group.

First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.

This method then calls the stop method on all the threads in this thread group and in all of its subgroups.

Exceptions
SecurityException if the current thread is not allowed to access this thread group or any of the threads in the thread group.
See Also
SecurityException, stop, checkAccess


 ThreadGroup.suspend

ThreadGroup.suspend

Syntax
public final void suspend()
Description
Suspends all processes in this thread group.

First, the checkAccess method of this thread group is called with no arguments; this may result in a security exception.

This method then calls the suspend method on all the threads in this thread group and in all of its subgroups.

Exceptions
SecurityException if the current thread is not allowed to access this thread group or any of the threads in the thread group.
See Also
SecurityException, suspend, checkAccess


 ThreadGroup.toString

ThreadGroup.toString

Syntax
public String toString()
Returns
a string representation of this thread group.
Description
Returns a string representation of this Thread group.

Overrides
toString in class Object


 ThreadGroup.uncaughtException

ThreadGroup.uncaughtException

Syntax
public void uncaughtException( Thread t, Throwable e )
Parameters
t
the thread that is about to exit.
e
the uncaught exception.
Description
Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception.

The uncaughtException method of ThreadGroup does the following:

  • If this thread group has a parent thread group, the uncaughtException method of that parent is called with the same two arguments.
  • Otherwise, this method determines if the Throwable argument is an instance of ThreadDeath. If so, nothing special is done. Otherwise, the Throwable's printStackTrace method is called to print a stack backtrace to the standard error stream.

Applications can override this method in subclasses of ThreadGroup to provide alternative handling of uncaught exceptions.

See Also
err, ThreadDeath, printStackTrace


 Class Throwable

Class java.lang.Throwable

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable

public class Throwable
extends Object
implements Serializable

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

A Throwable class contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error.

Here is one example of catching an exception:

     try {
         int a[] = new int[2];
         a[4];
     } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("exception: " + e.getMessage());
         e.printStackTrace();
     }


 Throwable Members

Throwable Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Throwable() | Constructs a new Throwable with no detail message.
Throwable(String) | Constructs a new Throwable with the specified detail message.

Methods
Name | Description
fillInStackTrace() | Fills in the execution stack trace.
getLocalizedMessage() | Creates a localized description of this Throwable.
getMessage() | Returns the detail message of this throwable object.
printStackTrace() | Prints this Throwable and its backtrace to the standard error stream.
printStackTrace(PrintStream) | Prints this Throwable and its backtrace to the specified print stream.
printStackTrace(PrintWriter) | Prints this Throwable and its backtrace to the specified print writer.
toString() | Returns a short description of this throwable object.


 Throwable.Throwable

Throwable.Throwable

Syntax 1
public Throwable()
Description
Constructs a new Throwable with no detail message. The stack trace is automatically filled in.

Syntax 2
public Throwable( String message )
Parameters
message
the detail message.
Description
Constructs a new Throwable with the specified detail message. The stack trace is automatically filled in.


 Throwable.fillInStackTrace

Throwable.fillInStackTrace

Syntax
public native Throwable fillInStackTrace()
Returns
this Throwable object.
Description
Fills in the execution stack trace. This method is useful when an application is re-throwing an error or exception. For example:

     try {
         a = b / c;
     } catch(ArithmeticThrowable e) {
         a = Number.MAX_VALUE;
         throw e.fillInStackTrace();
     }

See Also
printStackTrace


 Throwable.getLocalizedMessage

Throwable.getLocalizedMessage

Syntax
public String getLocalizedMessage()
Description
Creates a localized description of this Throwable. Subclasses may override this method in order to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().


 Throwable.getMessage

Throwable.getMessage

Syntax
public String getMessage()
Returns
the detail message of this Throwable, or null if this Throwable does not have a detail message.
Description
Returns the detail message of this throwable object.


 Throwable.printStackTrace

Throwable.printStackTrace

Syntax 1
public void printStackTrace()
Description
Prints this Throwable and its backtrace to the standard error stream.

See Also
err

Syntax 2
public void printStackTrace( PrintStream s )
Description
Prints this Throwable and its backtrace to the specified print stream.

Syntax 3
public void printStackTrace( PrintWriter s )
Description
Prints this Throwable and its backtrace to the specified print writer.


 Throwable.toString

Throwable.toString

Syntax
public String toString()
Returns
a string representation of this Throwable.
Description
Returns a short description of this throwable object.

Overrides
toString in class Object


 Class UnknownError

Class java.lang.UnknownError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.VirtualMachineError
                           |
                           +----java.lang.UnknownError

public class UnknownError
extends VirtualMachineError

Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.


 UnknownError Members

UnknownError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnknownError() | Constructs an UnknownError with no detail message.
UnknownError(String) | Constructs an UnknownError with the specified detail message.


 UnknownError.UnknownError

UnknownError.UnknownError

Syntax 1
public UnknownError()
Description
Constructs an UnknownError with no detail message.

Syntax 2
public UnknownError( String s )
Parameters
s
the detail message.
Description
Constructs an UnknownError with the specified detail message.


 Class UnsatisfiedLinkError

Class java.lang.UnsatisfiedLinkError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.UnsatisfiedLinkError

public class UnsatisfiedLinkError
extends LinkageError

Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native.

See Also:
Runtime


 UnsatisfiedLinkError Members

UnsatisfiedLinkError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnsatisfiedLinkError() | Constructs an UnsatisfiedLinkError with no detail message.
UnsatisfiedLinkError(String) | Constructs an UnsatisfiedLinkError with the specified detail message.


 UnsatisfiedLinkError.UnsatisfiedLinkError

UnsatisfiedLinkError.UnsatisfiedLinkError

Syntax 1
public UnsatisfiedLinkError()
Description
Constructs an UnsatisfiedLinkError with no detail message.

Syntax 2
public UnsatisfiedLinkError( String s )
Parameters
s
the detail message.
Description
Constructs an UnsatisfiedLinkError with the specified detail message.


 Class VerifyError

Class java.lang.VerifyError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.LinkageError
                           |
                           +----java.lang.VerifyError

public class VerifyError
extends LinkageError

Thrown when the "verifier" detects that a class file, though well formed, contains some sort of internal inconsistency or security problem.


 VerifyError Members

VerifyError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
VerifyError() | Constructs an VerifyError with no detail message.
VerifyError(String) | Constructs an VerifyError with the specified detail message.


 VerifyError.VerifyError

VerifyError.VerifyError

Syntax 1
public VerifyError()
Description
Constructs an VerifyError with no detail message.

Syntax 2
public VerifyError( String s )
Parameters
s
the detail message.
Description
Constructs an VerifyError with the specified detail message.


 Class VirtualMachineError

Class java.lang.VirtualMachineError

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Error
                   |
                   +----java.lang.VirtualMachineError

public abstract class VirtualMachineError
extends Error

Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.


 VirtualMachineError Members

VirtualMachineError Members

Class Overview | This Package | All Packages

Constructors
Name | Description
VirtualMachineError() | Constructs a VirtualMachineError with no detail message.
VirtualMachineError(String) | Constructs a VirtualMachineError with the specified detail message.


 VirtualMachineError.VirtualMachineError

VirtualMachineError.VirtualMachineError

Syntax 1
public VirtualMachineError()
Description
Constructs a VirtualMachineError with no detail message.

Syntax 2
public VirtualMachineError( String s )
Parameters
s
the detail message.
Description
Constructs a VirtualMachineError with the specified detail message.


 Class Void

Class java.lang.Void

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Void

public final class Void
extends Object

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.


 Void Members

Void Members

Class Overview | This Package | All Packages

Fields
Name | Description
TYPE | The Class object representing the primitive Java type void.


 Void.TYPE

Void.TYPE

Syntax
public static final Class TYPE
Description
The Class object representing the primitive Java type void.


 Package java.lang.reflect

Package java.lang.reflect

All Packages

Interfaces

  • Member

    • Classes

  • Array
  • Constructor
  • Field
  • Method
  • Modifier

    • Exceptions

  • InvocationTargetException


 Class Array

Class java.lang.reflect.Array

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.reflect.Array

public final class Array
extends Object

The Array class provides static methods to dynamically create and access Java arrays.

Array permits widening conversions to occur during a get or set operation, but throws an IllegalArgumentException if a narrowing conversion would occur.


 Array Members

Array Members

Class Overview | This Package | All Packages

Methods
Name | Description
get(Object, int) | Returns the value of the indexed component in the specified array object.
getBoolean(Object, int) | Returns the value of the indexed component in the specified array object, as a boolean.
getByte(Object, int) | Returns the value of the indexed component in the specified array object, as a byte.
getChar(Object, int) | Returns the value of the indexed component in the specified array object, as a char.
getDouble(Object, int) | Returns the value of the indexed component in the specified array object, as a double.
getFloat(Object, int) | Returns the value of the indexed component in the specified array object, as a float.
getInt(Object, int) | Returns the value of the indexed component in the specified array object, as an int.
getLength(Object) | Returns the length of the specified array object, as an int.
getLong(Object, int) | Returns the value of the indexed component in the specified array object, as a long.
getShort(Object, int) | Returns the value of the indexed component in the specified array object, as a short.
newInstance(Class, int) | Creates a new array with the specified component type and length.
newInstance(Class, int[]) | Creates a new array with the specified component type and dimensions.
set(Object, int, Object) | Sets the value of the indexed component of the specified array object to the specified new value.
setBoolean(Object, int, boolean) | Sets the value of the indexed component of the specified array object to the specified boolean value.
setByte(Object, int, byte) | Sets the value of the indexed component of the specified array object to the specified boolean value.
setChar(Object, int, char) | Sets the value of the indexed component of the specified array object to the specified byte value.
setDouble(Object, int, double) | Sets the value of the indexed component of the specified array object to the specified double value.
setFloat(Object, int, float) | Sets the value of the indexed component of the specified array object to the specified float value.
setInt(Object, int, int) | Sets the value of the indexed component of the specified array object to the specified int value.
setLong(Object, int, long) | Sets the value of the indexed component of the specified array object to the specified long value.
setShort(Object, int, short) | Sets the value of the indexed component of the specified array object to the specified short value.


 Array.get

Array.get

Syntax
public static native Object get( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the (possibly wrapped) value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array


 Array.getBoolean

Array.getBoolean

Syntax
public static native boolean getBoolean( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a boolean.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getByte

Array.getByte

Syntax
public static native byte getByte( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a byte.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getChar

Array.getChar

Syntax
public static native char getChar( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a char.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getDouble

Array.getDouble

Syntax
public static native double getDouble( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a double.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getFloat

Array.getFloat

Syntax
public static native float getFloat( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a float.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getInt

Array.getInt

Syntax
public static native int getInt( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as an int.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getLength

Array.getLength

Syntax
public static native int getLength( Object array ) throws IllegalArgumentException
Parameters
array
the array
Returns
the length of the array
Description
Returns the length of the specified array object, as an int.

Exceptions
IllegalArgumentException if the object argument is not an array


 Array.getLong

Array.getLong

Syntax
public static native long getLong( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a long.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.getShort

Array.getShort

Syntax
public static native short getShort( Object array, int index ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index
Returns
the value of the indexed component in the specified array
Description
Returns the value of the indexed component in the specified array object, as a short.

Exceptions
NullPointerException If the specified object is null
Exceptions
IllegalArgumentException If the specified object is not an array, or if the indexed element cannot be converted to the return type by an identity or widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
get


 Array.newInstance

Array.newInstance

Syntax 1
public static Object newInstance( Class componentType, int length ) throws NegativeArraySizeException
Parameters
componentType
the Class object representing the component type of the new array
length
the length of the new array
Returns
the new array
Description
Creates a new array with the specified component type and length. The effect is that of the equivalent array creation expression:
    new componentType[length]

Exceptions
NullPointerException if the specified componentType parameter is null
Exceptions
NegativeArraySizeException if the specified length is negative

Syntax 2
public static Object newInstance( Class componentType, int dimensions[] ) throws IllegalArgumentException, NegativeArraySizeException
Parameters
componentType
the Class object representing the component type of the new array
dimensions
an array of ints representing the dimensions of the new array
Returns
the new array
Description
Creates a new array with the specified component type and dimensions.

The effect is that of the equivalent array creation expression:

    new componentType[dimensions[0]][dimensions[1]]...

Exceptions
NullPointerException if the specified componentType argument is null
Exceptions
IllegalArgumentException if the specified dimensions argument is a zero-dimensional array, or if the number of requested dimensions exceeds the limit on the number of array dimensions supported by the implementation (typically 255).
Exceptions
NegativeArraySizeException if any of the components in the specified dimension argument is negative.


 Array.set

Array.set

Syntax
public static native void set( Object array, int index, Object value ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type.

Exceptions
NullPointerException If the specified object argument is null, or if the array component type is primitive and the specified value is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the array component type is primitive and the specified value cannot be converted to the primitive type by a combination of unwrapping and identity or widening conversions
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array


 Array.setBoolean

Array.setBoolean

Syntax
public static native void setBoolean( Object array, int index, boolean z ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified boolean value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setByte

Array.setByte

Syntax
public static native void setByte( Object array, int index, byte b ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified boolean value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setChar

Array.setChar

Syntax
public static native void setChar( Object array, int index, char c ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified byte value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setDouble

Array.setDouble

Syntax
public static native void setDouble( Object array, int index, double d ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified double value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setFloat

Array.setFloat

Syntax
public static native void setFloat( Object array, int index, float f ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified float value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setInt

Array.setInt

Syntax
public static native void setInt( Object array, int index, int i ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified int value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setLong

Array.setLong

Syntax
public static native void setLong( Object array, int index, long l ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified long value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Array.setShort

Array.setShort

Syntax
public static native void setShort( Object array, int index, short s ) throws IllegalArgumentException, ArrayIndexOutOfBoundsException
Parameters
array
the array
index
the index into the array
value
the new value of the indexed component
Description
Sets the value of the indexed component of the specified array object to the specified short value.

Exceptions
NullPointerException If the specified object argument is null
Exceptions
IllegalArgumentException If the specified object argument is not an array, or if the the specified value cannot be converted to the underlying array's component type by an identity or a primitive widening widening conversion
Exceptions
ArrayIndexOutOfBoundsException If the specified index argument is negative, or if it is greater than or equal to the length of the specified array
See Also
set


 Class Constructor

Class java.lang.reflect.Constructor

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.reflect.Constructor

public final class Constructor
extends Object
implements Member

Constructor provides information about, and access to, a single constructor for a class.

Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor's formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

See Also:
Member, Class, getConstructors, getConstructor, getDeclaredConstructors


 Constructor Members

Constructor Members

Class Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Compares this Constructor against the specified object.
getDeclaringClass() | Returns the Class object representing the class that declares the constructor represented by this Constructor object.
getExceptionTypes() | Returns an array of Class objects that represent the types of the checked exceptions thrown by the underlying constructor represented by this Constructor object.
getModifiers() | Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer.
getName() | Returns the name of this constructor, as a string.
getParameterTypes() | Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object.
hashCode() | Returns a hashcode for this Constructor.
newInstance(Object[]) | Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.
toString() | Return a string describing this Constructor.


 Constructor.equals

Constructor.equals

Syntax
public boolean equals( Object obj )
Description
Compares this Constructor against the specified object. Returns true if the objects are the same. Two Constructors are the same if they were declared by the same class and have the same formal parameter types.

Overrides
equals in class Object


 Constructor.getDeclaringClass

Constructor.getDeclaringClass

Syntax
public Class getDeclaringClass()
Description
Returns the Class object representing the class that declares the constructor represented by this Constructor object.


 Constructor.getExceptionTypes

Constructor.getExceptionTypes

Syntax
public Class[] getExceptionTypes()
Description
Returns an array of Class objects that represent the types of the checked exceptions thrown by the underlying constructor represented by this Constructor object. Returns an array of length 0 if the constructor throws no checked exceptions.


 Constructor.getModifiers

Constructor.getModifiers

Syntax
public native int getModifiers()
Description
Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer. The Modifier class should be used to decode the modifiers.

See Also
Modifier


 Constructor.getName

Constructor.getName

Syntax
public String getName()
Description
Returns the name of this constructor, as a string. This is always the same as the name of the constructor's declaring class.


 Constructor.getParameterTypes

Constructor.getParameterTypes

Syntax
public Class[] getParameterTypes()
Description
Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object. Returns an array of length 0 if the underlying constructor takes no parameters.


 Constructor.hashCode

Constructor.hashCode

Syntax
public int hashCode()
Description
Returns a hashcode for this Constructor. The hashcode is the same as the hashcode for the underlying constructor's declaring class name.

Overrides
hashCode in class Object


 Constructor.newInstance

Constructor.newInstance

Syntax
public native Object newInstance( Object initargs[] ) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
Description
Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to widening conversions as necessary. Returns the newly created and initialized object.

Creation proceeds with the following steps, in order:

If the class that declares the underlying constructor represents an abstract class, the creation throws an InstantiationException.

If this Constructor object enforces Java language access control and the underlying constructor is inaccessible, the creation throws an IllegalAccessException.

If the number of actual parameters supplied via initargs is different from the number of formal parameters required by the underlying constructor, the creation throws an IllegalArgumentException.

A new instance of the constructor's declaring class is created, and its fields are initialized to their default initial values.

For each actual parameter in the supplied initargs array:

If the corresponding formal parameter has a primitive type, an unwrapping conversion is attempted to convert the object value to a value of the primitive type. If this attempt fails, the creation throws an IllegalArgumentException.

If, after possible unwrapping, the parameter value cannot be converted to the corresponding formal parameter type by an identity or widening conversion, the creation throws an IllegalArgumentException.

Control transfers to the underlying constructor to initialize the new instance. If the constructor completes abruptly by throwing an exception, the exception is placed in an InvocationTargetException and thrown in turn to the caller of newInstance.

If the constructor completes normally, returns the newly created and initialized instance.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the number of actual and formal parameters differ, or if an unwrapping conversion fails.
Exceptions
InstantiationException if the class that declares the underlying constructor represents an abstract class.
Exceptions
InvocationTargetException if the underlying constructor throws an exception.


 Constructor.toString

Constructor.toString

Syntax
public String toString()
Description
Return a string describing this Constructor. The string is formatted as the constructor access modifiers, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor's formal parameter types. For example:
    public java.util.Hashtable(int,float)

The only possible modifiers for constructors are the access modifiers public, protected or private. Only one of these may appear, or none if the constructor has default (package) access.

Overrides
toString in class Object


 Class Field

Class java.lang.reflect.Field

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.reflect.Field

public final class Field
extends Object
implements Member

A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.

A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

See Also:
Member, Class, getFields, getField, getDeclaredFields, getDeclaredField


 Field Members

Field Members

Class Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Compares this Field against the specified object.
get(Object) | Returns the value of the field represented by this Field, on the specified object.
getBoolean(Object) | Get the value of a field as a boolean on specified object.
getByte(Object) | Get the value of a field as a byte on specified object.
getChar(Object) | Get the value of a field as a char on specified object.
getDeclaringClass() | Returns the Class object representing the class or interface that declares the field represented by this Field object.
getDouble(Object) | Get the value of a field as a double on specified object.
getFloat(Object) | Get the value of a field as a float on specified object.
getInt(Object) | Get the value of a field as a int on specified object.
getLong(Object) | Get the value of a field as a long on specified object.
getModifiers() | Returns the Java language modifiers for the field represented by this Field object, as an integer.
getName() | Returns the name of the field represented by this Field object.
getShort(Object) | Get the value of a field as a short on specified object.
getType() | Returns a Class object that identifies the declared type for the field represented by this Field object.
hashCode() | Returns a hashcode for this Field.
set(Object, Object) | Sets the field represented by this Field object on the specified object argument to the specified new value.
setBoolean(Object, boolean) | Set the value of a field as a boolean on specified object.
setByte(Object, byte) | Set the value of a field as a byte on specified object.
setChar(Object, char) | Set the value of a field as a char on specified object.
setDouble(Object, double) | Set the value of a field as a double on specified object.
setFloat(Object, float) | Set the value of a field as a float on specified object.
setInt(Object, int) | Set the value of a field as an int on specified object.
setLong(Object, long) | Set the value of a field as a long on specified object.
setShort(Object, short) | Set the value of a field as a short on specified object.
toString() | Return a string describing this Field.


 Field.equals

Field.equals

Syntax
public boolean equals( Object obj )
Description
Compares this Field against the specified object. Returns true if the objects are the same. Two Fields are the same if they were declared by the same class and have the same name and type.

Overrides
equals in class Object


 Field.get

Field.get

Syntax
public native Object get( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.

The underlying field's value is obtained as follows:

If the underlying field is a static field, the object argument is ignored; it may be null.

Otherwise, the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException. If the specified object is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException.

If this Field object enforces Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException.

Otherwise, the value is retrieved from the underlying instance or static field. If the field has a primitive type, the value is wrapped in an object before being returned, otherwise it is returned as is.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field.
Exceptions
NullPointerException if the specified object is null.


 Field.getBoolean

Field.getBoolean

Syntax
public native boolean getBoolean( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a boolean on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getByte

Field.getByte

Syntax
public native byte getByte( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a byte on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getChar

Field.getChar

Syntax
public native char getChar( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a char on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getDeclaringClass

Field.getDeclaringClass

Syntax
public Class getDeclaringClass()
Description
Returns the Class object representing the class or interface that declares the field represented by this Field object.


 Field.getDouble

Field.getDouble

Syntax
public native double getDouble( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a double on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getFloat

Field.getFloat

Syntax
public native float getFloat( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a float on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getInt

Field.getInt

Syntax
public native int getInt( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a int on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getLong

Field.getLong

Syntax
public native long getLong( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a long on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getModifiers

Field.getModifiers

Syntax
public native int getModifiers()
Description
Returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.

See Also
Modifier


 Field.getName

Field.getName

Syntax
public String getName()
Description
Returns the name of the field represented by this Field object.


 Field.getShort

Field.getShort

Syntax
public native short getShort( Object obj ) throws IllegalArgumentException, IllegalAccessException
Description
Get the value of a field as a short on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the field value cannot be converted to the return type by a widening conversion.
See Also
get


 Field.getType

Field.getType

Syntax
public Class getType()
Description
Returns a Class object that identifies the declared type for the field represented by this Field object.


 Field.hashCode

Field.hashCode

Syntax
public int hashCode()
Description
Returns a hashcode for this Field. This is computed as the exclusive-or of the hashcodes for the underlying field's declaring class name and its name.

Overrides
hashCode in class Object


 Field.set

Field.set

Syntax
public native void set( Object obj, Object value ) throws IllegalArgumentException, IllegalAccessException
Description
Sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.

The operation proceeds as follows:

If the underlying field is static, the object argument is ignored; it may be null.

Otherwise the underlying field is an instance field. If the specified object argument is null, the method throws a NullPointerException. If the specified object argument is not an instance of the class or interface declaring the underlying field, the method throws an IllegalArgumentException.

If this Field object enforces Java language access control, and the underlying field is inaccessible, the method throws an IllegalAccessException.

If the underlying field is final, the method throws an IllegalAccessException.

If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type. If this attempt fails, the method throws an IllegalArgumentException.

If, after possible unwrapping, the new value cannot be converted to the type of the underlying field by an identity or widening conversion, the method throws an IllegalArgumentException.

The field is set to the possibly unwrapped and widened new value.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
Exceptions
NullPointerException if the specified object is null.


 Field.setBoolean

Field.setBoolean

Syntax
public native void setBoolean( Object obj, boolean z ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a boolean on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setByte

Field.setByte

Syntax
public native void setByte( Object obj, byte b ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a byte on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setChar

Field.setChar

Syntax
public native void setChar( Object obj, char c ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a char on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setDouble

Field.setDouble

Syntax
public native void setDouble( Object obj, double d ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a double on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setFloat

Field.setFloat

Syntax
public native void setFloat( Object obj, float f ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a float on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setInt

Field.setInt

Syntax
public native void setInt( Object obj, int i ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as an int on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setLong

Field.setLong

Syntax
public native void setLong( Object obj, long l ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a long on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.setShort

Field.setShort

Syntax
public native void setShort( Object obj, short s ) throws IllegalArgumentException, IllegalAccessException
Description
Set the value of a field as a short on specified object.

Exceptions
IllegalAccessException if the underlying constructor is inaccessible.
Exceptions
IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field, or if an unwrapping conversion fails.
See Also
set


 Field.toString

Field.toString

Syntax
public String toString()
Description
Return a string describing this Field. The format is the access modifiers for the field, if any, followed by the field type, followed by a space, followed by the fully-qualified name of the class declaring the field, followed by a period, followed by the name of the field. For example:
    public static final int java.lang.Thread.MIN_PRIORITY
    private int java.io.FileDescriptor.fd

The modifiers are placed in canonical order as specified by "The Java Language Specification". This is public, protected or private first, and then other modifiers in the following order: static, final, transient, volatile.

Overrides
toString in class Object


 Class InvocationTargetException

Class java.lang.reflect.InvocationTargetException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.reflect.InvocationTargetException

public class InvocationTargetException
extends Exception

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.

See Also:
Method, Constructor


 InvocationTargetException Members

InvocationTargetException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InvocationTargetException() |
InvocationTargetException(Throwable) | Constructs a InvocationTargetException with a target exception.
InvocationTargetException(Throwable, String) | Constructs a InvocationTargetException with a target exception and a detail message.

Methods
Name | Description
getTargetException() | Get the thrown target exception.


 InvocationTargetException.InvocationTargetException

InvocationTargetException.InvocationTargetException

Syntax 1
protected InvocationTargetException()

Syntax 2
public InvocationTargetException( Throwable target )
Description
Constructs a InvocationTargetException with a target exception.

Syntax 3
public InvocationTargetException( Throwable target, String s )
Description
Constructs a InvocationTargetException with a target exception and a detail message.


 InvocationTargetException.getTargetException

InvocationTargetException.getTargetException

Syntax
public Throwable getTargetException()
Description
Get the thrown target exception.


 Interface Member

Interface java.lang.reflect.Member

Interface Members | This Package | All Packages

public interface Member

Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

See Also:
Class, Field, Method, Constructor


 Member Members

Member Members

Interface Overview | This Package | All Packages

Fields
Name | Description
DECLARED | Identifies the set of declared members of a class or interface.
PUBLIC | Identifies the set of all public members of a class or interface, including inherited members.

Methods
Name | Description
getDeclaringClass() | Returns the Class object representing the class or interface that declares the member or constructor represented by this Member.
getModifiers() | Returns the Java language modifiers for the member or constructor represented by this Member, as an integer.
getName() | Returns the simple name of the underlying member or constructor represented by this Member.


 Member.DECLARED

Member.DECLARED

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int DECLARED
Description
Identifies the set of declared members of a class or interface. Inherited members are not included.

See Also
checkMemberAccess


 Member.PUBLIC

Member.PUBLIC

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int PUBLIC
Description
Identifies the set of all public members of a class or interface, including inherited members.

See Also
checkMemberAccess


 Member.getDeclaringClass

Member.getDeclaringClass

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Class getDeclaringClass()
Description
Returns the Class object representing the class or interface that declares the member or constructor represented by this Member.


 Member.getModifiers

Member.getModifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getModifiers()
Description
Returns the Java language modifiers for the member or constructor represented by this Member, as an integer. The Modifier class should be used to decode the modifiers in the integer.

See Also
Modifier


 Member.getName

Member.getName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getName()
Description
Returns the simple name of the underlying member or constructor represented by this Member.


 Class Method

Class java.lang.reflect.Method

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.reflect.Method

public final class Method
extends Object
implements Member

A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).

A Method permits widening conversions to occur when matching the actual parameters to invokewith the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

See Also:
Member, Class, getMethods, getMethod, getDeclaredMethods, getDeclaredMethod


 Method Members

Method Members

Class Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Compares this Method against the specified object.
getDeclaringClass() | Returns the Class object representing the class or interface that declares the method represented by this Method object.
getExceptionTypes() | Returns an array of Class objects that represent the types of the checked exceptions thrown by the underlying method represented by this Method object.
getModifiers() | Returns the Java language modifiers for the method represented by this Method object, as an integer.
getName() | Returns the name of the method represented by this Method object, as a String.
getParameterTypes() | Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object.
getReturnType() | Returns a Class object that represents the formal return type of the method represented by this Method object.
hashCode() | Returns a hashcode for this Method.
invoke(Object, Object[]) | Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
toString() | Returns a string describing this Method.


 Method.equals

Method.equals

Syntax
public boolean equals( Object obj )
Description
Compares this Method against the specified object. Returns true if the objects are the same. Two Methods are the same if they were declared by the same class and have the same name and formal parameter types.

Overrides
equals in class Object


 Method.getDeclaringClass

Method.getDeclaringClass

Syntax
public Class getDeclaringClass()
Description
Returns the Class object representing the class or interface that declares the method represented by this Method object.


 Method.getExceptionTypes

Method.getExceptionTypes

Syntax
public Class[] getExceptionTypes()
Description
Returns an array of Class objects that represent the types of the checked exceptions thrown by the underlying method represented by this Method object. Returns an array of length 0 if the method throws no checked exceptions.


 Method.getModifiers

Method.getModifiers

Syntax
public native int getModifiers()
Description
Returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers.

See Also
Modifier


 Method.getName

Method.getName

Syntax
public String getName()
Description
Returns the name of the method represented by this Method object, as a String.


 Method.getParameterTypes

Method.getParameterTypes

Syntax
public Class[] getParameterTypes()
Description
Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. Returns an array of length 0 if the underlying method takes no parameters.


 Method.getReturnType

Method.getReturnType

Syntax
public Class getReturnType()
Description
Returns a Class object that represents the formal return type of the method represented by this Method object.


 Method.hashCode

Method.hashCode

Syntax
public int hashCode()
Description
Returns a hashcode for this Method. The hashcode is computed as the exclusive-or of the hashcodes for the underlying method's declaring class name and the method's name.

Overrides
hashCode in class Object


 Method.invoke

Method.invoke

Syntax
public native Object invoke( Object obj, Object args[] ) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
Description
Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to widening conversions as necessary. The value returned by the underlying method is automatically wrapped in an object if it has a primitive type.

Method invocation proceeds with the following steps, in order:

If the underlying method is static, then the specified object argument is ignored. It may be null.

Otherwise, the method is an instance method. If the specified object argument is null, the invocation throws a NullPointerException. Otherwise, if the specified object argument is not an instance of the class or interface declaring the underlying method, the invocation throws an IllegalArgumentException.

If this Method object enforces Java language access control and the underlying method is inaccessible, the invocation throws an IllegalAccessException.

If the number of actual parameters supplied via args is different from the number of formal parameters required by the underlying method, the invocation throws an IllegalArgumentException.

For each actual parameter in the supplied args array:

If the corresponding formal parameter has a primitive type, an unwrapping conversion is attempted to convert the object value to a value of a primitive type. If this attempt fails, the invocation throws an IllegalArgumentException.

If, after possible unwrapping, the parameter value cannot be converted to the corresponding formal parameter type by an identity or widening conversion, the invocation throws an IllegalArgumentException.

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, section 15.11.4.4; in particular, overriding based on the runtime type of the target object will occur.

If the underlying method is static, it is invoked as exactly the method on the declaring class.

Control transfers to the underlying method. If the method completes abruptly by throwing an exception, the exception is placed in an InvocationTargetException and thrown in turn to the caller of invoke.

If the method completes normally, the value it returns is returned to the caller of invoke; if the value has a primitive type, it is first appropriately wrapped in an object. If the underlying method return type is void, the invocation returns null.

Exceptions
IllegalAccessException if the underlying method is inaccessible.
Exceptions
IllegalArgumentException if the number of actual and formal parameters differ, or if an unwrapping conversion fails.
Exceptions
InvocationTargetException if the underlying method throws an exception.
Exceptions
NullPointerException if the specified object is null.


 Method.toString

Method.toString

Syntax
public String toString()
Description
Returns a string describing this Method. The string is formatted as the method access modifiers, if any, followed by the method return type, followed by a space, followed by the class declaring the method, followed by a period, followed by the method name, followed by a parenthesized, comma-separated list of the method's formal parameter types. If the method throws checked exceptions, the parameter list is followed by a space, followed by the word throws followed by a comma-separated list of the thrown exception types. For example:
    public boolean java.lang.Object.equals(java.lang.Object)

The access modifiers are placed in canonical order as specified by "The Java Language Specification". This is public, protected or private first, and then other modifiers in the following order: abstract, static, final, synchronized native.

Overrides
toString in class Object


 Class Modifier

Class java.lang.reflect.Modifier

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.reflect.Modifier

public class Modifier
extends Object

The Modifier class provides static methods and constants to decode class and member access modifiers.

See Also:
getModifiers, getModifiers


 Modifier Members

Modifier Members

Class Overview | This Package | All Packages

Fields
Name | Description
ABSTRACT |
FINAL |
INTERFACE |
NATIVE |
PRIVATE |
PROTECTED |
PUBLIC |
STATIC |
SYNCHRONIZED |
TRANSIENT |
VOLATILE |

Constructors
Name | Description
Modifier() |

Methods
Name | Description
isAbstract(int) | Return true if the specifier integer includes the abstract modifier.
isFinal(int) | Return true if the specifier integer includes the final modifier.
isInterface(int) | Return true if the specifier integer includes the interface modifier.
isNative(int) | Return true if the specifier integer includes the native modifier.
isPrivate(int) | Return true if the specifier integer includes the private modifier.
isProtected(int) | Return true if the specifier integer includes the protected modifier.
isPublic(int) | Return true if the specified integer includes the public modifier.
isStatic(int) | Return true if the specifier integer includes the static modifier.
isSynchronized(int) | Return true if the specifier integer includes the final modifier.
isTransient(int) | Return true if the specifier integer includes the transient modifier.
isVolatile(int) | Return true if the specifier integer includes the volatile modifier.
toString(int) | Return a string describing the access modifier flags in the specified modifier.


 Modifier.ABSTRACT

Modifier.ABSTRACT

Syntax
public static final int ABSTRACT


 Modifier.FINAL

Modifier.FINAL

Syntax
public static final int FINAL


 Modifier.INTERFACE

Modifier.INTERFACE

Syntax
public static final int INTERFACE


 Modifier.NATIVE

Modifier.NATIVE

Syntax
public static final int NATIVE


 Modifier.PRIVATE

Modifier.PRIVATE

Syntax
public static final int PRIVATE


 Modifier.PROTECTED

Modifier.PROTECTED

Syntax
public static final int PROTECTED


 Modifier.PUBLIC

Modifier.PUBLIC

Syntax
public static final int PUBLIC


 Modifier.STATIC

Modifier.STATIC

Syntax
public static final int STATIC


 Modifier.SYNCHRONIZED

Modifier.SYNCHRONIZED

Syntax
public static final int SYNCHRONIZED


 Modifier.TRANSIENT

Modifier.TRANSIENT

Syntax
public static final int TRANSIENT


 Modifier.VOLATILE

Modifier.VOLATILE

Syntax
public static final int VOLATILE


 Modifier.Modifier

Modifier.Modifier

Syntax
public Modifier()


 Modifier.isAbstract

Modifier.isAbstract

Syntax
public static boolean isAbstract( int mod )
Description
Return true if the specifier integer includes the abstract modifier.


 Modifier.isFinal

Modifier.isFinal

Syntax
public static boolean isFinal( int mod )
Description
Return true if the specifier integer includes the final modifier.


 Modifier.isInterface

Modifier.isInterface

Syntax
public static boolean isInterface( int mod )
Description
Return true if the specifier integer includes the interface modifier.


 Modifier.isNative

Modifier.isNative

Syntax
public static boolean isNative( int mod )
Description
Return true if the specifier integer includes the native modifier.


 Modifier.isPrivate

Modifier.isPrivate

Syntax
public static boolean isPrivate( int mod )
Description
Return true if the specifier integer includes the private modifier.


 Modifier.isProtected

Modifier.isProtected

Syntax
public static boolean isProtected( int mod )
Description
Return true if the specifier integer includes the protected modifier.


 Modifier.isPublic

Modifier.isPublic

Syntax
public static boolean isPublic( int mod )
Description
Return true if the specified integer includes the public modifier.


 Modifier.isStatic

Modifier.isStatic

Syntax
public static boolean isStatic( int mod )
Description
Return true if the specifier integer includes the static modifier.


 Modifier.isSynchronized

Modifier.isSynchronized

Syntax
public static boolean isSynchronized( int mod )
Description
Return true if the specifier integer includes the final modifier.


 Modifier.isTransient

Modifier.isTransient

Syntax
public static boolean isTransient( int mod )
Description
Return true if the specifier integer includes the transient modifier.


 Modifier.isVolatile

Modifier.isVolatile

Syntax
public static boolean isVolatile( int mod )
Description
Return true if the specifier integer includes the volatile modifier.


 Modifier.toString

Modifier.toString

Syntax
public static String toString( int mod )
Description
Return a string describing the access modifier flags in the specified modifier. For example:
    public final synchronized
    private transient volatile
The modifier names are return in canonical order, as specified by The Java Language Specification.


 Package java.math

Package java.math

All Packages

Classes

  • BigDecimal
  • BigInteger


 Class BigDecimal

Class java.math.BigDecimal

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.math.BigDecimal

public class BigDecimal
extends Number

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer value and a non-negative integer scale, which represents the number of decimal digits to the right of the decimal point. (The number represented by the BigDecimal is intVal/10**scale.) BigDecimals provide operations for basic arithmetic, scale manipulation, comparison, format conversion and hashing.

The BigDecimal class gives its user complete control over rounding behavior, forcing the user to explicitly specify a rounding behavior for operations capable of discarding precision (divide and setScale). Eight rounding modes are provided for this purpose. Two types of operations are provided for manipulating the scale of a BigDecimal: scaling/rounding operations and decimal point motion operations. Scaling/Rounding operations (SetScale) return a BigDecimal whose value is approximately (or exactly) equal to that of the operand, but whose scale is the specified value; that is, they increase or decrease the precision of the number with minimal effect on its value. Decimal point motion operations (movePointLeft and movePointRight) return a BigDecimal created from the operand by moving the decimal point a specified distance in the specified direction; that is, they change a number's value without affecting its precision.

See Also:
BigInteger


 BigDecimal Members

BigDecimal Members

Class Overview | This Package | All Packages

Fields
Name | Description
ROUND_CEILING | If the BigDecimal is positive, behave as for ROUND_UP; if negative, behave as for ROUND_DOWN.
ROUND_DOWN | Never increment the digit prior to a discarded fraction (i.e., truncate).
ROUND_FLOOR | If the BigDecimal is positive, behave as for ROUND_DOWN; if negative behave as for ROUND_UP.
ROUND_HALF_DOWN | Behave as for ROUND_UP if the discarded fraction is > .5; otherwise, behave as for ROUND_DOWN.
ROUND_HALF_EVEN | Behave as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behave as for ROUND_HALF_DOWN if it's even.
ROUND_HALF_UP | Behave as for ROUND_UP if the discarded fraction is >= .5; otherwise, behave as for ROUND_DOWN.
ROUND_UNNECESSARY | This "pseudo-rounding-mode" is actually an assertion that the requested operation has an exact result, hence no rounding is necessary.
ROUND_UP | Always increment the digit prior to a non-zero discarded fraction.

Constructors
Name | Description
BigDecimal(BigInteger) | Translates a BigInteger into a BigDecimal.
BigDecimal(BigInteger, int) | Translates a BigInteger and a scale into a BigDecimal.
BigDecimal(double) | Translates a double into a BigDecimal.
BigDecimal(String) | Constructs a BigDecimal from a string containing an optional minus sign followed by a sequence of zero or more decimal digits, optionally followed by a fraction, which consists of a decimal point followed by zero or more decimal digits.

Methods
Name | Description
abs() | Returns a BigDecimal whose value is the absolute value of this number, and whose scale is this.scale().
add(BigDecimal) | Returns a BigDecimal whose value is (this + val), and whose scale is MAX(this.scale(), val.scale).
compareTo(BigDecimal) | Returns -1, 0 or 1 as this number is less than, equal to, or greater than val.
divide(BigDecimal, int) | Returns a BigDecimal whose value is (this / val), and whose scale is this.scale().
divide(BigDecimal, int, int) | Returns a BigDecimal whose value is (this / val), and whose scale is as specified.
doubleValue() | Converts the number to a double.
equals(Object) | Returns true iff x is a BigDecimal whose value is equal to this number.
floatValue() | Converts this number to a float.
hashCode() | Computes a hash code for this object.
intValue() | Converts this number to an int.
longValue() | Converts this number to a long.
max(BigDecimal) | Returns the BigDecimal whose value is the greater of this and val.
min(BigDecimal) | Returns the BigDecimal whose value is the lesser of this and val.
movePointLeft(int) | Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
movePointRight(int) | Moves the decimal point the specified number of places to the right.
multiply(BigDecimal) | Returns a BigDecimal whose value is (this * val), and whose scale is this.scale() + val.scale.
negate() | Returns a BigDecimal whose value is -1 * this, and whose scale is this.scale().
scale() | Returns the scale of this number.
setScale(int) | Returns a BigDecimal whose scale is the specified value, and whose value is exactly equal to this number's.
setScale(int, int) | Returns a BigDecimal whose scale is the specified value, and whose integer value is determined by multiplying or dividing this BigDecimal's integer value by the appropriate power of ten to maintain the overall value.
signum() | Returns the signum function of this number (i.e., -1, 0 or 1 as the value of this number is negative, zero or positive).
subtract(BigDecimal) | Returns a BigDecimal whose value is (this - val), and whose scale is MAX(this.scale(), val.scale).
toBigInteger() | Converts this number to a BigInteger.
toString() | Returns the string representation of this number.
valueOf(long) | Returns a BigDecimal with the given value and a scale of zero.
valueOf(long, int) | Returns a BigDecimal with a value of (val/10**scale).


 BigDecimal.ROUND_CEILING

BigDecimal.ROUND_CEILING

Syntax
public static final int ROUND_CEILING
Description
If the BigDecimal is positive, behave as for ROUND_UP; if negative, behave as for ROUND_DOWN. Note that this rounding mode never decreases the value. (Rounds towards positive infinity.)


 BigDecimal.ROUND_DOWN

BigDecimal.ROUND_DOWN

Syntax
public static final int ROUND_DOWN
Description
Never increment the digit prior to a discarded fraction (i.e., truncate). Note that this rounding mode never increases the magnitude. (Rounds towards zero.)


 BigDecimal.ROUND_FLOOR

BigDecimal.ROUND_FLOOR

Syntax
public static final int ROUND_FLOOR
Description
If the BigDecimal is positive, behave as for ROUND_DOWN; if negative behave as for ROUND_UP. Note that this rounding mode never increases the value. (Rounds towards negative infinity.)


 BigDecimal.ROUND_HALF_DOWN

BigDecimal.ROUND_HALF_DOWN

Syntax
public static final int ROUND_HALF_DOWN
Description
Behave as for ROUND_UP if the discarded fraction is > .5; otherwise, behave as for ROUND_DOWN. (Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case rounds down.)


 BigDecimal.ROUND_HALF_EVEN

BigDecimal.ROUND_HALF_EVEN

Syntax
public static final int ROUND_HALF_EVEN
Description
Behave as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behave as for ROUND_HALF_DOWN if it's even. (Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case, rounds towards the even neighbor.)


 BigDecimal.ROUND_HALF_UP

BigDecimal.ROUND_HALF_UP

Syntax
public static final int ROUND_HALF_UP
Description
Behave as for ROUND_UP if the discarded fraction is >= .5; otherwise, behave as for ROUND_DOWN. (Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case rounds up.)


 BigDecimal.ROUND_UNNECESSARY

BigDecimal.ROUND_UNNECESSARY

Syntax
public static final int ROUND_UNNECESSARY
Description
This "pseudo-rounding-mode" is actually an assertion that the requested operation has an exact result, hence no rounding is necessary. If this rounding mode is specified on an operation that yields an inexact result, an arithmetic exception is thrown.


 BigDecimal.ROUND_UP

BigDecimal.ROUND_UP

Syntax
public static final int ROUND_UP
Description
Always increment the digit prior to a non-zero discarded fraction. Note that this rounding mode never decreases the magnitude. (Rounds away from zero.)


 BigDecimal.BigDecimal

BigDecimal.BigDecimal

Syntax 1
public BigDecimal( String val ) throws NumberFormatException
Description
Constructs a BigDecimal from a string containing an optional minus sign followed by a sequence of zero or more decimal digits, optionally followed by a fraction, which consists of a decimal point followed by zero or more decimal digits. The string must contain at least one digit in the integer or fractional part. The scale of the resulting BigDecimal will be the number of digits to the right of the decimal point in the string, or 0 if the string contains no decimal point. The character-to-digit mapping is provided by Character.digit. Any extraneous characters (including whitespace) will result in a NumberFormatException.

Syntax 2
public BigDecimal( double val ) throws NumberFormatException
Description
Translates a double into a BigDecimal. The scale of the BigDecimal is the smallest value such that (10**scale * val) is an integer. A double whose value is -infinity, +infinity or NaN will result in a NumberFormatException.

Syntax 3
public BigDecimal( BigInteger val )
Description
Translates a BigInteger into a BigDecimal. The scale of the BigDecimal is zero.

Syntax 4
public BigDecimal( BigInteger val, int scale ) throws NumberFormatException
Description
Translates a BigInteger and a scale into a BigDecimal. The value of the BigDecimal is (BigInteger/10**scale). A negative scale will result in a NumberFormatException.


 BigDecimal.abs

BigDecimal.abs

Syntax
public BigDecimal abs()
Description
Returns a BigDecimal whose value is the absolute value of this number, and whose scale is this.scale().


 BigDecimal.add

BigDecimal.add

Syntax
public BigDecimal add( BigDecimal val )
Description
Returns a BigDecimal whose value is (this + val), and whose scale is MAX(this.scale(), val.scale).


 BigDecimal.compareTo

BigDecimal.compareTo

Syntax
public int compareTo( BigDecimal val )
Description
Returns -1, 0 or 1 as this number is less than, equal to, or greater than val. Two BigDecimals that are equal in value but have a different scale (e.g., 2.0, 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.


 BigDecimal.divide

BigDecimal.divide

Syntax 1
public BigDecimal divide( BigDecimal val, int scale, int roundingMode ) throws ArithmeticException, IllegalArgumentException
Description
Returns a BigDecimal whose value is (this / val), and whose scale is as specified. If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied. Throws an ArithmeticException if val == 0, scale < 0, or the rounding mode is ROUND_UNNECESSARY and the specified scale is insufficient to represent the result of the division exactly. Throws an IllegalArgumentException if roundingMode does not represent a valid rounding mode.

Syntax 2
public BigDecimal divide( BigDecimal val, int roundingMode ) throws ArithmeticException, IllegalArgumentException
Description
Returns a BigDecimal whose value is (this / val), and whose scale is this.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied. Throws an ArithmeticException if val == 0. Throws an IllegalArgumentException if roundingMode does not represent a valid rounding mode.


 BigDecimal.doubleValue

BigDecimal.doubleValue

Syntax
public double doubleValue()
Description
Converts the number to a double. Similar to the double-to-float narrowing primitive conversion defined in The Java Language Specification: if the number has too great a magnitude to represent as a double, it will be converted to infinity or negative infinity, as appropriate.

Overrides
doubleValue in class Number


 BigDecimal.equals

BigDecimal.equals

Syntax
public boolean equals( Object x )
Description
Returns true iff x is a BigDecimal whose value is equal to this number. This method is provided so that BigDecimals can be used as hash keys. Unlike compareTo, this method considers two BigDecimals equal only if they are equal in value and scale.

Overrides
equals in class Object


 BigDecimal.floatValue

BigDecimal.floatValue

Syntax
public float floatValue()
Description
Converts this number to a float. Similar to the double-to-float narrowing primitive conversion defined in The Java Language Specification: if the number has too great a magnitude to represent as a float, it will be converted to infinity or negative infinity, as appropriate.

Overrides
floatValue in class Number


 BigDecimal.hashCode

BigDecimal.hashCode

Syntax
public int hashCode()
Description
Computes a hash code for this object. Note that two BigDecimals that are numerically equal but differ in scale (e.g., 2.0, 2.00) will not generally have the same hash code.

Overrides
hashCode in class Object


 BigDecimal.intValue

BigDecimal.intValue

Syntax
public int intValue()
Description
Converts this number to an int. Standard narrowing primitive conversion as per The Java Language Specification. In particular, note that any fractional part of this number will be truncated.

Overrides
intValue in class Number


 BigDecimal.longValue

BigDecimal.longValue

Syntax
public long longValue()
Description
Converts this number to a long. Standard narrowing primitive conversion as per The Java Language Specification. In particular, note that any fractional part of this number will be truncated.

Overrides
longValue in class Number


 BigDecimal.max

BigDecimal.max

Syntax
public BigDecimal max( BigDecimal val )
Description
Returns the BigDecimal whose value is the greater of this and val. If the values are equal (as defined by the compareTo operator), either may be returned.


 BigDecimal.min

BigDecimal.min

Syntax
public BigDecimal min( BigDecimal val )
Description
Returns the BigDecimal whose value is the lesser of this and val. If the values are equal (as defined by the compareTo operator), either may be returned.


 BigDecimal.movePointLeft

BigDecimal.movePointLeft

Syntax
public BigDecimal movePointLeft( int n )
Description
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left. If n is non-negative, the call merely adds n to the scale. If n is negative, the call is equivalent to movePointRight(-n). (The BigDecimal returned by this call has value (this * 10**-n) and scale MAX(this.scale()+n, 0).)


 BigDecimal.movePointRight

BigDecimal.movePointRight

Syntax
public BigDecimal movePointRight( int n )
Description
Moves the decimal point the specified number of places to the right. If this number's scale is >= n, the call merely subtracts n from the scale; otherwise, it sets the scale to zero, and multiplies the integer value by 10 ** (n - this.scale). If n is negative, the call is equivalent to movePointLeft(-n). (The BigDecimal returned by this call has value (this * 10**n) and scale MAX(this.scale()-n, 0).)


 BigDecimal.multiply

BigDecimal.multiply

Syntax
public BigDecimal multiply( BigDecimal val )
Description
Returns a BigDecimal whose value is (this * val), and whose scale is this.scale() + val.scale.


 BigDecimal.negate

BigDecimal.negate

Syntax
public BigDecimal negate()
Description
Returns a BigDecimal whose value is -1 * this, and whose scale is this.scale().


 BigDecimal.scale

BigDecimal.scale

Syntax
public int scale()
Description
Returns the scale of this number.


 BigDecimal.setScale

BigDecimal.setScale

Syntax 1
public BigDecimal setScale( int scale, int roundingMode ) throws ArithmeticException, IllegalArgumentException
Description
Returns a BigDecimal whose scale is the specified value, and whose integer value is determined by multiplying or dividing this BigDecimal's integer value by the appropriate power of ten to maintain the overall value. If the scale is reduced by the operation, the integer value must be divided (rather than multiplied), and precision may be lost; in this case, the specified rounding mode is applied to the division. Throws an ArithmeticException if scale is negative, or the rounding mode is ROUND_UNNECESSARY and it is impossible to perform the specified scaling operation without loss of precision. Throws an IllegalArgumentException if roundingMode does not represent a valid rounding mode.

Syntax 2
public BigDecimal setScale( int scale ) throws ArithmeticException, IllegalArgumentException
Description
Returns a BigDecimal whose scale is the specified value, and whose value is exactly equal to this number's. Throws an ArithmeticException if this is not possible. This call is typically used to increase the scale, in which case it is guaranteed that there exists a BigDecimal of the specified scale and the correct value. The call can also be used to reduce the scale if the caller knows that the number has sufficiently many zeros at the end of its fractional part (i.e., factors of ten in its integer value) to allow for the rescaling without loss of precision. Note that this call returns the same result as the two argument version of setScale, but saves the caller the trouble of specifying a rounding mode in cases where it is irrelevant.


 BigDecimal.signum

BigDecimal.signum

Syntax
public int signum()
Description
Returns the signum function of this number (i.e., -1, 0 or 1 as the value of this number is negative, zero or positive).


 BigDecimal.subtract

BigDecimal.subtract

Syntax
public BigDecimal subtract( BigDecimal val )
Description
Returns a BigDecimal whose value is (this - val), and whose scale is MAX(this.scale(), val.scale).


 BigDecimal.toBigInteger

BigDecimal.toBigInteger

Syntax
public BigInteger toBigInteger()
Description
Converts this number to a BigInteger. Standard narrowing primitive conversion as per The Java Language Specification. In particular, note that any fractional part of this number will be truncated.


 BigDecimal.toString

BigDecimal.toString

Syntax
public String toString()
Description
Returns the string representation of this number. The digit-to- character mapping provided by Character.forDigit is used. The minus sign and decimal point are used to indicate sign and scale. (This representation is compatible with the (String, int) constructor.)

Overrides
toString in class Object


 BigDecimal.valueOf

BigDecimal.valueOf

Syntax 1
public static BigDecimal valueOf( long val, int scale ) throws NumberFormatException
Description
Returns a BigDecimal with a value of (val/10**scale). This factory is provided in preference to a (long) constructor because it allows for reuse of frequently used BigDecimals (like 0 and 1), obviating the need for exported constants. A negative scale will result in a NumberFormatException.

Syntax 2
public static BigDecimal valueOf( long val )
Description
Returns a BigDecimal with the given value and a scale of zero. This factory is provided in preference to a (long) constructor because it allows for reuse of frequently used BigDecimals (like 0 and 1), obviating the need for exported constants.


 Class BigInteger

Class java.math.BigInteger

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Number
           |
           +----java.math.BigInteger

public class BigInteger
extends Number

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigIntegers provide analogues to all of Java's primitive integer operators, and all relevant static methods from java.lang.Math. Additionally, BigIntegers provide operations for modular arithmetic, GCD calculation, primality testing, prime generation, single-bit manipulation, and a few other odds and ends.

Semantics of arithmetic operations exactly mimic those of java's integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the results of an operation.

Semantics of shift operations extend those of Java's shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator (>>>) is omitted, as this operation makes little sense in combination with the "infinite word size" abstraction provided by this class.

Semantics of bitwise logical operations are are exactly mimic those of Java's bitwise integer operators. The Binary operators (and, or, xor) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.

Comparison operations perform signed integer comparisons, analogous to those performed by java's relational and equality operators.

Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus - 1), inclusive.

Single-bit operations operate on a single bit of the two's-complement representation of their operand. If necessary, the operand is sign extended so that it contains the designated bit. None of the single-bit operations can produce a number with a different sign from the the BigInteger being operated on, as they affect only a single bit, and the "infinite word size" abstraction provided by this class ensures that there are infinitely many "virtual sign bits" preceding each BigInteger.

See Also:
BigDecimal


 BigInteger Members

BigInteger Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BigInteger(byte[]) | Translates a byte array containing the two's-complement representation of a (signed) integer into a BigInteger.
BigInteger(int, byte[]) | Translates the sign-magnitude representation of an integer into a BigInteger.
BigInteger(int, int, Random) | Returns a randomly selected BigInteger with the specified bitLength that is probably prime.
BigInteger(int, Random) | Returns a random number uniformly distributed on [0, 2**numBits - 1] (assuming a fair source of random bits is provided in rndSrc).
BigInteger(String) | Translates a string containing an optional minus sign followed by a sequence of one or more decimal digits into a BigInteger.
BigInteger(String, int) | Translates a string containing an optional minus sign followed by a sequence of one or more digits in the specified radix into a BigInteger.

Methods
Name | Description
abs() | Returns a BigInteger whose value is the absolute value of this number.
add(BigInteger) | Returns a BigInteger whose value is (this + val).
and(BigInteger) | Returns a BigInteger whose value is (this & val).
andNot(BigInteger) | Returns a BigInteger whose value is (this & ~val).
bitCount() | Returns the number of bits in the two's complement representation of this number that differ from its sign bit.
bitLength() | Returns the number of bits in the minimal two's-complement representation of this number, *excluding* a sign bit, i.e., (ceil(log2(this < 0 ? -this : this + 1))).
clearBit(int) | Returns a BigInteger whose value is equivalent to this number with the designated bit cleared.
compareTo(BigInteger) | Returns -1, 0 or 1 as this number is less than, equal to, or greater than val.
divide(BigInteger) | Returns a BigInteger whose value is (this / val).
divideAndRemainder(BigInteger) | Returns an array of two BigIntegers.
doubleValue() | Converts the number to a double.
equals(Object) | Returns true iff x is a BigInteger whose value is equal to this number.
flipBit(int) | Returns a BigInteger whose value is equivalent to this number with the designated bit flipped.
floatValue() | Converts this number to a float.
gcd(BigInteger) | Returns a BigInteger whose value is the greatest common denominator of abs(this) and abs(val).
getLowestSetBit() | Returns the index of the rightmost (lowest-order) one bit in this number (i.e., the number of zero bits to the right of the rightmost one bit).
hashCode() | Computes a hash code for this object.
intValue() | Converts this number to an int.
isProbablePrime(int) | Returns true if this BigInteger is probably prime, false if it's definitely composite.
longValue() | Converts this number to a long.
max(BigInteger) | Returns the BigInteger whose value is the greater of this and val.
min(BigInteger) | Returns the BigInteger whose value is the lesser of this and val.
mod(BigInteger) | Returns a BigInteger whose value is this mod m.
modInverse(BigInteger) | Returns modular multiplicative inverse of this, mod m.
modPow(BigInteger, BigInteger) | Returns a BigInteger whose value is (this ** exponent) mod m.
multiply(BigInteger) | Returns a BigInteger whose value is (this * val).
negate() | Returns a BigInteger whose value is (-1 * this).
not() | Returns a BigInteger whose value is (~this).
or(BigInteger) | Returns a BigInteger whose value is (this | val).
pow(int) | Returns a BigInteger whose value is (this ** exponent).
remainder(BigInteger) | Returns a BigInteger whose value is (this % val).
setBit(int) | Returns a BigInteger whose value is equivalent to this number with the designated bit set.
shiftLeft(int) | Returns a BigInteger whose value is (this << n).
shiftRight(int) | Returns a BigInteger whose value is (this >> n).
signum() | Returns the signum function of this number (i.e., -1, 0 or 1 as the value of this number is negative, zero or positive).
subtract(BigInteger) | Returns a BigInteger whose value is (this - val).
testBit(int) | Returns true iff the designated bit is set.
toByteArray() | Returns the two's-complement representation of this number.
toString() | Returns the string representation of this number, radix 10.
toString(int) | Returns the string representation of this number in the given radix.
valueOf(long) | Returns a BigInteger with the specified value.
xor(BigInteger) | Returns a BigInteger whose value is (this ^ val).


 BigInteger.BigInteger

BigInteger.BigInteger

Syntax 1
public BigInteger( byte val[] ) throws NumberFormatException
Description
Translates a byte array containing the two's-complement representation of a (signed) integer into a BigInteger. The input array is assumed to be big-endian (i.e., the most significant byte is in the [0] position). (The most significant bit of the most significant byte is the sign bit.) The array must contain at least one byte or a NumberFormatException will be thrown.

Syntax 2
public BigInteger( int signum, byte magnitude[] ) throws NumberFormatException
Description
Translates the sign-magnitude representation of an integer into a BigInteger. The sign is represented as an integer signum value (-1 for negative, 0 for zero, 1 for positive). The magnitude is represented as a big-endian byte array (i.e., the most significant byte is in the [0] position). An invalid signum value or a 0 signum value coupled with a nonzero magnitude will result in a NumberFormatException. A zero length magnitude array is permissible, and will result in in a value of 0 (irrespective of the given signum value).

Syntax 3
public BigInteger( String val, int radix ) throws NumberFormatException
Description
Translates a string containing an optional minus sign followed by a sequence of one or more digits in the specified radix into a BigInteger. The character-to-digit mapping is provided by Character.digit. Any extraneous characters (including whitespace), or a radix outside the range from Character.MIN_RADIX(2) to Character.MAX_RADIX(36), inclusive, will result in a NumberFormatException.

Syntax 4
public BigInteger( String val ) throws NumberFormatException
Description
Translates a string containing an optional minus sign followed by a sequence of one or more decimal digits into a BigInteger. The character-to-digit mapping is provided by Character.digit. Any extraneous characters (including whitespace) will result in a NumberFormatException.

Syntax 5
public BigInteger( int numBits, Random rndSrc ) throws IllegalArgumentException
Description
Returns a random number uniformly distributed on [0, 2**numBits - 1] (assuming a fair source of random bits is provided in rndSrc). Note that this constructor always returns a non-negative BigInteger. Throws an IllegalArgumentException if numBits < 0.

Syntax 6
public BigInteger( int bitLength, int certainty, Random rnd )
Description
Returns a randomly selected BigInteger with the specified bitLength that is probably prime. The certainty parameter is a measure of the uncertainty that the caller is willing to tolerate: the probability that the number is prime will exceed 1 - 1/2**certainty. The execution time is proportional to the value of the certainty parameter. The given random number generator is used to select candidates to be tested for primality. Throws an ArithmeticException if bitLength < 2.


 BigInteger.abs

BigInteger.abs

Syntax
public BigInteger abs()
Description
Returns a BigInteger whose value is the absolute value of this number.


 BigInteger.add

BigInteger.add

Syntax
public BigInteger add( BigInteger val ) throws ArithmeticException
Description
Returns a BigInteger whose value is (this + val).


 BigInteger.and

BigInteger.and

Syntax
public BigInteger and( BigInteger val )
Description
Returns a BigInteger whose value is (this & val). (This method returns a negative number iff this and val are both negative.)


 BigInteger.andNot

BigInteger.andNot

Syntax
public BigInteger andNot( BigInteger val )
Description
Returns a BigInteger whose value is (this & ~val). This method, which is equivalent to and(val.not()), is provided as a convenience for masking operations. (This method returns a negative number iff this is negative and val is positive.)


 BigInteger.bitCount

BigInteger.bitCount

Syntax
public int bitCount()
Description
Returns the number of bits in the two's complement representation of this number that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.


 BigInteger.bitLength

BigInteger.bitLength

Syntax
public int bitLength()
Description
Returns the number of bits in the minimal two's-complement representation of this number, *excluding* a sign bit, i.e., (ceil(log2(this < 0 ? -this : this + 1))). (For positive numbers, this is equivalent to the number of bits in the ordinary binary representation.)


 BigInteger.clearBit

BigInteger.clearBit

Syntax
public BigInteger clearBit( int n ) throws ArithmeticException
Description
Returns a BigInteger whose value is equivalent to this number with the designated bit cleared. (Computes (this & ~(1 << n)).) Throws an ArithmeticException if n < 0.


 BigInteger.compareTo

BigInteger.compareTo

Syntax
public int compareTo( BigInteger val )
Description
Returns -1, 0 or 1 as this number is less than, equal to, or greater than val. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.


 BigInteger.divide

BigInteger.divide

Syntax
public BigInteger divide( BigInteger val ) throws ArithmeticException
Description
Returns a BigInteger whose value is (this / val). Throws an ArithmeticException if val == 0.


 BigInteger.divideAndRemainder

BigInteger.divideAndRemainder

Syntax
public BigInteger[] divideAndRemainder( BigInteger val ) throws ArithmeticException
Description
Returns an array of two BigIntegers. The first ([0]) element of the return value is the quotient (this / val), and the second ([1]) element is the remainder (this % val). Throws an ArithmeticException if val == 0.


 BigInteger.doubleValue

BigInteger.doubleValue

Syntax
public double doubleValue()
Description
Converts the number to a double. Similar to the double-to-float narrowing primitive conversion defined in The Java Language Specification: if the number has too great a magnitude to represent as a double, it will be converted to infinity or negative infinity, as appropriate.

Overrides
doubleValue in class Number


 BigInteger.equals

BigInteger.equals

Syntax
public boolean equals( Object x )
Description
Returns true iff x is a BigInteger whose value is equal to this number. This method is provided so that BigIntegers can be used as hash keys.

Overrides
equals in class Object


 BigInteger.flipBit

BigInteger.flipBit

Syntax
public BigInteger flipBit( int n ) throws ArithmeticException
Description
Returns a BigInteger whose value is equivalent to this number with the designated bit flipped. (Computes (this ^ (1 << n)).) Throws an ArithmeticException if n < 0.


 BigInteger.floatValue

BigInteger.floatValue

Syntax
public float floatValue()
Description
Converts this number to a float. Similar to the double-to-float narrowing primitive conversion defined in The Java Language Specification: if the number has too great a magnitude to represent as a float, it will be converted to infinity or negative infinity, as appropriate.

Overrides
floatValue in class Number


 BigInteger.gcd

BigInteger.gcd

Syntax
public BigInteger gcd( BigInteger val )
Description
Returns a BigInteger whose value is the greatest common denominator of abs(this) and abs(val). Returns 0 if this == 0 && val == 0.


 BigInteger.getLowestSetBit

BigInteger.getLowestSetBit

Syntax
public int getLowestSetBit()
Description
Returns the index of the rightmost (lowest-order) one bit in this number (i.e., the number of zero bits to the right of the rightmost one bit). Returns -1 if this number contains no one bits. (Computes (this==0? -1 : log2(this & -this)).)


 BigInteger.hashCode

BigInteger.hashCode

Syntax
public int hashCode()
Description
Computes a hash code for this object.

Overrides
hashCode in class Object


 BigInteger.intValue

BigInteger.intValue

Syntax
public int intValue()
Description
Converts this number to an int. Standard narrowing primitive conversion as per The Java Language Specification.

Overrides
intValue in class Number


 BigInteger.isProbablePrime

BigInteger.isProbablePrime

Syntax
public boolean isProbablePrime( int certainty )
Description
Returns true if this BigInteger is probably prime, false if it's definitely composite. The certainty parameter is a measure of the uncertainty that the caller is willing to tolerate: the method returns true if the probability that this number is is prime exceeds 1 - 1/2**certainty. The execution time is proportional to the value of the certainty parameter.


 BigInteger.longValue

BigInteger.longValue

Syntax
public long longValue()
Description
Converts this number to a long. Standard narrowing primitive conversion as per The Java Language Specification.

Overrides
longValue in class Number


 BigInteger.max

BigInteger.max

Syntax
public BigInteger max( BigInteger val )
Description
Returns the BigInteger whose value is the greater of this and val. If the values are equal, either may be returned.


 BigInteger.min

BigInteger.min

Syntax
public BigInteger min( BigInteger val )
Description
Returns the BigInteger whose value is the lesser of this and val. If the values are equal, either may be returned.


 BigInteger.mod

BigInteger.mod

Syntax
public BigInteger mod( BigInteger m )
Description
Returns a BigInteger whose value is this mod m. Throws an ArithmeticException if m <= 0.


 BigInteger.modInverse

BigInteger.modInverse

Syntax
public BigInteger modInverse( BigInteger m ) throws ArithmeticException
Description
Returns modular multiplicative inverse of this, mod m. Throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1).


 BigInteger.modPow

BigInteger.modPow

Syntax
public BigInteger modPow( BigInteger exponent, BigInteger m )
Description
Returns a BigInteger whose value is (this ** exponent) mod m. (If exponent == 1, the returned value is (this mod m). If exponent < 0, the returned value is the modular multiplicative inverse of (this ** -exponent).) Throws an ArithmeticException if m <= 0.


 BigInteger.multiply

BigInteger.multiply

Syntax
public BigInteger multiply( BigInteger val )
Description
Returns a BigInteger whose value is (this * val).


 BigInteger.negate

BigInteger.negate

Syntax
public BigInteger negate()
Description
Returns a BigInteger whose value is (-1 * this).


 BigInteger.not

BigInteger.not

Syntax
public BigInteger not()
Description
Returns a BigInteger whose value is (~this). (This method returns a negative value iff this number is non-negative.)


 BigInteger.or

BigInteger.or

Syntax
public BigInteger or( BigInteger val )
Description
Returns a BigInteger whose value is (this | val). (This method returns a negative number iff either this or val is negative.)


 BigInteger.pow

BigInteger.pow

Syntax
public BigInteger pow( int exponent ) throws ArithmeticException
Description
Returns a BigInteger whose value is (this ** exponent). Throws an ArithmeticException if exponent < 0 (as the operation would yield a non-integer value). Note that exponent is an integer rather than a BigInteger.


 BigInteger.remainder

BigInteger.remainder

Syntax
public BigInteger remainder( BigInteger val ) throws ArithmeticException
Description
Returns a BigInteger whose value is (this % val). Throws an ArithmeticException if val == 0.


 BigInteger.setBit

BigInteger.setBit

Syntax
public BigInteger setBit( int n ) throws ArithmeticException
Description
Returns a BigInteger whose value is equivalent to this number with the designated bit set. (Computes (this | (1 << n)).) Throws an ArithmeticException if n < 0.


 BigInteger.shiftLeft

BigInteger.shiftLeft

Syntax
public BigInteger shiftLeft( int n )
Description
Returns a BigInteger whose value is (this << n). (Computes floor(this * 2**n).)


 BigInteger.shiftRight

BigInteger.shiftRight

Syntax
public BigInteger shiftRight( int n )
Description
Returns a BigInteger whose value is (this >> n). Sign extension is performed. (Computes floor(this / 2**n).)


 BigInteger.signum

BigInteger.signum

Syntax
public int signum()
Description
Returns the signum function of this number (i.e., -1, 0 or 1 as the value of this number is negative, zero or positive).


 BigInteger.subtract

BigInteger.subtract

Syntax
public BigInteger subtract( BigInteger val )
Description
Returns a BigInteger whose value is (this - val).


 BigInteger.testBit

BigInteger.testBit

Syntax
public boolean testBit( int n ) throws ArithmeticException
Description
Returns true iff the designated bit is set. (Computes ((this & (1 << n)) != 0).) Throws an ArithmeticException if n < 0.


 BigInteger.toByteArray

BigInteger.toByteArray

Syntax
public byte[] toByteArray()
Description
Returns the two's-complement representation of this number. The array is big-endian (i.e., the most significant byte is in the [0] position). The array contains the minimum number of bytes required to represent the number (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)


 BigInteger.toString

BigInteger.toString

Syntax 1
public String toString( int radix )
Description
Returns the string representation of this number in the given radix. If the radix is outside the range from Character.MIN_RADIX(2) to Character.MAX_RADIX(36) inclusive, it will default to 10 (as is the case for Integer.toString). The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String, int) constructor.)

Syntax 2
public String toString()
Description
Returns the string representation of this number, radix 10. The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String) constructor, and allows for string concatenation with Java's + operator.)

Overrides
toString in class Object


 BigInteger.valueOf

BigInteger.valueOf

Syntax
public static BigInteger valueOf( long val )
Description
Returns a BigInteger with the specified value. This factory is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers (like 0 and 1), obviating the need for exported constants.


 BigInteger.xor

BigInteger.xor

Syntax
public BigInteger xor( BigInteger val )
Description
Returns a BigInteger whose value is (this ^ val). (This method returns a negative number iff exactly one of this and val are negative.)


 Package java.net

Package java.net

All Packages

Interfaces

  • ContentHandlerFactory
  • FileNameMap
  • SocketImplFactory
  • URLStreamHandlerFactory

    • Classes

  • ContentHandler
  • DatagramPacket
  • DatagramSocket
  • DatagramSocketImpl
  • HttpURLConnection
  • InetAddress
  • MulticastSocket
  • ServerSocket
  • Socket
  • SocketImpl
  • URL
  • URLConnection
  • URLEncoder
  • URLStreamHandler

    • Exceptions

  • BindException
  • ConnectException
  • MalformedURLException
  • NoRouteToHostException
  • ProtocolException
  • SocketException
  • UnknownHostException
  • UnknownServiceException


 Class BindException

Class java.net.BindException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.SocketException
                                   |
                                   +----java.net.BindException

public class BindException
extends SocketException

Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned.


 BindException Members

BindException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BindException() | Construct a new BindException with no detailed message.
BindException(String) | Constructs a new BindException with the specified detail message as to why the bind error occurred.


 BindException.BindException

BindException.BindException

Syntax 1
public BindException( String msg )
Parameters
msg
the detail message
Description
Constructs a new BindException with the specified detail message as to why the bind error occurred. A detail message is a String that gives a specific description of this error.

Syntax 2
public BindException()
Description
Construct a new BindException with no detailed message.


 Class ConnectException

Class java.net.ConnectException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.SocketException
                                   |
                                   +----java.net.ConnectException

public class ConnectException
extends SocketException

Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the connection was refused remotely (e.g., no process is listening on the remote address/port).


 ConnectException Members

ConnectException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ConnectException() | Construct a new ConnectException with no detailed message.
ConnectException(String) | Constructs a new ConnectException with the specified detail message as to why the connect error occurred.


 ConnectException.ConnectException

ConnectException.ConnectException

Syntax 1
public ConnectException( String msg )
Parameters
msg
the detail message
Description
Constructs a new ConnectException with the specified detail message as to why the connect error occurred. A detail message is a String that gives a specific description of this error.

Syntax 2
public ConnectException()
Description
Construct a new ConnectException with no detailed message.


 Class ContentHandler

Class java.net.ContentHandler

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.ContentHandler

public abstract class ContentHandler
extends Object

The abstract class ContentHandler is the superclass of all classes that read an Object from a URLConnection.

An application does not generally call the getContent method in this class directly. Instead, an application calls the getContent method in class URL or in URLConnection. The application's content handler factory (an instance of a class that implements the interface ContentHandlerFactory set up by a call to setContentHandler) is called with a String giving the MIME type of the object being received on the socket. The factory returns an instance of a subclass of ContentHandler, and its getContent method is called to create the object.

See Also:
getContent, ContentHandlerFactory, getContent, URLConnection, getContent, setContentHandlerFactory


 ContentHandler Members

ContentHandler Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ContentHandler() |

Methods
Name | Description
getContent(URLConnection) | Given a URL connect stream positioned at the beginning of the representation of an object, this method reads that stream and creates an object from it.


 ContentHandler.ContentHandler

ContentHandler.ContentHandler

Syntax
public ContentHandler()


 ContentHandler.getContent

ContentHandler.getContent

Syntax
public abstract Object getContent( URLConnection urlc ) throws IOException
Parameters
urlc
a URL connection.
Returns
the object read by the ContentHandler.
Description
Given a URL connect stream positioned at the beginning of the representation of an object, this method reads that stream and creates an object from it.

Exceptions
IOException if an I/O error occurs while reading the object.


 Interface ContentHandlerFactory

Interface java.net.ContentHandlerFactory

Interface Members | This Package | All Packages

public interface ContentHandlerFactory

This interface defines a factory for content handlers. An implementation of this interface should map a MIME type into an instance of ContentHandler.

This interface is used by the URLStreamHandler class to create a ContentHandler for a MIME type.

See Also:
ContentHandler, URLStreamHandler


 ContentHandlerFactory Members

ContentHandlerFactory Members

Interface Overview | This Package | All Packages

Methods
Name | Description
createContentHandler(String) | Creates a new ContentHandler to read an object from a URLStreamHandler.


 ContentHandlerFactory.createContentHandler

ContentHandlerFactory.createContentHandler

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ContentHandler createContentHandler( String mimetype )
Parameters
mimetype
the MIME type for which a content handler is desired.
Returns
a new ContentHandler to read an object from a URLStreamHandler.
Description
Creates a new ContentHandler to read an object from a URLStreamHandler.

See Also
ContentHandler, URLStreamHandler


 Class DatagramPacket

Class java.net.DatagramPacket

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.DatagramPacket

public final class DatagramPacket
extends Object

This class represents a datagram packet.

Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to another based solely on information contained within that packet. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order.


 DatagramPacket Members

DatagramPacket Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DatagramPacket(byte[], int) | Constructs a DatagramPacket for receiving packets of length ilength.
DatagramPacket(byte[], int, InetAddress, int) | Constructs a datagram packet for sending packets of length ilength to the specified port number on the specified host.

Methods
Name | Description
getAddress() | Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
getData() | Returns the data received or the data to be sent.
getLength() | Returns the length of the data to be sent or the length of the data received.
getPort() | Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.
setAddress(InetAddress) |
setData(byte[]) |
setLength(int) |
setPort(int) |


 DatagramPacket.DatagramPacket

DatagramPacket.DatagramPacket

Syntax 1
public DatagramPacket( byte ibuf[], int ilength )
Parameters
ibuf
buffer for holding the incoming datagram.
ilength
the number of bytes to read.
Description
Constructs a DatagramPacket for receiving packets of length ilength.

The length argument must be less than or equal to ibuf.length.

Syntax 2
public DatagramPacket( byte ibuf[], int ilength, InetAddress iaddr, int iport )
Parameters
ibuf
the packet data.
ilength
the packet length.
iaddr
the destination address.
iport
the destination port number.
Description
Constructs a datagram packet for sending packets of length ilength to the specified port number on the specified host. The length argument must be less than or equal to ibuf.length.

See Also
InetAddress


 DatagramPacket.getAddress

DatagramPacket.getAddress

Syntax
public synchronized InetAddress getAddress()
Returns
the IP address of the machine to which this datagram is being sent or from which the datagram was received.
Description
Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

See Also
InetAddress


 DatagramPacket.getData

DatagramPacket.getData

Syntax
public synchronized byte[] getData()
Returns
the data received or the data to be sent.
Description
Returns the data received or the data to be sent.


 DatagramPacket.getLength

DatagramPacket.getLength

Syntax
public synchronized int getLength()
Returns
the length of the data to be sent or the length of the data received.
Description
Returns the length of the data to be sent or the length of the data received.


 DatagramPacket.getPort

DatagramPacket.getPort

Syntax
public synchronized int getPort()
Returns
the port number on the remote host to which this datagram is being sent or from which the datagram was received.
Description
Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received.


 DatagramPacket.setAddress

DatagramPacket.setAddress

Syntax
public synchronized void setAddress( InetAddress iaddr )


 DatagramPacket.setData

DatagramPacket.setData

Syntax
public synchronized void setData( byte ibuf[] )


 DatagramPacket.setLength

DatagramPacket.setLength

Syntax
public synchronized void setLength( int ilength )


 DatagramPacket.setPort

DatagramPacket.setPort

Syntax
public synchronized void setPort( int iport )


 Class DatagramSocket

Class java.net.DatagramSocket

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.DatagramSocket

public class DatagramSocket
extends Object

This class represents a socket for sending and receiving datagram packets.

A datagram socket is the sending or receiving point for a connectionless packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order.

See Also:
DatagramPacket


 DatagramSocket Members

DatagramSocket Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DatagramSocket() | Constructs a datagram socket and binds it to any available port on the local host machine.
DatagramSocket(int) | Constructs a datagram socket and binds it to the specified port on the local host machine.
DatagramSocket(int, InetAddress) | Creates a datagram socket, bound to the specified local address.

Methods
Name | Description
close() | Closes this datagram socket.
getLocalAddress() | Gets the local address to which the socket is bound.
getLocalPort() | Returns the port number on the local host to which this socket is bound.
getSoTimeout() | Retrive setting for SO_TIMEOUT.
receive(DatagramPacket) | Receives a datagram packet from this socket.
send(DatagramPacket) | Sends a datagram packet from this socket.
setSoTimeout(int) | Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.


 DatagramSocket.DatagramSocket

DatagramSocket.DatagramSocket

Syntax 1
public DatagramSocket() throws SocketException
Description
Constructs a datagram socket and binds it to any available port on the local host machine.

Exceptions
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.

Syntax 2
public DatagramSocket( int port ) throws SocketException
Parameters
local
port to use.
Description
Constructs a datagram socket and binds it to the specified port on the local host machine.

Exceptions
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.

Syntax 3
public DatagramSocket( int port, InetAddress laddr ) throws SocketException
Parameters
port
local port to use
laddr
local address to bind
Description
Creates a datagram socket, bound to the specified local address. The local port must be between 0 and 65535 inclusive.


 DatagramSocket.close

DatagramSocket.close

Syntax
public void close()
Description
Closes this datagram socket.


 DatagramSocket.getLocalAddress

DatagramSocket.getLocalAddress

Syntax
public InetAddress getLocalAddress()
Description
Gets the local address to which the socket is bound.


 DatagramSocket.getLocalPort

DatagramSocket.getLocalPort

Syntax
public int getLocalPort()
Returns
the port number on the local host to which this socket is bound.
Description
Returns the port number on the local host to which this socket is bound.


 DatagramSocket.getSoTimeout

DatagramSocket.getSoTimeout

Syntax
public synchronized int getSoTimeout() throws SocketException
Description
Retrive setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).


 DatagramSocket.receive

DatagramSocket.receive

Syntax
public synchronized void receive( DatagramPacket p ) throws IOException
Parameters
p
the DatagramPacket into which to place the incoming data.
Description
Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.

This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the buffer length, the message is truncated.

Exceptions
IOException if an I/O error occurs.
See Also
DatagramPacket, DatagramSocket


 DatagramSocket.send

DatagramSocket.send

Syntax
public void send( DatagramPacket p ) throws IOException
Parameters
p
the DatagramPacket to be sent.
Description
Sends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host.

Exceptions
IOException if an I/O error occurs.
See Also
DatagramPacket


 DatagramSocket.setSoTimeout

DatagramSocket.setSoTimeout

Syntax
public synchronized void setSoTimeout( int timeout ) throws SocketException
Description
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.io.InterruptedIOException is raised, though the ServerSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.


 Class DatagramSocketImpl

Class java.net.DatagramSocketImpl

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.DatagramSocketImpl

public abstract class DatagramSocketImpl
extends Object
implements SocketOptions

Abstract datagram and multicast socket implementation base class.


 DatagramSocketImpl Members

DatagramSocketImpl Members

Class Overview | This Package | All Packages

Fields
Name | Description
fd | The file descriptor object
localPort |

Constructors
Name | Description
DatagramSocketImpl() |

Methods
Name | Description
bind(int, InetAddress) | Binds a datagram socket to a local port and address.
close() | Close the socket.
create() | Creates a datagram socket
getFileDescriptor() | Get the datagram socket file descriptor
getLocalPort() | Get the local port.
getTTL() | Retrieve the TTL (time-to-live) option.
join(InetAddress) | Join the multicast group.
leave(InetAddress) | Leave the multicast group.
peek(InetAddress) | Peek at the packet to see who it is from.
receive(DatagramPacket) | Receive the datagram packet.
send(DatagramPacket) | Sends a datagram packet.
setTTL(byte) | Set the TTL (time-to-live) option.


 DatagramSocketImpl.fd

DatagramSocketImpl.fd

Syntax
protected FileDescriptor fd
Description
The file descriptor object


 DatagramSocketImpl.localPort

DatagramSocketImpl.localPort

Syntax
protected int localPort


 DatagramSocketImpl.DatagramSocketImpl

DatagramSocketImpl.DatagramSocketImpl

Syntax
public DatagramSocketImpl()


 DatagramSocketImpl.bind

DatagramSocketImpl.bind

Syntax
protected abstract void bind( int lport, InetAddress laddr ) throws SocketException
Description
Binds a datagram socket to a local port and address.


 DatagramSocketImpl.close

DatagramSocketImpl.close

Syntax
protected abstract void close()
Description
Close the socket.


 DatagramSocketImpl.create

DatagramSocketImpl.create

Syntax
protected abstract void create() throws SocketException
Description
Creates a datagram socket


 DatagramSocketImpl.getFileDescriptor

DatagramSocketImpl.getFileDescriptor

Syntax
protected FileDescriptor getFileDescriptor()
Description
Get the datagram socket file descriptor


 DatagramSocketImpl.getLocalPort

DatagramSocketImpl.getLocalPort

Syntax
protected int getLocalPort()
Description
Get the local port.


 DatagramSocketImpl.getTTL

DatagramSocketImpl.getTTL

Syntax
protected abstract byte getTTL() throws IOException
Description
Retrieve the TTL (time-to-live) option.


 DatagramSocketImpl.join

DatagramSocketImpl.join

Syntax
protected abstract void join( InetAddress inetaddr ) throws IOException
Parameters
multicast
address to join.
Description
Join the multicast group.


 DatagramSocketImpl.leave

DatagramSocketImpl.leave

Syntax
protected abstract void leave( InetAddress inetaddr ) throws IOException
Parameters
multicast
address to leave.
Description
Leave the multicast group.


 DatagramSocketImpl.peek

DatagramSocketImpl.peek

Syntax
protected abstract int peek( InetAddress i ) throws IOException
Parameters
return
the address which the packet came from.
Description
Peek at the packet to see who it is from.


 DatagramSocketImpl.receive

DatagramSocketImpl.receive

Syntax
protected abstract void receive( DatagramPacket p ) throws IOException
Parameters
Packet
Received.
Description
Receive the datagram packet.


 DatagramSocketImpl.send

DatagramSocketImpl.send

Syntax
protected abstract void send( DatagramPacket p ) throws IOException
Parameters
packet
to be sent.
Description
Sends a datagram packet. The packet contains the data and the destination address to send the packet to.


 DatagramSocketImpl.setTTL

DatagramSocketImpl.setTTL

Syntax
protected abstract void setTTL( byte ttl ) throws IOException
Parameters
TTL
to be set.
Description
Set the TTL (time-to-live) option.


 Interface FileNameMap

Interface java.net.FileNameMap

Interface Members | This Package | All Packages

public interface FileNameMap

A simple interface which provides a mechanism to map between between a file name and a MIME type string.


 FileNameMap Members

FileNameMap Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getContentTypeFor(String) |


 FileNameMap.getContentTypeFor

FileNameMap.getContentTypeFor

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getContentTypeFor( String fileName )


 Class HttpURLConnection

Class java.net.HttpURLConnection

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.URLConnection
           |
           +----java.net.HttpURLConnection

public abstract class HttpURLConnection
extends URLConnection

A URLConnection with support for HTTP-specific features. See the spec for details.


 HttpURLConnection Members

HttpURLConnection Members

Class Overview | This Package | All Packages

Fields
Name | Description
HTTP_ACCEPTED |
HTTP_BAD_GATEWAY |
HTTP_BAD_METHOD |
HTTP_BAD_REQUEST | 4XX: client error
HTTP_CLIENT_TIMEOUT |
HTTP_CONFLICT |
HTTP_CREATED |
HTTP_ENTITY_TOO_LARGE |
HTTP_FORBIDDEN |
HTTP_GATEWAY_TIMEOUT |
HTTP_GONE |
HTTP_INTERNAL_ERROR |
HTTP_LENGTH_REQUIRED |
HTTP_MOVED_PERM |
HTTP_MOVED_TEMP |
HTTP_MULT_CHOICE | 3XX: relocation/redirect
HTTP_NO_CONTENT |
HTTP_NOT_ACCEPTABLE |
HTTP_NOT_AUTHORITATIVE |
HTTP_NOT_FOUND |
HTTP_NOT_MODIFIED |
HTTP_OK | 2XX: generally "OK"
HTTP_PARTIAL |
HTTP_PAYMENT_REQUIRED |
HTTP_PRECON_FAILED |
HTTP_PROXY_AUTH |
HTTP_REQ_TOO_LONG |
HTTP_RESET |
HTTP_SEE_OTHER |
HTTP_SERVER_ERROR | 5XX: server error
HTTP_UNAUTHORIZED |
HTTP_UNAVAILABLE |
HTTP_UNSUPPORTED_TYPE |
HTTP_USE_PROXY |
HTTP_VERSION |
method |
responseCode |
responseMessage |

Constructors
Name | Description
HttpURLConnection(URL) | Constructor for the URLStreamHandler.

Methods
Name | Description
disconnect() | Close the connection to the server.
getFollowRedirects()
getRequestMethod() | Get the request method.
getResponseCode() | Gets HTTP response status.
getResponseMessage() | Gets the HTTP response message, if any, returned along with the response code from a server.
setFollowRedirects(boolean) | Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.
setRequestMethod(String) Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.
usingProxy() | Indicates if the connection is going through a proxy.


 HttpURLConnection.HTTP_ACCEPTED

HttpURLConnection.HTTP_ACCEPTED

Syntax
public static final int HTTP_ACCEPTED


 HttpURLConnection.HTTP_BAD_GATEWAY

HttpURLConnection.HTTP_BAD_GATEWAY

Syntax
public static final int HTTP_BAD_GATEWAY


 HttpURLConnection.HTTP_BAD_METHOD

HttpURLConnection.HTTP_BAD_METHOD

Syntax
public static final int HTTP_BAD_METHOD


 HttpURLConnection.HTTP_BAD_REQUEST

HttpURLConnection.HTTP_BAD_REQUEST

Syntax
public static final int HTTP_BAD_REQUEST
Description
4XX: client error


 HttpURLConnection.HTTP_CLIENT_TIMEOUT

HttpURLConnection.HTTP_CLIENT_TIMEOUT

Syntax
public static final int HTTP_CLIENT_TIMEOUT


 HttpURLConnection.HTTP_CONFLICT

HttpURLConnection.HTTP_CONFLICT

Syntax
public static final int HTTP_CONFLICT


 HttpURLConnection.HTTP_CREATED

HttpURLConnection.HTTP_CREATED

Syntax
public static final int HTTP_CREATED


 HttpURLConnection.HTTP_ENTITY_TOO_LARGE

HttpURLConnection.HTTP_ENTITY_TOO_LARGE

Syntax
public static final int HTTP_ENTITY_TOO_LARGE


 HttpURLConnection.HTTP_FORBIDDEN

HttpURLConnection.HTTP_FORBIDDEN

Syntax
public static final int HTTP_FORBIDDEN


 HttpURLConnection.HTTP_GATEWAY_TIMEOUT

HttpURLConnection.HTTP_GATEWAY_TIMEOUT

Syntax
public static final int HTTP_GATEWAY_TIMEOUT


 HttpURLConnection.HTTP_GONE

HttpURLConnection.HTTP_GONE

Syntax
public static final int HTTP_GONE


 HttpURLConnection.HTTP_INTERNAL_ERROR

HttpURLConnection.HTTP_INTERNAL_ERROR

Syntax
public static final int HTTP_INTERNAL_ERROR


 HttpURLConnection.HTTP_LENGTH_REQUIRED

HttpURLConnection.HTTP_LENGTH_REQUIRED

Syntax
public static final int HTTP_LENGTH_REQUIRED


 HttpURLConnection.HTTP_MOVED_PERM

HttpURLConnection.HTTP_MOVED_PERM

Syntax
public static final int HTTP_MOVED_PERM


 HttpURLConnection.HTTP_MOVED_TEMP

HttpURLConnection.HTTP_MOVED_TEMP

Syntax
public static final int HTTP_MOVED_TEMP


 HttpURLConnection.HTTP_MULT_CHOICE

HttpURLConnection.HTTP_MULT_CHOICE

Syntax
public static final int HTTP_MULT_CHOICE
Description
3XX: relocation/redirect


 HttpURLConnection.HTTP_NO_CONTENT

HttpURLConnection.HTTP_NO_CONTENT

Syntax
public static final int HTTP_NO_CONTENT


 HttpURLConnection.HTTP_NOT_ACCEPTABLE

HttpURLConnection.HTTP_NOT_ACCEPTABLE

Syntax
public static final int HTTP_NOT_ACCEPTABLE


 HttpURLConnection.HTTP_NOT_AUTHORITATIVE

HttpURLConnection.HTTP_NOT_AUTHORITATIVE

Syntax
public static final int HTTP_NOT_AUTHORITATIVE


 HttpURLConnection.HTTP_NOT_FOUND

HttpURLConnection.HTTP_NOT_FOUND

Syntax
public static final int HTTP_NOT_FOUND


 HttpURLConnection.HTTP_NOT_MODIFIED

HttpURLConnection.HTTP_NOT_MODIFIED

Syntax
public static final int HTTP_NOT_MODIFIED


 HttpURLConnection.HTTP_OK

HttpURLConnection.HTTP_OK

Syntax
public static final int HTTP_OK
Description
2XX: generally "OK"


 HttpURLConnection.HTTP_PARTIAL

HttpURLConnection.HTTP_PARTIAL

Syntax
public static final int HTTP_PARTIAL


 HttpURLConnection.HTTP_PAYMENT_REQUIRED

HttpURLConnection.HTTP_PAYMENT_REQUIRED

Syntax
public static final int HTTP_PAYMENT_REQUIRED


 HttpURLConnection.HTTP_PRECON_FAILED

HttpURLConnection.HTTP_PRECON_FAILED

Syntax
public static final int HTTP_PRECON_FAILED


 HttpURLConnection.HTTP_PROXY_AUTH

HttpURLConnection.HTTP_PROXY_AUTH

Syntax
public static final int HTTP_PROXY_AUTH


 HttpURLConnection.HTTP_REQ_TOO_LONG

HttpURLConnection.HTTP_REQ_TOO_LONG

Syntax
public static final int HTTP_REQ_TOO_LONG


 HttpURLConnection.HTTP_RESET

HttpURLConnection.HTTP_RESET

Syntax
public static final int HTTP_RESET


 HttpURLConnection.HTTP_SEE_OTHER

HttpURLConnection.HTTP_SEE_OTHER

Syntax
public static final int HTTP_SEE_OTHER


 HttpURLConnection.HTTP_SERVER_ERROR

HttpURLConnection.HTTP_SERVER_ERROR

Syntax
public static final int HTTP_SERVER_ERROR
Description
5XX: server error


 HttpURLConnection.HTTP_UNAUTHORIZED

HttpURLConnection.HTTP_UNAUTHORIZED

Syntax
public static final int HTTP_UNAUTHORIZED


 HttpURLConnection.HTTP_UNAVAILABLE

HttpURLConnection.HTTP_UNAVAILABLE

Syntax
public static final int HTTP_UNAVAILABLE


 HttpURLConnection.HTTP_UNSUPPORTED_TYPE

HttpURLConnection.HTTP_UNSUPPORTED_TYPE

Syntax
public static final int HTTP_UNSUPPORTED_TYPE


 HttpURLConnection.HTTP_USE_PROXY

HttpURLConnection.HTTP_USE_PROXY

Syntax
public static final int HTTP_USE_PROXY


 HttpURLConnection.HTTP_VERSION

HttpURLConnection.HTTP_VERSION

Syntax
public static final int HTTP_VERSION


 HttpURLConnection.method

HttpURLConnection.method

Syntax
protected String method


 HttpURLConnection.responseCode

HttpURLConnection.responseCode

Syntax
protected int responseCode


 HttpURLConnection.responseMessage

HttpURLConnection.responseMessage

Syntax
protected String responseMessage


 HttpURLConnection.HttpURLConnection

HttpURLConnection.HttpURLConnection

Syntax
protected HttpURLConnection( URL u )
Description
Constructor for the URLStreamHandler.


 HttpURLConnection.disconnect

HttpURLConnection.disconnect

Syntax
public abstract void disconnect()
Description
Close the connection to the server.


 HttpURLConnection.getFollowRedirects

HttpURLConnection.getFollowRedirects

Syntax
public static boolean getFollowRedirects()


 HttpURLConnection.getRequestMethod

HttpURLConnection.getRequestMethod

Syntax
public String getRequestMethod()
Description
Get the request method.


 HttpURLConnection.getResponseCode

HttpURLConnection.getResponseCode

Syntax
public int getResponseCode() throws IOException
Description
Gets HTTP response status. From responses like:
 HTTP/1.0 200 OK
 HTTP/1.0 401 Unauthorized
Extracts the ints 200 and 401 respectively. Returns -1 if none can be discerned from the response (i.e., the response is not valid HTTP).


 HttpURLConnection.getResponseMessage

HttpURLConnection.getResponseMessage

Syntax
public String getResponseMessage() throws IOException
Description
Gets the HTTP response message, if any, returned along with the response code from a server. From responses like:
 HTTP/1.0 200 OK
 HTTP/1.0 404 Not Found
Extracts the Strings "OK" and "Not Found" respectively. Returns null if none could be discerned from the responses (the result was not valid HTTP).


 HttpURLConnection.setFollowRedirects

HttpURLConnection.setFollowRedirects

Syntax
public static void setFollowRedirects( boolean set )
Description
Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class. False by default. Applets cannot change this variable.


 HttpURLConnection.setRequestMethod

HttpURLConnection.setRequestMethod

Syntax
public void setRequestMethod( String method ) throws ProtocolException
Description
Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions. The default method is GET.

Exceptions
ProtocolException if the method cannot be reset or if the requested method isn't valid for HTTP.


 HttpURLConnection.usingProxy

HttpURLConnection.usingProxy

Syntax
public abstract boolean usingProxy()
Description
Indicates if the connection is going through a proxy.


 Class InetAddress

Class java.net.InetAddress

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.InetAddress

public final class InetAddress
extends Object
implements Serializable

This class represents an Internet Protocol (IP) address.

Applications should use the methods getLocalHost, getByName, or getAllByName to create a new InetAddress instance.

See Also:
getAllByName, getByName, getLocalHost


 InetAddress Members

InetAddress Members

Class Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Compares this object against the specified object.
getAddress() | Returns the raw IP address of this InetAddress object.
getAllByName(String) | Determines all the IP addresses of a host, given the host's name.
getByName(String) | Determines the IP address of a host, given the host's name.
getHostAddress() | Returns the IP address string "%d.%d.%d.%d"
getHostName() | Returns the hostname for this address.
getLocalHost() | Returns the local host.
hashCode() | Returns a hashcode for this IP address.
isMulticastAddress() | Utility routine to check if the InetAddress is a IP multicast address.
toString() | Converts this IP address to a String.


 InetAddress.equals

InetAddress.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare against.
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object. The result is true if and only if the argument is not null and it represents the same IP address as this object.

Two instances of InetAddress represent the same IP address if the length of the byte arrays returned by getAddress is the same for both, and each of the array components is the same for the byte arrays.

Overrides
equals in class Object
See Also
getAddress


 InetAddress.getAddress

InetAddress.getAddress

Syntax
public byte[] getAddress()
Returns
the raw IP address of this object.
Description
Returns the raw IP address of this InetAddress object. The result is in network byte order: the highest order byte of the address is in getAddress()[0].


 InetAddress.getAllByName

InetAddress.getAllByName

Syntax
public static InetAddress[] getAllByName( String host ) throws UnknownHostException
Parameters
host
the name of the host.
Returns
an array of all the IP addresses for a given host name.
Description
Determines all the IP addresses of a host, given the host's name. The host name can either be a machine name, such as "java.sun.com", or a string representing its IP address, such as "206.26.48.100".

Exceptions
UnknownHostException if no IP address for the host could be found.


 InetAddress.getByName

InetAddress.getByName

Syntax
public static InetAddress getByName( String host ) throws UnknownHostException
Parameters
host
the specified host, or null for the local host.
Returns
an IP address for the given host name.
Description
Determines the IP address of a host, given the host's name. The host name can either be a machine name, such as "java.sun.com", or a string representing its IP address, such as "206.26.48.100".

Exceptions
UnknownHostException if no IP address for the host could be found.


 InetAddress.getHostAddress

InetAddress.getHostAddress

Syntax
public String getHostAddress()
Returns
raw IP address in a string format
Description
Returns the IP address string "%d.%d.%d.%d"


 InetAddress.getHostName

InetAddress.getHostName

Syntax
public String getHostName()
Returns
the host name for this IP address.
Description
Returns the hostname for this address. If the host is equal to null, then this address refers to any of the local machine's available network addresses.


 InetAddress.getLocalHost

InetAddress.getLocalHost

Syntax
public static InetAddress getLocalHost() throws UnknownHostException
Returns
the IP address of the local host.
Description
Returns the local host.

Exceptions
UnknownHostException if no IP address for the host could be found.


 InetAddress.hashCode

InetAddress.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this IP address.
Description
Returns a hashcode for this IP address.

Overrides
hashCode in class Object


 InetAddress.isMulticastAddress

InetAddress.isMulticastAddress

Syntax
public boolean isMulticastAddress()
Description
Utility routine to check if the InetAddress is a IP multicast address. IP multicast address is a Class D address i.e first four bits of the address are 1110.


 InetAddress.toString

InetAddress.toString

Syntax
public String toString()
Returns
a string representation of this IP address.
Description
Converts this IP address to a String.

Overrides
toString in class Object


 Class MalformedURLException

Class java.net.MalformedURLException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.MalformedURLException

public class MalformedURLException
extends IOException

Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.


 MalformedURLException Members

MalformedURLException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MalformedURLException() | Constructs a MalformedURLException with no detail message.
MalformedURLException(String) | Constructs a MalformedURLException with the specified detail message.


 MalformedURLException.MalformedURLException

MalformedURLException.MalformedURLException

Syntax 1
public MalformedURLException()
Description
Constructs a MalformedURLException with no detail message.

Syntax 2
public MalformedURLException( String msg )
Parameters
msg
the detail message.
Description
Constructs a MalformedURLException with the specified detail message.


 Class MulticastSocket

Class java.net.MulticastSocket

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.DatagramSocket
           |
           +----java.net.MulticastSocket

public class MulticastSocket
extends DatagramSocket

The multicast datagram socket class is useful for sending and receiving IP multicast packets. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining "groups" of other multicast hosts on the internet.

A multicast group is specified by a class D IP address, those in the range 224.0.0.1 to 239.255.255.255, inclusive, and by a standard UDP port number. One would join a multicast group by first creating a MulticastSocket with the desired port, then invoking the joinGroup(InetAddress groupAddr) method:

 // join a Multicast group and send the group salutations
 ...
 byte[] msg = {'H', 'e', 'l', 'l', 'o'};
 InetAddress group = InetAddress.getByName("228.5.6.7");
 MulticastSocket s = new MulticastSocket(6789);
 s.joinGroup(group);
 DatagramPacket hi = new DatagramPacket(msg, msg.length,
                             group, 6789);
 s.send(hi);
 // get their responses!
 byte[] buf = new byte[1000];
 DatagramPacket recv = new DatagramPacket(buf, buf.length);
 s.receive(recv);
 ...
 // OK, I'm done talking - leave the group...
 s.leaveGroup(group);
When one sends a message to a multicast group, all subscribing recipients to that host and port receive the message (within the time-to-live range of the packet, see below). The socket needn't be a member of the multicast group to send messages to it.

When a socket subscribes to a multicast group/port, it receives datagrams sent by other hosts to the group/port, as do all other members of the group and port. A socket relinquishes membership in a group by the leaveGroup(InetAddress addr) method. Multiple MulticastSocket's may subscribe to a multicast group and port concurrently, and they will all receive group datagrams.

Currently applets are not allowed ot use multicast sockets.


 MulticastSocket Members

MulticastSocket Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MulticastSocket() | Create a multicast socket.
MulticastSocket(int) | Create a multicast socket and bind it to a specific port.

Methods
Name | Description
getInterface() | Retrieve the address of the network interface used for multicast packets.
getTTL() | Get the default time-to-live for multicast packets sent out on the socket.
joinGroup(InetAddress) | Joins a multicast group.
leaveGroup(InetAddress) | Leave a multicast group.
send(DatagramPacket, byte) | Sends a datagram packet to the destination, with a TTL (time- to-live) other than the default for the socket.
setInterface(InetAddress) | Set the outgoing network interface for multicast packets on this socket, to other than the system default.
setTTL(byte) | Set the default time-to-live for multicast packets sent out on this socket.


 MulticastSocket.MulticastSocket

MulticastSocket.MulticastSocket

Syntax 1
public MulticastSocket() throws IOException
Description
Create a multicast socket.

Syntax 2
public MulticastSocket( int port ) throws IOException
Parameters
local
port to use
Description
Create a multicast socket and bind it to a specific port.


 MulticastSocket.getInterface

MulticastSocket.getInterface

Syntax
public InetAddress getInterface() throws SocketException
Description
Retrieve the address of the network interface used for multicast packets.


 MulticastSocket.getTTL

MulticastSocket.getTTL

Syntax
public byte getTTL() throws IOException
Description
Get the default time-to-live for multicast packets sent out on the socket.


 MulticastSocket.joinGroup

MulticastSocket.joinGroup

Syntax
public void joinGroup( InetAddress mcastaddr ) throws IOException
Parameters
mcastaddr
is the multicast address to join
Description
Joins a multicast group.

Exceptions
IOException is raised if there is an error joining or when address is not a multicast address.


 MulticastSocket.leaveGroup

MulticastSocket.leaveGroup

Syntax
public void leaveGroup( InetAddress mcastaddr ) throws IOException
Parameters
mcastaddr
is the multicast address to leave
Description
Leave a multicast group.

Exceptions
IOException is raised if there is an error leaving or when address is not a multicast address.


 MulticastSocket.send

MulticastSocket.send

Syntax
public synchronized void send( DatagramPacket p, byte ttl ) throws IOException
Parameters
p
is the packet to be sent. The packet should contain the destination multicast ip address and the data to be sent. One does not need to be the member of the group to send packets to a destination multicast address.
ttl
optional time to live for multicast packet. default ttl is 1.
Description
Sends a datagram packet to the destination, with a TTL (time- to-live) other than the default for the socket. This method need only be used in instances where a particular TTL is desired; otherwise it is preferable to set a TTL once on the socket, and use that default TTL for all packets. This method does not alter the default TTL for the socket.

Exceptions
IOException is raised if an error occurs i.e error while setting ttl.
See Also
send, receive


 MulticastSocket.setInterface

MulticastSocket.setInterface

Syntax
public void setInterface( InetAddress inf ) throws SocketException
Description
Set the outgoing network interface for multicast packets on this socket, to other than the system default. Useful for multihomed hosts.


 MulticastSocket.setTTL

MulticastSocket.setTTL

Syntax
public void setTTL( byte ttl ) throws IOException
Parameters
ttl
the time-to-live
Description
Set the default time-to-live for multicast packets sent out on this socket. The TTL sets the IP time-to-live for DatagramPackets sent to a MulticastGroup, which specifies how many "hops" that the packet will be forwarded on the network before it expires.

The ttl is an unsigned 8-bit quantity, and so must be in the range 0 < ttl <= 0xFF .


 Class NoRouteToHostException

Class java.net.NoRouteToHostException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.SocketException
                                   |
                                   +----java.net.NoRouteToHostException

public class NoRouteToHostException
extends SocketException

Signals that an error occurred while attempting to connect a socket to a remote address and port. Typically, the remote host cannot be reached because of an intervening firewall, or if an intermediate router is down.


 NoRouteToHostException Members

NoRouteToHostException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoRouteToHostException() | Construct a new NoRouteToHostException with no detailed message.
NoRouteToHostException(String) | Constructs a new NoRouteToHostException with the specified detail message as to why the remote host cannot be reached.


 NoRouteToHostException.NoRouteToHostException

NoRouteToHostException.NoRouteToHostException

Syntax 1
public NoRouteToHostException( String msg )
Parameters
msg
the detail message
Description
Constructs a new NoRouteToHostException with the specified detail message as to why the remote host cannot be reached. A detail message is a String that gives a specific description of this error.

Syntax 2
public NoRouteToHostException()
Description
Construct a new NoRouteToHostException with no detailed message.


 Class ProtocolException

Class java.net.ProtocolException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.ProtocolException

public class ProtocolException
extends IOException

Thrown to indicate that there is an error in the underlying protocol, such as a TCP error.


 ProtocolException Members

ProtocolException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ProtocolException() | Constructs a new ProtocolException with no detail message.
ProtocolException(String) | Constructs a new ProtocolException with the specified detail message.


 ProtocolException.ProtocolException

ProtocolException.ProtocolException

Syntax 1
public ProtocolException( String host )
Parameters
host
the detail message.
Description
Constructs a new ProtocolException with the specified detail message.

Syntax 2
public ProtocolException()
Description
Constructs a new ProtocolException with no detail message.


 Class ServerSocket

Class java.net.ServerSocket

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.ServerSocket

public class ServerSocket
extends Object

This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

The actual work of the server socket is performed by an instance of the SocketImpl class. An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall.

See Also:
SocketImpl, setSocketFactory


 ServerSocket Members

ServerSocket Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ServerSocket(int) | Creates a server socket on a specified port.
ServerSocket(int, int) | Creates a server socket and binds it to the specified local port number.
ServerSocket(int, int, InetAddress) | Create a server with the specified port, listen backlog, and local IP address to bind to.

Methods
Name | Description
accept() | Listens for a connection to be made to this socket and accepts it.
close() | Closes this socket.
getInetAddress() | Returns the local address of this server socket.
getLocalPort() | Returns the port on which this socket is listening.
getSoTimeout() | Retrive setting for SO_TIMEOUT.
implAccept(Socket) | Subclasses of ServerSocket use this method to override accept() to return their own subclass of socket.
setSocketFactory(SocketImplFactory) | Sets the server socket implementation factory for the application.
setSoTimeout(int) | Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
toString() | Returns the implementation address and implementation port of this socket as a String.


 ServerSocket.ServerSocket

ServerSocket.ServerSocket

Syntax 1
public ServerSocket( int port ) throws IOException
Parameters
port
the port number, or 0 to use any free port.
Description
Creates a server socket on a specified port. A port of 0 creates a socket on any free port.

The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when opening the socket.
See Also
SocketImpl, createSocketImpl, setSocketFactory

Syntax 2
public ServerSocket( int port, int backlog ) throws IOException
Parameters
port
the specified port, or 0 to use any free port.
backlog
the maximum length of the queue.
Description
Creates a server socket and binds it to the specified local port number. A port number of 0 creates a socket on any free port.

The maximum queue length for incoming connection indications (a request to connect) is set to the count parameter. If a connection indication arrives when the queue is full, the connection is refused.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when opening the socket.
See Also
SocketImpl, createSocketImpl, setSocketFactory

Syntax 3
public ServerSocket( int port, int backlog, InetAddress bindAddr ) throws IOException
Parameters
port
the local TCP port
backlog
the listen backlog
bindAddr
the local InetAddress the server will bind to
Description
Create a server with the specified port, listen backlog, and local IP address to bind to. The bindAddr argument can be used on a multi-homed host for a ServerSocket that will only accept connect requests to one of its addresses. If bindAddr is null, it will default accepting connections on any/all local addresses. The port must be between 0 and 65535, inclusive.

See Also
SocketConstants, SocketOption, SocketImpl, 1


 ServerSocket.accept

ServerSocket.accept

Syntax
public Socket accept() throws IOException
Description
Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

Exceptions
IOException if an I/O error occurs when waiting for a connection.


 ServerSocket.close

ServerSocket.close

Syntax
public void close() throws IOException
Description
Closes this socket.

Exceptions
IOException if an I/O error occurs when closing the socket.


 ServerSocket.getInetAddress

ServerSocket.getInetAddress

Syntax
public InetAddress getInetAddress()
Returns
the address to which this socket is connected, or null if the socket is not yet connected.
Description
Returns the local address of this server socket.


 ServerSocket.getLocalPort

ServerSocket.getLocalPort

Syntax
public int getLocalPort()
Returns
the port number to which this socket is listening.
Description
Returns the port on which this socket is listening.


 ServerSocket.getSoTimeout

ServerSocket.getSoTimeout

Syntax
public synchronized int getSoTimeout() throws IOException
Description
Retrive setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).


 ServerSocket.implAccept

ServerSocket.implAccept

Syntax
protected final void implAccept( Socket s ) throws IOException
Description
Subclasses of ServerSocket use this method to override accept() to return their own subclass of socket. So a FooServerSocket will typically hand this method an empty FooSocket(). On return from implAccept the FooSocket will be connected to a client.


 ServerSocket.setSocketFactory

ServerSocket.setSocketFactory

Syntax
public static synchronized void setSocketFactory( SocketImplFactory fac ) throws IOException
Parameters
fac
the desired factory.
Description
Sets the server socket implementation factory for the application. The factory can be specified only once.

When an application creates a new server socket, the socket implementation factory's createSocketImpl method is called to create the actual socket implementation.

Exceptions
IOException if an I/O error occurs when setting the socket factory.
Exceptions
SocketException if the factory has already been defined.
See Also
createSocketImpl


 ServerSocket.setSoTimeout

ServerSocket.setSoTimeout

Syntax
public synchronized void setSoTimeout( int timeout ) throws SocketException
Description
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a call to accept() for this ServerSocket will block for only this amount of time. If the timeout expires, a java.io.InterruptedIOException is raised, though the ServerSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.


 ServerSocket.toString

ServerSocket.toString

Syntax
public String toString()
Returns
a string representation of this socket.
Description
Returns the implementation address and implementation port of this socket as a String.

Overrides
toString in class Object


 Class Socket

Class java.net.Socket

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.Socket

public class Socket
extends Object

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

See Also:
setSocketImplFactory, SocketImpl


 Socket Members

Socket Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Socket() | Creates an unconnected socket, with the system-default type of SocketImpl.
Socket(InetAddress, int) | Creates a stream socket and connects it to the specified port number at the specified IP address.
Socket(InetAddress, int, boolean) | Creates a socket and connects it to the specified port number at the specified IP address. Deprecated.
Socket(InetAddress, int, InetAddress, int) | Creates a socket and connects it to the specified remote address on the specified remote port.
Socket(SocketImpl) | Creates an unconnected Socket with a user-specified SocketImpl.
Socket(String, int) | Creates a stream socket and connects it to the specified port number on the named host.
Socket(String, int, boolean) | Creates a stream socket and connects it to the specified port number on the named host. Deprecated.
Socket(String, int, InetAddress, int) | Creates a socket and connects it to the specified remote host on the specified remote port.

Methods
Name | Description
close() | Closes this socket.
getInetAddress() | Returns the address to which the socket is connected.
getInputStream() | Returns an input stream for this socket.
getLocalAddress() | Gets the local address to which the socket is bound.
getLocalPort() | Returns the local port to which this socket is bound.
getOutputStream() | Returns an output stream for this socket.
getPort() | Returns the remote port to which this socket is connected.
getSoLinger() | Returns setting for SO_LINGER.
getSoTimeout() | Returns setting for SO_TIMEOUT.
getTcpNoDelay() | Tests if TCP_NODELAY is enabled.
setSocketImplFactory(SocketImplFactory) | Sets the client socket implementation factory for the application.
setSoLinger(boolean, int) | Enable/disable SO_LINGER with the specified linger time.
setSoTimeout(int) | Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
setTcpNoDelay(boolean) | Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
toString() | Converts this socket to a String.


 Socket.Socket

Socket.Socket

Syntax 1
protected Socket()
Description
Creates an unconnected socket, with the system-default type of SocketImpl.

Syntax 2
protected Socket( SocketImpl impl ) throws SocketException
Description
Creates an unconnected Socket with a user-specified SocketImpl.

The impl parameter is an instance of a SocketImpl the subclass wishes to use on the Socket.

Syntax 3
public Socket( String host, int port ) throws UnknownHostException, IOException
Parameters
host
the host name.
port
the port number.
Description
Creates a stream socket and connects it to the specified port number on the named host.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when creating the socket.
See Also
setSocketImplFactory, SocketImpl, createSocketImpl

Syntax 4
public Socket( InetAddress address, int port ) throws IOException
Parameters
address
the IP address.
port
the port number.
Description
Creates a stream socket and connects it to the specified port number at the specified IP address.

If the application has specified a socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when creating the socket.
See Also
setSocketImplFactory, SocketImpl, createSocketImpl

Syntax 5
public Socket( String host, int port, InetAddress localAddr, int localPort ) throws IOException
Parameters
host
the name of the remote host
port
the remote port
localAddr
the local address the socket is bound to
localPort
the local port the socket is bound to
Description
Creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

Syntax 6
public Socket( InetAddress address, int port, InetAddress localAddr, int localPort ) throws IOException
Parameters
address
the remote address
port
the remote port
localAddr
the local address the socket is bound to
localPort
the local port the socket is bound to
Description
Creates a socket and connects it to the specified remote address on the specified remote port. The Socket will also bind() to the local address and port supplied.

Syntax 7
public Socket( String host, int port, boolean stream ) throws IOException
Parameters
host
the host name.
port
the port number.
stream
a boolean indicating whether this is a stream socket or a datagram socket.
Description
Note: Socket() is deprecated. Use DatagramSocket instead for UDP transport.

Creates a stream socket and connects it to the specified port number on the named host.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when creating the socket.
See Also
setSocketImplFactory, SocketImpl, createSocketImpl

Syntax 8
public Socket( InetAddress host, int port, boolean stream ) throws IOException
Parameters
address
the IP address.
port
the port number.
stream
if true, create a stream socket; otherwise, create a datagram socket.
Description
Note: Socket() is deprecated. Use DatagramSocket instead for UDP transport.

Creates a socket and connects it to the specified port number at the specified IP address.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

Exceptions
IOException if an I/O error occurs when creating the socket.
See Also
setSocketImplFactory, SocketImpl, createSocketImpl


 Socket.close

Socket.close

Syntax
public synchronized void close() throws IOException
Description
Closes this socket.

Exceptions
IOException if an I/O error occurs when closing this socket.


 Socket.getInetAddress

Socket.getInetAddress

Syntax
public InetAddress getInetAddress()
Returns
the remote IP address to which this socket is connected.
Description
Returns the address to which the socket is connected.


 Socket.getInputStream

Socket.getInputStream

Syntax
public InputStream getInputStream() throws IOException
Returns
an input stream for reading bytes from this socket.
Description
Returns an input stream for this socket.

Exceptions
IOException if an I/O error occurs when creating the input stream.


 Socket.getLocalAddress

Socket.getLocalAddress

Syntax
public InetAddress getLocalAddress()
Description
Gets the local address to which the socket is bound.


 Socket.getLocalPort

Socket.getLocalPort

Syntax
public int getLocalPort()
Returns
the local port number to which this socket is connected.
Description
Returns the local port to which this socket is bound.


 Socket.getOutputStream

Socket.getOutputStream

Syntax
public OutputStream getOutputStream() throws IOException
Returns
an output stream for writing bytes to this socket.
Description
Returns an output stream for this socket.

Exceptions
IOException if an I/O error occurs when creating the output stream.


 Socket.getPort

Socket.getPort

Syntax
public int getPort()
Returns
the remote port number to which this socket is connected.
Description
Returns the remote port to which this socket is connected.


 Socket.getSoLinger

Socket.getSoLinger

Syntax
public int getSoLinger() throws SocketException
Description
Returns setting for SO_LINGER. -1 returns implies that the option is disabled.


 Socket.getSoTimeout

Socket.getSoTimeout

Syntax
public synchronized int getSoTimeout() throws SocketException
Description
Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).


 Socket.getTcpNoDelay

Socket.getTcpNoDelay

Syntax
public boolean getTcpNoDelay() throws SocketException
Description
Tests if TCP_NODELAY is enabled.


 Socket.setSocketImplFactory

Socket.setSocketImplFactory

Syntax
public static synchronized void setSocketImplFactory( SocketImplFactory fac ) throws IOException
Parameters
fac
the desired factory.
Description
Sets the client socket implementation factory for the application. The factory can be specified only once.

When an application creates a new client socket, the socket implementation factory's createSocketImpl method is called to create the actual socket implementation.

Exceptions
IOException if an I/O error occurs when setting the socket factory.
Exceptions
SocketException if the factory is already defined.
See Also
createSocketImpl


 Socket.setSoLinger

Socket.setSoLinger

Syntax
public void setSoLinger( boolean on, int val ) throws SocketException
Description
Enable/disable SO_LINGER with the specified linger time.


 Socket.setSoTimeout

Socket.setSoTimeout

Syntax
public synchronized void setSoTimeout( int timeout ) throws SocketException
Description
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.io.InterruptedIOException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.


 Socket.setTcpNoDelay

Socket.setTcpNoDelay

Syntax
public void setTcpNoDelay( boolean on ) throws SocketException
Description
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).


 Socket.toString

Socket.toString

Syntax
public String toString()
Returns
a string representation of this socket.
Description
Converts this socket to a String.

Overrides
toString in class Object


 Class SocketException

Class java.net.SocketException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.SocketException

public class SocketException
extends IOException

Thrown to indicate that there is an error in the underlying protocol, such as a TCP error.


 SocketException Members

SocketException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SocketException() | Constructs a new ProtocolException with no detail message.
SocketException(String) | Constructs a new ProtocolException with the specified detail message.


 SocketException.SocketException

SocketException.SocketException

Syntax 1
public SocketException( String msg )
Parameters
host
the detail message.
Description
Constructs a new ProtocolException with the specified detail message.

Syntax 2
public SocketException()
Description
Constructs a new ProtocolException with no detail message.


 Class SocketImpl

Class java.net.SocketImpl

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.SocketImpl

public abstract class SocketImpl
extends Object
implements SocketOptions

The abstract class SocketImpl is a common superclass of all classes that actually implement sockets. It is used to create both client and server sockets.

A "plain" socket implements these methods exactly as described, without attempting to go through a firewall or proxy.


 SocketImpl Members

SocketImpl Members

Class Overview | This Package | All Packages

Fields
Name | Description
address | The IP address of the remote end of this socket.
fd | The file descriptor object for this socket.
localport | The local port number to which this socket is connected.
port | The port number on the remote host to which this socket is connected.

Constructors
Name | Description
SocketImpl() |

Methods
Name | Description
accept(SocketImpl) | Accepts a connection.
available() | Returns the number of bytes that can be read from this socket without blocking.
bind(InetAddress, int) | Binds this socket to the specified port number on the specified host.
close() | Closes this socket.
connect(InetAddress, int) | Connects this socket to the specified port number on the specified host.
connect(String, int) | Connects this socket to the specified port on the named host.
create(boolean) | Creates either a stream or a datagram socket.
getFileDescriptor() | Returns the value of this socket's fd field.
getInetAddress() | Returns the value of this socket's address field.
getInputStream() | Returns an input stream for this socket.
getLocalPort() | Returns the value of this socket's localport field.
getOutputStream() | Returns an output stream for this socket.
getPort() | Returns the value of this socket's port field.
listen(int) | Sets the maximum queue length for incoming connection indications (a request to connect) to the count argument.
toString() | Returns the address and port of this socket as a String.


 SocketImpl.address

SocketImpl.address

Syntax
protected InetAddress address
Description
The IP address of the remote end of this socket.


 SocketImpl.fd

SocketImpl.fd

Syntax
protected FileDescriptor fd
Description
The file descriptor object for this socket.


 SocketImpl.localport

SocketImpl.localport

Syntax
protected int localport
Description
The local port number to which this socket is connected.


 SocketImpl.port

SocketImpl.port

Syntax
protected int port
Description
The port number on the remote host to which this socket is connected.


 SocketImpl.SocketImpl

SocketImpl.SocketImpl

Syntax
public SocketImpl()


 SocketImpl.accept

SocketImpl.accept

Syntax
protected abstract void accept( SocketImpl s ) throws IOException
Parameters
s
the accepted connection.
Description
Accepts a connection.

Exceptions
IOException if an I/O error occurs when accepting the connection.


 SocketImpl.available

SocketImpl.available

Syntax
protected abstract int available() throws IOException
Returns
the number of bytes that can be read from this socket without blocking.
Description
Returns the number of bytes that can be read from this socket without blocking.

Exceptions
IOException if an I/O error occurs when determining the number of bytes available.


 SocketImpl.bind

SocketImpl.bind

Syntax
protected abstract void bind( InetAddress host, int port ) throws IOException
Parameters
host
the IP address of the remote host.
port
the port number.
Description
Binds this socket to the specified port number on the specified host.

Exceptions
IOException if an I/O error occurs when binding this socket.


 SocketImpl.close

SocketImpl.close

Syntax
protected abstract void close() throws IOException
Description
Closes this socket.

Exceptions
IOException if an I/O error occurs when closing this socket.


 SocketImpl.connect

SocketImpl.connect

Syntax 1
protected abstract void connect( String host, int port ) throws IOException
Parameters
host
the name of the remote host.
port
the port number.
Description
Connects this socket to the specified port on the named host.

Exceptions
IOException if an I/O error occurs when connecting to the remote host.

Syntax 2
protected abstract void connect( InetAddress address, int port ) throws IOException
Parameters
address
the IP address of the remote host.
port
the port number.
Description
Connects this socket to the specified port number on the specified host.

Exceptions
IOException if an I/O error occurs when attempting a connection.


 SocketImpl.create

SocketImpl.create

Syntax
protected abstract void create( boolean stream ) throws IOException
Parameters
stream
if true, create a stream socket; otherwise, create a datagram socket.
Description
Creates either a stream or a datagram socket.

Exceptions
IOException if an I/O error occurs while creating the socket.


 SocketImpl.getFileDescriptor

SocketImpl.getFileDescriptor

Syntax
protected FileDescriptor getFileDescriptor()
Returns
the value of this socket's fd field.
Description
Returns the value of this socket's fd field.

See Also
fd


 SocketImpl.getInetAddress

SocketImpl.getInetAddress

Syntax
protected InetAddress getInetAddress()
Returns
the value of this socket's address field.
Description
Returns the value of this socket's address field.

See Also
address


 SocketImpl.getInputStream

SocketImpl.getInputStream

Syntax
protected abstract InputStream getInputStream() throws IOException
Returns
a stream for reading from this socket.
Description
Returns an input stream for this socket.

Exceptions
IOException if an I/O error occurs when creating the input stream.


 SocketImpl.getLocalPort

SocketImpl.getLocalPort

Syntax
protected int getLocalPort()
Returns
the value of this socket's localport field.
Description
Returns the value of this socket's localport field.

See Also
localport


 SocketImpl.getOutputStream

SocketImpl.getOutputStream

Syntax
protected abstract OutputStream getOutputStream() throws IOException
Returns
an output stream for writing to this socket.
Description
Returns an output stream for this socket.

Exceptions
IOException if an I/O error occurs when creating the output stream.


 SocketImpl.getPort

SocketImpl.getPort

Syntax
protected int getPort()
Returns
the value of this socket's port field.
Description
Returns the value of this socket's port field.

See Also
port


 SocketImpl.listen

SocketImpl.listen

Syntax
protected abstract void listen( int backlog ) throws IOException
Parameters
backlog
the maximum length of the queue.
Description
Sets the maximum queue length for incoming connection indications (a request to connect) to the count argument. If a connection indication arrives when the queue is full, the connection is refused.

Exceptions
IOException if an I/O error occurs when creating the queue.


 SocketImpl.toString

SocketImpl.toString

Syntax
public String toString()
Returns
a string representation of this socket.
Description
Returns the address and port of this socket as a String.

Overrides
toString in class Object


 Interface SocketImplFactory

Interface java.net.SocketImplFactory

Interface Members | This Package | All Packages

public interface SocketImplFactory

This interface defines a factory for socket implementations. It is used by the classes Socket and ServerSocket to create actual socket implementations.

See Also:
Socket, ServerSocket


 SocketImplFactory Members

SocketImplFactory Members

Interface Overview | This Package | All Packages

Methods
Name | Description
createSocketImpl() | Creates a new SocketImpl instance.


 SocketImplFactory.createSocketImpl

SocketImplFactory.createSocketImpl

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract SocketImpl createSocketImpl()
Returns
a new instance of SocketImpl.
Description
Creates a new SocketImpl instance.

See Also
SocketImpl


 Class URL

Class java.net.URL

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.URL

public final class URL
extends Object
implements Serializable

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. More information on the types of URLs and their formats can be found at:

    http://www.ncsa.uiuc.edu/demoweb/url-primer.html

In general, a URL can be broken into several parts. The previous example of a URL indicates that the protocol to use is http (HyperText Transport Protocol) and that the information resides on a host machine named www.ncsa.uiuc.edu. The information on that host machine is named demoweb/url-primer.html. The exact meaning of this name on the host machine is both protocol dependent and host dependent. The information normally resides in a file, but it could be generated on the fly. This component of the URL is called the file component, even though the information is not necessarily in a file.

A URL can optionally specify a "port", which is the port number to which the TCP connection is made on the remote host machine. If the port is not specified, the default port for the protocol is used instead. For example, the default port for http is 80. An alternative port could be specified as:

    http://www.ncsa.uiuc.edu:8080/demoweb/url-primer.html

A URL may have appended to it an "anchor", also known as a "ref" or a "reference". The anchor is indicated by the sharp sign character "#" followed by more characters. For example,

    http://java.sun.com/index.html#chapter1

This anchor is not technically part of the URL. Rather, it indicates that after the specified resource is retrieved, the application is specifically interested in that part of the document that has the tag chapter1 attached to it. The meaning of a tag is resource specific.

An application can also specify a "relative URL", which contains only enough information to reach the resource relative to another URL. Relative URLs are frequently used within HTML pages. For example, if the contents of the URL:

    http://java.sun.com/index.html
contained within it the relative URL:
    FAQ.html
it would be a shorthand for:
    http://java.sun.com/FAQ.html

The relative URL need not specify all the components of a URL. If the protocol, host name, or port number is missing, the value is inherited from the fully specified URL. The file component must be specified. The optional anchor is not inherited.


 URL Members

URL Members

Class Overview | This Package | All Packages

Constructors
Name | Description
URL(String) | Creates a URL object from the String representation.
URL(String, String, int, String) | Creates a URL object from the specified protocol, host, port number, and file.
URL(String, String, String) | Creates an absolute URL from the specified protocol name, host name, and file name.
URL(URL, String) | Creates a URL by parsing the specification spec within a specified context.

Methods
Name | Description
equals(Object) | Compares two URLs.
getContent() | Returns the contents of this URL.
getFile() | Returns the file name of this URL.
getHost() | Returns the host name of this URL, if applicable.
getPort() | Returns the port number of this URL.
getProtocol() | Returns the protocol name this URL.
getRef() | Returns the anchor (also known as the "reference") of this URL.
hashCode() | Creates an integer suitable for hash table indexing.
openConnection() | Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
openStream() | Opens a connection to this URL and returns an InputStream for reading from that connection.
sameFile(URL) | Compares two URLs, excluding the "ref" fields.
set(String, String, int, String, String) | Sets the fields of the URL.
setURLStreamHandlerFactory(URLStreamHandlerFactory) | Sets an application's URLStreamHandlerFactory.
toExternalForm() | Constructs a string representation of this URL.
toString() | Constructs a string representation of this URL.


 URL.URL

URL.URL

Syntax 1
public URL( String protocol, String host, int port, String file ) throws MalformedURLException
Parameters
protocol
the name of the protocol.
host
the name of the host.
port
the port number.
file
the host file.
Description
Creates a URL object from the specified protocol, host, port number, and file. Specifying a port number of -1 indicates that the URL should use the default port for the protocol.

If this is the first URL object being created with the specified protocol, a stream protocol handler object, an instance of class URLStreamHandler, is created for that protocol:

  1. If the application has previously set up an instance of URLStreamHandlerFactory as the stream handler factory, then the createURLStreamHandler method of that instance is called with the protocol string as an argument to create the stream protocol handler.
  2. If no URLStreamHandlerFactory has yet been set up, or if the factory's createURLStreamHandler method returns null, then the constructor finds the value of the system property:
      java.handler.protol.pkgs
    If the value of that system property is not null, it is interpreted as a list of packages separated by a vertical slash character '|'. The constructor tries to load the class named:
      <package>.<protocol>.Handler
    where <package> is replaced by the name of the package and <protocol> is replaced by the name of the protocol. If this class does not exist, or if the class exists but it is not a subclass of URLStreamHandler, then the next package in the list is tried.
  3. If the previous step fails to find a protocol handler, then the constructor tries to load the class named:
      sun.net.www.protocol.<protocol>.Handler
    If this class does not exist, or if the class exists but it is not a subclass of URLStreamHandler, then a MalformedURLException is thrown.

Exceptions
MalformedURLException if an unknown protocol is specified.
See Also
getProperty, setURLStreamHandlerFactory, URLStreamHandler, createURLStreamHandler

Syntax 2
public URL( String protocol, String host, String file ) throws MalformedURLException
Parameters
protocol
the protocol to use.
host
the host to connect to.
file
the file on that host.
Description
Creates an absolute URL from the specified protocol name, host name, and file name. The default port for the specified protocol is used.

This method is equivalent to calling the four-argument constructor with the arguments being protocol, host, -1, and file.

Exceptions
MalformedURLException if an unknown protocol is specified.
See Also
URL

Syntax 3
public URL( String spec ) throws MalformedURLException
Parameters
spec
the String to parse as a URL.
Description
Creates a URL object from the String representation.

This constructor is equivalent to a call to the two-argument constructor with a null first argument.

Exceptions
MalformedURLException If the string specifies an unknown protocol.
See Also
URL

Syntax 4
public URL( URL context, String spec ) throws MalformedURLException
Parameters
context
the context in which to parse the specification.
spec
a String representation of a URL.
Description
Creates a URL by parsing the specification spec within a specified context. If the context argument is not null and the spec argument is a partial URL specification, then any of the strings missing components are inherited from the context argument.

The specification given by the String argument is parsed to determine if it specifies a protocol. If the String contains an ASCII colon ':' character before the first occurrence of an ASCII slash character '/', then the characters before the colon comprise the protocol.

  • If the spec argument does not specify a protocol:
    • If the context argument is not null, then the protocol is copied from the context argument.
    • If the context argument is null, then a MalformedURLException is thrown.
  • If the spec argument does specify a protocol:
    • If the context argument is null, or specifies a different protocol than the specification argument, the context argument is ignored.
    • If the context argument is not null and specifies the same protocol as the specification, the host, port number, and file are copied from the context argument into the newly created URL.

The constructor then searches for an appropriate stream protocol handler of type URLStreamHandler as outlined for:

    java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String)
The stream protocol handler's parseURL method is called to parse the remaining fields of the specification that override any defaults set by the context argument.

Exceptions
MalformedURLException if no protocol is specified, or an unknown protocol is found.
See Also
URL, URLStreamHandler, parseURL


 URL.equals

URL.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the URL to compare against.
Returns
true if the objects are the same; false otherwise.
Description
Compares two URLs. The result is true if and only if the argument is not null and is a URL object that represents the same URL as this object. Two URL objects are equal if they have the same protocol and reference the same host, the same port number on the host, and the same file on the host. The anchors of the URL objects are not compared.

This method is equivalent to:

    (obj instanceof URL) && sameFile((URL)obj)

Overrides
equals in class Object


 URL.getContent

URL.getContent

Syntax
public final Object getContent() throws IOException
Returns
the contents of this URL.
Description
Returns the contents of this URL. This method is a shorthand for:
    openConnection().getContent()

Exceptions
IOException if an I/O exception occurs.
See Also
getContent


 URL.getFile

URL.getFile

Syntax
public String getFile()
Returns
the file name of this URL.
Description
Returns the file name of this URL.


 URL.getHost

URL.getHost

Syntax
public String getHost()
Returns
the host name of this URL.
Description
Returns the host name of this URL, if applicable. For "file" protocol, this is an empty string.


 URL.getPort

URL.getPort

Syntax
public int getPort()
Returns
the port number
Description
Returns the port number of this URL. Returns -1 if the port is not set.


 URL.getProtocol

URL.getProtocol

Syntax
public String getProtocol()
Returns
the protocol of this URL.
Description
Returns the protocol name this URL.


 URL.getRef

URL.getRef

Syntax
public String getRef()
Returns
the anchor (also known as the "reference") of this URL.
Description
Returns the anchor (also known as the "reference") of this URL.


 URL.hashCode

URL.hashCode

Syntax
public int hashCode()
Returns
a hash code for this URL.
Description
Creates an integer suitable for hash table indexing.

Overrides
hashCode in class Object


 URL.openConnection

URL.openConnection

Syntax
public URLConnection openConnection() throws IOException
Returns
a URLConnection to the URL.
Description
Returns a URLConnection object that represents a connection to the remote object referred to by the URL.

If there is not already an open connection, the connection is opened by calling the openConnection method of the protocol handler for this URL.

Exceptions
IOException if an I/O exception occurs.
See Also
URL, URLConnection, openConnection


 URL.openStream

URL.openStream

Syntax
public final InputStream openStream() throws IOException
Returns
an input stream for reading from the URL connection.
Description
Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for:
    openConnection().getInputStream()

Exceptions
IOException if an I/O exception occurs.


 URL.sameFile

URL.sameFile

Syntax
public boolean sameFile( URL other )
Parameters
other
the URL to compare against.
Returns
true if they reference the same remote object; false otherwise.
Description
Compares two URLs, excluding the "ref" fields. Returns true if this URL and the other argument both refer to the same resource. The two URLs might not both contain the same anchor.


 URL.set

URL.set

Syntax
protected void set( String protocol, String host, int port, String file, String ref )
Parameters
protocol
the protocol to use
host
the host name to connecto to
port
the protocol port to connect to
file
the specified file name on that host
ref
the reference
Description
Sets the fields of the URL. This is not a public method so that only URLStreamHandlers can modify URL fields. URLs are otherwise constant. REMIND: this method will be moved to URLStreamHandler


 URL.setURLStreamHandlerFactory

URL.setURLStreamHandlerFactory

Syntax
public static synchronized void setURLStreamHandlerFactory( URLStreamHandlerFactory fac )
Parameters
fac
the desired factory.
Description
Sets an application's URLStreamHandlerFactory. This method can be called at most once by an application.

The URLStreamHandlerFactory instance is used to construct a stream protocol handler from a protocol name.

Exceptions
Error if the application has already set a factory.
See Also
URL, URLStreamHandlerFactory


 URL.toExternalForm

URL.toExternalForm

Syntax
public String toExternalForm()
Returns
a string representation of this object.
Description
Constructs a string representation of this URL. The string is created by calling the toExternalForm method of the stream protocol handler for this object.

See Also
URL, toExternalForm


 URL.toString

URL.toString

Syntax
public String toString()
Returns
a string representation of this object.
Description
Constructs a string representation of this URL. The string is created by calling the toExternalForm method of the stream protocol handler for this object.

Overrides
toString in class Object
See Also
URL, toExternalForm


 Class URLConnection

Class java.net.URLConnection

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.URLConnection

public abstract class URLConnection
extends Object

The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:

openConnection() | connect()
Manipulate parameters that affect the connection to the remote resource. | Interact with the resource; query header fields and contents.
---------------------------->
time
  1. The connection object is created by invoking the openConnection method on a URL.
  2. The setup parameters and general request properties are manipulated.
  3. The actual connection to the remote object is made, using the connect method.
  4. The remote object becomes available. The header fields and the contents of the remote object can be accessed.

The setup parameters are modified using the following methods:

  • setAllowUserInteraction
  • setDoInput
  • setDoOutput
  • setIfModifiedSince
  • setUseCaches

and the general request properties are modified using the method:

  • setRequestProperty

Default values for the AllowUserInteraction and UseCaches parameters can be set using the methods setDefaultAllowUserInteraction and setDefaultUseCaches. Default values for general request properties can be set using the setDefaultRequestProperty method.

Each of the above set methods has a corresponding get method to retrieve the value of the parameter or general request property. The specific parameters and general request properties that are applicable are protocol specific.

The following methods are used to access the header fields and the contents after the connection is made to the remote object:

  • getContent
  • getHeaderField
  • getInputStream
  • getOutputStream

Certain header fields are accessed frequently. The methods:

  • getContentEncoding
  • getContentLength
  • getContentType
  • getDate
  • getExpiration
  • getLastModifed

provide convenient access to these fields. The getContentType method is used by the getContent method to determine the type of the remote object; subclasses may find it convenient to override the getContentType method.

In the common case, all of the pre-connection parameters and general request properties can be ignored: the pre-connection parameters and request properties default to sensible values. For most clients of this interface, there are only two interesting methods: getInputStream and getObject, which are mirrored in the URL class by convenience methods.

More information on the request properties and header fields of an http connection can be found at:

    http://www.w3.org/hypertext/WWW/Protocols/HTTP1.0/draft-ietf-http-spec.html

See Also:
openConnection, connect, getContent, getContentEncoding, getContentLength, getContentType, getDate, getExpiration, getHeaderField, getHeaderField, getInputStream, getLastModified, getOutputStream, setAllowUserInteraction, setDefaultRequestProperty, setDefaultUseCaches, setDoInput, setDoOutput, setIfModifiedSince, setRequestProperty, setUseCaches


 URLConnection Members

URLConnection Members

Class Overview | This Package | All Packages

Fields
Name | Description
allowUserInteraction | If true, this URL is being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog.
connected | If false, this connection object has not created a communications link to the specified URL.
doInput | This variable is set by the setDoInput method.
doOutput | This variable is set by the setDoOutput method.
fileNameMap |
ifModifiedSince | Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time.
url | The URL represents the remote object on the World Wide Web to which this connection is opened.
useCaches | If true, the protocol is allowed to use caching whenever it can.

Constructors
Name | Description
URLConnection(URL) | Constructs a URL connection to the specified URL.

Methods
Name | Description
connect() | Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.
getAllowUserInteraction() | Returns the value of the allowUserInteraction field for this object.
getContent() | Retrieves the contents of this URL connection.
getContentEncoding() | Returns the value of the content-encoding header field.
getContentLength() | Returns the value of the content-length header field.
getContentType() | Returns the value of the content-type header field.
getDate() | Returns the value of the date header field.
getDefaultAllowUserInteraction() | Returns the default value of the allowUserInteraction field.
getDefaultRequestProperty(String) | Returns the value of the default request property.
getDefaultUseCaches() | Returns the default value of a URLConnection's useCaches flag.
getDoInput() | Returns the value of this URLConnection's doInput flag.
getDoOutput() | Returns the value of this URLConnection's doOutput flag.
getExpiration() | Returns the value of the expires header field.
getHeaderField(int) | Returns the value for the nth header field.
getHeaderField(String) | Returns the name of the specified header field.
getHeaderFieldDate(String, long) | Returns the value of the named field parsed as date.
getHeaderFieldInt(String, int) | Returns the value of the named field parsed as a number.
getHeaderFieldKey(int) | Returns the key for the nth header field.
getIfModifiedSince() | Returns the value of this object's ifModifiedSince field.
getInputStream() | Returns an input stream that reads from this open connection.
getLastModified() | Returns the value of the last-modified header field.
getOutputStream() | Returns an output stream that writes to this connection.
getRequestProperty(String) | Returns the value of the named general request property for this connection.
getURL() | Returns the value of this URLConnection's URL field.
getUseCaches() | Returns the value of this URLConnection's useCaches field.
guessContentTypeFromName(String) | Tries to determine the content type of an object, based on the specified "file" component of a URL.
guessContentTypeFromStream(InputStream) | Tries to determine the type of an input stream based on the characters at the beginning of the input stream.
setAllowUserInteraction(boolean) | Set the value of the allowUserInteraction field of this URLConnection.
setContentHandlerFactory(ContentHandlerFactory) | Sets the ContentHandlerFactory of an application.
setDefaultAllowUserInteraction(boolean) | Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.
setDefaultRequestProperty(String, String) | Sets the default value of a general request property.
setDefaultUseCaches(boolean) | Sets the default value of the useCaches field to the specified value.
setDoInput(boolean) | Sets the value of the doInput field for this URLConnection to the specified value.
setDoOutput(boolean) | Sets the value of the doOutput field for this URLConnection to the specified value.
setIfModifiedSince(long) | Sets the value of the ifModifiedSince field of this URLConnection to the specified value.
setRequestProperty(String, String) | Sets the general request property.
setUseCaches(boolean) | Sets the value of the useCaches field of this URLConnection to the specified value.
toString() | Returns a String representation of this URL connection.


 URLConnection.allowUserInteraction

URLConnection.allowUserInteraction

Syntax
protected boolean allowUserInteraction
Description
If true, this URL is being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog. If false, then no user interaction is allowed.

The value of this field can be set by the setAllowUserInteraction method. Its value is returned by the getAllowUserInteraction method. Its default value is the value of the argument in the last invocation of the setDefaultAllowUserInteraction method.

See Also
getAllowUserInteraction, setAllowUserInteraction, setDefaultAllowUserInteraction


 URLConnection.connected

URLConnection.connected

Syntax
protected boolean connected
Description
If false, this connection object has not created a communications link to the specified URL. If true, the communications link has been established.


 URLConnection.doInput

URLConnection.doInput

Syntax
protected boolean doInput
Description
This variable is set by the setDoInput method. Its value is returned by the getDoInput method.

A URL connection can be used for input and/or output. Setting the doInput flag to true indicates that the application intends to read data from the URL connection.

The default value of this field is true.

See Also
getDoInput, setDoInput


 URLConnection.doOutput

URLConnection.doOutput

Syntax
protected boolean doOutput
Description
This variable is set by the setDoOutput method. Its value is returned by the getDoInput method.

A URL connection can be used for input and/or output. Setting the doOutput flag to true indicates that the application intends to write data to the URL connection.

The default value of this field is false.

See Also
getDoOutput, setDoOutput


 URLConnection.fileNameMap

URLConnection.fileNameMap

Syntax
public static FileNameMap fileNameMap


 URLConnection.ifModifiedSince

URLConnection.ifModifiedSince

Syntax
protected long ifModifiedSince
Description
Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time.

A nonzero value gives a time as the number of seconds since January 1, 1970, GMT. The object is fetched only if it has been modified more recently than that time.

This variable is set by the setIfModifiedSince method. Its value is returned by the getIfModifiedSince method.

The default value of this field is 0, indicating that the fetching must always occur.

See Also
getIfModifiedSince, setIfModifiedSince


 URLConnection.url

URLConnection.url

Syntax
protected URL url
Description
The URL represents the remote object on the World Wide Web to which this connection is opened.

The value of this field can be accessed by the getURL method.

The default value of this variable is the value of the URL argument in the URLConnection constructor.

See Also
getURL, url


 URLConnection.useCaches

URLConnection.useCaches

Syntax
protected boolean useCaches
Description
If true, the protocol is allowed to use caching whenever it can. If false, the protocol must always try to get a fresh copy of the object.

This field is set by the setUseCaches method. Its value is returned by the getUseCaches method.

Its default value is the value given in the last invocation of the setDefaultUseCaches method.

See Also
setUseCaches, getUseCaches, setDefaultUseCaches


 URLConnection.URLConnection

URLConnection.URLConnection

Syntax
protected URLConnection( URL url )
Parameters
url
the specified URL.
Description
Constructs a URL connection to the specified URL. A connection to the object referenced by the URL is not created.


 URLConnection.connect

URLConnection.connect

Syntax
public abstract void connect() throws IOException
Description
Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

If the connect method is called when the connection has already been opened (indicated by the connected field having the value true), the call is ignored.

URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified (e.g., doInput and UseCaches). After connecting, it is an error to try to set them. Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

Exceptions
IOException if an I/O error occurs while opening the connection.
See Also
connected


 URLConnection.getAllowUserInteraction

URLConnection.getAllowUserInteraction

Syntax
public boolean getAllowUserInteraction()
Returns
the value of the allowUserInteraction field for this object.
Description
Returns the value of the allowUserInteraction field for this object.

See Also
allowUserInteraction


 URLConnection.getContent

URLConnection.getContent

Syntax
public Object getContent() throws IOException
Returns
the object fetched. The instanceOf operation should be used to determine the specific kind of object returned.
Description
Retrieves the contents of this URL connection.

This method first determines the content type of the object by calling the getContentType method. If this is the first time that the application has seen that specific content type, a content handler for that content type is created:

  1. If the application has set up a content handler factory instance using the setContentHandlerFactory method, the createContentHandler method of that instance is called with the content type as an argument; the result is a content handler for that content type.
  2. If no content handler factory has yet been set up, or if the factory's createContentHandler method returns null, then the application loads the class named:
      sun.net.www.content.<contentType>
    where <contentType> is formed by taking the content-type string, replacing all slash characters with a period ('.'), and all other non-alphanumeric characters with the underscore character '_'. The alphanumeric characters are specifically the 26 uppercase ASCII letters 'A' through 'Z', the 26 lowercase ASCII letters 'a' through 'z', and the 10 ASCII digits '0' through '9'. If the specified class does not exist, or is not a subclass of ContentHandler, then an UnknownServiceException is thrown.

Exceptions
IOException if an I/O error occurs while getting the content.
Exceptions
UnknownServiceException if the protocol does not support the content type.
See Also
createContentHandler, getContentType, setContentHandlerFactory


 URLConnection.getContentEncoding

URLConnection.getContentEncoding

Syntax
public String getContentEncoding()
Returns
the content encoding of the resource that the URL references, or null if not known.
Description
Returns the value of the content-encoding header field.

See Also
getHeaderField


 URLConnection.getContentLength

URLConnection.getContentLength

Syntax
public int getContentLength()
Returns
the content length of the resource that this connection's URL references, or -1 if the content length is not known.
Description
Returns the value of the content-length header field.


 URLConnection.getContentType

URLConnection.getContentType

Syntax
public String getContentType()
Returns
the content type of the resource that the URL references, or null if not known.
Description
Returns the value of the content-type header field.

See Also
getHeaderField


 URLConnection.getDate

URLConnection.getDate

Syntax
public long getDate()
Returns
the sending date of the resource that the URL references, or 0 if not known. The value returned is the number of seconds since January 1, 1970 GMT.
Description
Returns the value of the date header field.

See Also
getHeaderField


 URLConnection.getDefaultAllowUserInteraction

URLConnection.getDefaultAllowUserInteraction

Syntax
public static boolean getDefaultAllowUserInteraction()
Returns
the default value of the allowUserInteraction field.
Description
Returns the default value of the allowUserInteraction field.

Ths default is "sticky", being a part of the static state of all URLConnections. This flag applies to the next, and all following URLConnections that are created.

See Also
allowUserInteraction


 URLConnection.getDefaultRequestProperty

URLConnection.getDefaultRequestProperty

Syntax
public static String getDefaultRequestProperty( String key )
Returns
the value of the default request property for the specified key.
Description
Returns the value of the default request property. Default request properties are set for every connection.

See Also
setDefaultRequestProperty


 URLConnection.getDefaultUseCaches

URLConnection.getDefaultUseCaches

Syntax
public boolean getDefaultUseCaches()
Returns
the default value of a URLConnection's useCaches flag.
Description
Returns the default value of a URLConnection's useCaches flag.

Ths default is "sticky", being a part of the static state of all URLConnections. This flag applies to the next, and all following URLConnections that are created.

See Also
useCaches


 URLConnection.getDoInput

URLConnection.getDoInput

Syntax
public boolean getDoInput()
Returns
the value of this URLConnection's doInput flag.
Description
Returns the value of this URLConnection's doInput flag.

See Also
doInput


 URLConnection.getDoOutput

URLConnection.getDoOutput

Syntax
public boolean getDoOutput()
Returns
the value of this URLConnection's doOutput flag.
Description
Returns the value of this URLConnection's doOutput flag.

See Also
doOutput


 URLConnection.getExpiration

URLConnection.getExpiration

Syntax
public long getExpiration()
Returns
the expiration date of the resource that this URL references, or 0 if not known. The value is the number of seconds since January 1, 1970 GMT.
Description
Returns the value of the expires header field.

See Also
getHeaderField


 URLConnection.getHeaderField

URLConnection.getHeaderField

Syntax
public String getHeaderField( String name )
Parameters
name
the name of a header field.
Returns
the value of the named header field, or null if there is no such field in the header.
Description
Returns the name of the specified header field.


 URLConnection.getHeaderField

URLConnection.getHeaderField

Syntax
public String getHeaderField( int n )
Parameters
n
an index.
Returns
the value of the nth header field.
Description
Returns the value for the nth header field. It returns null if there are fewer than n fields.

This method can be used in conjunction with the getHeaderFieldKey method to iterate through all the headers in the message.

See Also
getHeaderFieldKey


 URLConnection.getHeaderFieldDate

URLConnection.getHeaderFieldDate

Syntax
public long getHeaderFieldDate( String name, long Default )
Parameters
name
the name of the header field.
Default
a default value.
Returns
the value of the field, parsed as a date. The value of the Default argument is returned if the field is missing or malformed.
Description
Returns the value of the named field parsed as date. The result is the number of seconds since January 1, 1970 GMT represented by the named field.

This form of getHeaderField exists because some connection types (e.g., http-ng) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing.


 URLConnection.getHeaderFieldInt

URLConnection.getHeaderFieldInt

Syntax
public int getHeaderFieldInt( String name, int Default )
Parameters
name
the name of the header field.
Default
the default value.
Returns
the value of the named field, parsed as an integer. The Default value is returned if the field is missing or malformed.
Description
Returns the value of the named field parsed as a number.

This form of getHeaderField exists because some connection types (e.g., http-ng) have pre-parsed headers. Classes for that connection type can override this method and short-circuit the parsing.


 URLConnection.getHeaderFieldKey

URLConnection.getHeaderFieldKey

Syntax
public String getHeaderFieldKey( int n )
Parameters
n
an index.
Returns
the key for the nth header field, or null if there are fewer than n fields.
Description
Returns the key for the nth header field.


 URLConnection.getIfModifiedSince

URLConnection.getIfModifiedSince

Syntax
public long getIfModifiedSince()
Returns
the value of this object's ifModifiedSince field.
Description
Returns the value of this object's ifModifiedSince field.

See Also
ifModifiedSince


 URLConnection.getInputStream

URLConnection.getInputStream

Syntax
public InputStream getInputStream() throws IOException
Returns
an input stream that reads from this open connection.
Description
Returns an input stream that reads from this open connection.

Exceptions
IOException if an I/O error occurs while creating the input stream.
Exceptions
UnknownServiceException if the protocol does not support input.


 URLConnection.getLastModified

URLConnection.getLastModified

Syntax
public long getLastModified()
Returns
the date the resource referenced by this URLConnection was last modified, or 0 if not known.
Description
Returns the value of the last-modified header field. The result is the number of seconds since January 1, 1970 GMT.

See Also
getHeaderField


 URLConnection.getOutputStream

URLConnection.getOutputStream

Syntax
public OutputStream getOutputStream() throws IOException
Returns
an output stream that writes to this connection.
Description
Returns an output stream that writes to this connection.

Exceptions
IOException if an I/O error occurs while creating the output stream.
Exceptions
UnknownServiceException if the protocol does not support output.


 URLConnection.getRequestProperty

URLConnection.getRequestProperty

Syntax
public String getRequestProperty( String key )
Returns
the value of the named general request property for this connection.
Description
Returns the value of the named general request property for this connection.


 URLConnection.getURL

URLConnection.getURL

Syntax
public URL getURL()
Returns
the value of this URLConnection's URL field.
Description
Returns the value of this URLConnection's URL field.

See Also
url


 URLConnection.getUseCaches

URLConnection.getUseCaches

Syntax
public boolean getUseCaches()
Returns
the value of this URLConnection's useCaches field.
Description
Returns the value of this URLConnection's useCaches field.

See Also
useCaches


 URLConnection.guessContentTypeFromName

URLConnection.guessContentTypeFromName

Syntax
protected static String guessContentTypeFromName( String fname )
Parameters
fname
a filename.
Returns
a guess as to what the content type of the object is, based upon its file name.
Description
Tries to determine the content type of an object, based on the specified "file" component of a URL. This is a convenience method that can be used by subclasses that override the getContentType method.

See Also
getContentType


 URLConnection.guessContentTypeFromStream

URLConnection.guessContentTypeFromStream

Syntax
public static String guessContentTypeFromStream( InputStream is ) throws IOException
Parameters
is
an input stream that supports marks.
Returns
a guess at the content type, or null if none can be determined.
Description
Tries to determine the type of an input stream based on the characters at the beginning of the input stream. This method can be used by subclasses that override the getContentType method.

Ideally, this routine would not be needed. But many http servers return the incorrect content type; in addition, there are many nonstandard extensions. Direct inspection of the bytes to determine the content type is often more accurate than believing the content type claimed by the http server.

Exceptions
IOException if an I/O error occurs while reading the input stream.
See Also
mark, markSupported, getContentType


 URLConnection.setAllowUserInteraction

URLConnection.setAllowUserInteraction

Syntax
public void setAllowUserInteraction( boolean allowuserinteraction )
Parameters
allowuserinteraction
the new value.
Description
Set the value of the allowUserInteraction field of this URLConnection.

See Also
allowUserInteraction


 URLConnection.setContentHandlerFactory

URLConnection.setContentHandlerFactory

Syntax
public static synchronized void setContentHandlerFactory( ContentHandlerFactory fac )
Parameters
fac
the desired factory.
Description
Sets the ContentHandlerFactory of an application. It can be called at most once by an application.

The ContentHandlerFactory instance is used to construct a content handler from a content type

Exceptions
Error if the factory has already been defined.
See Also
ContentHandlerFactory, getContent


 URLConnection.setDefaultAllowUserInteraction

URLConnection.setDefaultAllowUserInteraction

Syntax
public static void setDefaultAllowUserInteraction( boolean defaultallowuserinteraction )
Parameters
defaultallowuserinteraction
the new value.
Description
Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.

See Also
allowUserInteraction


 URLConnection.setDefaultRequestProperty

URLConnection.setDefaultRequestProperty

Syntax
public static void setDefaultRequestProperty( String key, String value )
Parameters
key
the keyword by which the request is known (e.g., "accept").
value
the value associated with the key.
Description
Sets the default value of a general request property. When a URLConnection is created, it is initialized with these properties.


 URLConnection.setDefaultUseCaches

URLConnection.setDefaultUseCaches

Syntax
public void setDefaultUseCaches( boolean defaultusecaches )
Parameters
defaultusecaches
the new value.
Description
Sets the default value of the useCaches field to the specified value.

See Also
useCaches


 URLConnection.setDoInput

URLConnection.setDoInput

Syntax
public void setDoInput( boolean doinput )
Parameters
value
the new value.
Description
Sets the value of the doInput field for this URLConnection to the specified value.

A URL connection can be used for input and/or output. Set the DoInput flag to true if you intend to use the URL connection for input, false if not. The default is true unless DoOutput is explicitly set to true, in which case DoInput defaults to false.

See Also
doInput


 URLConnection.setDoOutput

URLConnection.setDoOutput

Syntax
public void setDoOutput( boolean dooutput )
Parameters
value
the new value.
Description
Sets the value of the doOutput field for this URLConnection to the specified value.

A URL connection can be used for input and/or output. Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. The default is false.

See Also
doOutput


 URLConnection.setIfModifiedSince

URLConnection.setIfModifiedSince

Syntax
public void setIfModifiedSince( long ifmodifiedsince )
Parameters
value
the new value.
Description
Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

See Also
ifModifiedSince


 URLConnection.setRequestProperty

URLConnection.setRequestProperty

Syntax
public void setRequestProperty( String key, String value )
Parameters
key
the keyword by which the request is known (e.g., "accept").
value
the value associated with it.
Description
Sets the general request property.


 URLConnection.setUseCaches

URLConnection.setUseCaches

Syntax
public void setUseCaches( boolean usecaches )
Description
Sets the value of the useCaches field of this URLConnection to the specified value.

Some protocols do caching of documents. Occasionally, it is important to be able to "tunnel through" and ignore the caches (e.g., the "reload" button in a browser). If the UseCaches flag on a connection is true, the connection is allowed to use whatever caches it can. If false, caches are to be ignored. The default value comes from DefaultUseCaches, which defaults to true.

See Also
useCaches


 URLConnection.toString

URLConnection.toString

Syntax
public String toString()
Returns
a string representation of this URLConnection.
Description
Returns a String representation of this URL connection.

Overrides
toString in class Object


 Class URLEncoder

Class java.net.URLEncoder

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.URLEncoder

public class URLEncoder
extends Object

The class contains a utility method for converting a String into a MIME format called "x-www-form-urlencoded" format.

To convert a String, each character is examined in turn:

  • The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same.
  • The space character ' ' is converted into a plus sign '+'.
  • All other characters are converted into the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the lower 8-bits of the character.


 URLEncoder Members

URLEncoder Members

Class Overview | This Package | All Packages

Methods
Name | Description
encode(String) | Translates a string into x-www-form-urlencoded format.


 URLEncoder.encode

URLEncoder.encode

Syntax
public static String encode( String s )
Parameters
s
String to be translated.
Returns
the translated String.
Description
Translates a string into x-www-form-urlencoded format.


 Class URLStreamHandler

Class java.net.URLStreamHandler

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.net.URLStreamHandler

public abstract class URLStreamHandler
extends Object

The abstract class URLStreamHandler is the common superclass for all stream protocol handlers. A stream protocol handler knows how to make a connection for a particular protocol type, such as http, ftp, or gopher.

In most cases, an instance of a URLStreamHandler subclass is not created directly by an application. Rather, the first time a protocol name is encountered when constructing a URL, the appropriate stream protocol handler is automatically loaded.

See Also:
URL


 URLStreamHandler Members

URLStreamHandler Members

Class Overview | This Package | All Packages

Constructors
Name | Description
URLStreamHandler() |

Methods
Name | Description
openConnection(URL) | Opens a connection to the object referenced by the URL argument.
parseURL(URL, String, int, int) | Parses the string representation of a URL into a URL object.
setURL(URL, String, String, int, String, String) | Sets the fields of the URL argument to the indicated values.
toExternalForm(URL) | Converts a URL of a specific protocol to a String.


 URLStreamHandler.URLStreamHandler

URLStreamHandler.URLStreamHandler

Syntax
public URLStreamHandler()


 URLStreamHandler.openConnection

URLStreamHandler.openConnection

Syntax
protected abstract URLConnection openConnection( URL u ) throws IOException
Parameters
u
the URL that this connects to.
Returns
a URLConnection object for the URL.
Description
Opens a connection to the object referenced by the URL argument. This method should be overridden by a subclass.

Exceptions
IOException if an I/O error occurs while opening the connection.


 URLStreamHandler.parseURL

URLStreamHandler.parseURL

Syntax
protected void parseURL( URL u, String spec, int start, int limit )
Parameters
u
the URL to receive the result of parsing the spec.
spec
the String representing the URL that must be parsed.
start
the character index at which to begin parsing. This is just past the ':' (if there is one) that specifies the determination of the protocol name.
limit
the character position to stop parsing at. This is the end of the string or the position of the "#" character, if present. All information after the sharp sign indicates an anchor.
Description
Parses the string representation of a URL into a URL object.

If there is any inherited context, then it has already been copied into the URL argument.

The parseURL method of URLStreamHandler parses the string representation as if it were an http specification. Most URL protocol families have a similar parsing. A stream protocol handler for a protocol that has a different syntax must override this routine.


 URLStreamHandler.setURL

URLStreamHandler.setURL

Syntax
protected void setURL( URL u, String protocol, String host, int port, String file, String ref )
Parameters
u
the URL to modify.
protocol
the protocol name.
host
the remote host value for the URL.
port
the port on the remote machine.
file
the file.
ref
the reference.
Description
Sets the fields of the URL argument to the indicated values. Only classes derived from URLStreamHandler are supposed to be able to call the set method on a URL.

See Also
set


 URLStreamHandler.toExternalForm

URLStreamHandler.toExternalForm

Syntax
protected String toExternalForm( URL u )
Parameters
u
the URL.
Returns
a string representation of the URL argument.
Description
Converts a URL of a specific protocol to a String.


 Interface URLStreamHandlerFactory

Interface java.net.URLStreamHandlerFactory

Interface Members | This Package | All Packages

public interface URLStreamHandlerFactory

This interface defines a factory for URL stream protocol handlers.

It is used by the URL class to create a URLStreamHandler for a specific protocol.

See Also:
URL, URLStreamHandler


 URLStreamHandlerFactory Members

URLStreamHandlerFactory Members

Interface Overview | This Package | All Packages

Methods
Name | Description
createURLStreamHandler(String) | Creates a new URLStreamHandler instance with the specified protocol.


 URLStreamHandlerFactory.createURLStreamHandler

URLStreamHandlerFactory.createURLStreamHandler

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract URLStreamHandler createURLStreamHandler( String protocol )
Parameters
protocol
the protocol ("ftp", "http", "nntp", etc.).
Returns
a URLStreamHandler for the specific protocol.
Description
Creates a new URLStreamHandler instance with the specified protocol.

See Also
URLStreamHandler


 Class UnknownHostException

Class java.net.UnknownHostException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.UnknownHostException

public class UnknownHostException
extends IOException

Thrown to indicate that the IP address of a host could not be determined.


 UnknownHostException Members

UnknownHostException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnknownHostException() | Constructs a new UnknownHostException with no detail message.
UnknownHostException(String) | Constructs a new UnknownHostException with the specified detail message.


 UnknownHostException.UnknownHostException

UnknownHostException.UnknownHostException

Syntax 1
public UnknownHostException( String host )
Parameters
host
the detail message.
Description
Constructs a new UnknownHostException with the specified detail message.

Syntax 2
public UnknownHostException()
Description
Constructs a new UnknownHostException with no detail message.


 Class UnknownServiceException

Class java.net.UnknownServiceException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.net.UnknownServiceException

public class UnknownServiceException
extends IOException

Thrown to indicate that an unknown service exception has occurred. Either the MIME type returned by a URL connection does not make sense, or the application is attempting to write to a read-only URL connection.


 UnknownServiceException Members

UnknownServiceException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
UnknownServiceException() | Constructs a new UnknownServiceException with no detail message.
UnknownServiceException(String) | Constructs a new UnknownServiceException with the specified detail message.


 UnknownServiceException.UnknownServiceException

UnknownServiceException.UnknownServiceException

Syntax 1
public UnknownServiceException()
Description
Constructs a new UnknownServiceException with no detail message.

Syntax 2
public UnknownServiceException( String msg )
Parameters
msg
the detail message.
Description
Constructs a new UnknownServiceException with the specified detail message.


 Package java.security

Package java.security

All Packages

Interfaces

  • Certificate
  • Key
  • Principal
  • PrivateKey
  • PublicKey

    • Classes

  • DigestInputStream
  • DigestOutputStream
  • Identity
  • IdentityScope
  • KeyPair
  • KeyPairGenerator
  • MessageDigest
  • Provider
  • SecureRandom
  • Security
  • Signature
  • Signer

    • Exceptions

  • DigestException
  • InvalidKeyException
  • InvalidParameterException
  • KeyException
  • KeyManagementException
  • NoSuchAlgorithmException
  • NoSuchProviderException
  • ProviderException
  • SignatureException


 Interface Certificate

Interface java.security.Certificate

Interface Members | This Package | All Packages

public interface Certificate

This is an interface of abstract methods for managing an identity certificate. An identity certificate is a guarantee by a principal that a public key is that of another principal. (A principal represents an entity such as an individual user or a group.)

In particular, this interface is intended to be a common abstraction for constructs that have different formats but important common uses. For example, different types of certificates, such as X.509 certificates and PGP certificates, share general certificate functionality (the need to encode and decode certificates) and some types of information, such as a public key, the principal whose key it is, and the guarantor guaranteeing that the public key is that of the specified principal. So an implementation of X.509 certificates and an implementation of PGP certificates can both utilize the Certificate interface, even though their formats and additional types and amounts of information stored are different.

Important: This interface is useful for cataloging and grouping objects sharing certain common uses. It does not have any semantics of its own. In particular, a Certificate object does not make any statement as to the validity of the binding. It is the duty of the application implementing this interface to verify the certificate and satisfy itself of its validity.


 Certificate Members

Certificate Members

Interface Overview | This Package | All Packages

Methods
Name | Description
decode(InputStream) | Decodes a certificate from an input stream.
encode(OutputStream) | Encodes the certificate to an output stream in a format that can be decoded by the decode method.
getFormat() | Returns the name of the coding format.
getGuarantor() | Returns the guarantor of the certificate, that is, the principal guaranteeing that the public key associated with this certificate is that of the principal associated with this certificate.
getPrincipal() | Returns the principal of the principal-key pair being guaranteed by the guarantor.
getPublicKey() | Returns the key of the principal-key pair being guaranteed by the guarantor.
toString(boolean) | Returns a string that represents the contents of the certificate.


 Certificate.decode

Certificate.decode

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void decode( InputStream stream ) throws KeyException, IOException
Parameters
stream
the input stream from which to fetch the data being decoded.
Description
Decodes a certificate from an input stream. The format should be that returned by getFormat and produced by encode.

Exceptions
KeyException if the certificate is not properly initialized, or data is missing, etc.
Exceptions
IOException if an exception occurs while trying to input the encoded certificate from the input stream.
See Also
encode, getFormat


 Certificate.encode

Certificate.encode

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void encode( OutputStream stream ) throws KeyException, IOException
Parameters
stream
the output stream to which to encode the certificate.
Description
Encodes the certificate to an output stream in a format that can be decoded by the decode method.

Exceptions
KeyException if the certificate is not properly initialized, or data is missing, etc.
Exceptions
IOException if a stream exception occurs while trying to output the encoded certificate to the output stream.
See Also
decode, getFormat


 Certificate.getFormat

Certificate.getFormat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getFormat()
Returns
the name of the coding format.
Description
Returns the name of the coding format. This is used as a hint to find an appropriate parser. It could be "X.509", "PGP", etc. This is the format produced and understood by the encode and decode methods.


 Certificate.getGuarantor

Certificate.getGuarantor

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Principal getGuarantor()
Returns
the guarantor which guaranteed the principal-key binding.
Description
Returns the guarantor of the certificate, that is, the principal guaranteeing that the public key associated with this certificate is that of the principal associated with this certificate. For X.509 certificates, the guarantor will typically be a Certificate Authority (such as the United States Postal Service or Verisign, Inc.).


 Certificate.getPrincipal

Certificate.getPrincipal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Principal getPrincipal()
Returns
the principal to which this certificate is bound.
Description
Returns the principal of the principal-key pair being guaranteed by the guarantor.


 Certificate.getPublicKey

Certificate.getPublicKey

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract PublicKey getPublicKey()
Returns
the public key that this certificate certifies belongs to a particular principal.
Description
Returns the key of the principal-key pair being guaranteed by the guarantor.


 Certificate.toString

Certificate.toString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String toString( boolean detailed )
Parameters
detailed
whether or not to give detailed information about the certificate.
Description
Returns a string that represents the contents of the certificate.


 Class DigestException

Class java.security.DigestException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.DigestException

public class DigestException
extends Exception

This is the generic Message Digest exception.


 DigestException Members

DigestException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DigestException() | Constructs a DigestException with no detail message.
DigestException(String) | Constructs a DigestException with the specified detail message.


 DigestException.DigestException

DigestException.DigestException

Syntax 1
public DigestException()
Description
Constructs a DigestException with no detail message. (A detail message is a String that describes this particular exception.)

Syntax 2
public DigestException( String msg )
Parameters
msg
the detail message.
Description
Constructs a DigestException with the specified detail message. (A detail message is a String that describes this particular exception.)


 Class DigestInputStream

Class java.security.DigestInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.security.DigestInputStream

public class DigestInputStream
extends FilterInputStream

A transparent stream that updates the associated message digest using the bits going through the stream.

To complete the message digest computation, call one of the digest methods on the associated message digest after your calls to one of this digest input stream's read methods.

It is possible to turn this stream on or off (see on). When it is on, a call to read results in an update on the message digest. But when it is off, the message digest is not updated. The default is for the stream to be on.

Note that digest objects can compute only one digest (see MessageDigest), so that in order to compute intermediate digests, a caller should retain a handle onto the digest object, and clone it for each digest to be computed, leaving the orginal digest untouched.

See Also:
MessageDigest, DigestOutputStream


 DigestInputStream Members

DigestInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
digest | The message digest associated with this stream.

Constructors
Name | Description
DigestInputStream(InputStream, MessageDigest) | Creates a digest input stream, using the specified input stream and message digest.

Methods
Name | Description
getMessageDigest() | Returns the message digest associated with this stream.
on(boolean) | Turns the digest function on or off.
read() | Reads a byte, and updates the message digest (if the digest function is on).
read(byte[], int, int) | Reads into a byte array, and updates the message digest (if the digest function is on).
setMessageDigest(MessageDigest) | Associates the specified message digest with this stream.
toString() | Prints a string representation of this digest input stream and its associated message digest object.


 DigestInputStream.digest

DigestInputStream.digest

Syntax
protected MessageDigest digest
Description
The message digest associated with this stream.


 DigestInputStream.DigestInputStream

DigestInputStream.DigestInputStream

Syntax
public DigestInputStream( InputStream stream, MessageDigest digest )
Parameters
stream
the input stream.
digest
the message digest to associate with this stream.
Description
Creates a digest input stream, using the specified input stream and message digest.


 DigestInputStream.getMessageDigest

DigestInputStream.getMessageDigest

Syntax
public MessageDigest getMessageDigest()
Returns
the message digest associated with this stream.
Description
Returns the message digest associated with this stream.


 DigestInputStream.on

DigestInputStream.on

Syntax
public void on( boolean on )
Parameters
on
true to turn the digest function on, false to turn it off.
Description
Turns the digest function on or off. The default is on. When it is on, a call to read results in an update on the message digest. But when it is off, the message digest is not updated.


 DigestInputStream.read

DigestInputStream.read

Syntax 1
public int read() throws IOException
Returns
the byte read.
Description
Reads a byte, and updates the message digest (if the digest function is on). That is, this method reads a byte from the input stream, blocking until the byte is actually read. If the digest function is on (see on), this method will then call update on the message digest associated with this stream, passing it the byte read.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
update

Syntax 2
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the array into which the data is read.
off
the starting offset into b of where the data should be placed.
len
the maximum number of bytes to be read from the input stream into b, starting at offset off.
Returns
the actual number of bytes read. This is less than len if the end of the stream is reached prior to reading len bytes. -1 is returned if no bytes were read because the end of the stream had already been reached when the call was made.
Description
Reads into a byte array, and updates the message digest (if the digest function is on). That is, this method reads up to len bytes from the input stream into the array b, starting at offset off. This method blocks until the data is actually read. If the digest function is on (see on), this method will then call update on the message digest associated with this stream, passing it the data.

Exceptions
IOException if an I/O error occurs.
Overrides
read in class FilterInputStream
See Also
update


 DigestInputStream.setMessageDigest

DigestInputStream.setMessageDigest

Syntax
public void setMessageDigest( MessageDigest digest )
Parameters
digest
the message digest to be associated with this stream.
Description
Associates the specified message digest with this stream.


 DigestInputStream.toString

DigestInputStream.toString

Syntax
public String toString()
Description
Prints a string representation of this digest input stream and its associated message digest object.

Overrides
toString in class Object


 Class DigestOutputStream

Class java.security.DigestOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.security.DigestOutputStream

public class DigestOutputStream
extends FilterOutputStream

A transparent stream that updates the associated message digest using the bits going through the stream.

To complete the message digest computation, call one of the digest methods on the associated message digest after your calls to one of this digest ouput stream's write methods.

It is possible to turn this stream on or off (see on). When it is on, a call to write results in an update on the message digest. But when it is off, the message digest is not updated. The default is for the stream to be on.

See Also:
MessageDigest, DigestInputStream


 DigestOutputStream Members

DigestOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
digest | The message digest associated with this stream.

Constructors
Name | Description
DigestOutputStream(OutputStream, MessageDigest) | Creates a digest output stream, using the specified output stream and message digest.

Methods
Name | Description
getMessageDigest() | Returns the message digest associated with this stream.
on(boolean) | Turns the digest function on or off.
setMessageDigest(MessageDigest) | Associates the specified message digest with this stream.
toString() | Prints a string representation of this digest output stream and its associated message digest object.
write(byte[], int, int) | Updates the message digest (if the digest function is on) using the specified subarray, and in any case writes the subarray to the output stream.
write(int) | Updates the message digest (if the digest function is on) using the specified byte, and in any case writes the byte to the output stream.


 DigestOutputStream.digest

DigestOutputStream.digest

Syntax
protected MessageDigest digest
Description
The message digest associated with this stream.


 DigestOutputStream.DigestOutputStream

DigestOutputStream.DigestOutputStream

Syntax
public DigestOutputStream( OutputStream stream, MessageDigest digest )
Parameters
stream
the output stream.
digest
the message digest to associate with this stream.
Description
Creates a digest output stream, using the specified output stream and message digest.


 DigestOutputStream.getMessageDigest

DigestOutputStream.getMessageDigest

Syntax
public MessageDigest getMessageDigest()
Returns
the message digest associated with this stream.
Description
Returns the message digest associated with this stream.


 DigestOutputStream.on

DigestOutputStream.on

Syntax
public void on( boolean on )
Parameters
on
true to turn the digest function on, false to turn it off.
Description
Turns the digest function on or off. The default is on. When it is on, a call to write results in an update on the message digest. But when it is off, the message digest is not updated.


 DigestOutputStream.setMessageDigest

DigestOutputStream.setMessageDigest

Syntax
public void setMessageDigest( MessageDigest digest )
Parameters
digest
the message digest to be associated with this stream.
Description
Associates the specified message digest with this stream.


 DigestOutputStream.toString

DigestOutputStream.toString

Syntax
public String toString()
Description
Prints a string representation of this digest output stream and its associated message digest object.

Overrides
toString in class Object


 DigestOutputStream.write

DigestOutputStream.write

Syntax 1
public void write( int b ) throws IOException
Parameters
b
the byte to be used for updating and writing to the output stream.
Description
Updates the message digest (if the digest function is on) using the specified byte, and in any case writes the byte to the output stream. That is, if the digest function is on (see on), this method calls update on the message digest associated with this stream, passing it the byte b. This method then writes the byte to the output stream, blocking until the byte is actually written.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream
See Also
update

Syntax 2
public void write( byte b[], int off, int len ) throws IOException
Parameters
b
the array containing the subarray to be used for updating and writing to the output stream.
off
the offset into b of the first byte to be updated and written.
len
the number of bytes of data to be updated and written from b, starting at offset off.
Description
Updates the message digest (if the digest function is on) using the specified subarray, and in any case writes the subarray to the output stream. That is, if the digest function is on (see on), this method calls update on the message digest associated with this stream, passing it the subarray specifications. This method then writes the subarray bytes to the output stream, blocking until the bytes are actually written.

Exceptions
IOException if an I/O error occurs.
Overrides
write in class FilterOutputStream
See Also
update


 Class Identity

Class java.security.Identity

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.Identity

public abstract class Identity
extends Object
implements Principal, Serializable

This class represents identities: real-world objects such as people, companies or organizations whose identities can be authenticated using their public keys. Identities may also be more abstract (or concrete) constructs, such as daemon threads or smart cards.

All Identity objects have a name and a public key. Names are immutable. Identities may also be scoped. That is, if an Identity is specified to have a particular scope, then the name and public key of the Identity are unique within that scope.

An Identity also has a set of certificates (all certifying its own public key). The Principal names specified in these certificates need not be the same, only the key.

An Identity can be subclassed, to include postal and email addresses, telephone numbers, images of faces and logos, and so on.

See Also:
IdentityScope, Signer, Principal


 Identity Members

Identity Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Identity() | Constructor for serialization only.
Identity(String) | Constructs an identity with the specified name and no scope.
Identity(String, IdentityScope) | Constructs an identity with the specified name and scope.

Methods
Name | Description
addCertificate(Certificate) | Adds a certificate for this identity.
certificates() | Returns a copy of all the certificates for this identity.
equals(Object) | Tests for equality between the specified object and this identity.
getInfo() | Returns general information previously specified for this identity.
getName() | Returns this identity's name.
getPublicKey() | Returns this identity's public key.
getScope() | Returns this identity's scope.
hashCode() | Returns a hashcode for this identity.
identityEquals(Identity) | Tests for equality between the specified identity and this identity.
removeCertificate(Certificate) | Removes a certificate from this identity.
setInfo(String) | Specifies a general information string for this identity.
setPublicKey(PublicKey) | Sets this identity's public key.
toString() | Returns a short string describing this identity, telling its name and its scope (if any).
toString(boolean) | Returns a string representation of this identity, with optionally more details than that provided by the toString method without any arguments.


 Identity.Identity

Identity.Identity

Syntax 1
protected Identity()
Description
Constructor for serialization only.

Syntax 2
public Identity( String name, IdentityScope scope ) throws KeyManagementException
Parameters
name
the identity name.
scope
the scope of the identity.
Description
Constructs an identity with the specified name and scope.

Exceptions
KeyManagementException if there is already an identity with the same name in the scope.

Syntax 3
public Identity( String name )
Parameters
name
the identity name.
Description
Constructs an identity with the specified name and no scope.


 Identity.addCertificate

Identity.addCertificate

Syntax
public void addCertificate( Certificate certificate ) throws KeyManagementException
Parameters
certificate
the certificate to be added.
Description
Adds a certificate for this identity. If the identity has a public key, the public key in the certificate must be the same, and if the identity does not have a public key, the identity's public key is set to be that specified in the certificate.

Exceptions
KeyManagementException if the certificate is not valid, if the public key in the certificate being added conflicts with this identity's public key, or if another exception occurs.


 Identity.certificates

Identity.certificates

Syntax
public Certificate[] certificates()
Returns
a copy of all the certificates for this identity.
Description
Returns a copy of all the certificates for this identity.


 Identity.equals

Identity.equals

Syntax
public final boolean equals( Object identity )
Parameters
identity
the object to test for equality with this identity.
Returns
true if the objects are considered equal, false otherwise.
Description
Tests for equality between the specified object and this identity. This first tests to see if the entities actually refer to the same object, in which case it returns true. Next, it checks to see if the entities have the same name and the same scope. If they do, the method returns true. Otherwise, it calls identityEquals, which subclasses should override.

Overrides
equals in class Object
See Also
identityEquals


 Identity.getInfo

Identity.getInfo

Syntax
public String getInfo()
Returns
general information about this identity.
Description
Returns general information previously specified for this identity.

See Also
setInfo


 Identity.getName

Identity.getName

Syntax
public final String getName()
Returns
the name of this identity.
Description
Returns this identity's name.


 Identity.getPublicKey

Identity.getPublicKey

Syntax
public PublicKey getPublicKey()
Returns
the public key for this identity.
Description
Returns this identity's public key.


 Identity.getScope

Identity.getScope

Syntax
public final IdentityScope getScope()
Returns
the scope of this identity.
Description
Returns this identity's scope.


 Identity.hashCode

Identity.hashCode

Syntax
public int hashCode()
Returns
a hashcode for this identity.
Description
Returns a hashcode for this identity.

Overrides
hashCode in class Object


 Identity.identityEquals

Identity.identityEquals

Syntax
protected boolean identityEquals( Identity identity )
Parameters
identity
the identity to test for equality with this identity.
Returns
true if the identities are considered equal, false otherwise.
Description
Tests for equality between the specified identity and this identity. This method should be overriden by subclasses to test for equality. The default behavior is to return true if the names and public keys are equal.

See Also
equals


 Identity.removeCertificate

Identity.removeCertificate

Syntax
public void removeCertificate( Certificate certificate ) throws KeyManagementException
Parameters
certificate
the certificate to be removed.
Description
Removes a certificate from this identity.

Exceptions
KeyManagementException if the certificate is missing, or if another exception occurs.


 Identity.setInfo

Identity.setInfo

Syntax
public void setInfo( String info )
Parameters
info
the information string.
Description
Specifies a general information string for this identity.

See Also
getInfo


 Identity.setPublicKey

Identity.setPublicKey

Syntax
public void setPublicKey( PublicKey key ) throws KeyManagementException
Parameters
key
the public key for this identity.
Description
Sets this identity's public key. The old key and all of this identity's certificates are removed by this operation.

Exceptions
KeyManagementException if another identity in the identity's scope has the same public key, or if another exception occurs.


 Identity.toString

Identity.toString

Syntax 1
public String toString()
Returns
information about this identity, such as its name and the name of its scope (if any).
Description
Returns a short string describing this identity, telling its name and its scope (if any).

Overrides
toString in class Object

Syntax 2
public String toString( boolean detailed )
Parameters
detailed
whether or not to provide detailed information.
Returns
information about this identity. If detailed is true, then this method returns more information than that provided by the toString method without any arguments.
Description
Returns a string representation of this identity, with optionally more details than that provided by the toString method without any arguments.

See Also
toString


 Class IdentityScope

Class java.security.IdentityScope

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.Identity
           |
           +----java.security.IdentityScope

public abstract class IdentityScope
extends Identity

This class represents a scope for identities. It is an Identity itself, and therefore has a name and can have a scope. It can also optionally have a public key and associated certificates.

An IdentityScope can contain Identity objects of all kinds, including Signers. All types of Identity objects can be retrieved, added, and removed using the same methods. Note that it is possible, and in fact expected, that different types of identity scopes will apply different policies for their various operations on the various types of Identities.

There is a one-to-one mapping between keys and identities, and there can only be one copy of one key per scope. For example, suppose Acme Software, Inc is a software publisher known to a user. Suppose it is an Identity, that is, it has a public key, and a set of associated certificates. It is named in the scope using the name "Acme Software". No other named Identity in the scope has the same public key. Of course, none has the same name as well.

See Also:
Identity, Signer, Principal, Key


 IdentityScope Members

IdentityScope Members

Class Overview | This Package | All Packages

Constructors
Name | Description
IdentityScope() | This constructor is used for serialization only and should not be used by subclasses.
IdentityScope(String) | Constructs a new identity scope with the specified name.
IdentityScope(String, IdentityScope) | Constructs a new identity scope with the specified name and scope.

Methods
Name | Description
addIdentity(Identity) | Adds an identity to this identity scope.
getIdentity(Principal) | Retrieves the identity whose name is the same as that of the specified principal.
getIdentity(PublicKey) | Retrieves the identity with the specified public key.
getIdentity(String) | Returns the identity in this scope with the specified name (if any).
getSystemScope() | Returns the system's identity scope.
identities() | Returns an enumeration of all identities in this identity scope.
removeIdentity(Identity) | Removes an identity from this identity scope.
setSystemScope(IdentityScope) | Sets the system's identity scope.
size() | Returns the number of identities within this identity scope.
toString() | Returns a string representation of this identity scope, including its name, its scope name, and the number of identities in this identity scope.


 IdentityScope.IdentityScope

IdentityScope.IdentityScope

Syntax 1
protected IdentityScope()
Description
This constructor is used for serialization only and should not be used by subclasses.

Syntax 2
public IdentityScope( String name )
Parameters
name
the scope name.
Description
Constructs a new identity scope with the specified name.

Syntax 3
public IdentityScope( String name, IdentityScope scope ) throws KeyManagementException
Parameters
name
the scope name.
scope
the scope for the new identity scope.
Description
Constructs a new identity scope with the specified name and scope.

Exceptions
KeyManagementException if there is already an identity with the same name in the scope.


 IdentityScope.addIdentity

IdentityScope.addIdentity

Syntax
public abstract void addIdentity( Identity identity ) throws KeyManagementException
Parameters
identity
the identity to be added.
Description
Adds an identity to this identity scope.

Exceptions
KeyManagementException if the identity is not valid, a name conflict occurs, another identity has the same public key as the identity being added, or another exception occurs.


 IdentityScope.getIdentity

IdentityScope.getIdentity

Syntax 1
public abstract Identity getIdentity( String name )
Parameters
name
the name of the identity to be retrieved.
Returns
the identity named name, or null if there are no identities named name in this scope.
Description
Returns the identity in this scope with the specified name (if any).

Syntax 2
public Identity getIdentity( Principal principal )
Parameters
principal
the principal corresponding to the identity to be retrieved.
Returns
the identity whose name is the same as that of the principal, or null if there are no identities of the same name in this scope.
Description
Retrieves the identity whose name is the same as that of the specified principal. (Note: Identity implements Principal.)

Syntax 3
public abstract Identity getIdentity( PublicKey key )
Parameters
key
the public key for the identity to be returned.
Returns
the identity with the given key, or null if there are no identities in this scope with that key.
Description
Retrieves the identity with the specified public key.


 IdentityScope.getSystemScope

IdentityScope.getSystemScope

Syntax
public static IdentityScope getSystemScope()
Returns
the system's identity scope.
Description
Returns the system's identity scope. See the "System Identity Scope" section in the Java Cryptography Architecture API Specification & Reference.


 IdentityScope.identities

IdentityScope.identities

Syntax
public abstract Enumeration identities()
Returns
an enumeration of all identities in this identity scope.
Description
Returns an enumeration of all identities in this identity scope.


 IdentityScope.removeIdentity

IdentityScope.removeIdentity

Syntax
public abstract void removeIdentity( Identity identity ) throws KeyManagementException
Parameters
identity
the identity to be removed.
Description
Removes an identity from this identity scope.

Exceptions
KeyManagementException if the identity is missing, or another exception occurs.


 IdentityScope.setSystemScope

IdentityScope.setSystemScope

Syntax
protected static void setSystemScope( IdentityScope scope )
Parameters
scope
the scope to set.
Description
Sets the system's identity scope. See the "System Identity Scope" section in the Java Cryptography Architecture API Specification & Reference.


 IdentityScope.size

IdentityScope.size

Syntax
public abstract int size()
Returns
the number of identities within this identity scope.
Description
Returns the number of identities within this identity scope.


 IdentityScope.toString

IdentityScope.toString

Syntax
public String toString()
Returns
a string representation of this identity scope.
Description
Returns a string representation of this identity scope, including its name, its scope name, and the number of identities in this identity scope.

Overrides
toString in class Identity


 Class InvalidKeyException

Class java.security.InvalidKeyException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.KeyException
                           |
                           +----java.security.InvalidKeyException

public class InvalidKeyException
extends KeyException

This is the exception for invalid Keys (invalid encoding, wrong length, uninitialized, etc).


 InvalidKeyException Members

InvalidKeyException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InvalidKeyException() | Constructs an InvalidKeyException with no detail message.
InvalidKeyException(String) | Constructs an InvalidKeyException with the specified detail message.


 InvalidKeyException.InvalidKeyException

InvalidKeyException.InvalidKeyException

Syntax 1
public InvalidKeyException()
Description
Constructs an InvalidKeyException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public InvalidKeyException( String msg )
Parameters
msg
the detail message.
Description
Constructs an InvalidKeyException with the specified detail message. A detail message is a String that describes this particular exception.


 Class InvalidParameterException

Class java.security.InvalidParameterException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.lang.IllegalArgumentException
                                   |
                                   +----java.security.InvalidParameterException

public class InvalidParameterException
extends IllegalArgumentException

This exception is thrown when an invalid parameter is passed to a method.


 InvalidParameterException Members

InvalidParameterException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
InvalidParameterException() | Constructs an InvalidParameterException with no detail message.
InvalidParameterException(String) | Constructs an InvalidParameterException with the specified detail message.


 InvalidParameterException.InvalidParameterException

InvalidParameterException.InvalidParameterException

Syntax 1
public InvalidParameterException()
Description
Constructs an InvalidParameterException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public InvalidParameterException( String msg )
Parameters
msg
the detail message.
Description
Constructs an InvalidParameterException with the specified detail message. A detail message is a String that describes this particular exception.


 Interface Key

Interface java.security.Key

Interface Members | This Package | All Packages

public interface Key
extends Serializable

The Key interface is the top-level interface for all keys. It defines the functionality shared by all key objects. All keys have three characteristics:

  • An Algorithm

    This is the key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as DSA or RSA), which will work with those algorithms and with related algorithms (such as MD5 with RSA, SHA-1 with RSA, Raw DSA, etc.) The name of the algorithm of a key is obtained using the getAlgorithm method.

  • An Encoded Form

    This is an external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party. The key is encoded according to a standard format (such as X.509 or PKCS#8), and is returned using the getEncoded method.

  • A Format

    This is the name of the format of the encoded key. It is returned by the getFormat method.

Keys are generally obtained through key generators, certificates, or various Identity classes used to manage keys. There are no provisions in this release for the parsing of encoded keys and certificates.

See Also:
PublicKey, PrivateKey, KeyPair, KeyPairGenerator, Identity, IdentityScope, Signer


 Key Members

Key Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getAlgorithm() | Returns the standard algorithm name this key is for.
getEncoded() | Returns the encoded key.
getFormat() | Returns the format used to encode the key or null if the key does not support encoding.


 Key.getAlgorithm

Key.getAlgorithm

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getAlgorithm()
Returns
the name of the algorithm this key is for, or null if the algorithm this key is for is unknown.
Description
Returns the standard algorithm name this key is for. For example, "DSA" would indicate that this key is a DSA key. Note that this method may return null, when the algorithm this key is for is unknown.

See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.


 Key.getEncoded

Key.getEncoded

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte[] getEncoded()
Returns
the encoded key, or null if the key does not support encoding.
Description
Returns the encoded key.


 Key.getFormat

Key.getFormat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getFormat()
Returns
the format used to encode the key.
Description
Returns the format used to encode the key or null if the key does not support encoding.


 Class KeyException

Class java.security.KeyException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.KeyException

public class KeyException
extends Exception

This is the basic key exception.

See Also:
Key, InvalidKeyException, KeyManagementException


 KeyException Members

KeyException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
KeyException() | Constructs a KeyException with no detail message.
KeyException(String) | Constructs a KeyException with the specified detail message.


 KeyException.KeyException

KeyException.KeyException

Syntax 1
public KeyException()
Description
Constructs a KeyException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public KeyException( String msg )
Parameters
msg
the detail message.
Description
Constructs a KeyException with the specified detail message. A detail message is a String that describes this particular exception.


 Class KeyManagementException

Class java.security.KeyManagementException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.KeyException
                           |
                           +----java.security.KeyManagementException

public class KeyManagementException
extends KeyException

This is the general key management exception, for all operations dealing with key management. Subclasses could include:

  • KeyIDConflict
  • KeyAuthorizationFailureException
  • ExpiredKeyException

See Also:
Key, KeyException


 KeyManagementException Members

KeyManagementException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
KeyManagementException() | Constructs a KeyManagementException with no detail message.
KeyManagementException(String) | Constructs a KeyManagementException with the specified detail message.


 KeyManagementException.KeyManagementException

KeyManagementException.KeyManagementException

Syntax 1
public KeyManagementException()
Description
Constructs a KeyManagementException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public KeyManagementException( String msg )
Parameters
msg
the detail message.
Description
Constructs a KeyManagementException with the specified detail message. A detail message is a String that describes this particular exception.


 Class KeyPair

Class java.security.KeyPair

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.KeyPair

public final class KeyPair
extends Object

This class is a simple holder for a key pair (a public key and a private key). It does not enforce any security, and, when initialized, should be treated like a PrivateKey.

See Also:
PublicKey, PrivateKey


 KeyPair Members

KeyPair Members

Class Overview | This Package | All Packages

Constructors
Name | Description
KeyPair(PublicKey, PrivateKey) | Constructs a key with the specified public key and private key.

Methods
Name | Description
getPrivate() | Returns the private key from this key pair.
getPublic() | Returns the public key from this key pair.


 KeyPair.KeyPair

KeyPair.KeyPair

Syntax
public KeyPair( PublicKey publicKey, PrivateKey privateKey )
Parameters
publicKey
the public key.
privateKey
the private key.
Description
Constructs a key with the specified public key and private key.


 KeyPair.getPrivate

KeyPair.getPrivate

Syntax
public PrivateKey getPrivate()
Returns
the private key.
Description
Returns the private key from this key pair.


 KeyPair.getPublic

KeyPair.getPublic

Syntax
public PublicKey getPublic()
Returns
the public key.
Description
Returns the public key from this key pair.


 Class KeyPairGenerator

Class java.security.KeyPairGenerator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.KeyPairGenerator

public abstract class KeyPairGenerator
extends Object

The KeyPairGenerator class is used to generate pairs of public and private keys. Key generators are constructed using the getInstance factory methods (static methods that return instances of a given class).

Key generation is an area that sometimes does not lend itself well to algorithm independence. For example, it is possible to generate a DSA key pair specifying key family parameters (p, q and g), while it is not possible to do so for an RSA key pair. That is, those parameters are applicable to DSA but not to RSA.

There are therefore two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object.

All key pair generators share the concepts of a "strength" and a source of randomness. The measure of strength is universally shared by all algorithms, though it is interpreted differently for different algorithms. The initialize method in this KeyPairGenerator class takes these two universally shared types of arguments.

Since no other parameters are specified when you call this algorithm-independent initialize method, all other values, such as algorithm parameters, public exponent, etc., are defaulted to standard values.

It is sometimes desirable to initialize a key pair generator object using algorithm-specific semantics. For example, you may want to initialize a DSA key generator for a given set of parameters p, q and g, or an RSA key generator for a given public exponent.

This is done through algorithm-specific standard interfaces. Rather than calling the algorithm-independent KeyPairGenerator initialize method, the key pair generator is cast to an algorithm-specific interface so that one of its specialized parameter initialization methods can be called. An example is the DSAKeyPairGenerator interface (from java.security.interfaces).

See "The KeyPairGenerator Class" in the Java Cryptography Architecture API Specification & Reference for more information and examples.

See Also:
DSAKeyPairGenerator


 KeyPairGenerator Members

KeyPairGenerator Members

Class Overview | This Package | All Packages

Constructors
Name | Description
KeyPairGenerator(String) | Creates a KeyPairGenerator object for the specified algorithm.

Methods
Name | Description
generateKeyPair() | Generates a key pair.
getAlgorithm() | Returns the standard name of the algorithm for this key generator.
getInstance(String) | Generates a KeyPairGenerator object that implements the algorithm requested, as available in the environment.
getInstance(String, String) | Generates a KeyPairGenerator object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.
initialize(int) | Initializes the key pair generator for a certain strength using a system-provided source of randomness.
initialize(int, SecureRandom) | Initializes the key pair generator for a certain strength.


 KeyPairGenerator.KeyPairGenerator

KeyPairGenerator.KeyPairGenerator

Syntax
protected KeyPairGenerator( String algorithm )
Parameters
algorithm
the standard string name of the algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Description
Creates a KeyPairGenerator object for the specified algorithm.


 KeyPairGenerator.generateKeyPair

KeyPairGenerator.generateKeyPair

Syntax
public abstract KeyPair generateKeyPair()
Description
Generates a key pair. Unless an initialization method is called using a KeyPairGenerator interface, algorithm-specific defaults will be used. This will generate a new key pair every time it is called.


 KeyPairGenerator.getAlgorithm

KeyPairGenerator.getAlgorithm

Syntax
public String getAlgorithm()
Returns
the standard string name of the algorithm.
Description
Returns the standard name of the algorithm for this key generator. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.


 KeyPairGenerator.getInstance

KeyPairGenerator.getInstance

Syntax 1
public static KeyPairGenerator getInstance( String algorithm ) throws NoSuchAlgorithmException
Parameters
algorithm
the standard string name of the algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Returns
the new KeyPairGenerator object.
Description
Generates a KeyPairGenerator object that implements the algorithm requested, as available in the environment.

Exceptions
NoSuchAlgorithmException if the algorithm is not available in the environment.

Syntax 2
public static KeyPairGenerator getInstance( String algorithm, String provider ) throws NoSuchAlgorithmException, NoSuchProviderException
Parameters
algorithm
the standard string name of the algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
provider
the string name of the provider.
Returns
the new KeyPairGenerator object.
Description
Generates a KeyPairGenerator object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.

Exceptions
NoSuchAlgorithmException if the algorithm is not available from the provider.
Exceptions
NoSuchProviderException if the provider is not available in the environment.
See Also
Provider


 KeyPairGenerator.initialize

KeyPairGenerator.initialize

Syntax 1
public abstract void initialize( int strength, SecureRandom random )
Parameters
strength
the strength of the key. This is an algorithm-specific metric, such as modulus length.
random
the source of randomness for this generator.
Description
Initializes the key pair generator for a certain strength.

Syntax 2
public void initialize( int strength )
Parameters
strength
the strength of the key. This is an algorithm-specific metric, such as modulus length.
Description
Initializes the key pair generator for a certain strength using a system-provided source of randomness.


 Class MessageDigest

Class java.security.MessageDigest

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.MessageDigest

public abstract class MessageDigest
extends Object

This MessageDigest class provides the functionality of a message digest algorithm, such as MD5 or SHA. Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value.

Like other algorithm-based classes in Java Security, MessageDigest has two major components:

Message Digest API (Application Program Interface)
This is the interface of methods called by applications needing message digest services. The API consists of all public methods.
Message Digest SPI (Service Provider Interface)
This is the interface implemented by providers that supply specific algorithms. It consists of all methods whose names are prefixed by engine. Each such method is called by a correspondingly-named public API method. For example, the engineReset method is called by the reset method. The SPI methods are abstract; providers must supply a concrete implementation.

A MessageDigest object starts out initialized. The data is processed through it using the update methods. At any point reset can be called to reset the digest. Once all the data to be updated has been updated, one of the digest methods should be called to complete the hash computation.

The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.

Implementations are free to implement the Cloneable interface, and doing so will let client applications test cloneability using instanceof Cloneable before cloning:

 MessageDigest md = MessageDigest.getInstance("SHA");
 if (md instanceof Cloneable) {
     md.update(toChapter1);
     MessageDigest tc1 = md.clone();
     byte[] toChapter1Digest = tc1.digest;
     md.update(toChapter2);
     ...etc.
 } else {
     throw new DigestException("couldn't make digest of partial content");
 }

Note that if a given implementation is not cloneable, it is still possible to compute intermediate digests by instantiating several instances, if the number of digests is known in advance.

See Also:
DigestInputStream, DigestOutputStream


 MessageDigest Members

MessageDigest Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MessageDigest(String) | Creates a message digest with the specified algorithm name.

Methods
Name | Description
clone() | Returns a clone if the implementation is cloneable.
digest() | Completes the hash computation by performing final operations such as padding.
digest(byte[]) | Performs a final update on the digest using the specified array of bytes, then completes the digest computation.
engineDigest() | SPI: Completes the hash computation by performing final operations such as padding.
engineReset() | SPI: Resets the digest for further use.
engineUpdate(byte) | SPI: Updates the digest using the specified byte.
engineUpdate(byte[], int, int) | SPI: Updates the digest using the specified array of bytes, starting at the specified offset.
getAlgorithm() | Returns a string that identifies the algorithm, independent of implementation details.
getInstance(String) | Generates a MessageDigest object that implements the specified digest algorithm.
getInstance(String, String) | Generates a MessageDigest object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.
isEqual(byte[], byte[]) | Compares two digests for equality.
reset() | Resets the digest for further use.
toString() | Returns a string representation of this message digest object.
update(byte) | Updates the digest using the specified byte.
update(byte[]) | Updates the digest using the specified array of bytes.
update(byte[], int, int) | Updates the digest using the specified array of bytes, starting at the specified offset.


 MessageDigest.MessageDigest

MessageDigest.MessageDigest

Syntax
protected MessageDigest( String algorithm )
Parameters
algorithm
the standard name of the digest algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Description
Creates a message digest with the specified algorithm name.


 MessageDigest.clone

MessageDigest.clone

Syntax
public Object clone() throws CloneNotSupportedException
Returns
a clone if the implementation is cloneable.
Description
Returns a clone if the implementation is cloneable.

Exceptions
CloneNotSupportedException if this is called on an implementation that does not support Cloneable.
Overrides
clone in class Object


 MessageDigest.digest

MessageDigest.digest

Syntax 1
public byte[] digest()
Returns
the array of bytes for the resulting hash value.
Description
Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

Syntax 2
public byte[] digest( byte input[] )
Parameters
input
the input to be updated before the digest is completed.
Returns
the array of bytes for the resulting hash value.
Description
Performs a final update on the digest using the specified array of bytes, then completes the digest computation. That is, this method first calls update on the array, then calls digest().


 MessageDigest.engineDigest

MessageDigest.engineDigest

Syntax
protected abstract byte[] engineDigest()
Returns
the array of bytes for the resulting hash value.
Description
SPI: Completes the hash computation by performing final operations such as padding. Once engineDigest has been called, the engine should be reset (see reset). Resetting is the responsibility of the engine implementor.


 MessageDigest.engineReset

MessageDigest.engineReset

Syntax
protected abstract void engineReset()
Description
SPI: Resets the digest for further use.


 MessageDigest.engineUpdate

MessageDigest.engineUpdate

Syntax 1
protected abstract void engineUpdate( byte input )
Parameters
input
the byte to use for the update.
Description
SPI: Updates the digest using the specified byte.

Syntax 2
protected abstract void engineUpdate( byte input[], int offset, int len )
Parameters
input
the array of bytes to use for the update.
offset
the offset to start from in the array of bytes.
len
the number of bytes to use, starting at offset.
Description
SPI: Updates the digest using the specified array of bytes, starting at the specified offset. This should be a no-op if the digest has been finalized.


 MessageDigest.getAlgorithm

MessageDigest.getAlgorithm

Syntax
public final String getAlgorithm()
Description
Returns a string that identifies the algorithm, independent of implementation details. The name should be a standard Java Security name (such as "SHA", "MD5", and so on). See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.


 MessageDigest.getInstance

MessageDigest.getInstance

Syntax 1
public static MessageDigest getInstance( String algorithm ) throws NoSuchAlgorithmException
Parameters
algorithm
the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Returns
a Message Digest object implementing the specified algorithm.
Description
Generates a MessageDigest object that implements the specified digest algorithm. If the default provider package contains a MessageDigest subclass implementing the algorithm, an instance of that subclass is returned. If the algorithm is not available in the default package, other packages are searched.

Exceptions
NoSuchAlgorithmException if the algorithm is not available in the caller's environment.

Syntax 2
public static MessageDigest getInstance( String algorithm, String provider ) throws NoSuchAlgorithmException, NoSuchProviderException
Parameters
algorithm
the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
provider
the name of the provider.
Returns
a Message Digest object implementing the specified algorithm.
Description
Generates a MessageDigest object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.

Exceptions
NoSuchAlgorithmException if the algorithm is not available in the package supplied by the requested provider.
Exceptions
NoSuchProviderException if the provider is not available in the environment.
See Also
Provider


 MessageDigest.isEqual

MessageDigest.isEqual

Syntax
public static boolean isEqual( byte digesta[], byte digestb[] )
Parameters
digesta
one of the digests to compare.
digestb
the other digest to compare.
Returns
true if the digests are equal, false otherwise.
Description
Compares two digests for equality. Does a simple byte compare.


 MessageDigest.reset

MessageDigest.reset

Syntax
public void reset()
Description
Resets the digest for further use.


 MessageDigest.toString

MessageDigest.toString

Syntax
public String toString()
Description
Returns a string representation of this message digest object.

Overrides
toString in class Object


 MessageDigest.update

MessageDigest.update

Syntax 1
public void update( byte input )
Parameters
input
the byte with which to update the digest.
Description
Updates the digest using the specified byte.

Syntax 2
public void update( byte input[], int offset, int len )
Parameters
input
the array of bytes.
offset
the offset to start from in the array of bytes.
len
the number of bytes to use, starting at offset.
Description
Updates the digest using the specified array of bytes, starting at the specified offset.

Syntax 3
public void update( byte input[] )
Parameters
input
the array of bytes.
Description
Updates the digest using the specified array of bytes.


 Class NoSuchAlgorithmException

Class java.security.NoSuchAlgorithmException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.NoSuchAlgorithmException

public class NoSuchAlgorithmException
extends Exception

This exception is thrown when a particular cryptographic algorithm is requested but is not available in the environment.


 NoSuchAlgorithmException Members

NoSuchAlgorithmException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchAlgorithmException() | Constructs a NoSuchAlgorithmException with no detail message.
NoSuchAlgorithmException(String) | Constructs a NoSuchAlgorithmException with the specified detail message.


 NoSuchAlgorithmException.NoSuchAlgorithmException

NoSuchAlgorithmException.NoSuchAlgorithmException

Syntax 1
public NoSuchAlgorithmException()
Description
Constructs a NoSuchAlgorithmException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public NoSuchAlgorithmException( String msg )
Parameters
msg
the detail message.
Description
Constructs a NoSuchAlgorithmException with the specified detail message. A detail message is a String that describes this particular exception, which may, for example, specify which algorithm is not available.


 Class NoSuchProviderException

Class java.security.NoSuchProviderException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.NoSuchProviderException

public class NoSuchProviderException
extends Exception

This exception is thrown when a particular security provider is requested but is not available in the environment.


 NoSuchProviderException Members

NoSuchProviderException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchProviderException() | Constructs a NoSuchProviderException with no detail message.
NoSuchProviderException(String) | Constructs a NoSuchProviderException with the specified detail message.


 NoSuchProviderException.NoSuchProviderException

NoSuchProviderException.NoSuchProviderException

Syntax 1
public NoSuchProviderException()
Description
Constructs a NoSuchProviderException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public NoSuchProviderException( String msg )
Parameters
msg
the detail message.
Description
Constructs a NoSuchProviderException with the specified detail message. A detail message is a String that describes this particular exception.


 Interface Principal

Interface java.security.Principal

Interface Members | This Package | All Packages

public interface Principal

This interface represents a principal. A principal can be an individual, a corporation, a program thread; anything which can have an identity. See the ACL white paper for more information.

See Also:
Identity, Certificate, Acl, Group


 Principal Members

Principal Members

Interface Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Compares this principal to the specified object.
getName() | Returns the name of this principal.
hashCode() | Returns a hashcode for this principal.
toString() | Returns a string representation of this principal.


 Principal.equals

Principal.equals

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean equals( Object another )
Parameters
another
the principal to compare with.
Returns
true if the principal passed in is the same as that encapsulated by this principal, false otherwise.
Description
Compares this principal to the specified object. Returns true if the object passed in matches the principal represented by the implementation of this interface.

Overrides
equals in class Object


 Principal.getName

Principal.getName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getName()
Returns
the name of this principal.
Description
Returns the name of this principal.


 Principal.hashCode

Principal.hashCode

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int hashCode()
Returns
a hashcode for this principal.
Description
Returns a hashcode for this principal.

Overrides
hashCode in class Object


 Principal.toString

Principal.toString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String toString()
Returns
a string representation of this principal.
Description
Returns a string representation of this principal.

Overrides
toString in class Object


 Interface PrivateKey

Interface java.security.PrivateKey

This Package | All Packages

public interface PrivateKey
extends Key

A private key. This interface contains no methods or constants. It merely serves to group (and provide type safety for) all private key interfaces. Note: The specialized private key interfaces extend this interface. See, for example, the DSAPrivateKey interface in java.security.interfaces.

See Also:
Key, PublicKey, Certificate, initVerify, DSAPrivateKey


 Class Provider

Class java.security.Provider

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Dictionary
           |
           +----java.util.Hashtable
                   |
                   +----java.util.Properties
                           |
                           +----java.security.Provider

public abstract class Provider
extends Properties

This class represents a "provider" for the Java Security API. A provider implements some or all parts of Java Security, including:

  • Algorithms (such as DSA, RSA, MD5 or SHA-1).
  • Key generation and management facilities (such as for algorithm-specific keys).

Each provider has a name and a version number, and is configured in each runtime it is installed in.

There is a default provider that comes standard with the JDK. It is called the SUN Provider. See "The Provider Class" in the Java Cryptography Architecture API Specification & Reference for information about how providers work and how to install them.


 Provider Members

Provider Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Provider(String, double, String) | Constructs a provider with the specified name, version number, and information.

Methods
Name | Description
getInfo() | Returns a human-readable description of the provider and its services.
getName() | Returns the name of this provider.
getVersion() | Returns the version number for this provider.
toString() | Returns a string with the name and the version number of this provider.


 Provider.Provider

Provider.Provider

Syntax
protected Provider( String name, double version, String info )
Parameters
name
the provider name.
version
the provider version number.
info
a description of the provider and its services.
Description
Constructs a provider with the specified name, version number, and information.


 Provider.getInfo

Provider.getInfo

Syntax
public String getInfo()
Returns
a description of the provider and its services.
Description
Returns a human-readable description of the provider and its services. This may return an HTML page, with relevant links.


 Provider.getName

Provider.getName

Syntax
public String getName()
Returns
the name of this provider.
Description
Returns the name of this provider.


 Provider.getVersion

Provider.getVersion

Syntax
public double getVersion()
Returns
the version number for this provider.
Description
Returns the version number for this provider.


 Provider.toString

Provider.toString

Syntax
public String toString()
Returns
the string with the name and the version number for this provider.
Description
Returns a string with the name and the version number of this provider.

Overrides
toString in class Hashtable


 Class ProviderException

Class java.security.ProviderException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.security.ProviderException

public class ProviderException
extends RuntimeException

A runtime exception for Provider exceptions (such as misconfiguration errors), which may be subclassed by Providers to throw specialized, provider-specific runtime errors.


 ProviderException Members

ProviderException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ProviderException() | Constructs a ProviderException with no detail message.
ProviderException(String) | Constructs a ProviderException with the specified detail message.


 ProviderException.ProviderException

ProviderException.ProviderException

Syntax 1
public ProviderException()
Description
Constructs a ProviderException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public ProviderException( String s )
Parameters
s
the detail message.
Description
Constructs a ProviderException with the specified detail message. A detail message is a String that describes this particular exception.


 Interface PublicKey

Interface java.security.PublicKey

This Package | All Packages

public interface PublicKey
extends Key

A public key. This interface contains no methods or constants. It merely serves to group (and provide type safety for) all public key interfaces. Note: The specialized public key interfaces extend this interface. See, for example, the DSAPublicKey interface in java.security.interfaces.

See Also:
Key, PublicKey, Certificate, initVerify, DSAPublicKey


 Class SecureRandom

Class java.security.SecureRandom

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Random
           |
           +----java.security.SecureRandom

public class SecureRandom
extends Random

This class provides a crytpographically strong pseudo-random number generator based on the SHA-1 hash algorithm.

The calls inherited from Random will be implemented in terms of the strengthened functionality.

See Also:
Random


 SecureRandom Members

SecureRandom Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SecureRandom() | This empty constructor automatically seeds the generator.
SecureRandom(byte[]) | This constructor uses a user-provided seed in preference to the self-seeding algorithm referred to in the empty constructor description.

Methods
Name | Description
getSeed(int) | Returns the given number of seed bytes, computed using the seed generation algorithm that this class uses to seed itself.
next(int) | Generates an integer containing the user-specified number of pseudo-random bits (right justified, with leading zeros).
nextBytes(byte[]) | Generates a user-specified number of random bytes.
setSeed(byte[]) | Reseeds this random object.
setSeed(long) | Reseeds this random object, using the eight bytes contained in the given long seed.


 SecureRandom.SecureRandom

SecureRandom.SecureRandom

Syntax 1
public SecureRandom()
Description
This empty constructor automatically seeds the generator. We attempt to provide sufficient seed bytes to completely randomize the internal state of the generator (20 bytes). Note, however, that our seed generation algorithm has not been thoroughly studied or widely deployed. It relies on counting the number of times that the calling thread can yield while waiting for another thread to sleep for a specified interval.

The first time this constructor is called in a given Virtual Machine, it may take several seconds of CPU time to seed the generator, depending on the underlying hardware. Successive calls run quickly because they rely on the same (internal) pseudo-random number generator for their seed bits.

The seeding procedure implemented by this constructor ensures that the sequence of pseudo-random bytes produced by each SecureRandom instance yields no useful information about the byte-sequence produced by any other instance. If however, the user wishes to produce multiple instances with truly unrelated seeds, the following code yields the desired result (at substantial CPU cost per instance!):

 SecureRandom rnd = new SecureRandom(SecureRandom.getSeed(20));

Syntax 2
public SecureRandom( byte seed[] )
Parameters
seed
the seed.
Description
This constructor uses a user-provided seed in preference to the self-seeding algorithm referred to in the empty constructor description. It may be preferable to the empty constructor if the caller has access to high-quality random bytes from some physical device (for example, a radiation detector or a noisy diode).


 SecureRandom.getSeed

SecureRandom.getSeed

Syntax
public static byte[] getSeed( int numBytes )
Parameters
numBytes
the number of seed bytes to generate.
Returns
the seed bytes.
Description
Returns the given number of seed bytes, computed using the seed generation algorithm that this class uses to seed itself. This call may be used to seed other random number generators. While we attempt to return a "truly random" sequence of bytes, we do not know exactly how random the bytes returned by this call are. (See the empty constructor SecureRandom for a brief description of the underlying algorithm.) The prudent user will err on the side of caution and get extra seed bytes, although it should be noted that seed generation is somewhat costly.


 SecureRandom.next

SecureRandom.next

Syntax
protected final int next( int numBits )
Parameters
numBits
number of pseudo-random bits to be generated, where 0 <= numBits <= 32.
Description
Generates an integer containing the user-specified number of pseudo-random bits (right justified, with leading zeros). This method overrides a java.util.Random method, and serves to provide a source of random bits to all of the methods inherited from that class (for example, nextInt, nextLong, and nextFloat).

Overrides
next in class Random


 SecureRandom.nextBytes

SecureRandom.nextBytes

Syntax
public synchronized void nextBytes( byte bytes[] )
Parameters
bytes
the array to be filled in with random bytes.
Description
Generates a user-specified number of random bytes. This method is used as the basis of all random entities returned by this class (except seed bytes). Thus, it may be overridden to change the behavior of the class.

Overrides
nextBytes in class Random


 SecureRandom.setSeed

SecureRandom.setSeed

Syntax 1
public synchronized void setSeed( byte seed[] )
Parameters
seed
the seed.
Description
Reseeds this random object. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness.

Syntax 2
public void setSeed( long seed )
Parameters
seed
the seed.
Description
Reseeds this random object, using the eight bytes contained in the given long seed. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness.

This method is defined for compatibility with java.util.Random.

Overrides
setSeed in class Random


 Class Security

Class java.security.Security

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.Security

public final class Security
extends Object

This class centralizes all security properties and common security methods. One of its primary uses is to manage providers.


 Security Members

Security Members

Class Overview | This Package | All Packages

Methods
Name | Description
addProvider(Provider) | Adds a provider to the next position available.
getAlgorithmProperty(String, String) | Gets a specified property for an algorithm.
getProperty(String) | Gets a security property.
getProvider(String) | Returns the provider installed with the specified name, if any.
getProviders() | Returns all providers currently installed.
insertProviderAt(Provider, int) | Adds a new provider, at a specified position.
removeProvider(String) | Removes the provider with the specified name.
setProperty(String, String) | Sets a security property.


 Security.addProvider

Security.addProvider

Syntax
public static int addProvider( Provider provider )
Parameters
provider
the provider to be added.
Returns
the preference position in which the provider was added, or -1 if the provider was not added because it is already installed.
Description
Adds a provider to the next position available.

See Also
getProvider, removeProvider


 Security.getAlgorithmProperty

Security.getAlgorithmProperty

Syntax
public static String getAlgorithmProperty( String algName, String propName )
Parameters
algName
the algorithm name.
propName
the name of the property to get.
Returns
the value of the specified property.
Description
Gets a specified property for an algorithm. The algorithm name should be a standard name. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names. One possible use is by specialized algorithm parsers, which may map classes to algorithms which they understand (much like Key parsers do).


 Security.getProperty

Security.getProperty

Syntax
public static String getProperty( String key )
Parameters
key
the key of the property being retrieved.
Returns
the valeu of the security property corresponding to key.
Description
Gets a security property.


 Security.getProvider

Security.getProvider

Syntax
public static Provider getProvider( String name )
Parameters
name
the name of the provider to get.
Returns
the provider of the specified name.
Description
Returns the provider installed with the specified name, if any. Returns null if no provider with the speicified name is installed.

See Also
removeProvider, addProvider


 Security.getProviders

Security.getProviders

Syntax
public static Provider[] getProviders()
Returns
an array of all providers currently installed.
Description
Returns all providers currently installed.


 Security.insertProviderAt

Security.insertProviderAt

Syntax
public static int insertProviderAt( Provider provider, int position )
Parameters
provider
the provider to be added.
position
the preference position that the caller would like for this provider.
Returns
the actual preference position in which the provider was added, or -1 if the provider was not added because it is already installed.
Description
Adds a new provider, at a specified position. The position is the preference order in which providers are searched for requested algorithms. Note that it is not guaranteed that this preference will be respected. The position is 1-based, that is, 1 is most preferred, followed by 2, and so on. Sometimes it will be legal to add a provider, but only in the last position, in which case the position argument will be ignored.

A provider cannot be added if it is already installed.

See Also
getProvider, removeProvider


 Security.removeProvider

Security.removeProvider

Syntax
public static void removeProvider( String name )
Parameters
name
the name of the provider to remove.
Description
Removes the provider with the specified name. This method returns silently if the provider is not installed.

See Also
getProvider, addProvider


 Security.setProperty

Security.setProperty

Syntax
public static void setProperty( String key, String datum )
Parameters
key
the name of the property to be set.
datum
the value of the property to be set.
Description
Sets a security property.


 Class Signature

Class java.security.Signature

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.Signature

public abstract class Signature
extends Object

This Signature class is used to provide the functionality of a digital signature algorithm, such as RSA with MD5 or DSA. Digital signatures are used for authentication and integrity assurance of digital data.

Like other algorithm-based classes in Java Security, the Signature class has two major components:

Digital Signature API (Application Program Interface)
This is the interface of methods called by applications needing digital signature services. The API consists of all public methods.
Digital Signature SPI (Service Provider Interface)
This is the interface implemented by providers that supply specific algorithms. It consists of all methods whose names are prefixed by engine. Each such method is called by a correspondingly-named public API method. For example, the engineSign method is called by the sign method. The SPI methods are abstract; providers must supply a concrete implementation.

Also like other algorithm-based classes in Java Security, Signature provides implementation-independent algorithms, whereby a caller (application code) requests a particular signature algorithm and is handed back a properly initialized Signature object. It is also possible, if desired, to request a particular algorithm from a particular provider. See the getInstance methods.

Thus, there are two ways to request a Signature algorithm object: by specifying either just an algorithm name, or both an algorithm name and a package provider.

  • If just an algorithm name is specified, the system will determine if there is an implementation of the algorithm requested available in the environment, and if there is more than one, if there is a preferred one.
  • If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the algorithm in the package requested, and throw an exception if there is not.

A Signature object can be used to generate and verify digital signatures.

There are three phases to the use of a Signature object for either signing data or verifying a signature:

  1. Initialization, with either
    • a public key, which initializes the signature for verification (see initVerify), or
    • a private key, which initializes the signature for signing (see initSign).

  2. Updating

    Depending on the type of initialization, this will update the bytes to be signed or verified. See the update methods.

  3. Signing or Verifying

    a signature on all updated bytes. See sign and verify.


 Signature Members

Signature Members

Class Overview | This Package | All Packages

Fields
Name | Description
SIGN | Possible state value, signifying that this signature object has been initialized for signing.
state | Current state of this signature object.
UNINITIALIZED | Possible state value, signifying that this signature object has not yet been initialized.
VERIFY | Possible state value, signifying that this signature object has been initialized for verification.

Constructors
Name | Description
Signature(String) | Creates a Signature object for the specified algorithm.

Methods
Name | Description
clone() | Returns a clone if the implementation is cloneable.
engineGetParameter(String) | SPI: Gets the value of the specified algorithm parameter.
engineInitSign(PrivateKey) | SPI: Initializes this signature object with the specified private key for signing operations.
engineInitVerify(PublicKey) | SPI: Initializes this signature object with the specified public key for verification operations.
engineSetParameter(String, Object) | SPI: Sets the specified algorithm parameter to the specified value.
engineSign() | SPI: Returns the signature bytes of all the data updated so far.
engineUpdate(byte) | SPI: Updates the data to be signed or verified using the specified byte.
engineUpdate(byte[], int, int) | SPI: Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.
engineVerify(byte[]) | SPI: Verifies the passed-in signature.
getAlgorithm() | Returns the name of the algorithm for this signature object.
getInstance(String) | Generates a Signature object that implements the specified algorithm.
getInstance(String, String) | Generates a Signature object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.
getParameter(String) | Gets the value of the specified algorithm parameter.
initSign(PrivateKey) | Initialize this object for signing.
initVerify(PublicKey) | Initializes this object for verification.
setParameter(String, Object) | Sets the specified algorithm parameter to the specified value.
sign() | Returns the signature bytes of all the data updated.
toString() | Returns a string representation of this signature object, providing information that includes the state of the object and the name of the algorithm used.
update(byte) | Updates the data to be signed or verified by a byte.
update(byte[]) | Updates the data to be signed or verified, using the specified array of bytes.
update(byte[], int, int) | Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.
verify(byte[]) | Verifies the passed-in signature.


 Signature.SIGN

Signature.SIGN

Syntax
protected static final int SIGN
Description
Possible state value, signifying that this signature object has been initialized for signing.


 Signature.state

Signature.state

Syntax
protected int state
Description
Current state of this signature object.


 Signature.UNINITIALIZED

Signature.UNINITIALIZED

Syntax
protected static final int UNINITIALIZED
Description
Possible state value, signifying that this signature object has not yet been initialized.


 Signature.VERIFY

Signature.VERIFY

Syntax
protected static final int VERIFY
Description
Possible state value, signifying that this signature object has been initialized for verification.


 Signature.Signature

Signature.Signature

Syntax
protected Signature( String algorithm )
Parameters
algorithm
the standard string name of the algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Description
Creates a Signature object for the specified algorithm.


 Signature.clone

Signature.clone

Syntax
public Object clone() throws CloneNotSupportedException
Returns
a clone if the implementation is cloneable.
Description
Returns a clone if the implementation is cloneable.

Exceptions
CloneNotSupportedException if this is called on an implementation that does not support Cloneable.
Overrides
clone in class Object


 Signature.engineGetParameter

Signature.engineGetParameter

Syntax
protected abstract Object engineGetParameter( String param ) throws InvalidParameterException
Parameters
param
the string name of the parameter.
Returns
the object that represents the parameter value, or null if there is none.
Description
SPI: Gets the value of the specified algorithm parameter. This method supplies a general-purpose mechanism through which it is possible to get the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

Exceptions
InvalidParameterException if param is an invalid parameter for this engine, or another exception occurs while trying to get this parameter.


 Signature.engineInitSign

Signature.engineInitSign

Syntax
protected abstract void engineInitSign( PrivateKey privateKey ) throws InvalidKeyException
Parameters
privateKey
the private key of the identity whose signature will be generated.
Description
SPI: Initializes this signature object with the specified private key for signing operations.

Exceptions
InvalidKeyException if the key is improperly encoded, parameters are missing, and so on.


 Signature.engineInitVerify

Signature.engineInitVerify

Syntax
protected abstract void engineInitVerify( PublicKey publicKey ) throws InvalidKeyException
Parameters
publicKey
the public key of the identity whose signature is going to be verified.
Description
SPI: Initializes this signature object with the specified public key for verification operations.

Exceptions
InvalidKeyException if the key is improperly encoded, parameters are missing, and so on.


 Signature.engineSetParameter

Signature.engineSetParameter

Syntax
protected abstract void engineSetParameter( String param, Object value ) throws InvalidParameterException
Parameters
param
the string identifier of the parameter.
value
the parameter value.
Description
SPI: Sets the specified algorithm parameter to the specified value. This method supplies a general-purpose mechanism through which it is possible to set the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

Exceptions
InvalidParameterException if param is an invalid parameter for this signature algorithm engine, the parameter is already set and cannot be set again, a security exception occurs, and so on.


 Signature.engineSign

Signature.engineSign

Syntax
protected abstract byte[] engineSign() throws SignatureException
Returns
the signature bytes of the signing operation's result.
Description
SPI: Returns the signature bytes of all the data updated so far. The signature returned is X.509-encoded. For more information about the X.509 encoding, see "Why should I care about X.509 certificates?"

Exceptions
SignatureException if the engine is not initialized properly.


 Signature.engineUpdate

Signature.engineUpdate

Syntax 1
protected abstract void engineUpdate( byte b ) throws SignatureException
Parameters
b
the byte to use for the update.
Description
SPI: Updates the data to be signed or verified using the specified byte.

Exceptions
SignatureException if the engine is not initialized properly.

Syntax 2
protected abstract void engineUpdate( byte b[], int off, int len ) throws SignatureException
Parameters
data
the array of bytes.
off
the offset to start from in the array of bytes.
len
the number of bytes to use, starting at offset.
Description
SPI: Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.

Exceptions
SignatureException if the engine is not initialized properly.


 Signature.engineVerify

Signature.engineVerify

Syntax
protected abstract boolean engineVerify( byte sigBytes[] ) throws SignatureException
Parameters
sigBytes
the signature bytes to be verified.
Returns
true if the signature was verified, false if not.
Description
SPI: Verifies the passed-in signature. The signature bytes are expected to be X.509-encoded. For more information about the X.509 encoding, see "Why should I care about X.509 certificates?"

Exceptions
SignatureException if the engine is not initialized properly, or the passed-in signature is improperly encoded or of the wrong type, etc.


 Signature.getAlgorithm

Signature.getAlgorithm

Syntax
public final String getAlgorithm()
Returns
the name of the algorithm for this signature object.
Description
Returns the name of the algorithm for this signature object.


 Signature.getInstance

Signature.getInstance

Syntax 1
public static Signature getInstance( String algorithm ) throws NoSuchAlgorithmException
Parameters
algorithm
the standard name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
Returns
the new Signature object.
Description
Generates a Signature object that implements the specified algorithm. If the default provider package contains a Signature subclass implementing the algorithm, an instance of that subclass is returned. If the algorithm is not available in the default package, other packages are searched.

Exceptions
NoSuchAlgorithmException if the algorithm is not available in the environment.

Syntax 2
public static Signature getInstance( String algorithm, String provider ) throws NoSuchAlgorithmException, NoSuchProviderException
Parameters
algorithm
the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
provider
the name of the provider.
Returns
the new Signature object.
Description
Generates a Signature object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.

Exceptions
NoSuchAlgorithmException if the algorithm is not available in the package supplied by the requested provider.
Exceptions
NoSuchProviderException if the provider is not available in the environment.
See Also
Provider


 Signature.getParameter

Signature.getParameter

Syntax
public final Object getParameter( String param ) throws InvalidParameterException
Parameters
param
the string name of the parameter.
Returns
the object that represents the parameter value, or null if there is none.
Description
Gets the value of the specified algorithm parameter. This method supplies a general-purpose mechanism through which it is possible to get the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

Exceptions
InvalidParameterException if param is an invalid parameter for this engine, or another exception occurs while trying to get this parameter.


 Signature.initSign

Signature.initSign

Syntax
public final void initSign( PrivateKey privateKey ) throws InvalidKeyException
Parameters
privateKey
the private key of the identity whose signature is going to be generated.
Description
Initialize this object for signing. If this method is called again with a different argument, it negates the effect of this call.

Exceptions
InvalidKeyException if the key is invalid.


 Signature.initVerify

Signature.initVerify

Syntax
public final void initVerify( PublicKey publicKey ) throws InvalidKeyException
Parameters
publicKey
the public key of the identity whose signature is going to be verified.
Description
Initializes this object for verification. If this method is called again with a different argument, it negates the effect of this call.

Exceptions
InvalidKeyException if the key is invalid.


 Signature.setParameter

Signature.setParameter

Syntax
public final void setParameter( String param, Object value ) throws InvalidParameterException
Parameters
param
the string identifier of the parameter.
value
the parameter value.
Description
Sets the specified algorithm parameter to the specified value. This method supplies a general-purpose mechanism through which it is possible to set the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

Exceptions
InvalidParameterException if param is an invalid parameter for this signature algorithm engine, the parameter is already set and cannot be set again, a security exception occurs, and so on.


 Signature.sign

Signature.sign

Syntax
public final byte[] sign() throws SignatureException
Returns
the signature bytes of the signing operation's result.
Description
Returns the signature bytes of all the data updated. The signature returned is X.509-encoded.

A call to this method resets this signature object to the state it was in when previously initialized for signing via a call to initSign(PrivateKey). That is, the object is reset and available to generate another signature from the same signer, if desired, via new calls to update and sign.

Exceptions
SignatureException if this signature object is not initialized properly.


 Signature.toString

Signature.toString

Syntax
public String toString()
Returns
a string representation of this signature object.
Description
Returns a string representation of this signature object, providing information that includes the state of the object and the name of the algorithm used.

Overrides
toString in class Object


 Signature.update

Signature.update

Syntax 1
public final void update( byte b ) throws SignatureException
Parameters
b
the byte to use for the update.
Description
Updates the data to be signed or verified by a byte.

Exceptions
SignatureException if this signature object is not initialized properly.

Syntax 2
public final void update( byte data[] ) throws SignatureException
Parameters
data
the byte array to use for the update.
Description
Updates the data to be signed or verified, using the specified array of bytes.

Exceptions
SignatureException if this signature object is not initialized properly.

Syntax 3
public final void update( byte data[], int off, int len ) throws SignatureException
Parameters
data
the array of bytes.
off
the offset to start from in the array of bytes.
len
the number of bytes to use, starting at offset.
Description
Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.

Exceptions
SignatureException if this signature object is not initialized properly.


 Signature.verify

Signature.verify

Syntax
public final boolean verify( byte signature[] ) throws SignatureException
Parameters
signature
the signature bytes to be verified.
Returns
true if the signature was verified, false if not.
Description
Verifies the passed-in signature. The signature bytes are expected to be X.509-encoded.

A call to this method resets this signature object to the state it was in when previously initialized for verification via a call to initVerify(PublicKey). That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

Exceptions
SignatureException if this signature object is not initialized properly, or the passed-in signature is improperly encoded or of the wrong type, etc.


 Class SignatureException

Class java.security.SignatureException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.SignatureException

public class SignatureException
extends Exception

This is the generic Signature exception.


 SignatureException Members

SignatureException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SignatureException() | Constructs a SignatureException with no detail message.
SignatureException(String) | Constructs a SignatureException with the specified detail message.


 SignatureException.SignatureException

SignatureException.SignatureException

Syntax 1
public SignatureException()
Description
Constructs a SignatureException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public SignatureException( String msg )
Parameters
msg
the detail message.
Description
Constructs a SignatureException with the specified detail message. A detail message is a String that describes this particular exception.


 Class Signer

Class java.security.Signer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.security.Identity
           |
           +----java.security.Signer

public abstract class Signer
extends Identity

This class is used to represent an Identity that can also digitally sign data.

The management of a signer's private keys is an important and sensitive issue that should be handled by subclasses as appropriate to their intended use.

See Also:
Identity


 Signer Members

Signer Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Signer() | Creates a signer.
Signer(String) | Creates a signer with the specified identity name.
Signer(String, IdentityScope) | Creates a signer with the specified identity name and scope.

Methods
Name | Description
getPrivateKey() | Returns this signer's private key.
setKeyPair(KeyPair) | Sets the key pair (public key and private key) for this signer.
toString() | Returns a string of information about the signer.


 Signer.Signer

Signer.Signer

Syntax 1
protected Signer()
Description
Creates a signer. This constructor should only be used for serialization.

Syntax 2
public Signer( String name )
Parameters
name
the identity name.
Description
Creates a signer with the specified identity name.

Syntax 3
public Signer( String name, IdentityScope scope ) throws KeyManagementException
Parameters
name
the identity name.
scope
the scope of the identity.
Description
Creates a signer with the specified identity name and scope.

Exceptions
KeyManagementException if there is already an identity with the same name in the scope.


 Signer.getPrivateKey

Signer.getPrivateKey

Syntax
public PrivateKey getPrivateKey()
Returns
this signer's private key, or null if the private key has not yet been set.
Description
Returns this signer's private key.


 Signer.setKeyPair

Signer.setKeyPair

Syntax
public final void setKeyPair( KeyPair pair ) throws InvalidParameterException, KeyException
Parameters
pair
an initialized key pair.
Description
Sets the key pair (public key and private key) for this signer.

Exceptions
InvalidParameterException if the key pair is not properly initialized.
Exceptions
KeyException if the key pair cannot be set for any other reason.


 Signer.toString

Signer.toString

Syntax
public String toString()
Returns
a string of information about the signer.
Description
Returns a string of information about the signer.

Overrides
toString in class Identity


 Package java.security.acl

Package java.security.acl

All Packages

Interfaces

  • Acl
  • AclEntry
  • Group
  • Owner
  • Permission

    • Exceptions

  • AclNotFoundException
  • LastOwnerException
  • NotOwnerException


 Interface Acl

Interface java.security.acl.Acl

Interface Members | This Package | All Packages

public interface Acl
extends Owner

Interface representing an Access Control List (ACL). An Access Control List is a data structure used to guard access to resources.

An ACL can be thought of as a data structure with multiple ACL entries. Each ACL entry, of interface type AclEntry, contains a set of permissions associated with a particular principal. (A principal represents an entity such as an individual user or a group). Additionally, each ACL entry is specified as being either positive or negative. If positive, the permissions are to be granted to the associated principal. If negative, the permissions are to be denied.

The ACL Entries in each ACL observe the following rules:

  • Each principal can have at most one positive ACL entry and one negative entry; that is, multiple positive or negative ACL entries are not allowed for any principal. Each entry specifies the set of permissions that are to be granted (if positive) or denied (if negative).

  • If there is no entry for a particular principal, then the principal is considered to have a null (empty) permission set.

  • If there is a positive entry that grants a principal a particular permission, and a negative entry that denies the principal the same permission, the result is as though the permission was never granted or denied.

  • Individual permissions always override permissions of the group(s) to which the individual belongs. That is, individual negative permissions (specific denial of permissions) override the groups' positive permissions. And individual positive permissions override the groups' negative permissions.

The java.security.acl package provides the interfaces to the ACL and related data structures (ACL entries, groups, permissions, etc.), and the sun.security.acl classes provide a default implementation of the interfaces. For example, java.security.acl.Acl provides the interface to an ACL and the sun.security.acl.AclImpl class provides the default implementation of the interface.

The java.security.acl.Acl interface extends the java.security.acl.Owner interface. The Owner interface is used to maintain a list of owners for each ACL. Only owners are allowed to modify an ACL. For example, only an owner can call the ACL's addEntry method to add a new ACL entry to the ACL.

See Also:
AclEntry, Owner, getPermissions


 Acl Members

Acl Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addEntry(Principal, AclEntry) | Adds an ACL entry to this ACL.
checkPermission(Principal, Permission) | Checks whether or not the specified principal has the specified permission.
entries() | Returns an enumeration of the entries in this ACL.
getName() | Returns the name of this ACL.
getPermissions(Principal) | Returns an enumeration for the set of allowed permissions for the specified principal (representing an entity such as an individual or a group).
removeEntry(Principal, AclEntry) | Removes an ACL entry from this ACL.
setName(Principal, String) | Sets the name of this ACL.
toString() | Returns a string representation of the ACL contents.


 Acl.addEntry

Acl.addEntry

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean addEntry( Principal caller, AclEntry entry ) throws NotOwnerException
Parameters
caller
the principal invoking this method. It must be an owner of this ACL.
entry
the ACL entry to be added to this ACL.
Returns
true on success, false if an entry of the same type (positive or negative) for the same principal is already present in this ACL.
Description
Adds an ACL entry to this ACL. An entry associates a principal (e.g., an individual or a group) with a set of permissions. Each principal can have at most one positive ACL entry (specifying permissions to be granted to the principal) and one negative ACL entry (specifying permissions to be denied). If there is already an ACL entry of the same type (negative or positive) already in the ACL, false is returned.

Exceptions
NotOwnerException if the caller principal is not an owner of this ACL.


 Acl.checkPermission

Acl.checkPermission

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean checkPermission( Principal principal, Permission permission )
Parameters
principal
the principal, assumed to be a valid authenticated Principal.
permission
the permission to be checked for.
Returns
true if the principal has the specified permission, false otherwise.
Description
Checks whether or not the specified principal has the specified permission. If it does, true is returned, otherwise false is returned. More specifically, this method checks whether the passed permission is a member of the allowed permission set of the specified principal. The allowed permission set is determined by the same algorithm as is used by the getPermissions method.

See Also
getPermissions


 Acl.entries

Acl.entries

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Enumeration entries()
Returns
an enumeration of the entries in this ACL.
Description
Returns an enumeration of the entries in this ACL. Each element in the enumeration is of type AclEntry.


 Acl.getName

Acl.getName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getName()
Returns
the name of this ACL.
Description
Returns the name of this ACL.


 Acl.getPermissions

Acl.getPermissions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Enumeration getPermissions( Principal user )
Parameters
user
the principal whose permission set is to be returned.
Returns
the permission set specifying the permissions the principal is allowed.
Description
Returns an enumeration for the set of allowed permissions for the specified principal (representing an entity such as an individual or a group). This set of allowed permissions is calculated as follows:

  • If there is no entry in this Access Control List for the specified principal, an empty permission set is returned.

  • Otherwise, the principal's group permission sets are determined. (A principal can belong to one or more groups, where a group is a group of principals, represented by the Group interface.) The group positive permission set is the union of all the positive permissions of each group that the principal belongs to. The group negative permission set is the union of all the negative permissions of each group that the principal belongs to. If there is a specific permission that occurs in both the positive permission set and the negative permission set, it is removed from both.

    The individual positive and negative permission sets are also determined. The positive permission set contains the permissions specified in the positive ACL entry (if any) for the principal. Similarly, the negative permission set contains the permissions specified in the negative ACL entry (if any) for the principal. The individual positive (or negative) permission set is considered to be null if there is not a positive (negative) ACL entry for the principal in this ACL.

    The set of permissions granted to the principal is then calculated using the simple rule that individual permissions always override the group permissions. That is, the principal's individual negative permission set (specific denial of permissions) overrides the group positive permission set, and the principal's individual positive permission set overrides the group negative permission set.


 Acl.removeEntry

Acl.removeEntry

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean removeEntry( Principal caller, AclEntry entry ) throws NotOwnerException
Parameters
caller
the principal invoking this method. It must be an owner of this ACL.
entry
the ACL entry to be removed from this ACL.
Returns
true on success, false if the entry is not part of this ACL.
Description
Removes an ACL entry from this ACL.

Exceptions
NotOwnerException if the caller principal is not an owner of this Acl.


 Acl.setName

Acl.setName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setName( Principal caller, String name ) throws NotOwnerException
Parameters
caller
the principal invoking this method. It must be an owner of this ACL.
name
the name to be given to this ACL.
Description
Sets the name of this ACL.

Exceptions
NotOwnerException if the caller principal is not an owner of this ACL.


 Acl.toString

Acl.toString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String toString()
Returns
a string representation of the ACL contents.
Description
Returns a string representation of the ACL contents.

Overrides
toString in class Object


 Interface AclEntry

Interface java.security.acl.AclEntry

Interface Members | This Package | All Packages

public interface AclEntry
extends Cloneable

This is the interface used for representing one entry in an Access Control List (ACL).

An ACL can be thought of as a data structure with multiple ACL entry objects. Each ACL entry object contains a set of permissions associated with a particular principal. (A principal represents an entity such as an individual user or a group). Additionally, each ACL entry is specified as being either positive or negative. If positive, the permissions are to be granted to the associated principal. If negative, the permissions are to be denied. Each principal can have at most one positive ACL entry and one negative entry; that is, multiple positive or negative ACL entries are not allowed for any principal. Note: ACL entries are by default positive. An entry becomes a negative entry only if the setNegativePermissions method is called on it.

See Also:
Acl


 AclEntry Members

AclEntry Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addPermission(Permission) | Adds the specified permission to this ACL entry.
checkPermission(Permission) | Checks if the specified permission is part of the permission set in this entry.
clone() | Clones this ACL entry.
getPrincipal() | Returns the principal for which permissions are granted or denied by this ACL entry.
isNegative() | Returns true if this is a negative ACL entry (one denying the associated principal the set of permissions in the entry), false otherwise.
permissions() | Returns an enumeration of the permissions in this ACL entry.
removePermission(Permission) | Removes the specified permission from this ACL entry.
setNegativePermissions() | Sets this ACL entry to be a negative one.
setPrincipal(Principal) | Specifies the principal for which permissions are granted or denied by this ACL entry.
toString() | Returns a string representation of the contents of this ACL entry.


 AclEntry.addPermission

AclEntry.addPermission

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean addPermission( Permission permission )
Parameters
permission
the permission to be associated with the principal in this entry.
Returns
true if the permission was added, false if the permission was already part of this entry's permission set.
Description
Adds the specified permission to this ACL entry. Note: An entry can have multiple permissions.


 AclEntry.checkPermission

AclEntry.checkPermission

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean checkPermission( Permission permission )
Parameters
permission
the permission to be checked for.
Returns
true if the permission is part of the permission set in this entry, false otherwise.
Description
Checks if the specified permission is part of the permission set in this entry.


 AclEntry.clone

AclEntry.clone

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object clone()
Returns
a clone of this ACL entry.
Description
Clones this ACL entry.

Overrides
clone in class Object


 AclEntry.getPrincipal

AclEntry.getPrincipal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Principal getPrincipal()
Returns
the principal associated with this entry.
Description
Returns the principal for which permissions are granted or denied by this ACL entry. Returns null if there is no principal set for this entry yet.


 AclEntry.isNegative

AclEntry.isNegative

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isNegative()
Returns
true if this is a negative ACL entry, false if it's not.
Description
Returns true if this is a negative ACL entry (one denying the associated principal the set of permissions in the entry), false otherwise.


 AclEntry.permissions

AclEntry.permissions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Enumeration permissions()
Returns
an enumeration of the permissions in this ACL entry.
Description
Returns an enumeration of the permissions in this ACL entry.


 AclEntry.removePermission

AclEntry.removePermission

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean removePermission( Permission permission )
Parameters
permission
the permission to be removed from this entry.
Returns
true if the permission is removed, false if the permission was not part of this entry's permission set.
Description
Removes the specified permission from this ACL entry.


 AclEntry.setNegativePermissions

AclEntry.setNegativePermissions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setNegativePermissions()
Description
Sets this ACL entry to be a negative one. That is, the associated principal (e.g., a user or a group) will be denied the permission set specified in the entry. Note: ACL entries are by default positive. An entry becomes a negative entry only if this setNegativePermissions method is called on it.


 AclEntry.setPrincipal

AclEntry.setPrincipal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean setPrincipal( Principal user )
Parameters
user
the principal to be set for this entry.
Returns
true if the principal is set, false if there was already a principal set for this entry.
Description
Specifies the principal for which permissions are granted or denied by this ACL entry. If a principal was already set for this ACL entry, false is returned, otherwise true is returned.


 AclEntry.toString

AclEntry.toString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String toString()
Returns
a string representation of the contents.
Description
Returns a string representation of the contents of this ACL entry.

Overrides
toString in class Object


 Class AclNotFoundException

Class java.security.acl.AclNotFoundException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.acl.AclNotFoundException

public class AclNotFoundException
extends Exception

This is an exception that is thrown whenever a reference is made to a non-existent ACL (Access Control List).


 AclNotFoundException Members

AclNotFoundException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
AclNotFoundException() | Constructs an AclNotFoundException.


 AclNotFoundException.AclNotFoundException

AclNotFoundException.AclNotFoundException

Syntax
public AclNotFoundException()
Description
Constructs an AclNotFoundException.


 Interface Group

Interface java.security.acl.Group

Interface Members | This Package | All Packages

public interface Group
extends Principal

This interface is used to represent a group of principals. (A principal represents an entity such as an individual user or a company).

Note that Group extends Principal. Thus, either a Principal or a Group can be passed as an argument to methods containing a Principal parameter. For example, you can add either a Principal or a Group to a Group object by calling the object's addMember method, passing it the Principal or Group.


 Group Members

Group Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addMember(Principal) | Adds the specified member to the group.
isMember(Principal) | Returns true if the passed principal is a member of the group.
members() | Returns an enumeration of the members in the group.
removeMember(Principal) | Removes the specified member from the group.


 Group.addMember

Group.addMember

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean addMember( Principal user )
Parameters
user
the principal to add to this group.
Returns
true if the member was successfully added, false if the principal was already a member.
Description
Adds the specified member to the group.


 Group.isMember

Group.isMember

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isMember( Principal member )
Parameters
member
the principal whose membership is to be checked.
Returns
true if the principal is a member of this group, false otherwise.
Description
Returns true if the passed principal is a member of the group. This method does a recursive search, so if a principal belongs to a group which is a member of this group, true is returned.


 Group.members

Group.members

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Enumeration members()
Returns
an enumeration of the group members.
Description
Returns an enumeration of the members in the group. The returned objects can be instances of either Principal or Group (which is a subclass of Principal).


 Group.removeMember

Group.removeMember

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean removeMember( Principal user )
Parameters
user
the principal to remove from this group.
Returns
true if the principal was removed, or false if the principal was not a member.
Description
Removes the specified member from the group.


 Class LastOwnerException

Class java.security.acl.LastOwnerException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.acl.LastOwnerException

public class LastOwnerException
extends Exception

This is an exception that is thrown whenever an attempt is made to delete the last owner of an Access Control List.

See Also:
deleteOwner


 LastOwnerException Members

LastOwnerException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
LastOwnerException() | Constructs a LastOwnerException.


 LastOwnerException.LastOwnerException

LastOwnerException.LastOwnerException

Syntax
public LastOwnerException()
Description
Constructs a LastOwnerException.


 Class NotOwnerException

Class java.security.acl.NotOwnerException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.security.acl.NotOwnerException

public class NotOwnerException
extends Exception

This is an exception that is thrown whenever the modification of an object (such as an Access Control List) is only allowed to be done by an owner of the object, but the Principal attempting the modification is not an owner.


 NotOwnerException Members

NotOwnerException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NotOwnerException() | Constructs a NotOwnerException.


 NotOwnerException.NotOwnerException

NotOwnerException.NotOwnerException

Syntax
public NotOwnerException()
Description
Constructs a NotOwnerException.


 Interface Owner

Interface java.security.acl.Owner

Interface Members | This Package | All Packages

public interface Owner

Interface for managing owners of Access Control Lists (ACLs) or ACL configurations. (Note that the Acl interface in the java.security.acl package extends this Owner interface.) The initial owner Principal should be specified as an argument to the constructor of the class implementing this interface.

See Also:
Acl


 Owner Members

Owner Members

Interface Overview | This Package | All Packages

Methods
Name | Description
addOwner(Principal, Principal) | Adds an owner.
deleteOwner(Principal, Principal) | Deletes an owner.
isOwner(Principal) | Returns true if the given principal is an owner of the ACL.


 Owner.addOwner

Owner.addOwner

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean addOwner( Principal caller, Principal owner ) throws NotOwnerException
Parameters
caller
the principal invoking this method. It must be an owner of the ACL.
owner
the owner that should be added to the list of owners.
Returns
true if successful, false if owner is already an owner.
Description
Adds an owner. Only owners can modify ACL contents. The caller principal must be an owner of the ACL in order to invoke this method. That is, only an owner can add another owner. The initial owner is configured at ACL construction time.

Exceptions
NotOwnerException if the caller principal is not an owner of the ACL.


 Owner.deleteOwner

Owner.deleteOwner

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean deleteOwner( Principal caller, Principal owner ) throws NotOwnerException, LastOwnerException
Parameters
caller
the principal invoking this method. It must be an owner of the ACL.
owner
the owner to be removed from the list of owners.
Returns
true if the owner is removed, false if the owner is not part of the list of owners.
Description
Deletes an owner. If this is the last owner in the ACL, an exception is raised.

The caller principal must be an owner of the ACL in order to invoke this method.

Exceptions
NotOwnerException if the caller principal is not an owner of the ACL.
Exceptions
LastOwnerException if there is only one owner left, so that deleteOwner would leave the ACL owner-less.


 Owner.isOwner

Owner.isOwner

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isOwner( Principal owner )
Parameters
owner
the principal to be checked to determine whether or not it is an owner.
Returns
true if the passed principal is in the list of owners, false if not.
Description
Returns true if the given principal is an owner of the ACL.


 Interface Permission

Interface java.security.acl.Permission

Interface Members | This Package | All Packages

public interface Permission

This interface represents a permission, such as that used to grant a particular type of access to a resource.


 Permission Members

Permission Members

Interface Overview | This Package | All Packages

Methods
Name | Description
equals(Object) | Returns true if the object passed matches the permission represented in this interface.
toString() | Prints a string representation of this permission.


 Permission.equals

Permission.equals

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean equals( Object another )
Parameters
another
the Permission object to compare with.
Returns
true if the Permission objects are equal, false otherwise
Description
Returns true if the object passed matches the permission represented in this interface.

Overrides
equals in class Object


 Permission.toString

Permission.toString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String toString()
Returns
the string representation of the permission.
Description
Prints a string representation of this permission.

Overrides
toString in class Object


 Package java.security.interfaces

Package java.security.interfaces

All Packages

Interfaces

  • DSAKey
  • DSAKeyPairGenerator
  • DSAParams
  • DSAPrivateKey
  • DSAPublicKey


 Interface DSAKey

Interface java.security.interfaces.DSAKey

Interface Members | This Package | All Packages

public interface DSAKey

The interface to a DSA public or private key. DSA (Digital Signature Algorithm) is defined in NIST's FIPS-186.

See Also:
DSAParams, Key, Signature


 DSAKey Members

DSAKey Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getParams() | Returns the DSA-specific key parameters.


 DSAKey.getParams

DSAKey.getParams

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract DSAParams getParams()
Returns
the DSA-specific key parameters.
Description
Returns the DSA-specific key parameters. These parameters are never secret.

See Also
DSAParams


 Interface DSAKeyPairGenerator

Interface java.security.interfaces.DSAKeyPairGenerator

Interface Members | This Package | All Packages

public interface DSAKeyPairGenerator

An interface to an object capable of generating DSA key pairs.

The initialize methods may each be called any number of times. If no initialize method is called on a DSAKeyPairGenerator, the default is to generate 1024-bit keys, using precomputed p, q and g parameters and an instance of SecureRandom as the random bit source.

Users wishing to indicate DSA-specific parameters, and to generate a key pair suitable for use with the DSA algorithm typically

  1. Get a key pair generator for the DSA algorithm by calling the KeyPairGenerator getInstance method with "DSA" as its argument.

  2. Initialize the generator by casting the result to a DSAKeyPairGenerator and calling one of the initialize methods from this DSAKeyPairGenerator interface.

  3. Generate a key pair by calling the generateKeyPair method from the KeyPairGenerator class.

Note: it is not always necessary to do do algorithm-specific initialization for a DSA key pair generator. That is, it is not always necessary to call an initialize method in this interface. Algorithm-independent initialization using the initialize method in the KeyPairGenerator interface is all that is needed when you accept defaults for algorithm-specific parameters.

See Also:
KeyPairGenerator


 DSAKeyPairGenerator Members

DSAKeyPairGenerator Members

Interface Overview | This Package | All Packages

Methods
Name | Description
initialize(DSAParams, SecureRandom) | Initializes the key pair generator using p, q and g, the DSA family parameters.
initialize(int, boolean, SecureRandom) | Initializes the key pair generator for a given modulus length, without parameters.


 DSAKeyPairGenerator.initialize

DSAKeyPairGenerator.initialize

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void initialize( DSAParams params, SecureRandom random ) throws InvalidParameterException
Parameters
params
the parameters to use to generate the keys.
random
the random bit source to use to generate key bits.
Description
Initializes the key pair generator using p, q and g, the DSA family parameters.

Exceptions
InvalidParameterException if the parameters passed are invalid or null.

Syntax 2
public abstract void initialize( int modlen, boolean genParams, SecureRandom random ) throws InvalidParameterException
Parameters
modlen
the modulus length, in bits. Valid values are any multiple of 8 between 512 and 1024, inclusive.
random
the random bit source to use to generate key bits.
genParams
whether or not to generate new parameters for the modulus length requested.
Description
Initializes the key pair generator for a given modulus length, without parameters.

If genParams is true, this method will generate new p, q and g parameters. If it is false, the method will use precomputed parameters for the modulus length requested. If there are no precomputed parameters for that modulus length, an exception will be thrown. It is guaranteed that there will always be default parameters for modulus lengths of 512 and 1024 bits.

Exceptions
InvalidParameterException if the modulus length is not between 512 and 1024, or if genParams is false and there are not precomputed parameters for the modulus length requested.


 Interface DSAParams

Interface java.security.interfaces.DSAParams

Interface Members | This Package | All Packages

public interface DSAParams

Interface to a DSA-specific set of key parameters, which defines a DSA key family. DSA (Digital Signature Algorithm) is defined in NIST's FIPS-186.

See Also:
DSAKey, Key, Signature


 DSAParams Members

DSAParams Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getG() | Returns the base, g.
getP() | Returns the prime, p.
getQ() | Returns the subprime, q.


 DSAParams.getG

DSAParams.getG

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigInteger getG()
Returns
the base, g.
Description
Returns the base, g.


 DSAParams.getP

DSAParams.getP

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigInteger getP()
Returns
the prime, p.
Description
Returns the prime, p.


 DSAParams.getQ

DSAParams.getQ

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigInteger getQ()
Returns
the subprime, q.
Description
Returns the subprime, q.


 Interface DSAPrivateKey

Interface java.security.interfaces.DSAPrivateKey

Interface Members | This Package | All Packages

public interface DSAPrivateKey
extends DSAKey, PrivateKey

The standard interface to a DSA private key. DSA (Digital Signature Algorithm) is defined in NIST's FIPS-186.

See Also:
Key, Signature, DSAKey, DSAPublicKey


 DSAPrivateKey Members

DSAPrivateKey Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getX() | Returns the value of the private key, x.


 DSAPrivateKey.getX

DSAPrivateKey.getX

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigInteger getX()
Returns
the value of the private key, x.
Description
Returns the value of the private key, x.


 Interface DSAPublicKey

Interface java.security.interfaces.DSAPublicKey

Interface Members | This Package | All Packages

public interface DSAPublicKey
extends DSAKey, PublicKey

The interface to a DSA public key. DSA (Digital Signature Algorithm) is defined in NIST's FIPS-186.

See Also:
Key, KeyParams, Signature


 DSAPublicKey Members

DSAPublicKey Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getY() | Returns the value of the public key, y.


 DSAPublicKey.getY

DSAPublicKey.getY

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigInteger getY()
Returns
the value of the public key, y.
Description
Returns the value of the public key, y.


 Package java.sql

Package java.sql

All Packages

Interfaces

  • CallableStatement
  • Connection
  • DatabaseMetaData
  • Driver
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • Statement

    • Classes

  • Date
  • DriverManager
  • DriverPropertyInfo
  • Time
  • Timestamp
  • Types

    • Exceptions

  • DataTruncation
  • SQLException
  • SQLWarning


 Interface CallableStatement

Interface java.sql.CallableStatement

Interface Members | This Package | All Packages

public interface CallableStatement
extends PreparedStatement

CallableStatement is used to execute SQL stored procedures.

JDBC provides a stored procedure SQL escape that allows stored procedures to be called in a standard way for all RDBMS's. This escape syntax has one form that includes a result parameter and one that does not. If used, the result parameter must be registered as an OUT parameter. The other parameters may be used for input, output or both. Parameters are refered to sequentially, by number. The first parameter is 1.

{?= call [,, ...]}
{call [,, ...]}

IN parameter values are set using the set methods inherited from PreparedStatement. The type of all OUT parameters must be registered prior to executing the stored procedure; their values are retrieved after execution via the get methods provided here.

A Callable statement may return a ResultSet or multiple ResultSets. Multiple ResultSets are handled using operations inherited from Statement.

For maximum portability, a call's ResultSets and update counts should be processed prior to getting the values of output parameters.

See Also:
prepareCall, ResultSet


 CallableStatement Members

CallableStatement Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getBigDecimal(int, int) | Get the value of a NUMERIC parameter as a java.math.BigDecimal object.
getBoolean(int) | Get the value of a BIT parameter as a Java boolean.
getByte(int) | Get the value of a TINYINT parameter as a Java byte.
getBytes(int) | Get the value of a SQL BINARY or VARBINARY parameter as a Java byte[]
getDate(int) | Get the value of a SQL DATE parameter as a java.sql.Date object
getDouble(int) | Get the value of a DOUBLE parameter as a Java double.
getFloat(int) | Get the value of a FLOAT parameter as a Java float.
getInt(int) | Get the value of an INTEGER parameter as a Java int.
getLong(int) | Get the value of a BIGINT parameter as a Java long.
getObject(int) | Get the value of a parameter as a Java object.
getShort(int) | Get the value of a SMALLINT parameter as a Java short.
getString(int) | Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a Java String.
getTime(int) | Get the value of a SQL TIME parameter as a java.sql.Time object.
getTimestamp(int) | Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.
registerOutParameter(int, int) | Before executing a stored procedure call, you must explicitly call registerOutParameter to register the java.sql.Type of each out parameter.
registerOutParameter(int, int, int) | Use this version of registerOutParameter for registering Numeric or Decimal out parameters.
wasNull() | An OUT parameter may have the value of SQL NULL; wasNull reports whether the last value read has this special value.


 CallableStatement.getBigDecimal

CallableStatement.getBigDecimal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigDecimal getBigDecimal( int parameterIndex, int scale ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
scale
a value greater than or equal to zero representing the desired number of digits to the right of the decimal point
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a NUMERIC parameter as a java.math.BigDecimal object.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getBoolean

CallableStatement.getBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean getBoolean( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is false
Description
Get the value of a BIT parameter as a Java boolean.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getByte

CallableStatement.getByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte getByte( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of a TINYINT parameter as a Java byte.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getBytes

CallableStatement.getBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte[] getBytes( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a SQL BINARY or VARBINARY parameter as a Java byte[]

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getDate

CallableStatement.getDate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Date getDate( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a SQL DATE parameter as a java.sql.Date object

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getDouble

CallableStatement.getDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract double getDouble( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of a DOUBLE parameter as a Java double.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getFloat

CallableStatement.getFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float getFloat( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of a FLOAT parameter as a Java float.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getInt

CallableStatement.getInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getInt( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of an INTEGER parameter as a Java int.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getLong

CallableStatement.getLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long getLong( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of a BIGINT parameter as a Java long.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getObject

CallableStatement.getObject

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object getObject( int parameterIndex ) throws SQLException
Parameters
parameterIndex
The first parameter is 1, the second is 2, ...
Returns
A java.lang.Object holding the OUT parameter value.
Description
Get the value of a parameter as a Java object.

This method returns a Java object whose type coresponds to the SQL type that was registered for this parameter using registerOutParameter.

Note that this method may be used to read datatabase-specific, abstract data types. This is done by specifying a targetSqlType of java.sql.types.OTHER, which allows the driver to return a database-specific Java type.

Exceptions
SQLException if a database-access error occurs.
See Also
Types


 CallableStatement.getShort

CallableStatement.getShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract short getShort( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is 0
Description
Get the value of a SMALLINT parameter as a Java short.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getString

CallableStatement.getString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getString( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a Java String.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getTime

CallableStatement.getTime

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Time getTime( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a SQL TIME parameter as a java.sql.Time object.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.getTimestamp

CallableStatement.getTimestamp

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Timestamp getTimestamp( int parameterIndex ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
Returns
the parameter value; if the value is SQL NULL, the result is null
Description
Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.

Exceptions
SQLException if a database-access error occurs.


 CallableStatement.registerOutParameter

CallableStatement.registerOutParameter

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void registerOutParameter( int parameterIndex, int sqlType ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2,...
sqlType
SQL type code defined by java.sql.Types; for parameters of type Numeric or Decimal use the version of registerOutParameter that accepts a scale value
Description
Before executing a stored procedure call, you must explicitly call registerOutParameter to register the java.sql.Type of each out parameter.

Note: When reading the value of an out parameter, you must use the getXXX method whose Java type XXX corresponds to the parameter's registered SQL type.

Exceptions
SQLException if a database-access error occurs.
See Also
Type

Syntax 2
public abstract void registerOutParameter( int parameterIndex, int sqlType, int scale ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
sqlType
use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL
scale
a value greater than or equal to zero representing the desired number of digits to the right of the decimal point
Description
Use this version of registerOutParameter for registering Numeric or Decimal out parameters.

Note: When reading the value of an out parameter, you must use the getXXX method whose Java type XXX corresponds to the parameter's registered SQL type.

Exceptions
SQLException if a database-access error occurs.
See Also
Type


 CallableStatement.wasNull

CallableStatement.wasNull

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean wasNull() throws SQLException
Returns
true if the last parameter read was SQL NULL
Description
An OUT parameter may have the value of SQL NULL; wasNull reports whether the last value read has this special value.

Note: You must first call getXXX on a parameter to read its value and then call wasNull() to see if the value was SQL NULL.

Exceptions
SQLException if a database-access error occurs.


 Interface Connection

Interface java.sql.Connection

Interface Members | This Package | All Packages

public interface Connection

A Connection represents a session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned.

A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, etc. This information is obtained with the getMetaData method.

Note: By default the Connection automatically commits changes after executing each statement. If auto commit has been disabled, an explicit commit must be done or database changes will not be saved.

See Also:
getConnection, Statement, ResultSet, DatabaseMetaData


 Connection Members

Connection Members

Interface Overview | This Package | All Packages

Fields
Name | Description
TRANSACTION_NONE | Transactions are not supported.
TRANSACTION_READ_COMMITTED | Dirty reads are prevented; non-repeatable reads and phantom reads can occur.
TRANSACTION_READ_UNCOMMITTED | Dirty reads, non-repeatable reads and phantom reads can occur.
TRANSACTION_REPEATABLE_READ | Dirty reads and non-repeatable reads are prevented; phantom reads can occur.
TRANSACTION_SERIALIZABLE | Dirty reads, non-repeatable reads and phantom reads are prevented.

Methods
Name | Description
clearWarnings() | After this call, getWarnings returns null until a new warning is reported for this Connection.
close() | In some cases, it is desirable to immediately release a Connection's database and JDBC resources instead of waiting for them to be automatically released; the close method provides this immediate release.
commit() | Commit makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by the Connection.
createStatement() | SQL statements without parameters are normally executed using Statement objects.
getAutoCommit() | Get the current auto-commit state.
getCatalog() | Return the Connection's current catalog name.
getMetaData() | A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, etc.
getTransactionIsolation() | Get this Connection's current transaction isolation mode.
getWarnings() | The first warning reported by calls on this Connection is returned.
isClosed() | Tests to see if a Connection is closed.
isReadOnly() | Tests to see if the connection is in read-only mode.
nativeSQL(String) | A driver may convert the JDBC sql grammar into its system's native SQL grammar prior to sending it; nativeSQL returns the native form of the statement that the driver would have sent.
prepareCall(String) | A SQL stored procedure call statement is handled by creating a CallableStatement for it.
prepareStatement(String) | A SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object.
rollback() | Rollback drops all changes made since the previous commit/rollback and releases any database locks currently held by the Connection.
setAutoCommit(boolean) | If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions.
setCatalog(String) | A sub-space of this Connection's database may be selected by setting a catalog name.
setReadOnly(boolean) | You can put a connection in read-only mode as a hint to enable database optimizations.
setTransactionIsolation(int) | You can call this method to try to change the transaction isolation level using one of the TRANSACTION_* values.


 Connection.TRANSACTION_NONE

Connection.TRANSACTION_NONE

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TRANSACTION_NONE
Description
Transactions are not supported.


 Connection.TRANSACTION_READ_COMMITTED

Connection.TRANSACTION_READ_COMMITTED

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TRANSACTION_READ_COMMITTED
Description
Dirty reads are prevented; non-repeatable reads and phantom reads can occur.


 Connection.TRANSACTION_READ_UNCOMMITTED

Connection.TRANSACTION_READ_UNCOMMITTED

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TRANSACTION_READ_UNCOMMITTED
Description
Dirty reads, non-repeatable reads and phantom reads can occur.


 Connection.TRANSACTION_REPEATABLE_READ

Connection.TRANSACTION_REPEATABLE_READ

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TRANSACTION_REPEATABLE_READ
Description
Dirty reads and non-repeatable reads are prevented; phantom reads can occur.


 Connection.TRANSACTION_SERIALIZABLE

Connection.TRANSACTION_SERIALIZABLE

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int TRANSACTION_SERIALIZABLE
Description
Dirty reads, non-repeatable reads and phantom reads are prevented.


 Connection.clearWarnings

Connection.clearWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void clearWarnings() throws SQLException
Description
After this call, getWarnings returns null until a new warning is reported for this Connection.

Exceptions
SQLException if a database-access error occurs.


 Connection.close

Connection.close

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void close() throws SQLException
Description
In some cases, it is desirable to immediately release a Connection's database and JDBC resources instead of waiting for them to be automatically released; the close method provides this immediate release.

Note: A Connection is automatically closed when it is garbage collected. Certain fatal errors also result in a closed Connection.

Exceptions
SQLException if a database-access error occurs.


 Connection.commit

Connection.commit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void commit() throws SQLException
Description
Commit makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by the Connection. This method should only be used when auto commit has been disabled.

Exceptions
SQLException if a database-access error occurs.
See Also
setAutoCommit


 Connection.createStatement

Connection.createStatement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Statement createStatement() throws SQLException
Returns
a new Statement object
Description
SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it is more efficient to use a PreparedStatement

Exceptions
SQLException if a database-access error occurs.


 Connection.getAutoCommit

Connection.getAutoCommit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean getAutoCommit() throws SQLException
Returns
Current state of auto-commit mode.
Description
Get the current auto-commit state.

Exceptions
SQLException if a database-access error occurs.
See Also
setAutoCommit


 Connection.getCatalog

Connection.getCatalog

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getCatalog() throws SQLException
Returns
the current catalog name or null
Description
Return the Connection's current catalog name.

Exceptions
SQLException if a database-access error occurs.


 Connection.getMetaData

Connection.getMetaData

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract DatabaseMetaData getMetaData() throws SQLException
Returns
a DatabaseMetaData object for this Connection
Description
A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, etc. This information is made available through a DatabaseMetaData object.

Exceptions
SQLException if a database-access error occurs.


 Connection.getTransactionIsolation

Connection.getTransactionIsolation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getTransactionIsolation() throws SQLException
Returns
the current TRANSACTION_* mode value
Description
Get this Connection's current transaction isolation mode.

Exceptions
SQLException if a database-access error occurs.


 Connection.getWarnings

Connection.getWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract SQLWarning getWarnings() throws SQLException
Returns
the first SQLWarning or null
Description
The first warning reported by calls on this Connection is returned.

Note: Subsequent warnings will be chained to this SQLWarning.

Exceptions
SQLException if a database-access error occurs.


 Connection.isClosed

Connection.isClosed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isClosed() throws SQLException
Returns
true if the connection is closed; false if it's still open
Description
Tests to see if a Connection is closed.

Exceptions
SQLException if a database-access error occurs.


 Connection.isReadOnly

Connection.isReadOnly

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isReadOnly() throws SQLException
Returns
true if connection is read-only
Description
Tests to see if the connection is in read-only mode.

Exceptions
SQLException if a database-access error occurs.


 Connection.nativeSQL

Connection.nativeSQL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String nativeSQL( String sql ) throws SQLException
Parameters
sql
a SQL statement that may contain one or more '?' parameter placeholders
Returns
the native form of this statement
Description
A driver may convert the JDBC sql grammar into its system's native SQL grammar prior to sending it; nativeSQL returns the native form of the statement that the driver would have sent.

Exceptions
SQLException if a database-access error occurs.


 Connection.prepareCall

Connection.prepareCall

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract CallableStatement prepareCall( String sql ) throws SQLException
Parameters
sql
a SQL statement that may contain one or more '?' parameter placeholders. Typically this statement is a JDBC function call escape string.
Returns
a new CallableStatement object containing the pre-compiled SQL statement
Description
A SQL stored procedure call statement is handled by creating a CallableStatement for it. The CallableStatement provides methods for setting up its IN and OUT parameters, and methods for executing it.

Note: This method is optimized for handling stored procedure call statements. Some drivers may send the call statement to the database when the prepareCall is done; others may wait until the CallableStatement is executed. This has no direct affect on users; however, it does affect which method throws certain SQLExceptions.

Exceptions
SQLException if a database-access error occurs.


 Connection.prepareStatement

Connection.prepareStatement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract PreparedStatement prepareStatement( String sql ) throws SQLException
Parameters
sql
a SQL statement that may contain one or more '?' IN parameter placeholders
Returns
a new PreparedStatement object containing the pre-compiled statement
Description
A SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement is executed. This has no direct affect on users; however, it does affect which method throws certain SQLExceptions.

Exceptions
SQLException if a database-access error occurs.


 Connection.rollback

Connection.rollback

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void rollback() throws SQLException
Description
Rollback drops all changes made since the previous commit/rollback and releases any database locks currently held by the Connection. This method should only be used when auto commit has been disabled.

Exceptions
SQLException if a database-access error occurs.
See Also
setAutoCommit


 Connection.setAutoCommit

Connection.setAutoCommit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setAutoCommit( boolean autoCommit ) throws SQLException
Parameters
autoCommit
true enables auto-commit; false disables auto-commit.
Description
If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by either commit() or rollback(). By default, new connections are in auto-commit mode. The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement completes when the last row of the ResultSet has been retrieved or the ResultSet has been closed. In advanced cases, a single statement may return multiple results as well as output parameter values. Here the commit occurs when all results and output param values have been retrieved.

Exceptions
SQLException if a database-access error occurs.


 Connection.setCatalog

Connection.setCatalog

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setCatalog( String catalog ) throws SQLException
Description
A sub-space of this Connection's database may be selected by setting a catalog name. If the driver does not support catalogs it will silently ignore this request.

Exceptions
SQLException if a database-access error occurs.


 Connection.setReadOnly

Connection.setReadOnly

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setReadOnly( boolean readOnly ) throws SQLException
Parameters
readOnly
true enables read-only mode; false disables read-only mode.
Description
You can put a connection in read-only mode as a hint to enable database optimizations.

Note: setReadOnly cannot be called while in the middle of a transaction.

Exceptions
SQLException if a database-access error occurs.


 Connection.setTransactionIsolation

Connection.setTransactionIsolation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setTransactionIsolation( int level ) throws SQLException
Parameters
level
one of the TRANSACTION_* isolation values with the exception of TRANSACTION_NONE; some databases may not support other values
Description
You can call this method to try to change the transaction isolation level using one of the TRANSACTION_* values.

Note: setTransactionIsolation cannot be called while in the middle of a transaction.

Exceptions
SQLException if a database-access error occurs.
See Also
supportsTransactionIsolationLevel


 Class DataTruncation

Class java.sql.DataTruncation

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.sql.SQLException
                           |
                           +----java.sql.SQLWarning
                                   |
                                   +----java.sql.DataTruncation

public class DataTruncation
extends SQLWarning

When JDBC unexpectedly truncates a data value, it reports a DataTruncation warning (on reads) or throws a DataTruncation exception (on writes).

The SQLstate for a DataTruncation is "01004".


 DataTruncation Members

DataTruncation Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DataTruncation(int, boolean, boolean, int, int) | Create a DataTruncation object.

Methods
Name | Description
getDataSize() | Get the number of bytes of data that should have been transferred.
getIndex() | Get the index of the column or parameter that was truncated.
getParameter() | Is this a truncated parameter value?
getRead() | Was this a read truncation?
getTransferSize() | Get the number of bytes of data actually transferred.


 DataTruncation.DataTruncation

DataTruncation.DataTruncation

Syntax
public DataTruncation( int index, boolean parameter, boolean read, int dataSize, int transferSize )
Parameters
index
The index of the parameter or column value
parameter
true if a parameter value was truncated
read
true if a read was truncated
dataSize
the original size of the data
transferSize
the size after truncation
Description

Create a DataTruncation object. The SQLState is initialized to 01004, the reason is set to "Data truncation" and the vendorCode is set to the SQLException default.


 DataTruncation.getDataSize

DataTruncation.getDataSize

Syntax
public int getDataSize()
Returns
the number of bytes of data that should have been transferred
Description
Get the number of bytes of data that should have been transferred. This number may be approximate if data conversions were being performed. The value may be "-1" if the size is unknown.


 DataTruncation.getIndex

DataTruncation.getIndex

Syntax
public int getIndex()
Returns
the index of the truncated paramter or column value.
Description
Get the index of the column or parameter that was truncated.

This may be -1 if the column or parameter index is unknown, in which case the "parameter" and "read" fields should be ignored.


 DataTruncation.getParameter

DataTruncation.getParameter

Syntax
public boolean getParameter()
Returns
True if the value was a parameter; false if it was a column value.
Description
Is this a truncated parameter value?


 DataTruncation.getRead

DataTruncation.getRead

Syntax
public boolean getRead()
Returns
True if the value was truncated when read from the database; false if the data was truncated on a write.
Description
Was this a read truncation?


 DataTruncation.getTransferSize

DataTruncation.getTransferSize

Syntax
public int getTransferSize()
Returns
the number of bytes of data actually transferred
Description
Get the number of bytes of data actually transferred. The value may be "-1" if the size is unknown.


 Interface DatabaseMetaData

Interface java.sql.DatabaseMetaData

Interface Members | This Package | All Packages

public interface DatabaseMetaData

This class provides information about the database as a whole.

Many of the methods here return lists of information in ResultSets. You can use the normal ResultSet methods such as getString and getInt to retrieve the data from these ResultSets. If a given form of metadata is not available, these methods should throw a SQLException.

Some of these methods take arguments that are String patterns. These arguments all have names such as fooPattern. Within a pattern String, "%" means match any substring of 0 or more characters, and "_" means match any one character. Only metadata entries matching the search pattern are returned. If a search pattern argument is set to a null ref, it means that argument's criteria should be dropped from the search.

A SQLException will be thrown if a driver does not support a meta data method. In the case of methods that return a ResultSet, either a ResultSet (which may be empty) is returned or a SQLException is thrown.


 DatabaseMetaData Members

DatabaseMetaData Members

Interface Overview | This Package | All Packages

Fields
Name | Description
bestRowNotPseudo | BEST ROW PSEUDO_COLUMN - is NOT a pseudo column.
bestRowPseudo | BEST ROW PSEUDO_COLUMN - is a pseudo column.
bestRowSession | BEST ROW SCOPE - valid for remainder of current session.
bestRowTemporary | BEST ROW SCOPE - very temporary, while using row.
bestRowTransaction | BEST ROW SCOPE - valid for remainder of current transaction.
bestRowUnknown | BEST ROW PSEUDO_COLUMN - may or may not be pseudo column.
columnNoNulls | COLUMN NULLABLE - might not allow NULL values.
columnNullable | COLUMN NULLABLE - definitely allows NULL values.
columnNullableUnknown | COLUMN NULLABLE - nullability unknown.
importedKeyCascade | IMPORT KEY UPDATE_RULE and DELETE_RULE - for update, change imported key to agree with primary key update; for delete, delete rows that import a deleted key.
importedKeyInitiallyDeferred | IMPORT KEY DEFERRABILITY - see SQL92 for definition
importedKeyInitiallyImmediate | IMPORT KEY DEFERRABILITY - see SQL92 for definition
importedKeyNoAction | IMPORT KEY UPDATE_RULE and DELETE_RULE - do not allow update or delete of primary key if it has been imported.
importedKeyNotDeferrable | IMPORT KEY DEFERRABILITY - see SQL92 for definition
importedKeyRestrict | IMPORT KEY UPDATE_RULE and DELETE_RULE - do not allow update or delete of primary key if it has been imported.
importedKeySetDefault | IMPORT KEY UPDATE_RULE and DELETE_RULE - change imported key to default values if its primary key has been updated or deleted.
importedKeySetNull | IMPORT KEY UPDATE_RULE and DELETE_RULE - change imported key to NULL if its primary key has been updated or deleted.
procedureColumnIn | COLUMN_TYPE - IN parameter.
procedureColumnInOut | COLUMN_TYPE - INOUT parameter.
procedureColumnOut | COLUMN_TYPE - OUT parameter.
procedureColumnResult | COLUMN_TYPE - result column in ResultSet.
procedureColumnReturn | COLUMN_TYPE - procedure return value.
procedureColumnUnknown | COLUMN_TYPE - nobody knows.
procedureNoNulls | TYPE NULLABLE - does not allow NULL values.
procedureNoResult | PROCEDURE_TYPE - Does not return a result.
procedureNullable | TYPE NULLABLE - allows NULL values.
procedureNullableUnknown | TYPE NULLABLE - nullability unknown.
procedureResultUnknown | PROCEDURE_TYPE - May return a result.
procedureReturnsResult | PROCEDURE_TYPE - Returns a result.
tableIndexClustered | INDEX INFO TYPE - this identifies a clustered index
tableIndexHashed | INDEX INFO TYPE - this identifies a hashed index
tableIndexOther | INDEX INFO TYPE - this identifies some other form of index
tableIndexStatistic | INDEX INFO TYPE - this identifies table statistics that are returned in conjuction with a table's index descriptions
typeNoNulls | TYPE NULLABLE - does not allow NULL values.
typeNullable | TYPE NULLABLE - allows NULL values.
typeNullableUnknown | TYPE NULLABLE - nullability unknown.
typePredBasic | TYPE INFO SEARCHABLE - Supported except for WHERE ..
typePredChar | TYPE INFO SEARCHABLE - Only supported with WHERE ..
typePredNone | TYPE INFO SEARCHABLE - No support.
typeSearchable | TYPE INFO SEARCHABLE - Supported for all WHERE ...
versionColumnNotPseudo | VERSION COLUMNS PSEUDO_COLUMN - is NOT a pseudo column.
versionColumnPseudo | VERSION COLUMNS PSEUDO_COLUMN - is a pseudo column.
versionColumnUnknown | VERSION COLUMNS PSEUDO_COLUMN - may or may not be pseudo column.

Methods
Name | Description
allProceduresAreCallable() | Can all the procedures returned by getProcedures be called by the current user?
allTablesAreSelectable() | Can all the tables returned by getTable be SELECTed by the current user?
dataDefinitionCausesTransactionCommit() | Does a data definition statement within a transaction force the transaction to commit?
dataDefinitionIgnoredInTransactions() | Is a data definition statement within a transaction ignored?
doesMaxRowSizeIncludeBlobs() | Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY blobs?
getBestRowIdentifier(String, String, String, int, boolean) | Get a description of a table's optimal set of columns that uniquely identifies a row.
getCatalogs() | Get the catalog names available in this database.
getCatalogSeparator() | What's the separator between catalog and table name?
getCatalogTerm() | What's the database vendor's preferred term for "catalog"?
getColumnPrivileges(String, String, String, String) | Get a description of the access rights for a table's columns.
getColumns(String, String, String, String) | Get a description of table columns available in a catalog.
getCrossReference(String, String, String, String, String, String) | Get a description of the foreign key columns in the foreign key table that reference the primary key columns of the primary key table (describe how one table imports another's key.) This should normally return a single foreign key/primary key pair (most tables only import a foreign key from a table once.) They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ.
getDatabaseProductName() | What's the name of this database product?
getDatabaseProductVersion() | What's the version of this database product?
getDefaultTransactionIsolation() | What's the database's default transaction isolation level? The values are defined in java.sql.Connection.
getDriverMajorVersion() | What's this JDBC driver's major version number?
getDriverMinorVersion() | What's this JDBC driver's minor version number?
getDriverName() | What's the name of this JDBC driver?
getDriverVersion() | What's the version of this JDBC driver?
getExportedKeys(String, String, String) | Get a description of the foreign key columns that reference a table's primary key columns (the foreign keys exported by a table).
getExtraNameCharacters() | Get all the "extra" characters that can be used in unquoted identifier names (those beyond a-z, A-Z, 0-9 and _).
getIdentifierQuoteString() | What's the string used to quote SQL identifiers? This returns a space " " if identifier quoting isn't supported.
getImportedKeys(String, String, String) | Get a description of the primary key columns that are referenced by a table's foreign key columns (the primary keys imported by a table).
getIndexInfo(String, String, String, boolean, boolean) | Get a description of a table's indices and statistics.
getMaxBinaryLiteralLength() | How many hex characters can you have in an inline binary literal?
getMaxCatalogNameLength() | What's the maximum length of a catalog name?
getMaxCharLiteralLength() | What's the max length for a character literal?
getMaxColumnNameLength() | What's the limit on column name length?
getMaxColumnsInGroupBy() | What's the maximum number of columns in a "GROUP BY" clause?
getMaxColumnsInIndex() | What's the maximum number of columns allowed in an index?
getMaxColumnsInOrderBy() | What's the maximum number of columns in an "ORDER BY" clause?
getMaxColumnsInSelect() | What's the maximum number of columns in a "SELECT" list?
getMaxColumnsInTable() | What's the maximum number of columns in a table?
getMaxConnections() | How many active connections can we have at a time to this database?
getMaxCursorNameLength() | What's the maximum cursor name length?
getMaxIndexLength() | What's the maximum length of an index (in bytes)?
getMaxProcedureNameLength() | What's the maximum length of a procedure name?
getMaxRowSize() | What's the maximum length of a single row?
getMaxSchemaNameLength() | What's the maximum length allowed for a schema name?
getMaxStatementLength() | What's the maximum length of a SQL statement?
getMaxStatements() | How many active statements can we have open at one time to this database?
getMaxTableNameLength() | What's the maximum length of a table name?
getMaxTablesInSelect() | What's the maximum number of tables in a SELECT?
getMaxUserNameLength() | What's the maximum length of a user name?
getNumericFunctions() | Get a comma separated list of math functions.
getPrimaryKeys(String, String, String) | Get a description of a table's primary key columns.
getProcedureColumns(String, String, String, String) | Get a description of a catalog's stored procedure parameters and result columns.
getProcedures(String, String, String) | Get a description of stored procedures available in a catalog.
getProcedureTerm() | What's the database vendor's preferred term for "procedure"?
getSchemas() | Get the schema names available in this database.
getSchemaTerm() | What's the database vendor's preferred term for "schema"?
getSearchStringEscape() | This is the string that can be used to escape '_' or '%' in the string pattern style catalog search parameters.
getSQLKeywords() | Get a comma separated list of all a database's SQL keywords that are NOT also SQL92 keywords.
getStringFunctions() | Get a comma separated list of string functions.
getSystemFunctions() | Get a comma separated list of system functions.
getTablePrivileges(String, String, String) | Get a description of the access rights for each table available in a catalog.
getTables(String, String, String, String[]) | Get a description of tables available in a catalog.
getTableTypes() | Get the table types available in this database.
getTimeDateFunctions() | Get a comma separated list of time and date functions.
getTypeInfo() | Get a description of all the standard SQL types supported by this database.
getURL() | What's the url for this database?
getUserName() | What's our user name as known to the database?
getVersionColumns(String, String, String) | Get a description of a table's columns that are automatically updated when any value in a row is updated.
isCatalogAtStart() | Does a catalog appear at the start of a qualified table name? (Otherwise it appears at the end)
isReadOnly() | Is the database in read-only mode?
nullPlusNonNullIsNull() | Are concatenations between NULL and non-NULL values NULL? A JDBC-Compliant driver always returns true.
nullsAreSortedAtEnd() | Are NULL values sorted at the end regardless of sort order?
nullsAreSortedAtStart() | Are NULL values sorted at the start regardless of sort order?
nullsAreSortedHigh() | Are NULL values sorted high?
nullsAreSortedLow() | Are NULL values sorted low?
storesLowerCaseIdentifiers() | Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in lower case?
storesLowerCaseQuotedIdentifiers() | Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in lower case?
storesMixedCaseIdentifiers() | Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in mixed case?
storesMixedCaseQuotedIdentifiers() | Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in mixed case?
storesUpperCaseIdentifiers() | Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in upper case?
storesUpperCaseQuotedIdentifiers() | Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in upper case?
supportsAlterTableWithAddColumn() | Is "ALTER TABLE" with add column supported?
supportsAlterTableWithDropColumn() | Is "ALTER TABLE" with drop column supported?
supportsANSI92EntryLevelSQL() | Is the ANSI92 entry level SQL grammar supported? All JDBC-Compliant drivers must return true.
supportsANSI92FullSQL() | Is the ANSI92 full SQL grammar supported?
supportsANSI92IntermediateSQL() | Is the ANSI92 intermediate SQL grammar supported?
supportsCatalogsInDataManipulation() | Can a catalog name be used in a data manipulation statement?
supportsCatalogsInIndexDefinitions() | Can a catalog name be used in an index definition statement?
supportsCatalogsInPrivilegeDefinitions() | Can a catalog name be used in a privilege definition statement?
supportsCatalogsInProcedureCalls() | Can a catalog name be used in a procedure call statement?
supportsCatalogsInTableDefinitions() | Can a catalog name be used in a table definition statement?
supportsColumnAliasing() | Is column aliasing supported? If so, the SQL AS clause can be used to provide names for computed columns or to provide alias names for columns as required.
supportsConvert() | Is the CONVERT function between SQL types supported?
supportsConvert(int, int) | Is CONVERT between the given SQL types supported?
supportsCoreSQLGrammar() | Is the ODBC Core SQL grammar supported?
supportsCorrelatedSubqueries() | Are correlated subqueries supported? A JDBC-Compliant driver always returns true.
supportsDataDefinitionAndDataManipulationTransactions() | Are both data definition and data manipulation statements within a transaction supported?
supportsDataManipulationTransactionsOnly() | Are only data manipulation statements within a transaction supported?
supportsDifferentTableCorrelationNames() | If table correlation names are supported, are they restricted to be different from the names of the tables?
supportsExpressionsInOrderBy() | Are expressions in "ORDER BY" lists supported?
supportsExtendedSQLGrammar() | Is the ODBC Extended SQL grammar supported?
supportsFullOuterJoins() | Are full nested outer joins supported?
supportsGroupBy() | Is some form of "GROUP BY" clause supported?
supportsGroupByBeyondSelect() | Can a "GROUP BY" clause add columns not in the SELECT provided it specifies all the columns in the SELECT?
supportsGroupByUnrelated() | Can a "GROUP BY" clause use columns not in the SELECT?
supportsIntegrityEnhancementFacility() | Is the SQL Integrity Enhancement Facility supported?
supportsLikeEscapeClause() | Is the escape character in "LIKE" clauses supported? A JDBC-Compliant driver always returns true.
supportsLimitedOuterJoins() | Is there limited support for outer joins? (This will be true if supportFullOuterJoins is true.)
supportsMinimumSQLGrammar() | Is the ODBC Minimum SQL grammar supported? All JDBC-Compliant drivers must return true.
supportsMixedCaseIdentifiers() | Does the database treat mixed case unquoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC-Compliant driver will always return false.
supportsMixedCaseQuotedIdentifiers() | Does the database treat mixed case quoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC-Compliant driver will always return true.
supportsMultipleResultSets() | Are multiple ResultSets from a single execute supported?
supportsMultipleTransactions() | Can we have multiple transactions open at once (on different connections)?
supportsNonNullableColumns() | Can columns be defined as non-nullable? A JDBC-Compliant driver always returns true.
supportsOpenCursorsAcrossCommit() | Can cursors remain open across commits?
supportsOpenCursorsAcrossRollback() | Can cursors remain open across rollbacks?
supportsOpenStatementsAcrossCommit() | Can statements remain open across commits?
supportsOpenStatementsAcrossRollback() | Can statements remain open across rollbacks?
supportsOrderByUnrelated() | Can an "ORDER BY" clause use columns not in the SELECT?
supportsOuterJoins() | Is some form of outer join supported?
supportsPositionedDelete() | Is positioned DELETE supported?
supportsPositionedUpdate() | Is positioned UPDATE supported?
supportsSchemasInDataManipulation() | Can a schema name be used in a data manipulation statement?
supportsSchemasInIndexDefinitions() | Can a schema name be used in an index definition statement?
supportsSchemasInPrivilegeDefinitions() | Can a schema name be used in a privilege definition statement?
supportsSchemasInProcedureCalls() | Can a schema name be used in a procedure call statement?
supportsSchemasInTableDefinitions() | Can a schema name be used in a table definition statement?
supportsSelectForUpdate() | Is SELECT for UPDATE supported?
supportsStoredProcedures() | Are stored procedure calls using the stored procedure escape syntax supported?
supportsSubqueriesInComparisons() | Are subqueries in comparison expressions supported? A JDBC-Compliant driver always returns true.
supportsSubqueriesInExists() | Are subqueries in 'exists' expressions supported? A JDBC-Compliant driver always returns true.
supportsSubqueriesInIns() | Are subqueries in 'in' statements supported? A JDBC-Compliant driver always returns true.
supportsSubqueriesInQuantifieds() | Are subqueries in quantified expressions supported? A JDBC-Compliant driver always returns true.
supportsTableCorrelationNames() | Are table correlation names supported? A JDBC-Compliant driver always returns true.
supportsTransactionIsolationLevel(int) | Does the database support the given transaction isolation level?
supportsTransactions() | Are transactions supported? If not, commit is a noop and the isolation level is TRANSACTION_NONE.
supportsUnion() | Is SQL UNION supported?
supportsUnionAll() | Is SQL UNION ALL supported?
usesLocalFilePerTable() | Does the database use a file for each table?
usesLocalFiles() | Does the database store tables in a local file?


 DatabaseMetaData.bestRowNotPseudo

DatabaseMetaData.bestRowNotPseudo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowNotPseudo
Description
BEST ROW PSEUDO_COLUMN - is NOT a pseudo column.


 DatabaseMetaData.bestRowPseudo

DatabaseMetaData.bestRowPseudo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowPseudo
Description
BEST ROW PSEUDO_COLUMN - is a pseudo column.


 DatabaseMetaData.bestRowSession

DatabaseMetaData.bestRowSession

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowSession
Description
BEST ROW SCOPE - valid for remainder of current session.


 DatabaseMetaData.bestRowTemporary

DatabaseMetaData.bestRowTemporary

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowTemporary
Description
BEST ROW SCOPE - very temporary, while using row.


 DatabaseMetaData.bestRowTransaction

DatabaseMetaData.bestRowTransaction

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowTransaction
Description
BEST ROW SCOPE - valid for remainder of current transaction.


 DatabaseMetaData.bestRowUnknown

DatabaseMetaData.bestRowUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int bestRowUnknown
Description
BEST ROW PSEUDO_COLUMN - may or may not be pseudo column.


 DatabaseMetaData.columnNoNulls

DatabaseMetaData.columnNoNulls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNoNulls
Description
COLUMN NULLABLE - might not allow NULL values.


 DatabaseMetaData.columnNullable

DatabaseMetaData.columnNullable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNullable
Description
COLUMN NULLABLE - definitely allows NULL values.


 DatabaseMetaData.columnNullableUnknown

DatabaseMetaData.columnNullableUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNullableUnknown
Description
COLUMN NULLABLE - nullability unknown.


 DatabaseMetaData.importedKeyCascade

DatabaseMetaData.importedKeyCascade

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyCascade
Description
IMPORT KEY UPDATE_RULE and DELETE_RULE - for update, change imported key to agree with primary key update; for delete, delete rows that import a deleted key.


 DatabaseMetaData.importedKeyInitiallyDeferred

DatabaseMetaData.importedKeyInitiallyDeferred

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyInitiallyDeferred
Description
IMPORT KEY DEFERRABILITY - see SQL92 for definition


 DatabaseMetaData.importedKeyInitiallyImmediate

DatabaseMetaData.importedKeyInitiallyImmediate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyInitiallyImmediate
Description
IMPORT KEY DEFERRABILITY - see SQL92 for definition


 DatabaseMetaData.importedKeyNoAction

DatabaseMetaData.importedKeyNoAction

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyNoAction
Description
IMPORT KEY UPDATE_RULE and DELETE_RULE - do not allow update or delete of primary key if it has been imported.


 DatabaseMetaData.importedKeyNotDeferrable

DatabaseMetaData.importedKeyNotDeferrable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyNotDeferrable
Description
IMPORT KEY DEFERRABILITY - see SQL92 for definition


 DatabaseMetaData.importedKeyRestrict

DatabaseMetaData.importedKeyRestrict

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeyRestrict
Description
IMPORT KEY UPDATE_RULE and DELETE_RULE - do not allow update or delete of primary key if it has been imported.


 DatabaseMetaData.importedKeySetDefault

DatabaseMetaData.importedKeySetDefault

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeySetDefault
Description
IMPORT KEY UPDATE_RULE and DELETE_RULE - change imported key to default values if its primary key has been updated or deleted.


 DatabaseMetaData.importedKeySetNull

DatabaseMetaData.importedKeySetNull

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int importedKeySetNull
Description
IMPORT KEY UPDATE_RULE and DELETE_RULE - change imported key to NULL if its primary key has been updated or deleted.


 DatabaseMetaData.procedureColumnIn

DatabaseMetaData.procedureColumnIn

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnIn
Description
COLUMN_TYPE - IN parameter.


 DatabaseMetaData.procedureColumnInOut

DatabaseMetaData.procedureColumnInOut

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnInOut
Description
COLUMN_TYPE - INOUT parameter.


 DatabaseMetaData.procedureColumnOut

DatabaseMetaData.procedureColumnOut

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnOut
Description
COLUMN_TYPE - OUT parameter.


 DatabaseMetaData.procedureColumnResult

DatabaseMetaData.procedureColumnResult

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnResult
Description
COLUMN_TYPE - result column in ResultSet.


 DatabaseMetaData.procedureColumnReturn

DatabaseMetaData.procedureColumnReturn

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnReturn
Description
COLUMN_TYPE - procedure return value.


 DatabaseMetaData.procedureColumnUnknown

DatabaseMetaData.procedureColumnUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureColumnUnknown
Description
COLUMN_TYPE - nobody knows.


 DatabaseMetaData.procedureNoNulls

DatabaseMetaData.procedureNoNulls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureNoNulls
Description
TYPE NULLABLE - does not allow NULL values.


 DatabaseMetaData.procedureNoResult

DatabaseMetaData.procedureNoResult

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureNoResult
Description
PROCEDURE_TYPE - Does not return a result.


 DatabaseMetaData.procedureNullable

DatabaseMetaData.procedureNullable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureNullable
Description
TYPE NULLABLE - allows NULL values.


 DatabaseMetaData.procedureNullableUnknown

DatabaseMetaData.procedureNullableUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureNullableUnknown
Description
TYPE NULLABLE - nullability unknown.


 DatabaseMetaData.procedureResultUnknown

DatabaseMetaData.procedureResultUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureResultUnknown
Description
PROCEDURE_TYPE - May return a result.


 DatabaseMetaData.procedureReturnsResult

DatabaseMetaData.procedureReturnsResult

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int procedureReturnsResult
Description
PROCEDURE_TYPE - Returns a result.


 DatabaseMetaData.tableIndexClustered

DatabaseMetaData.tableIndexClustered

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final short tableIndexClustered
Description
INDEX INFO TYPE - this identifies a clustered index


 DatabaseMetaData.tableIndexHashed

DatabaseMetaData.tableIndexHashed

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final short tableIndexHashed
Description
INDEX INFO TYPE - this identifies a hashed index


 DatabaseMetaData.tableIndexOther

DatabaseMetaData.tableIndexOther

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final short tableIndexOther
Description
INDEX INFO TYPE - this identifies some other form of index


 DatabaseMetaData.tableIndexStatistic

DatabaseMetaData.tableIndexStatistic

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final short tableIndexStatistic
Description
INDEX INFO TYPE - this identifies table statistics that are returned in conjuction with a table's index descriptions


 DatabaseMetaData.typeNoNulls

DatabaseMetaData.typeNoNulls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typeNoNulls
Description
TYPE NULLABLE - does not allow NULL values.


 DatabaseMetaData.typeNullable

DatabaseMetaData.typeNullable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typeNullable
Description
TYPE NULLABLE - allows NULL values.


 DatabaseMetaData.typeNullableUnknown

DatabaseMetaData.typeNullableUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typeNullableUnknown
Description
TYPE NULLABLE - nullability unknown.


 DatabaseMetaData.typePredBasic

DatabaseMetaData.typePredBasic

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typePredBasic
Description
TYPE INFO SEARCHABLE - Supported except for WHERE .. LIKE.


 DatabaseMetaData.typePredChar

DatabaseMetaData.typePredChar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typePredChar
Description
TYPE INFO SEARCHABLE - Only supported with WHERE .. LIKE.


 DatabaseMetaData.typePredNone

DatabaseMetaData.typePredNone

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typePredNone
Description
TYPE INFO SEARCHABLE - No support.


 DatabaseMetaData.typeSearchable

DatabaseMetaData.typeSearchable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int typeSearchable
Description
TYPE INFO SEARCHABLE - Supported for all WHERE ...


 DatabaseMetaData.versionColumnNotPseudo

DatabaseMetaData.versionColumnNotPseudo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int versionColumnNotPseudo
Description
VERSION COLUMNS PSEUDO_COLUMN - is NOT a pseudo column.


 DatabaseMetaData.versionColumnPseudo

DatabaseMetaData.versionColumnPseudo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int versionColumnPseudo
Description
VERSION COLUMNS PSEUDO_COLUMN - is a pseudo column.


 DatabaseMetaData.versionColumnUnknown

DatabaseMetaData.versionColumnUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int versionColumnUnknown
Description
VERSION COLUMNS PSEUDO_COLUMN - may or may not be pseudo column.


 DatabaseMetaData.allProceduresAreCallable

DatabaseMetaData.allProceduresAreCallable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean allProceduresAreCallable() throws SQLException
Returns
true if so
Description
Can all the procedures returned by getProcedures be called by the current user?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.allTablesAreSelectable

DatabaseMetaData.allTablesAreSelectable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean allTablesAreSelectable() throws SQLException
Returns
true if so
Description
Can all the tables returned by getTable be SELECTed by the current user?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.dataDefinitionCausesTransactionCommit

DatabaseMetaData.dataDefinitionCausesTransactionCommit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean dataDefinitionCausesTransactionCommit() throws SQLException
Returns
true if so
Description
Does a data definition statement within a transaction force the transaction to commit?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.dataDefinitionIgnoredInTransactions

DatabaseMetaData.dataDefinitionIgnoredInTransactions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean dataDefinitionIgnoredInTransactions() throws SQLException
Returns
true if so
Description
Is a data definition statement within a transaction ignored?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.doesMaxRowSizeIncludeBlobs

DatabaseMetaData.doesMaxRowSizeIncludeBlobs

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean doesMaxRowSizeIncludeBlobs() throws SQLException
Returns
true if so
Description
Did getMaxRowSize() include LONGVARCHAR and LONGVARBINARY blobs?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getBestRowIdentifier

DatabaseMetaData.getBestRowIdentifier

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getBestRowIdentifier( String catalog, String schema, String table, int scope, boolean nullable ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name; "" retrieves those without a schema
table
a table name
scope
the scope of interest; use same values as SCOPE
nullable
include columns that are nullable?
Returns
ResultSet - each row is a column description
Description
Get a description of a table's optimal set of columns that uniquely identifies a row. They are ordered by SCOPE.

Each column description has the following columns:

  1. SCOPE short => actual scope of result
    • bestRowTemporary - very temporary, while using row
    • bestRowTransaction - valid for remainder of current transaction
    • bestRowSession - valid for remainder of current session
  2. COLUMN_NAME String => column name
  3. DATA_TYPE short => SQL data type from java.sql.Types
  4. TYPE_NAME String => Data source dependent type name
  5. COLUMN_SIZE int => precision
  6. BUFFER_LENGTH int => not used
  7. DECIMAL_DIGITS short => scale
  8. PSEUDO_COLUMN short => is this a pseudo column like an Oracle ROWID
    • bestRowUnknown - may or may not be pseudo column
    • bestRowNotPseudo - is NOT a pseudo column
    • bestRowPseudo - is a pseudo column

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getCatalogs

DatabaseMetaData.getCatalogs

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getCatalogs() throws SQLException
Returns
ResultSet - each row has a single String column that is a catalog name
Description
Get the catalog names available in this database. The results are ordered by catalog name.

The catalog column is:

  1. TABLE_CAT String => catalog name

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getCatalogSeparator

DatabaseMetaData.getCatalogSeparator

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getCatalogSeparator() throws SQLException
Returns
the separator string
Description
What's the separator between catalog and table name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getCatalogTerm

DatabaseMetaData.getCatalogTerm

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getCatalogTerm() throws SQLException
Returns
the vendor term
Description
What's the database vendor's preferred term for "catalog"?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getColumnPrivileges

DatabaseMetaData.getColumnPrivileges

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getColumnPrivileges( String catalog, String schema, String table, String columnNamePattern ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name; "" retrieves those without a schema
table
a table name
columnNamePattern
a column name pattern
Returns
ResultSet - each row is a column privilege description
Description
Get a description of the access rights for a table's columns.

Only privileges matching the column name criteria are returned. They are ordered by COLUMN_NAME and PRIVILEGE.

Each privilige description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. COLUMN_NAME String => column name
  5. GRANTOR => grantor of access (may be null)
  6. GRANTEE String => grantee of access
  7. PRIVILEGE String => name of access (SELECT, INSERT, UPDATE, REFRENCES, ...)
  8. IS_GRANTABLE String => "YES" if grantee is permitted to grant to others; "NO" if not; null if unknown

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getColumns

DatabaseMetaData.getColumns

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getColumns( String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schemaPattern
a schema name pattern; "" retrieves those without a schema
tableNamePattern
a table name pattern
columnNamePattern
a column name pattern
Returns
ResultSet - each row is a column description
Description
Get a description of table columns available in a catalog.

Only column descriptions matching the catalog, schema, table and column name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.

Each column description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. COLUMN_NAME String => column name
  5. DATA_TYPE short => SQL type from java.sql.Types
  6. TYPE_NAME String => Data source dependent type name
  7. COLUMN_SIZE int => column size. For char or date types this is the maximum number of characters, for numeric or decimal types this is precision.
  8. BUFFER_LENGTH is not used.
  9. DECIMAL_DIGITS int => the number of fractional digits
  10. NUM_PREC_RADIX int => Radix (typically either 10 or 2)
  11. NULLABLE int => is NULL allowed?
    • columnNoNulls - might not allow NULL values
    • columnNullable - definitely allows NULL values
    • columnNullableUnknown - nullability unknown
  12. REMARKS String => comment describing column (may be null)
  13. COLUMN_DEF String => default value (may be null)
  14. SQL_DATA_TYPE int => unused
  15. SQL_DATETIME_SUB int => unused
  16. CHAR_OCTET_LENGTH int => for char types the maximum number of bytes in the column
  17. ORDINAL_POSITION int => index of column in table (starting at 1)
  18. IS_NULLABLE String => "NO" means column definitely does not allow NULL values; "YES" means the column might allow NULL values. An empty string means nobody knows.

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getCrossReference

DatabaseMetaData.getCrossReference

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getCrossReference( String primaryCatalog, String primarySchema, String primaryTable, String foreignCatalog, String foreignSchema, String foreignTable ) throws SQLException
Parameters
primaryCatalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
primarySchema
a schema name pattern; "" retrieves those without a schema
primaryTable
the table name that exports the key
foreignCatalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
foreignSchema
a schema name pattern; "" retrieves those without a schema
foreignTable
the table name that imports the key
Returns
ResultSet - each row is a foreign key column description
Description
Get a description of the foreign key columns in the foreign key table that reference the primary key columns of the primary key table (describe how one table imports another's key.) This should normally return a single foreign key/primary key pair (most tables only import a foreign key from a table once.) They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ.

Each foreign key column description has the following columns:

  1. PKTABLE_CAT String => primary key table catalog (may be null)
  2. PKTABLE_SCHEM String => primary key table schema (may be null)
  3. PKTABLE_NAME String => primary key table name
  4. PKCOLUMN_NAME String => primary key column name
  5. FKTABLE_CAT String => foreign key table catalog (may be null) being exported (may be null)
  6. FKTABLE_SCHEM String => foreign key table schema (may be null) being exported (may be null)
  7. FKTABLE_NAME String => foreign key table name being exported
  8. FKCOLUMN_NAME String => foreign key column name being exported
  9. KEY_SEQ short => sequence number within foreign key
  10. UPDATE_RULE short => What happens to foreign key when primary is updated:
    • importedNoAction - do not allow update of primary key if it has been imported
    • importedKeyCascade - change imported key to agree with primary key update
    • importedKeySetNull - change imported key to NULL if its primary key has been updated
    • importedKeySetDefault - change imported key to default values if its primary key has been updated
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
  11. DELETE_RULE short => What happens to the foreign key when primary is deleted.
    • importedKeyNoAction - do not allow delete of primary key if it has been imported
    • importedKeyCascade - delete rows that import a deleted key
    • importedKeySetNull - change imported key to NULL if its primary key has been deleted
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
    • importedKeySetDefault - change imported key to default if its primary key has been deleted
  12. FK_NAME String => foreign key name (may be null)
  13. PK_NAME String => primary key name (may be null)
  14. DEFERRABILITY short => can the evaluation of foreign key constraints be deferred until commit
    • importedKeyInitiallyDeferred - see SQL92 for definition
    • importedKeyInitiallyImmediate - see SQL92 for definition
    • importedKeyNotDeferrable - see SQL92 for definition

Exceptions
SQLException if a database-access error occurs.
See Also
getImportedKeys


 DatabaseMetaData.getDatabaseProductName

DatabaseMetaData.getDatabaseProductName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getDatabaseProductName() throws SQLException
Returns
database product name
Description
What's the name of this database product?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getDatabaseProductVersion

DatabaseMetaData.getDatabaseProductVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getDatabaseProductVersion() throws SQLException
Returns
database version
Description
What's the version of this database product?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getDefaultTransactionIsolation

DatabaseMetaData.getDefaultTransactionIsolation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getDefaultTransactionIsolation() throws SQLException
Returns
the default isolation level
Description
What's the database's default transaction isolation level? The values are defined in java.sql.Connection.

Exceptions
SQLException if a database-access error occurs.
See Also
Connection


 DatabaseMetaData.getDriverMajorVersion

DatabaseMetaData.getDriverMajorVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getDriverMajorVersion()
Returns
JDBC driver major version
Description
What's this JDBC driver's major version number?


 DatabaseMetaData.getDriverMinorVersion

DatabaseMetaData.getDriverMinorVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getDriverMinorVersion()
Returns
JDBC driver minor version number
Description
What's this JDBC driver's minor version number?


 DatabaseMetaData.getDriverName

DatabaseMetaData.getDriverName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getDriverName() throws SQLException
Returns
JDBC driver name
Description
What's the name of this JDBC driver?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getDriverVersion

DatabaseMetaData.getDriverVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getDriverVersion() throws SQLException
Returns
JDBC driver version
Description
What's the version of this JDBC driver?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getExportedKeys

DatabaseMetaData.getExportedKeys

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getExportedKeys( String catalog, String schema, String table ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name pattern; "" retrieves those without a schema
table
a table name
Returns
ResultSet - each row is a foreign key column description
Description
Get a description of the foreign key columns that reference a table's primary key columns (the foreign keys exported by a table). They are ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME, and KEY_SEQ.

Each foreign key column description has the following columns:

  1. PKTABLE_CAT String => primary key table catalog (may be null)
  2. PKTABLE_SCHEM String => primary key table schema (may be null)
  3. PKTABLE_NAME String => primary key table name
  4. PKCOLUMN_NAME String => primary key column name
  5. FKTABLE_CAT String => foreign key table catalog (may be null) being exported (may be null)
  6. FKTABLE_SCHEM String => foreign key table schema (may be null) being exported (may be null)
  7. FKTABLE_NAME String => foreign key table name being exported
  8. FKCOLUMN_NAME String => foreign key column name being exported
  9. KEY_SEQ short => sequence number within foreign key
  10. UPDATE_RULE short => What happens to foreign key when primary is updated:
    • importedNoAction - do not allow update of primary key if it has been imported
    • importedKeyCascade - change imported key to agree with primary key update
    • importedKeySetNull - change imported key to NULL if its primary key has been updated
    • importedKeySetDefault - change imported key to default values if its primary key has been updated
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
  11. DELETE_RULE short => What happens to the foreign key when primary is deleted.
    • importedKeyNoAction - do not allow delete of primary key if it has been imported
    • importedKeyCascade - delete rows that import a deleted key
    • importedKeySetNull - change imported key to NULL if its primary key has been deleted
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
    • importedKeySetDefault - change imported key to default if its primary key has been deleted
  12. FK_NAME String => foreign key name (may be null)
  13. PK_NAME String => primary key name (may be null)
  14. DEFERRABILITY short => can the evaluation of foreign key constraints be deferred until commit
    • importedKeyInitiallyDeferred - see SQL92 for definition
    • importedKeyInitiallyImmediate - see SQL92 for definition
    • importedKeyNotDeferrable - see SQL92 for definition

Exceptions
SQLException if a database-access error occurs.
See Also
getImportedKeys


 DatabaseMetaData.getExtraNameCharacters

DatabaseMetaData.getExtraNameCharacters

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getExtraNameCharacters() throws SQLException
Returns
the string containing the extra characters
Description
Get all the "extra" characters that can be used in unquoted identifier names (those beyond a-z, A-Z, 0-9 and _).

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getIdentifierQuoteString

DatabaseMetaData.getIdentifierQuoteString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getIdentifierQuoteString() throws SQLException
Returns
the quoting string
Description
What's the string used to quote SQL identifiers? This returns a space " " if identifier quoting isn't supported. A JDBC-Compliant driver always uses a double quote character.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getImportedKeys

DatabaseMetaData.getImportedKeys

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getImportedKeys( String catalog, String schema, String table ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name pattern; "" retrieves those without a schema
table
a table name
Returns
ResultSet - each row is a primary key column description
Description
Get a description of the primary key columns that are referenced by a table's foreign key columns (the primary keys imported by a table). They are ordered by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, and KEY_SEQ.

Each primary key column description has the following columns:

  1. PKTABLE_CAT String => primary key table catalog being imported (may be null)
  2. PKTABLE_SCHEM String => primary key table schema being imported (may be null)
  3. PKTABLE_NAME String => primary key table name being imported
  4. PKCOLUMN_NAME String => primary key column name being imported
  5. FKTABLE_CAT String => foreign key table catalog (may be null)
  6. FKTABLE_SCHEM String => foreign key table schema (may be null)
  7. FKTABLE_NAME String => foreign key table name
  8. FKCOLUMN_NAME String => foreign key column name
  9. KEY_SEQ short => sequence number within foreign key
  10. UPDATE_RULE short => What happens to foreign key when primary is updated:
    • importedNoAction - do not allow update of primary key if it has been imported
    • importedKeyCascade - change imported key to agree with primary key update
    • importedKeySetNull - change imported key to NULL if its primary key has been updated
    • importedKeySetDefault - change imported key to default values if its primary key has been updated
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
  11. DELETE_RULE short => What happens to the foreign key when primary is deleted.
    • importedKeyNoAction - do not allow delete of primary key if it has been imported
    • importedKeyCascade - delete rows that import a deleted key
    • importedKeySetNull - change imported key to NULL if its primary key has been deleted
    • importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
    • importedKeySetDefault - change imported key to default if its primary key has been deleted
  12. FK_NAME String => foreign key name (may be null)
  13. PK_NAME String => primary key name (may be null)
  14. DEFERRABILITY short => can the evaluation of foreign key constraints be deferred until commit
    • importedKeyInitiallyDeferred - see SQL92 for definition
    • importedKeyInitiallyImmediate - see SQL92 for definition
    • importedKeyNotDeferrable - see SQL92 for definition

Exceptions
SQLException if a database-access error occurs.
See Also
getExportedKeys


 DatabaseMetaData.getIndexInfo

DatabaseMetaData.getIndexInfo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getIndexInfo( String catalog, String schema, String table, boolean unique, boolean approximate ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name pattern; "" retrieves those without a schema
table
a table name
unique
when true, return only indices for unique values; when false, return indices regardless of whether unique or not
approximate
when true, result is allowed to reflect approximate or out of data values; when false, results are requested to be accurate
Returns
ResultSet - each row is an index column description
Description
Get a description of a table's indices and statistics. They are ordered by NON_UNIQUE, TYPE, INDEX_NAME, and ORDINAL_POSITION.

Each index column description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. NON_UNIQUE boolean => Can index values be non-unique? false when TYPE is tableIndexStatistic
  5. INDEX_QUALIFIER String => index catalog (may be null); null when TYPE is tableIndexStatistic
  6. INDEX_NAME String => index name; null when TYPE is tableIndexStatistic
  7. TYPE short => index type:
    • tableIndexStatistic - this identifies table statistics that are returned in conjuction with a table's index descriptions
    • tableIndexClustered - this is a clustered index
    • tableIndexHashed - this is a hashed index
    • tableIndexOther - this is some other style of index
  8. ORDINAL_POSITION short => column sequence number within index; zero when TYPE is tableIndexStatistic
  9. COLUMN_NAME String => column name; null when TYPE is tableIndexStatistic
  10. ASC_OR_DESC String => column sort sequence, "A" => ascending, "D" => descending, may be null if sort sequence is not supported; null when TYPE is tableIndexStatistic
  11. CARDINALITY int => When TYPE is tableIndexStatistic, then this is the number of rows in the table; otherwise, it is the number of unique values in the index.
  12. PAGES int => When TYPE is tableIndexStatisic then this is the number of pages used for the table, otherwise it is the number of pages used for the current index.
  13. FILTER_CONDITION String => Filter condition, if any. (may be null)

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxBinaryLiteralLength

DatabaseMetaData.getMaxBinaryLiteralLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxBinaryLiteralLength() throws SQLException
Returns
max literal length
Description
How many hex characters can you have in an inline binary literal?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxCatalogNameLength

DatabaseMetaData.getMaxCatalogNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxCatalogNameLength() throws SQLException
Returns
max name length in bytes
Description
What's the maximum length of a catalog name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxCharLiteralLength

DatabaseMetaData.getMaxCharLiteralLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxCharLiteralLength() throws SQLException
Returns
max literal length
Description
What's the max length for a character literal?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnNameLength

DatabaseMetaData.getMaxColumnNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnNameLength() throws SQLException
Returns
max literal length
Description
What's the limit on column name length?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnsInGroupBy

DatabaseMetaData.getMaxColumnsInGroupBy

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnsInGroupBy() throws SQLException
Returns
max number of columns
Description
What's the maximum number of columns in a "GROUP BY" clause?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnsInIndex

DatabaseMetaData.getMaxColumnsInIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnsInIndex() throws SQLException
Returns
max columns
Description
What's the maximum number of columns allowed in an index?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnsInOrderBy

DatabaseMetaData.getMaxColumnsInOrderBy

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnsInOrderBy() throws SQLException
Returns
max columns
Description
What's the maximum number of columns in an "ORDER BY" clause?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnsInSelect

DatabaseMetaData.getMaxColumnsInSelect

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnsInSelect() throws SQLException
Returns
max columns
Description
What's the maximum number of columns in a "SELECT" list?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxColumnsInTable

DatabaseMetaData.getMaxColumnsInTable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxColumnsInTable() throws SQLException
Returns
max columns
Description
What's the maximum number of columns in a table?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxConnections

DatabaseMetaData.getMaxConnections

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxConnections() throws SQLException
Returns
max connections
Description
How many active connections can we have at a time to this database?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxCursorNameLength

DatabaseMetaData.getMaxCursorNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxCursorNameLength() throws SQLException
Returns
max cursor name length in bytes
Description
What's the maximum cursor name length?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxIndexLength

DatabaseMetaData.getMaxIndexLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxIndexLength() throws SQLException
Returns
max index length in bytes
Description
What's the maximum length of an index (in bytes)?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxProcedureNameLength

DatabaseMetaData.getMaxProcedureNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxProcedureNameLength() throws SQLException
Returns
max name length in bytes
Description
What's the maximum length of a procedure name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxRowSize

DatabaseMetaData.getMaxRowSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxRowSize() throws SQLException
Returns
max row size in bytes
Description
What's the maximum length of a single row?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxSchemaNameLength

DatabaseMetaData.getMaxSchemaNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxSchemaNameLength() throws SQLException
Returns
max name length in bytes
Description
What's the maximum length allowed for a schema name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxStatementLength

DatabaseMetaData.getMaxStatementLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxStatementLength() throws SQLException
Returns
max length in bytes
Description
What's the maximum length of a SQL statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxStatements

DatabaseMetaData.getMaxStatements

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxStatements() throws SQLException
Returns
the maximum
Description
How many active statements can we have open at one time to this database?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxTableNameLength

DatabaseMetaData.getMaxTableNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxTableNameLength() throws SQLException
Returns
max name length in bytes
Description
What's the maximum length of a table name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxTablesInSelect

DatabaseMetaData.getMaxTablesInSelect

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxTablesInSelect() throws SQLException
Returns
the maximum
Description
What's the maximum number of tables in a SELECT?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getMaxUserNameLength

DatabaseMetaData.getMaxUserNameLength

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxUserNameLength() throws SQLException
Returns
max name length in bytes
Description
What's the maximum length of a user name?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getNumericFunctions

DatabaseMetaData.getNumericFunctions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getNumericFunctions() throws SQLException
Returns
the list
Description
Get a comma separated list of math functions.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getPrimaryKeys

DatabaseMetaData.getPrimaryKeys

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getPrimaryKeys( String catalog, String schema, String table ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name pattern; "" retrieves those without a schema
table
a table name
Returns
ResultSet - each row is a primary key column description
Description
Get a description of a table's primary key columns. They are ordered by COLUMN_NAME.

Each primary key column description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. COLUMN_NAME String => column name
  5. KEY_SEQ short => sequence number within primary key
  6. PK_NAME String => primary key name (may be null)

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getProcedureColumns

DatabaseMetaData.getProcedureColumns

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getProcedureColumns( String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schemaPattern
a schema name pattern; "" retrieves those without a schema
procedureNamePattern
a procedure name pattern
columnNamePattern
a column name pattern
Returns
ResultSet - each row is a stored procedure parameter or column description
Description
Get a description of a catalog's stored procedure parameters and result columns.

Only descriptions matching the schema, procedure and parameter name criteria are returned. They are ordered by PROCEDURE_SCHEM and PROCEDURE_NAME. Within this, the return value, if any, is first. Next are the parameter descriptions in call order. The column descriptions follow in column number order.

Each row in the ResultSet is a parameter description or column description with the following fields:

  1. PROCEDURE_CAT String => procedure catalog (may be null)
  2. PROCEDURE_SCHEM String => procedure schema (may be null)
  3. PROCEDURE_NAME String => procedure name
  4. COLUMN_NAME String => column/parameter name
  5. COLUMN_TYPE Short => kind of column/parameter:
    • procedureColumnUnknown - nobody knows
    • procedureColumnIn - IN parameter
    • procedureColumnInOut - INOUT parameter
    • procedureColumnOut - OUT parameter
    • procedureColumnReturn - procedure return value
    • procedureColumnResult - result column in ResultSet
  6. DATA_TYPE short => SQL type from java.sql.Types
  7. TYPE_NAME String => SQL type name
  8. PRECISION int => precision
  9. LENGTH int => length in bytes of data
  10. SCALE short => scale
  11. RADIX short => radix
  12. NULLABLE short => can it contain NULL?
    • procedureNoNulls - does not allow NULL values
    • procedureNullable - allows NULL values
    • procedureNullableUnknown - nullability unknown
  13. REMARKS String => comment describing parameter/column

Note: Some databases may not return the column descriptions for a procedure. Additional columns beyond REMARKS can be defined by the database.

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getProcedures

DatabaseMetaData.getProcedures

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getProcedures( String catalog, String schemaPattern, String procedureNamePattern ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schemaPattern
a schema name pattern; "" retrieves those without a schema
procedureNamePattern
a procedure name pattern
Returns
ResultSet - each row is a procedure description
Description
Get a description of stored procedures available in a catalog.

Only procedure descriptions matching the schema and procedure name criteria are returned. They are ordered by PROCEDURE_SCHEM, and PROCEDURE_NAME.

Each procedure description has the the following columns:

  1. PROCEDURE_CAT String => procedure catalog (may be null)
  2. PROCEDURE_SCHEM String => procedure schema (may be null)
  3. PROCEDURE_NAME String => procedure name
  4. reserved for future use
  5. reserved for future use
  6. reserved for future use
  7. REMARKS String => explanatory comment on the procedure
  8. PROCEDURE_TYPE short => kind of procedure:
    • procedureResultUnknown - May return a result
    • procedureNoResult - Does not return a result
    • procedureReturnsResult - Returns a result

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getProcedureTerm

DatabaseMetaData.getProcedureTerm

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getProcedureTerm() throws SQLException
Returns
the vendor term
Description
What's the database vendor's preferred term for "procedure"?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getSchemas

DatabaseMetaData.getSchemas

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getSchemas() throws SQLException
Returns
ResultSet - each row has a single String column that is a schema name
Description
Get the schema names available in this database. The results are ordered by schema name.

The schema column is:

  1. TABLE_SCHEM String => schema name

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getSchemaTerm

DatabaseMetaData.getSchemaTerm

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getSchemaTerm() throws SQLException
Returns
the vendor term
Description
What's the database vendor's preferred term for "schema"?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getSearchStringEscape

DatabaseMetaData.getSearchStringEscape

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getSearchStringEscape() throws SQLException
Returns
the string used to escape wildcard characters
Description
This is the string that can be used to escape '_' or '%' in the string pattern style catalog search parameters.

The '_' character represents any single character.

The '%' character represents any sequence of zero or more characters.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getSQLKeywords

DatabaseMetaData.getSQLKeywords

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getSQLKeywords() throws SQLException
Returns
the list
Description
Get a comma separated list of all a database's SQL keywords that are NOT also SQL92 keywords.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getStringFunctions

DatabaseMetaData.getStringFunctions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getStringFunctions() throws SQLException
Returns
the list
Description
Get a comma separated list of string functions.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getSystemFunctions

DatabaseMetaData.getSystemFunctions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getSystemFunctions() throws SQLException
Returns
the list
Description
Get a comma separated list of system functions.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getTablePrivileges

DatabaseMetaData.getTablePrivileges

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getTablePrivileges( String catalog, String schemaPattern, String tableNamePattern ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schemaPattern
a schema name pattern; "" retrieves those without a schema
tableNamePattern
a table name pattern
Returns
ResultSet - each row is a table privilege description
Description
Get a description of the access rights for each table available in a catalog. Note that a table privilege applies to one or more columns in the table. It would be wrong to assume that this priviledge applies to all columns (this may be true for some systems but is not true for all.)

Only privileges matching the schema and table name criteria are returned. They are ordered by TABLE_SCHEM, TABLE_NAME, and PRIVILEGE.

Each privilige description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. GRANTOR => grantor of access (may be null)
  5. GRANTEE String => grantee of access
  6. PRIVILEGE String => name of access (SELECT, INSERT, UPDATE, REFRENCES, ...)
  7. IS_GRANTABLE String => "YES" if grantee is permitted to grant to others; "NO" if not; null if unknown

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getTables

DatabaseMetaData.getTables

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getTables( String catalog, String schemaPattern, String tableNamePattern, String types[] ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schemaPattern
a schema name pattern; "" retrieves those without a schema
tableNamePattern
a table name pattern
types
a list of table types to include; null returns all types
Returns
ResultSet - each row is a table description
Description
Get a description of tables available in a catalog.

Only table descriptions matching the catalog, schema, table name and type criteria are returned. They are ordered by TABLE_TYPE, TABLE_SCHEM and TABLE_NAME.

Each table description has the following columns:

  1. TABLE_CAT String => table catalog (may be null)
  2. TABLE_SCHEM String => table schema (may be null)
  3. TABLE_NAME String => table name
  4. TABLE_TYPE String => table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
  5. REMARKS String => explanatory comment on the table

Note: Some databases may not return information for all tables.

Exceptions
SQLException if a database-access error occurs.
See Also
getSearchStringEscape


 DatabaseMetaData.getTableTypes

DatabaseMetaData.getTableTypes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getTableTypes() throws SQLException
Returns
ResultSet - each row has a single String column that is a table type
Description
Get the table types available in this database. The results are ordered by table type.

The table type is:

  1. TABLE_TYPE String => table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getTimeDateFunctions

DatabaseMetaData.getTimeDateFunctions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getTimeDateFunctions() throws SQLException
Returns
the list
Description
Get a comma separated list of time and date functions.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getTypeInfo

DatabaseMetaData.getTypeInfo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getTypeInfo() throws SQLException
Returns
ResultSet - each row is a SQL type description
Description
Get a description of all the standard SQL types supported by this database. They are ordered by DATA_TYPE and then by how closely the data type maps to the corresponding JDBC SQL type.

Each type description has the following columns:

  1. TYPE_NAME String => Type name
  2. DATA_TYPE short => SQL data type from java.sql.Types
  3. PRECISION int => maximum precision
  4. LITERAL_PREFIX String => prefix used to quote a literal (may be null)
  5. LITERAL_SUFFIX String => suffix used to quote a literal (may be null)
  6. CREATE_PARAMS String => parameters used in creating the type (may be null)
  7. NULLABLE short => can you use NULL for this type?
    • typeNoNulls - does not allow NULL values
    • typeNullable - allows NULL values
    • typeNullableUnknown - nullability unknown
  8. CASE_SENSITIVE boolean=> is it case sensitive?
  9. SEARCHABLE short => can you use "WHERE" based on this type:
    • typePredNone - No support
    • typePredChar - Only supported with WHERE .. LIKE
    • typePredBasic - Supported except for WHERE .. LIKE
    • typeSearchable - Supported for all WHERE ..
  10. UNSIGNED_ATTRIBUTE boolean => is it unsigned?
  11. FIXED_PREC_SCALE boolean => can it be a money value?
  12. AUTO_INCREMENT boolean => can it be used for an auto-increment value?
  13. LOCAL_TYPE_NAME String => localized version of type name (may be null)
  14. MINIMUM_SCALE short => minimum scale supported
  15. MAXIMUM_SCALE short => maximum scale supported
  16. SQL_DATA_TYPE int => unused
  17. SQL_DATETIME_SUB int => unused
  18. NUM_PREC_RADIX int => usually 2 or 10

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getURL

DatabaseMetaData.getURL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getURL() throws SQLException
Returns
the url or null if it can't be generated
Description
What's the url for this database?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getUserName

DatabaseMetaData.getUserName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getUserName() throws SQLException
Returns
our database user name
Description
What's our user name as known to the database?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.getVersionColumns

DatabaseMetaData.getVersionColumns

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getVersionColumns( String catalog, String schema, String table ) throws SQLException
Parameters
catalog
a catalog name; "" retrieves those without a catalog; null means drop catalog name from the selection criteria
schema
a schema name; "" retrieves those without a schema
table
a table name
Returns
ResultSet - each row is a column description
Description
Get a description of a table's columns that are automatically updated when any value in a row is updated. They are unordered.

Each column description has the following columns:

  1. SCOPE short => is not used
  2. COLUMN_NAME String => column name
  3. DATA_TYPE short => SQL data type from java.sql.Types
  4. TYPE_NAME String => Data source dependent type name
  5. COLUMN_SIZE int => precision
  6. BUFFER_LENGTH int => length of column value in bytes
  7. DECIMAL_DIGITS short => scale
  8. PSEUDO_COLUMN short => is this a pseudo column like an Oracle ROWID
    • versionColumnUnknown - may or may not be pseudo column
    • versionColumnNotPseudo - is NOT a pseudo column
    • versionColumnPseudo - is a pseudo column

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.isCatalogAtStart

DatabaseMetaData.isCatalogAtStart

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isCatalogAtStart() throws SQLException
Returns
true if it appears at the start
Description
Does a catalog appear at the start of a qualified table name? (Otherwise it appears at the end)

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.isReadOnly

DatabaseMetaData.isReadOnly

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isReadOnly() throws SQLException
Returns
true if so
Description
Is the database in read-only mode?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.nullPlusNonNullIsNull

DatabaseMetaData.nullPlusNonNullIsNull

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean nullPlusNonNullIsNull() throws SQLException
Returns
true if so
Description
Are concatenations between NULL and non-NULL values NULL? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.nullsAreSortedAtEnd

DatabaseMetaData.nullsAreSortedAtEnd

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean nullsAreSortedAtEnd() throws SQLException
Returns
true if so
Description
Are NULL values sorted at the end regardless of sort order?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.nullsAreSortedAtStart

DatabaseMetaData.nullsAreSortedAtStart

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean nullsAreSortedAtStart() throws SQLException
Returns
true if so
Description
Are NULL values sorted at the start regardless of sort order?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.nullsAreSortedHigh

DatabaseMetaData.nullsAreSortedHigh

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean nullsAreSortedHigh() throws SQLException
Returns
true if so
Description
Are NULL values sorted high?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.nullsAreSortedLow

DatabaseMetaData.nullsAreSortedLow

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean nullsAreSortedLow() throws SQLException
Returns
true if so
Description
Are NULL values sorted low?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesLowerCaseIdentifiers

DatabaseMetaData.storesLowerCaseIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesLowerCaseIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in lower case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesLowerCaseQuotedIdentifiers

DatabaseMetaData.storesLowerCaseQuotedIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesLowerCaseQuotedIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in lower case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesMixedCaseIdentifiers

DatabaseMetaData.storesMixedCaseIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesMixedCaseIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in mixed case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesMixedCaseQuotedIdentifiers

DatabaseMetaData.storesMixedCaseQuotedIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesMixedCaseQuotedIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in mixed case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesUpperCaseIdentifiers

DatabaseMetaData.storesUpperCaseIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesUpperCaseIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case unquoted SQL identifiers as case insensitive and store them in upper case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.storesUpperCaseQuotedIdentifiers

DatabaseMetaData.storesUpperCaseQuotedIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean storesUpperCaseQuotedIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case quoted SQL identifiers as case insensitive and store them in upper case?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsAlterTableWithAddColumn

DatabaseMetaData.supportsAlterTableWithAddColumn

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsAlterTableWithAddColumn() throws SQLException
Returns
true if so
Description
Is "ALTER TABLE" with add column supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsAlterTableWithDropColumn

DatabaseMetaData.supportsAlterTableWithDropColumn

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsAlterTableWithDropColumn() throws SQLException
Returns
true if so
Description
Is "ALTER TABLE" with drop column supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsANSI92EntryLevelSQL

DatabaseMetaData.supportsANSI92EntryLevelSQL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsANSI92EntryLevelSQL() throws SQLException
Returns
true if so
Description
Is the ANSI92 entry level SQL grammar supported? All JDBC-Compliant drivers must return true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsANSI92FullSQL

DatabaseMetaData.supportsANSI92FullSQL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsANSI92FullSQL() throws SQLException
Returns
true if so
Description
Is the ANSI92 full SQL grammar supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsANSI92IntermediateSQL

DatabaseMetaData.supportsANSI92IntermediateSQL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsANSI92IntermediateSQL() throws SQLException
Returns
true if so
Description
Is the ANSI92 intermediate SQL grammar supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCatalogsInDataManipulation

DatabaseMetaData.supportsCatalogsInDataManipulation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCatalogsInDataManipulation() throws SQLException
Returns
true if so
Description
Can a catalog name be used in a data manipulation statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCatalogsInIndexDefinitions

DatabaseMetaData.supportsCatalogsInIndexDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCatalogsInIndexDefinitions() throws SQLException
Returns
true if so
Description
Can a catalog name be used in an index definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCatalogsInPrivilegeDefinitions

DatabaseMetaData.supportsCatalogsInPrivilegeDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException
Returns
true if so
Description
Can a catalog name be used in a privilege definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCatalogsInProcedureCalls

DatabaseMetaData.supportsCatalogsInProcedureCalls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCatalogsInProcedureCalls() throws SQLException
Returns
true if so
Description
Can a catalog name be used in a procedure call statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCatalogsInTableDefinitions

DatabaseMetaData.supportsCatalogsInTableDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCatalogsInTableDefinitions() throws SQLException
Returns
true if so
Description
Can a catalog name be used in a table definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsColumnAliasing

DatabaseMetaData.supportsColumnAliasing

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsColumnAliasing() throws SQLException
Returns
true if so
Description
Is column aliasing supported?

If so, the SQL AS clause can be used to provide names for computed columns or to provide alias names for columns as required. A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsConvert

DatabaseMetaData.supportsConvert

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract boolean supportsConvert() throws SQLException
Returns
true if so
Description
Is the CONVERT function between SQL types supported?

Exceptions
SQLException if a database-access error occurs.

Syntax 2
public abstract boolean supportsConvert( int fromType, int toType ) throws SQLException
Parameters
fromType
the type to convert from
toType
the type to convert to
Returns
true if so
Description
Is CONVERT between the given SQL types supported?

Exceptions
SQLException if a database-access error occurs.
See Also
Types


 DatabaseMetaData.supportsCoreSQLGrammar

DatabaseMetaData.supportsCoreSQLGrammar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCoreSQLGrammar() throws SQLException
Returns
true if so
Description
Is the ODBC Core SQL grammar supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsCorrelatedSubqueries

DatabaseMetaData.supportsCorrelatedSubqueries

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsCorrelatedSubqueries() throws SQLException
Returns
true if so
Description
Are correlated subqueries supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsDataDefinitionAndDataManipulationTransactions

DatabaseMetaData.supportsDataDefinitionAndDataManipulationTransactions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException
Returns
true if so
Description
Are both data definition and data manipulation statements within a transaction supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsDataManipulationTransactionsOnly

DatabaseMetaData.supportsDataManipulationTransactionsOnly

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsDataManipulationTransactionsOnly() throws SQLException
Returns
true if so
Description
Are only data manipulation statements within a transaction supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsDifferentTableCorrelationNames

DatabaseMetaData.supportsDifferentTableCorrelationNames

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsDifferentTableCorrelationNames() throws SQLException
Returns
true if so
Description
If table correlation names are supported, are they restricted to be different from the names of the tables?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsExpressionsInOrderBy

DatabaseMetaData.supportsExpressionsInOrderBy

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsExpressionsInOrderBy() throws SQLException
Returns
true if so
Description
Are expressions in "ORDER BY" lists supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsExtendedSQLGrammar

DatabaseMetaData.supportsExtendedSQLGrammar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsExtendedSQLGrammar() throws SQLException
Returns
true if so
Description
Is the ODBC Extended SQL grammar supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsFullOuterJoins

DatabaseMetaData.supportsFullOuterJoins

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsFullOuterJoins() throws SQLException
Returns
true if so
Description
Are full nested outer joins supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsGroupBy

DatabaseMetaData.supportsGroupBy

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsGroupBy() throws SQLException
Returns
true if so
Description
Is some form of "GROUP BY" clause supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsGroupByBeyondSelect

DatabaseMetaData.supportsGroupByBeyondSelect

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsGroupByBeyondSelect() throws SQLException
Returns
true if so
Description
Can a "GROUP BY" clause add columns not in the SELECT provided it specifies all the columns in the SELECT?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsGroupByUnrelated

DatabaseMetaData.supportsGroupByUnrelated

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsGroupByUnrelated() throws SQLException
Returns
true if so
Description
Can a "GROUP BY" clause use columns not in the SELECT?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsIntegrityEnhancementFacility

DatabaseMetaData.supportsIntegrityEnhancementFacility

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsIntegrityEnhancementFacility() throws SQLException
Returns
true if so
Description
Is the SQL Integrity Enhancement Facility supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsLikeEscapeClause

DatabaseMetaData.supportsLikeEscapeClause

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsLikeEscapeClause() throws SQLException
Returns
true if so
Description
Is the escape character in "LIKE" clauses supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsLimitedOuterJoins

DatabaseMetaData.supportsLimitedOuterJoins

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsLimitedOuterJoins() throws SQLException
Returns
true if so
Description
Is there limited support for outer joins? (This will be true if supportFullOuterJoins is true.)

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsMinimumSQLGrammar

DatabaseMetaData.supportsMinimumSQLGrammar

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsMinimumSQLGrammar() throws SQLException
Returns
true if so
Description
Is the ODBC Minimum SQL grammar supported? All JDBC-Compliant drivers must return true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsMixedCaseIdentifiers

DatabaseMetaData.supportsMixedCaseIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsMixedCaseIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case unquoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC-Compliant driver will always return false.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsMixedCaseQuotedIdentifiers

DatabaseMetaData.supportsMixedCaseQuotedIdentifiers

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsMixedCaseQuotedIdentifiers() throws SQLException
Returns
true if so
Description
Does the database treat mixed case quoted SQL identifiers as case sensitive and as a result store them in mixed case? A JDBC-Compliant driver will always return true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsMultipleResultSets

DatabaseMetaData.supportsMultipleResultSets

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsMultipleResultSets() throws SQLException
Returns
true if so
Description
Are multiple ResultSets from a single execute supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsMultipleTransactions

DatabaseMetaData.supportsMultipleTransactions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsMultipleTransactions() throws SQLException
Returns
true if so
Description
Can we have multiple transactions open at once (on different connections)?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsNonNullableColumns

DatabaseMetaData.supportsNonNullableColumns

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsNonNullableColumns() throws SQLException
Returns
true if so
Description
Can columns be defined as non-nullable? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOpenCursorsAcrossCommit

DatabaseMetaData.supportsOpenCursorsAcrossCommit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOpenCursorsAcrossCommit() throws SQLException
Returns
true if cursors always remain open; false if they might not remain open
Description
Can cursors remain open across commits?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOpenCursorsAcrossRollback

DatabaseMetaData.supportsOpenCursorsAcrossRollback

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOpenCursorsAcrossRollback() throws SQLException
Returns
true if cursors always remain open; false if they might not remain open
Description
Can cursors remain open across rollbacks?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOpenStatementsAcrossCommit

DatabaseMetaData.supportsOpenStatementsAcrossCommit

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOpenStatementsAcrossCommit() throws SQLException
Returns
true if statements always remain open; false if they might not remain open
Description
Can statements remain open across commits?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOpenStatementsAcrossRollback

DatabaseMetaData.supportsOpenStatementsAcrossRollback

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOpenStatementsAcrossRollback() throws SQLException
Returns
true if statements always remain open; false if they might not remain open
Description
Can statements remain open across rollbacks?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOrderByUnrelated

DatabaseMetaData.supportsOrderByUnrelated

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOrderByUnrelated() throws SQLException
Returns
true if so
Description
Can an "ORDER BY" clause use columns not in the SELECT?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsOuterJoins

DatabaseMetaData.supportsOuterJoins

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsOuterJoins() throws SQLException
Returns
true if so
Description
Is some form of outer join supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsPositionedDelete

DatabaseMetaData.supportsPositionedDelete

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsPositionedDelete() throws SQLException
Returns
true if so
Description
Is positioned DELETE supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsPositionedUpdate

DatabaseMetaData.supportsPositionedUpdate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsPositionedUpdate() throws SQLException
Returns
true if so
Description
Is positioned UPDATE supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSchemasInDataManipulation

DatabaseMetaData.supportsSchemasInDataManipulation

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSchemasInDataManipulation() throws SQLException
Returns
true if so
Description
Can a schema name be used in a data manipulation statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSchemasInIndexDefinitions

DatabaseMetaData.supportsSchemasInIndexDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSchemasInIndexDefinitions() throws SQLException
Returns
true if so
Description
Can a schema name be used in an index definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSchemasInPrivilegeDefinitions

DatabaseMetaData.supportsSchemasInPrivilegeDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSchemasInPrivilegeDefinitions() throws SQLException
Returns
true if so
Description
Can a schema name be used in a privilege definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSchemasInProcedureCalls

DatabaseMetaData.supportsSchemasInProcedureCalls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSchemasInProcedureCalls() throws SQLException
Returns
true if so
Description
Can a schema name be used in a procedure call statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSchemasInTableDefinitions

DatabaseMetaData.supportsSchemasInTableDefinitions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSchemasInTableDefinitions() throws SQLException
Returns
true if so
Description
Can a schema name be used in a table definition statement?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSelectForUpdate

DatabaseMetaData.supportsSelectForUpdate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSelectForUpdate() throws SQLException
Returns
true if so
Description
Is SELECT for UPDATE supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsStoredProcedures

DatabaseMetaData.supportsStoredProcedures

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsStoredProcedures() throws SQLException
Returns
true if so
Description
Are stored procedure calls using the stored procedure escape syntax supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSubqueriesInComparisons

DatabaseMetaData.supportsSubqueriesInComparisons

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSubqueriesInComparisons() throws SQLException
Returns
true if so
Description
Are subqueries in comparison expressions supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSubqueriesInExists

DatabaseMetaData.supportsSubqueriesInExists

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSubqueriesInExists() throws SQLException
Returns
true if so
Description
Are subqueries in 'exists' expressions supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSubqueriesInIns

DatabaseMetaData.supportsSubqueriesInIns

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSubqueriesInIns() throws SQLException
Returns
true if so
Description
Are subqueries in 'in' statements supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsSubqueriesInQuantifieds

DatabaseMetaData.supportsSubqueriesInQuantifieds

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsSubqueriesInQuantifieds() throws SQLException
Returns
true if so
Description
Are subqueries in quantified expressions supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsTableCorrelationNames

DatabaseMetaData.supportsTableCorrelationNames

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsTableCorrelationNames() throws SQLException
Returns
true if so
Description
Are table correlation names supported? A JDBC-Compliant driver always returns true.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsTransactionIsolationLevel

DatabaseMetaData.supportsTransactionIsolationLevel

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsTransactionIsolationLevel( int level ) throws SQLException
Parameters
level
the values are defined in java.sql.Connection
Returns
true if so
Description
Does the database support the given transaction isolation level?

Exceptions
SQLException if a database-access error occurs.
See Also
Connection


 DatabaseMetaData.supportsTransactions

DatabaseMetaData.supportsTransactions

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsTransactions() throws SQLException
Returns
true if transactions are supported
Description
Are transactions supported? If not, commit is a noop and the isolation level is TRANSACTION_NONE.

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsUnion

DatabaseMetaData.supportsUnion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsUnion() throws SQLException
Returns
true if so
Description
Is SQL UNION supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.supportsUnionAll

DatabaseMetaData.supportsUnionAll

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean supportsUnionAll() throws SQLException
Returns
true if so
Description
Is SQL UNION ALL supported?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.usesLocalFilePerTable

DatabaseMetaData.usesLocalFilePerTable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean usesLocalFilePerTable() throws SQLException
Returns
true if the database uses a local file for each table
Description
Does the database use a file for each table?

Exceptions
SQLException if a database-access error occurs.


 DatabaseMetaData.usesLocalFiles

DatabaseMetaData.usesLocalFiles

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean usesLocalFiles() throws SQLException
Returns
true if so
Description
Does the database store tables in a local file?

Exceptions
SQLException if a database-access error occurs.


 Class Date

Class java.sql.Date

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Date
           |
           +----java.sql.Date

public class Date
extends Date

This class is a thin wrapper around java.util.Date that allows JDBC to identify this as a SQL DATE value. It adds formatting and parsing operations to support the JDBC escape syntax for date values.


 Date Members

Date Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Date(int, int, int) | Construct a Date
Date(long) | Construct a Date using a milliseconds time value

Methods
Name | Description
getHours() | Returns the hour represented by this date.
getMinutes() | Returns the number of minutes past the hour represented by this date.
getSeconds() | Returns the number of seconds past the minute represented by this date.
setHours(int) | Sets the hour of this date to the specified value.
setMinutes(int) | Sets the minutes of this date to the specified value.
setSeconds(int) | Sets the seconds of this date to the specified value.
setTime(long) | Set a Date using a milliseconds time value
toString() | Format a date in JDBC date escape format
valueOf(String) | Convert a string in JDBC date escape format to a Date value


 Date.Date

Date.Date

Syntax 1
public Date( int year, int month, int day )
Parameters
year
year-1900
month
0 to 11
day
1 to 31
Description
Construct a Date

Syntax 2
public Date( long date )
Parameters
date
milliseconds since January 1, 1970, 00:00:00 GMT
Description
Construct a Date using a milliseconds time value


 Date.getHours

Date.getHours

Syntax
public int getHours()
Description
Returns the hour represented by this date.

Overrides
getHours in class Date


 Date.getMinutes

Date.getMinutes

Syntax
public int getMinutes()
Description
Returns the number of minutes past the hour represented by this date.

Overrides
getMinutes in class Date


 Date.getSeconds

Date.getSeconds

Syntax
public int getSeconds()
Description
Returns the number of seconds past the minute represented by this date.

Overrides
getSeconds in class Date


 Date.setHours

Date.setHours

Syntax
public void setHours( int i )
Description
Sets the hour of this date to the specified value.

Overrides
setHours in class Date


 Date.setMinutes

Date.setMinutes

Syntax
public void setMinutes( int i )
Description
Sets the minutes of this date to the specified value.

Overrides
setMinutes in class Date


 Date.setSeconds

Date.setSeconds

Syntax
public void setSeconds( int i )
Description
Sets the seconds of this date to the specified value.

Overrides
setSeconds in class Date


 Date.setTime

Date.setTime

Syntax
public void setTime( long date )
Parameters
date
milliseconds since January 1, 1970, 00:00:00 GMT
Description
Set a Date using a milliseconds time value

Overrides
setTime in class Date


 Date.toString

Date.toString

Syntax
public String toString()
Returns
a String in yyyy-mm-dd format
Description
Format a date in JDBC date escape format

Overrides
toString in class Date


 Date.valueOf

Date.valueOf

Syntax
public static Date valueOf( String s )
Parameters
s
date in format "yyyy-mm-dd"
Returns
corresponding Date
Description
Convert a string in JDBC date escape format to a Date value


 Interface Driver

Interface java.sql.Driver

Interface Members | This Package | All Packages

public interface Driver

The Java SQL framework allows for multiple database drivers.

Each driver should supply a class that implements the Driver interface.

The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.

It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast quantities of supporting code.

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by doing Class.forName("foo.bah.Driver").

See Also:
DriverManager, Connection


 Driver Members

Driver Members

Interface Overview | This Package | All Packages

Methods
Name | Description
acceptsURL(String) | Returns true if the driver thinks that it can open a connection to the given URL.
connect(String, Properties) | Try to make a database connection to the given URL.
getMajorVersion() | Get the driver's major version number.
getMinorVersion() | Get the driver's minor version number.
getPropertyInfo(String, Properties) | The getPropertyInfo method is intended to allow a generic GUI tool to discover what properties it should prompt a human for in order to get enough information to connect to a database.
jdbcCompliant() | Report whether the Driver is a genuine JDBC COMPLIANT (tm) driver.


 Driver.acceptsURL

Driver.acceptsURL

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean acceptsURL( String url ) throws SQLException
Parameters
url
The URL of the database.
Returns
True if this driver can connect to the given URL.
Description
Returns true if the driver thinks that it can open a connection to the given URL. Typically drivers will return true if they understand the subprotocol specified in the URL and false if they don't.

Exceptions
SQLException if a database-access error occurs.


 Driver.connect

Driver.connect

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Connection connect( String url, Properties info ) throws SQLException
Parameters
url
The URL of the database to connect to
info
a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and "password" property should be included
Returns
a Connection to the URL
Description
Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.

The driver should raise a SQLException if it is the right driver to connect to the given URL, but has trouble connecting to the database.

The java.util.Properties argument can be used to passed arbitrary string tag/value pairs as connection arguments. Normally at least "user" and "password" properties should be included in the Properties.

Exceptions
SQLException if a database-access error occurs.


 Driver.getMajorVersion

Driver.getMajorVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMajorVersion()
Description
Get the driver's major version number. Initially this should be 1.


 Driver.getMinorVersion

Driver.getMinorVersion

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMinorVersion()
Description
Get the driver's minor version number. Initially this should be 0.


 Driver.getPropertyInfo

Driver.getPropertyInfo

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract DriverPropertyInfo[] getPropertyInfo( String url, Properties info ) throws SQLException
Parameters
url
The URL of the database to connect to.
info
A proposed list of tag/value pairs that will be sent on connect open.
Returns
An array of DriverPropertyInfo objects describing possible properties. This array may be an empty array if no properties are required.
Description

The getPropertyInfo method is intended to allow a generic GUI tool to discover what properties it should prompt a human for in order to get enough information to connect to a database. Note that depending on the values the human has supplied so far, additional values may become necessary, so it may be necessary to iterate though several calls to getPropertyInfo.

Exceptions
SQLException if a database-access error occurs.


 Driver.jdbcCompliant

Driver.jdbcCompliant

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean jdbcCompliant()
Description
Report whether the Driver is a genuine JDBC COMPLIANT (tm) driver. A driver may only report "true" here if it passes the JDBC compliance tests, otherwise it is required to return false. JDBC compliance requires full support for the JDBC API and full support for SQL 92 Entry Level. It is expected that JDBC compliant drivers will be available for all the major commercial databases. This method is not intended to encourage the development of non-JDBC compliant drivers, but is a recognition of the fact that some vendors are interested in using the JDBC API and framework for lightweight databases that do not support full database functionality, or for special databases such as document information retrieval where a SQL implementation may not be feasible.


 Class DriverManager

Class java.sql.DriverManager

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.sql.DriverManager

public class DriverManager
extends Object

The DriverManager provides a basic service for managing a set of JDBC drivers.

As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications. For example in your ~/.hotjava/properties file you might specify: jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver A program can also explicitly load JDBC drivers at any time. For example, the my.sql.Driver is loaded with the following statement: Class.forName("my.sql.Driver");

When getConnection is called the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

See Also:
Driver, Connection


 DriverManager Members

DriverManager Members

Class Overview | This Package | All Packages

Methods
Name | Description
deregisterDriver(Driver) | Drop a Driver from the DriverManager's list.
getConnection(String) | Attempt to establish a connection to the given database URL.
getConnection(String, Properties) | Attempt to establish a connection to the given database URL.
getConnection(String, String, String) | Attempt to establish a connection to the given database URL.
getDriver(String) | Attempt to locate a driver that understands the given URL.
getDrivers() | Return an Enumeration of all the currently loaded JDBC drivers which the current caller has access to.
getLoginTimeout() | Get the maximum time in seconds that all drivers can wait when attempting to log in to a database.
getLogStream() | Get the logging/tracing PrintStream that is used by the DriverManager and all drivers.
println(String) | Print a message to the current JDBC log stream
registerDriver(Driver) | A newly loaded driver class should call registerDriver to make itself known to the DriverManager.
setLoginTimeout(int) | Set the maximum time in seconds that all drivers can wait when attempting to log in to a database.
setLogStream(PrintStream) | Set the logging/tracing PrintStream that is used by the DriverManager and all drivers.


 DriverManager.deregisterDriver

DriverManager.deregisterDriver

Syntax
public static void deregisterDriver( Driver driver ) throws SQLException
Parameters
driver
the JDBC Driver to drop
Description
Drop a Driver from the DriverManager's list. Applets can only deregister Drivers from their own classloader.

Exceptions
SQLException if a database-access error occurs.


 DriverManager.getConnection

DriverManager.getConnection

Syntax 1
public static synchronized Connection getConnection( String url, Properties info ) throws SQLException
Parameters
url
a database url of the form jdbc:subprotocol:subname
info
a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and "password" property should be included
Returns
a Connection to the URL
Description
Attempt to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Exceptions
SQLException if a database-access error occurs.

Syntax 2
public static synchronized Connection getConnection( String url, String user, String password ) throws SQLException
Parameters
url
a database url of the form jdbc:subprotocol:subname
user
the database user on whose behalf the Connection is being made
password
the user's password
Returns
a Connection to the URL
Description
Attempt to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Exceptions
SQLException if a database-access error occurs.

Syntax 3
public static synchronized Connection getConnection( String url ) throws SQLException
Parameters
url
a database url of the form jdbc:subprotocol:subname
Returns
a Connection to the URL
Description
Attempt to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Exceptions
SQLException if a database-access error occurs.


 DriverManager.getDriver

DriverManager.getDriver

Syntax
public static Driver getDriver( String url ) throws SQLException
Parameters
url
a database url of the form jdbc:subprotocol:subname
Returns
a Driver that can connect to the URL
Description
Attempt to locate a driver that understands the given URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Exceptions
SQLException if a database-access error occurs.


 DriverManager.getDrivers

DriverManager.getDrivers

Syntax
public static Enumeration getDrivers()
Returns
the list of JDBC Drivers loaded by the caller's class loader
Description
Return an Enumeration of all the currently loaded JDBC drivers which the current caller has access to.

Note: The classname of a driver can be found using d.getClass().getName()


 DriverManager.getLoginTimeout

DriverManager.getLoginTimeout

Syntax
public static int getLoginTimeout()
Returns
the driver login time limit
Description
Get the maximum time in seconds that all drivers can wait when attempting to log in to a database.


 DriverManager.getLogStream

DriverManager.getLogStream

Syntax
public static PrintStream getLogStream()
Returns
the logging/tracing PrintStream; if disabled, is null
Description
Get the logging/tracing PrintStream that is used by the DriverManager and all drivers.


 DriverManager.println

DriverManager.println

Syntax
public static void println( String message )
Parameters
message
a log or tracing message
Description
Print a message to the current JDBC log stream


 DriverManager.registerDriver

DriverManager.registerDriver

Syntax
public static synchronized void registerDriver( Driver driver ) throws SQLException
Parameters
driver
the new JDBC Driver
Description
A newly loaded driver class should call registerDriver to make itself known to the DriverManager.

Exceptions
SQLException if a database-access error occurs.


 DriverManager.setLoginTimeout

DriverManager.setLoginTimeout

Syntax
public static void setLoginTimeout( int seconds )
Parameters
seconds
the driver login time limit
Description
Set the maximum time in seconds that all drivers can wait when attempting to log in to a database.


 DriverManager.setLogStream

DriverManager.setLogStream

Syntax
public static void setLogStream( PrintStream out )
Parameters
out
the new logging/tracing PrintStream; to disable, set to null
Description
Set the logging/tracing PrintStream that is used by the DriverManager and all drivers.


 Class DriverPropertyInfo

Class java.sql.DriverPropertyInfo

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.sql.DriverPropertyInfo

public class DriverPropertyInfo
extends Object

The DriverPropertyInfo class is only of interest to advanced programmers who need to interact with a Driver via getDriverProperties to discover and supply properties for connections.


 DriverPropertyInfo Members

DriverPropertyInfo Members

Class Overview | This Package | All Packages

Fields
Name | Description
choices | If the value may be selected from a particular set of values, then this is an array of the possible values.
description | A brief description of the property.
name | The name of the property.
required | "required" is true if a value must be supplied for this property during Driver.connect.
value | "value" specifies the current value of the property, based on a combination of the information supplied to getPropertyInfo, the Java environment, and driver supplied default values.

Constructors
Name | Description
DriverPropertyInfo(String, String) | Constructor a DriverPropertyInfo with a name and value; other members default to their initial values.


 DriverPropertyInfo.choices

DriverPropertyInfo.choices

Syntax
public String choices[]
Description
If the value may be selected from a particular set of values, then this is an array of the possible values. Otherwise it should be null.


 DriverPropertyInfo.description

DriverPropertyInfo.description

Syntax
public String description
Description
A brief description of the property. This may be null.


 DriverPropertyInfo.name

DriverPropertyInfo.name

Syntax
public String name
Description
The name of the property.


 DriverPropertyInfo.required

DriverPropertyInfo.required

Syntax
public boolean required
Description
"required" is true if a value must be supplied for this property during Driver.connect. Otherwise the property is optional.


 DriverPropertyInfo.value

DriverPropertyInfo.value

Syntax
public String value
Description
"value" specifies the current value of the property, based on a combination of the information supplied to getPropertyInfo, the Java environment, and driver supplied default values. This may be null if no value is known.


 DriverPropertyInfo.DriverPropertyInfo

DriverPropertyInfo.DriverPropertyInfo

Syntax
public DriverPropertyInfo( String name, String value )
Parameters
name
the name of the property
value
the current value, which may be null
Description
Constructor a DriverPropertyInfo with a name and value; other members default to their initial values.


 Interface PreparedStatement

Interface java.sql.PreparedStatement

Interface Members | This Package | All Packages

public interface PreparedStatement
extends Statement

A SQL statement is pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: The setXXX methods for setting IN parameter values must specify types that are compatible with the defined SQL type of the input parameter. For instance, if the IN parameter has SQL type Integer then setInt should be used.

If arbitrary parameter type conversions are required then the setObject method should be used with a target SQL type.

See Also:
prepareStatement, ResultSet


 PreparedStatement Members

PreparedStatement Members

Interface Overview | This Package | All Packages

Methods
Name | Description
clearParameters() | In general, parameter values remain in force for repeated use of a Statement.
execute() | Some prepared statements return multiple results; the execute method handles these complex statements as well as the simpler form of statements handled by executeQuery and executeUpdate.
executeQuery() | A prepared SQL query is executed and its ResultSet is returned.
executeUpdate() | Execute a SQL INSERT, UPDATE or DELETE statement.
setAsciiStream(int, InputStream, int) | When a very large ASCII value is input to a LONGVARCHAR parameter, it may be more practical to send it via a java.io.InputStream.
setBigDecimal(int, BigDecimal) | Set a parameter to a java.lang.BigDecimal value.
setBinaryStream(int, InputStream, int) | When a very large binary value is input to a LONGVARBINARY parameter, it may be more practical to send it via a java.io.InputStream.
setBoolean(int, boolean) | Set a parameter to a Java boolean value.
setByte(int, byte) | Set a parameter to a Java byte value.
setBytes(int, byte[]) | Set a parameter to a Java array of bytes.
setDate(int, Date) | Set a parameter to a java.sql.Date value.
setDouble(int, double) | Set a parameter to a Java double value.
setFloat(int, float) | Set a parameter to a Java float value.
setInt(int, int) | Set a parameter to a Java int value.
setLong(int, long) | Set a parameter to a Java long value.
setNull(int, int) | Set a parameter to SQL NULL.
setObject(int, Object) | Set the value of a parameter using an object; use the java.lang equivalent objects for integral values.
setObject(int, Object, int) | This method is like setObject above, but assumes a scale of zero.
setObject(int, Object, int, int) | Set the value of a parameter using an object; use the java.lang equivalent objects for integral values.
setShort(int, short) | Set a parameter to a Java short value.
setString(int, String) | Set a parameter to a Java String value.
setTime(int, Time) | Set a parameter to a java.sql.Time value.
setTimestamp(int, Timestamp) | Set a parameter to a java.sql.Timestamp value.
setUnicodeStream(int, InputStream, int) | When a very large UNICODE value is input to a LONGVARCHAR parameter, it may be more practical to send it via a java.io.InputStream.


 PreparedStatement.clearParameters

PreparedStatement.clearParameters

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void clearParameters() throws SQLException
Description

In general, parameter values remain in force for repeated use of a Statement. Setting a parameter value automatically clears its previous value. However, in some cases it is useful to immediately release the resources used by the current parameter values; this can be done by calling clearParameters.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.execute

PreparedStatement.execute

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean execute() throws SQLException
Description
Some prepared statements return multiple results; the execute method handles these complex statements as well as the simpler form of statements handled by executeQuery and executeUpdate.

Exceptions
SQLException if a database-access error occurs.
See Also
execute


 PreparedStatement.executeQuery

PreparedStatement.executeQuery

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet executeQuery() throws SQLException
Returns
a ResultSet that contains the data produced by the query; never null
Description
A prepared SQL query is executed and its ResultSet is returned.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.executeUpdate

PreparedStatement.executeUpdate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int executeUpdate() throws SQLException
Returns
either the row count for INSERT, UPDATE or DELETE; or 0 for SQL statements that return nothing
Description
Execute a SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements that return nothing such as SQL DDL statements can be executed.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setAsciiStream

PreparedStatement.setAsciiStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setAsciiStream( int parameterIndex, InputStream x, int length ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the java input stream which contains the ASCII parameter value
length
the number of bytes in the stream
Description
When a very large ASCII value is input to a LONGVARCHAR parameter, it may be more practical to send it via a java.io.InputStream. JDBC will read the data from the stream as needed, until it reaches end-of-file. The JDBC driver will do any necessary conversion from ASCII to the database char format.

Note: This stream object can either be a standard Java stream object or your own subclass that implements the standard interface.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setBigDecimal

PreparedStatement.setBigDecimal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setBigDecimal( int parameterIndex, BigDecimal x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a java.lang.BigDecimal value. The driver converts this to a SQL NUMERIC value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setBinaryStream

PreparedStatement.setBinaryStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setBinaryStream( int parameterIndex, InputStream x, int length ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the java input stream which contains the binary parameter value
length
the number of bytes in the stream
Description
When a very large binary value is input to a LONGVARBINARY parameter, it may be more practical to send it via a java.io.InputStream. JDBC will read the data from the stream as needed, until it reaches end-of-file.

Note: This stream object can either be a standard Java stream object or your own subclass that implements the standard interface.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setBoolean

PreparedStatement.setBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setBoolean( int parameterIndex, boolean x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java boolean value. The driver converts this to a SQL BIT value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setByte

PreparedStatement.setByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setByte( int parameterIndex, byte x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java byte value. The driver converts this to a SQL TINYINT value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setBytes

PreparedStatement.setBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setBytes( int parameterIndex, byte x[] ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java array of bytes. The driver converts this to a SQL VARBINARY or LONGVARBINARY (depending on the argument's size relative to the driver's limits on VARBINARYs) when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setDate

PreparedStatement.setDate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setDate( int parameterIndex, Date x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a java.sql.Date value. The driver converts this to a SQL DATE value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setDouble

PreparedStatement.setDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setDouble( int parameterIndex, double x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java double value. The driver converts this to a SQL DOUBLE value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setFloat

PreparedStatement.setFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setFloat( int parameterIndex, float x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java float value. The driver converts this to a SQL FLOAT value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setInt

PreparedStatement.setInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setInt( int parameterIndex, int x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java int value. The driver converts this to a SQL INTEGER value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setLong

PreparedStatement.setLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setLong( int parameterIndex, long x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java long value. The driver converts this to a SQL BIGINT value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setNull

PreparedStatement.setNull

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setNull( int parameterIndex, int sqlType ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
sqlType
SQL type code defined by java.sql.Types
Description
Set a parameter to SQL NULL.

Note: You must specify the parameter's SQL type.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setObject

PreparedStatement.setObject

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void setObject( int parameterIndex, Object x, int targetSqlType, int scale ) throws SQLException
Parameters
parameterIndex
The first parameter is 1, the second is 2, ...
x
The object containing the input parameter value
targetSqlType
The SQL type (as defined in java.sql.Types) to be sent to the database. The scale argument may further qualify this type.
scale
For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC types this is the number of digits after the decimal. For all other types this value will be ignored,
Description

Set the value of a parameter using an object; use the java.lang equivalent objects for integral values.

The given Java object will be converted to the targetSqlType before being sent to the database.

Note that this method may be used to pass datatabase- specific abstract data types. This is done by using a Driver- specific Java type and using a targetSqlType of java.sql.types.OTHER.

Exceptions
SQLException if a database-access error occurs.
See Also
Types

Syntax 2
public abstract void setObject( int parameterIndex, Object x, int targetSqlType ) throws SQLException
Description
This method is like setObject above, but assumes a scale of zero.

Exceptions
SQLException if a database-access error occurs.

Syntax 3
public abstract void setObject( int parameterIndex, Object x ) throws SQLException
Parameters
parameterIndex
The first parameter is 1, the second is 2, ...
x
The object containing the input parameter value
Description

Set the value of a parameter using an object; use the java.lang equivalent objects for integral values.

The JDBC specification specifies a standard mapping from Java Object types to SQL types. The given argument java object will be converted to the corresponding SQL type before being sent to the database.

Note that this method may be used to pass datatabase specific abstract data types, by using a Driver specific Java type.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setShort

PreparedStatement.setShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setShort( int parameterIndex, short x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java short value. The driver converts this to a SQL SMALLINT value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setString

PreparedStatement.setString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setString( int parameterIndex, String x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a Java String value. The driver converts this to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments size relative to the driver's limits on VARCHARs) when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setTime

PreparedStatement.setTime

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setTime( int parameterIndex, Time x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a java.sql.Time value. The driver converts this to a SQL TIME value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setTimestamp

PreparedStatement.setTimestamp

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setTimestamp( int parameterIndex, Timestamp x ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the parameter value
Description
Set a parameter to a java.sql.Timestamp value. The driver converts this to a SQL TIMESTAMP value when it sends it to the database.

Exceptions
SQLException if a database-access error occurs.


 PreparedStatement.setUnicodeStream

PreparedStatement.setUnicodeStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setUnicodeStream( int parameterIndex, InputStream x, int length ) throws SQLException
Parameters
parameterIndex
the first parameter is 1, the second is 2, ...
x
the java input stream which contains the UNICODE parameter value
length
the number of bytes in the stream
Description
When a very large UNICODE value is input to a LONGVARCHAR parameter, it may be more practical to send it via a java.io.InputStream. JDBC will read the data from the stream as needed, until it reaches end-of-file. The JDBC driver will do any necessary conversion from UNICODE to the database char format.

Note: This stream object can either be a standard Java stream object or your own subclass that implements the standard interface.

Exceptions
SQLException if a database-access error occurs.


 Interface ResultSet

Interface java.sql.ResultSet

Interface Members | This Package | All Packages

public interface ResultSet

A ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. Within a row its column values can be accessed in any order.

A ResultSet maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The 'next' method moves the cursor to the next row.

The getXXX methods retrieve column values for the current row. You can retrieve values either using the index number of the column, or by using the name of the column. In general using the column index will be more efficient. Columns are numbered from 1.

For maximum portability, ResultSet columns within each row should be read in left-to-right order and each column should be read only once.

For the getXXX methods, the JDBC driver attempts to convert the underlying data to the specified Java type and returns a suitable Java value. See the JDBC specification for allowable mappings from SQL types to Java types with the ResultSet.getXXX methods.

Column names used as input to getXXX methods are case insensitive. When performing a getXXX using a column name, if several columns have the same name, then the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names were used there is no way for the programmer to guarantee that they actually refer to the intended columns.

A ResultSet is automatically closed by the Statement that generated it when that Statement is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.

The number, types and properties of a ResultSet's columns are provided by the ResulSetMetaData object returned by the getMetaData method.

See Also:
executeQuery, getResultSet, ResultSetMetaData


 ResultSet Members

ResultSet Members

Interface Overview | This Package | All Packages

Methods
Name | Description
clearWarnings() | After this call getWarnings returns null until a new warning is reported for this ResultSet.
close() | In some cases, it is desirable to immediately release a ResultSet's database and JDBC resources instead of waiting for this to happen when it is automatically closed; the close method provides this immediate release.
findColumn(String) | Map a Resultset column name to a ResultSet column index.
getAsciiStream(int) | A column value can be retrieved as a stream of ASCII characters and then read in chunks from the stream.
getAsciiStream(String) | A column value can be retrieved as a stream of ASCII characters and then read in chunks from the stream.
getBigDecimal(int, int) | Get the value of a column in the current row as a java.lang.BigDecimal object.
getBigDecimal(String, int) | Get the value of a column in the current row as a java.lang.BigDecimal object.
getBinaryStream(int) | A column value can be retrieved as a stream of uninterpreted bytes and then read in chunks from the stream.
getBinaryStream(String) | A column value can be retrieved as a stream of uninterpreted bytes and then read in chunks from the stream.
getBoolean(int) | Get the value of a column in the current row as a Java boolean.
getBoolean(String) | Get the value of a column in the current row as a Java boolean.
getByte(int) | Get the value of a column in the current row as a Java byte.
getByte(String) | Get the value of a column in the current row as a Java byte.
getBytes(int) | Get the value of a column in the current row as a Java byte array.
getBytes(String) | Get the value of a column in the current row as a Java byte array.
getCursorName() | Get the name of the SQL cursor used by this ResultSet.
getDate(int) | Get the value of a column in the current row as a java.sql.Date object.
getDate(String) | Get the value of a column in the current row as a java.sql.Date object.
getDouble(int) | Get the value of a column in the current row as a Java double.
getDouble(String) | Get the value of a column in the current row as a Java double.
getFloat(int) | Get the value of a column in the current row as a Java float.
getFloat(String) | Get the value of a column in the current row as a Java float.
getInt(int) | Get the value of a column in the current row as a Java int.
getInt(String) | Get the value of a column in the current row as a Java int.
getLong(int) | Get the value of a column in the current row as a Java long.
getLong(String) | Get the value of a column in the current row as a Java long.
getMetaData() | The number, types and properties of a ResultSet's columns are provided by the getMetaData method.
getObject(int) | Get the value of a column in the current row as a Java object.
getObject(String) | Get the value of a column in the current row as a Java object.
getShort(int) | Get the value of a column in the current row as a Java short.
getShort(String) | Get the value of a column in the current row as a Java short.
getString(int) | Get the value of a column in the current row as a Java String.
getString(String) | Get the value of a column in the current row as a Java String.
getTime(int) | Get the value of a column in the current row as a java.sql.Time object.
getTime(String) | Get the value of a column in the current row as a java.sql.Time object.
getTimestamp(int) | Get the value of a column in the current row as a java.sql.Timestamp object.
getTimestamp(String) | Get the value of a column in the current row as a java.sql.Timestamp object.
getUnicodeStream(int) | A column value can be retrieved as a stream of Unicode characters and then read in chunks from the stream.
getUnicodeStream(String) | A column value can be retrieved as a stream of Unicode characters and then read in chunks from the stream.
getWarnings() | The first warning reported by calls on this ResultSet is returned.
next() | A ResultSet is initially positioned before its first row; the first call to next makes the first row the current row; the second call makes the second row the current row, etc.
wasNull() | A column may have the value of SQL NULL; wasNull reports whether the last column read had this special value.


 ResultSet.clearWarnings

ResultSet.clearWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void clearWarnings() throws SQLException
Description
After this call getWarnings returns null until a new warning is reported for this ResultSet.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.close

ResultSet.close

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void close() throws SQLException
Description
In some cases, it is desirable to immediately release a ResultSet's database and JDBC resources instead of waiting for this to happen when it is automatically closed; the close method provides this immediate release.

Note: A ResultSet is automatically closed by the Statement that generated it when that Statement is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results. A ResultSet is also automatically closed when it is garbage collected.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.findColumn

ResultSet.findColumn

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int findColumn( String columnName ) throws SQLException
Parameters
columnName
the name of the column
Returns
the column index
Description
Map a Resultset column name to a ResultSet column index.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getAsciiStream

ResultSet.getAsciiStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getAsciiStream( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
a Java input stream that delivers the database column value as a stream of one byte ASCII characters. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of ASCII characters and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARCHAR values. The JDBC driver will do any necessary conversion from the database format into ASCII.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream. . Also, a stream may return 0 for available() whether there is data available or not.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getAsciiStream

ResultSet.getAsciiStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getAsciiStream( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
a Java input stream that delivers the database column value as a stream of one byte ASCII characters. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of ASCII characters and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARCHAR values. The JDBC driver will do any necessary conversion from the database format into ASCII.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBigDecimal

ResultSet.getBigDecimal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigDecimal getBigDecimal( int columnIndex, int scale ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
scale
the number of digits to the right of the decimal
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.lang.BigDecimal object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBigDecimal

ResultSet.getBigDecimal

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract BigDecimal getBigDecimal( String columnName, int scale ) throws SQLException
Parameters
columnName
is the SQL name of the column
scale
the number of digits to the right of the decimal
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.lang.BigDecimal object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBinaryStream

ResultSet.getBinaryStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getBinaryStream( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
a Java input stream that delivers the database column value as a stream of uninterpreted bytes. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of uninterpreted bytes and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARBINARY values.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream. Also, a stream may return 0 for available() whether there is data available or not.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBinaryStream

ResultSet.getBinaryStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getBinaryStream( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
a Java input stream that delivers the database column value as a stream of uninterpreted bytes. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of uninterpreted bytes and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARBINARY values.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBoolean

ResultSet.getBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean getBoolean( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is false
Description
Get the value of a column in the current row as a Java boolean.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBoolean

ResultSet.getBoolean

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean getBoolean( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is false
Description
Get the value of a column in the current row as a Java boolean.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getByte

ResultSet.getByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte getByte( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java byte.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getByte

ResultSet.getByte

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte getByte( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java byte.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBytes

ResultSet.getBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte[] getBytes( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a Java byte array. The bytes represent the raw values returned by the driver.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getBytes

ResultSet.getBytes

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract byte[] getBytes( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a Java byte array. The bytes represent the raw values returned by the driver.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getCursorName

ResultSet.getCursorName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getCursorName() throws SQLException
Returns
the ResultSet's SQL cursor name
Description
Get the name of the SQL cursor used by this ResultSet.

In SQL, a result table is retrieved through a cursor that is named. The current row of a result can be updated or deleted using a positioned update/delete statement that references the cursor name.

JDBC supports this SQL feature by providing the name of the SQL cursor used by a ResultSet. The current row of a ResultSet is also the current row of this SQL cursor.

Note: If positioned update is not supported a SQLException is thrown

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getDate

ResultSet.getDate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Date getDate( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Date object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getDate

ResultSet.getDate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Date getDate( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Date object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getDouble

ResultSet.getDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract double getDouble( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java double.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getDouble

ResultSet.getDouble

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract double getDouble( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java double.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getFloat

ResultSet.getFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float getFloat( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java float.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getFloat

ResultSet.getFloat

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract float getFloat( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java float.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getInt

ResultSet.getInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getInt( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java int.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getInt

ResultSet.getInt

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getInt( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java int.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getLong

ResultSet.getLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long getLong( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java long.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getLong

ResultSet.getLong

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long getLong( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java long.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getMetaData

ResultSet.getMetaData

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSetMetaData getMetaData() throws SQLException
Returns
the description of a ResultSet's columns
Description
The number, types and properties of a ResultSet's columns are provided by the getMetaData method.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getObject

ResultSet.getObject

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract Object getObject( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
A java.lang.Object holding the column value.
Description

Get the value of a column in the current row as a Java object.

This method will return the value of the given column as a Java object. The type of the Java object will be the default Java Object type corresponding to the column's SQL type, following the mapping specified in the JDBC spec.

This method may also be used to read datatabase specific abstract data types.

Exceptions
SQLException if a database-access error occurs.

Syntax 2
public abstract Object getObject( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
A java.lang.Object holding the column value.
Description

Get the value of a column in the current row as a Java object.

This method will return the value of the given column as a Java object. The type of the Java object will be the default Java Object type corresponding to the column's SQL type, following the mapping specified in the JDBC spec.

This method may also be used to read datatabase specific abstract data types.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getShort

ResultSet.getShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract short getShort( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java short.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getShort

ResultSet.getShort

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract short getShort( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is 0
Description
Get the value of a column in the current row as a Java short.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getString

ResultSet.getString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getString( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a Java String.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getString

ResultSet.getString

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getString( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a Java String.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getTime

ResultSet.getTime

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Time getTime( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Time object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getTime

ResultSet.getTime

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Time getTime( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Time object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getTimestamp

ResultSet.getTimestamp

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Timestamp getTimestamp( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Timestamp object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getTimestamp

ResultSet.getTimestamp

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Timestamp getTimestamp( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
the column value; if the value is SQL NULL, the result is null
Description
Get the value of a column in the current row as a java.sql.Timestamp object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getUnicodeStream

ResultSet.getUnicodeStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getUnicodeStream( int columnIndex ) throws SQLException
Parameters
columnIndex
the first column is 1, the second is 2, ...
Returns
a Java input stream that delivers the database column value as a stream of two byte Unicode characters. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of Unicode characters and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARCHAR values. The JDBC driver will do any necessary conversion from the database format into Unicode.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream. . Also, a stream may return 0 for available() whether there is data available or not.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getUnicodeStream

ResultSet.getUnicodeStream

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract InputStream getUnicodeStream( String columnName ) throws SQLException
Parameters
columnName
is the SQL name of the column
Returns
a Java input stream that delivers the database column value as a stream of two byte Unicode characters. If the value is SQL NULL then the result is null.
Description
A column value can be retrieved as a stream of Unicode characters and then read in chunks from the stream. This method is particularly suitable for retrieving large LONGVARCHAR values. The JDBC driver will do any necessary conversion from the database format into Unicode.

Note: All the data in the returned stream must be read prior to getting the value of any other column. The next call to a get method implicitly closes the stream.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.getWarnings

ResultSet.getWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract SQLWarning getWarnings() throws SQLException
Returns
the first SQLWarning or null
Description

The first warning reported by calls on this ResultSet is returned. Subsequent ResultSet warnings will be chained to this SQLWarning.

The warning chain is automatically cleared each time a new row is read.

Note: This warning chain only covers warnings caused by ResultSet methods. Any warning caused by statement methods (such as reading OUT parameters) will be chained on the Statement object.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.next

ResultSet.next

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean next() throws SQLException
Returns
true if the new current row is valid; false if there are no more rows
Description
A ResultSet is initially positioned before its first row; the first call to next makes the first row the current row; the second call makes the second row the current row, etc.

If an input stream from the previous row is open, it is implicitly closed. The ResultSet's warning chain is cleared when a new row is read.

Exceptions
SQLException if a database-access error occurs.


 ResultSet.wasNull

ResultSet.wasNull

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean wasNull() throws SQLException
Returns
true if last column read was SQL NULL
Description
A column may have the value of SQL NULL; wasNull reports whether the last column read had this special value. Note that you must first call getXXX on a column to try to read its value and then call wasNull() to find if the value was the SQL NULL.

Exceptions
SQLException if a database-access error occurs.


 Interface ResultSetMetaData

Interface java.sql.ResultSetMetaData

Interface Members | This Package | All Packages

public interface ResultSetMetaData

A ResultSetMetaData object can be used to find out about the types and properties of the columns in a ResultSet.


 ResultSetMetaData Members

ResultSetMetaData Members

Interface Overview | This Package | All Packages

Fields
Name | Description
columnNoNulls | Does not allow NULL values.
columnNullable | Allows NULL values.
columnNullableUnknown | Nullability unknown.

Methods
Name | Description
getCatalogName(int) | What's a column's table's catalog name?
getColumnCount() | What's the number of columns in the ResultSet?
getColumnDisplaySize(int) | What's the column's normal max width in chars?
getColumnLabel(int) | What's the suggested column title for use in printouts and displays?
getColumnName(int) | What's a column's name?
getColumnType(int) | What's a column's SQL type?
getColumnTypeName(int) | What's a column's data source specific type name?
getPrecision(int) | What's a column's number of decimal digits?
getScale(int) | What's a column's number of digits to right of the decimal point?
getSchemaName(int) | What's a column's table's schema?
getTableName(int) | What's a column's table name?
isAutoIncrement(int) | Is the column automatically numbered, thus read-only?
isCaseSensitive(int) | Does a column's case matter?
isCurrency(int) | Is the column a cash value?
isDefinitelyWritable(int) | Will a write on the column definitely succeed?
isNullable(int) | Can you put a NULL in this column?
isReadOnly(int) | Is a column definitely not writable?
isSearchable(int) | Can the column be used in a where clause?
isSigned(int) | Is the column a signed number?
isWritable(int) | Is it possible for a write on the column to succeed?


 ResultSetMetaData.columnNoNulls

ResultSetMetaData.columnNoNulls

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNoNulls
Description
Does not allow NULL values.


 ResultSetMetaData.columnNullable

ResultSetMetaData.columnNullable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNullable
Description
Allows NULL values.


 ResultSetMetaData.columnNullableUnknown

ResultSetMetaData.columnNullableUnknown

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final int columnNullableUnknown
Description
Nullability unknown.


 ResultSetMetaData.getCatalogName

ResultSetMetaData.getCatalogName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getCatalogName( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
column name or "" if not applicable.
Description
What's a column's table's catalog name?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getColumnCount

ResultSetMetaData.getColumnCount

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getColumnCount() throws SQLException
Returns
the number
Description
What's the number of columns in the ResultSet?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getColumnDisplaySize

ResultSetMetaData.getColumnDisplaySize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getColumnDisplaySize( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
max width
Description
What's the column's normal max width in chars?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getColumnLabel

ResultSetMetaData.getColumnLabel

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getColumnLabel( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
What's the suggested column title for use in printouts and displays?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getColumnName

ResultSetMetaData.getColumnName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getColumnName( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
column name
Description
What's a column's name?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getColumnType

ResultSetMetaData.getColumnType

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getColumnType( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
SQL type
Description
What's a column's SQL type?

Exceptions
SQLException if a database-access error occurs.
See Also
Types


 ResultSetMetaData.getColumnTypeName

ResultSetMetaData.getColumnTypeName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getColumnTypeName( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
type name
Description
What's a column's data source specific type name?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getPrecision

ResultSetMetaData.getPrecision

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getPrecision( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
precision
Description
What's a column's number of decimal digits?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getScale

ResultSetMetaData.getScale

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getScale( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
scale
Description
What's a column's number of digits to right of the decimal point?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getSchemaName

ResultSetMetaData.getSchemaName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getSchemaName( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
schema name or "" if not applicable
Description
What's a column's table's schema?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.getTableName

ResultSetMetaData.getTableName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract String getTableName( int column ) throws SQLException
Returns
table name or "" if not applicable
Description
What's a column's table name?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isAutoIncrement

ResultSetMetaData.isAutoIncrement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isAutoIncrement( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Is the column automatically numbered, thus read-only?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isCaseSensitive

ResultSetMetaData.isCaseSensitive

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isCaseSensitive( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Does a column's case matter?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isCurrency

ResultSetMetaData.isCurrency

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isCurrency( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Is the column a cash value?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isDefinitelyWritable

ResultSetMetaData.isDefinitelyWritable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isDefinitelyWritable( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Will a write on the column definitely succeed?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isNullable

ResultSetMetaData.isNullable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int isNullable( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
columnNoNulls, columnNullable or columnNullableUnknown
Description
Can you put a NULL in this column?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isReadOnly

ResultSetMetaData.isReadOnly

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isReadOnly( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Is a column definitely not writable?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isSearchable

ResultSetMetaData.isSearchable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isSearchable( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Can the column be used in a where clause?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isSigned

ResultSetMetaData.isSigned

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isSigned( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Is the column a signed number?

Exceptions
SQLException if a database-access error occurs.


 ResultSetMetaData.isWritable

ResultSetMetaData.isWritable

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean isWritable( int column ) throws SQLException
Parameters
column
the first column is 1, the second is 2, ...
Returns
true if so
Description
Is it possible for a write on the column to succeed?

Exceptions
SQLException if a database-access error occurs.


 Class SQLException

Class java.sql.SQLException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.sql.SQLException

public class SQLException
extends Exception

The SQLException class provides information on a database access error.

Each SQLException provides several kinds of information:

  • a string describing the error. This is used as the Java Exception message, and is available via the getMesage() method
  • A "SQLstate" string which follows the XOPEN SQLstate conventions. The values of the SQLState string as described in the XOPEN SQL spec.
  • An integer error code that is vendor specific. Normally this will be the actual error code returned by the underlying database.
  • A chain to a next Exception. This can be used to provided additional error information.


 SQLException Members

SQLException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SQLException() | Construct an SQLException; reason defaults to null, SQLState defaults to null and vendorCode defaults to 0.
SQLException(String) | Construct an SQLException with a reason; SQLState defaults to null and vendorCode defaults to 0.
SQLException(String, String) | Construct an SQLException with a reason and SQLState; vendorCode defaults to 0.
SQLException(String, String, int) | Construct a fully-specified SQLException

Methods
Name | Description
getErrorCode() | Get the vendor specific exception code
getNextException() | Get the exception chained to this one.
getSQLState() | Get the SQLState
setNextException(SQLException) | Add an SQLException to the end of the chain.


 SQLException.SQLException

SQLException.SQLException

Syntax 1
public SQLException( String reason, String SQLState, int vendorCode )
Parameters
reason
a description of the exception
SQLState
an XOPEN code identifying the exception
vendorCode
a database vendor specific exception code
Description
Construct a fully-specified SQLException

Syntax 2
public SQLException( String reason, String SQLState )
Parameters
reason
a description of the exception
SQLState
an XOPEN code identifying the exception
Description
Construct an SQLException with a reason and SQLState; vendorCode defaults to 0.

Syntax 3
public SQLException( String reason )
Parameters
reason
a description of the exception
Description
Construct an SQLException with a reason; SQLState defaults to null and vendorCode defaults to 0.

Syntax 4
public SQLException()
Description
Construct an SQLException; reason defaults to null, SQLState defaults to null and vendorCode defaults to 0.


 SQLException.getErrorCode

SQLException.getErrorCode

Syntax
public int getErrorCode()
Returns
the vendor's error code
Description
Get the vendor specific exception code


 SQLException.getNextException

SQLException.getNextException

Syntax
public SQLException getNextException()
Returns
the next SQLException in the chain, null if none
Description
Get the exception chained to this one.


 SQLException.getSQLState

SQLException.getSQLState

Syntax
public String getSQLState()
Returns
the SQLState value
Description
Get the SQLState


 SQLException.setNextException

SQLException.setNextException

Syntax
public synchronized void setNextException( SQLException ex )
Parameters
ex
the new end of the SQLException chain
Description
Add an SQLException to the end of the chain.


 Class SQLWarning

Class java.sql.SQLWarning

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.sql.SQLException
                           |
                           +----java.sql.SQLWarning

public class SQLWarning
extends SQLException

The SQLWarning class provides information on a database access warnings. Warnings are silently chained to the object whose method caused it to be reported.

See Also:
getWarnings, getWarnings, getWarnings


 SQLWarning Members

SQLWarning Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SQLWarning() | Construct an SQLWarning ; reason defaults to null, SQLState defaults to null and vendorCode defaults to 0.
SQLWarning(String) | Construct an SQLWarning with a reason; SQLState defaults to null and vendorCode defaults to 0.
SQLWarning(String, String) | Construct an SQLWarning with a reason and SQLState; vendorCode defaults to 0.
SQLWarning(String, String, int) | Construct a fully specified SQLWarning.

Methods
Name | Description
getNextWarning() | Get the warning chained to this one
setNextWarning(SQLWarning) | Add an SQLWarning to the end of the chain.


 SQLWarning.SQLWarning

SQLWarning.SQLWarning

Syntax 1
public SQLWarning( String reason, String SQLstate, int vendorCode )
Parameters
reason
a description of the warning
SQLState
an XOPEN code identifying the warning
vendorCode
a database vendor specific warning code
Description
Construct a fully specified SQLWarning.

Syntax 2
public SQLWarning( String reason, String SQLstate )
Parameters
reason
a description of the warning
SQLState
an XOPEN code identifying the warning
Description
Construct an SQLWarning with a reason and SQLState; vendorCode defaults to 0.

Syntax 3
public SQLWarning( String reason )
Parameters
reason
a description of the warning
Description
Construct an SQLWarning with a reason; SQLState defaults to null and vendorCode defaults to 0.

Syntax 4
public SQLWarning()
Description
Construct an SQLWarning ; reason defaults to null, SQLState defaults to null and vendorCode defaults to 0.


 SQLWarning.getNextWarning

SQLWarning.getNextWarning

Syntax
public SQLWarning getNextWarning()
Returns
the next SQLException in the chain, null if none
Description
Get the warning chained to this one


 SQLWarning.setNextWarning

SQLWarning.setNextWarning

Syntax
public void setNextWarning( SQLWarning w )
Parameters
w
the new end of the SQLException chain
Description
Add an SQLWarning to the end of the chain.


 Interface Statement

Interface java.sql.Statement

Interface Members | This Package | All Packages

public interface Statement

A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

Only one ResultSet per Statement can be open at any point in time. Therefore, if the reading of one ResultSet is interleaved with the reading of another, each must have been generated by different Statements. All statement execute methods implicitly close a statment's current ResultSet if an open one exists.

See Also:
createStatement, ResultSet


 Statement Members

Statement Members

Interface Overview | This Package | All Packages

Methods
Name | Description
cancel() | Cancel can be used by one thread to cancel a statement that is being executed by another thread.
clearWarnings() | After this call, getWarnings returns null until a new warning is reported for this Statement.
close() | In many cases, it is desirable to immediately release a Statements's database and JDBC resources instead of waiting for this to happen when it is automatically closed; the close method provides this immediate release.
execute(String) | Execute a SQL statement that may return multiple results.
executeQuery(String) | Execute a SQL statement that returns a single ResultSet.
executeUpdate(String) | Execute a SQL INSERT, UPDATE or DELETE statement.
getMaxFieldSize() | The maxFieldSize limit (in bytes) is the maximum amount of data returned for any column value; it only applies to BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR columns.
getMaxRows() | The maxRows limit is the maximum number of rows that a ResultSet can contain.
getMoreResults() | getMoreResults moves to a Statement's next result.
getQueryTimeout() | The queryTimeout limit is the number of seconds the driver will wait for a Statement to execute.
getResultSet() | getResultSet returns the current result as a ResultSet.
getUpdateCount() | getUpdateCount returns the current result as an update count; if the result is a ResultSet or there are no more results, -1 is returned.
getWarnings() | The first warning reported by calls on this Statement is returned.
setCursorName(String) | setCursorname defines the SQL cursor name that will be used by subsequent Statement execute methods.
setEscapeProcessing(boolean) | If escape scanning is on (the default), the driver will do escape substitution before sending the SQL to the database.
setMaxFieldSize(int) | The maxFieldSize limit (in bytes) is set to limit the size of data that can be returned for any column value; it only applies to BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR fields.
setMaxRows(int) | The maxRows limit is set to limit the number of rows that any ResultSet can contain.
setQueryTimeout(int) | The queryTimeout limit is the number of seconds the driver will wait for a Statement to execute.


 Statement.cancel

Statement.cancel

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void cancel() throws SQLException
Description
Cancel can be used by one thread to cancel a statement that is being executed by another thread.

Exceptions
SQLException if a database-access error occurs.


 Statement.clearWarnings

Statement.clearWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void clearWarnings() throws SQLException
Description
After this call, getWarnings returns null until a new warning is reported for this Statement.

Exceptions
SQLException if a database-access error occurs.


 Statement.close

Statement.close

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void close() throws SQLException
Description
In many cases, it is desirable to immediately release a Statements's database and JDBC resources instead of waiting for this to happen when it is automatically closed; the close method provides this immediate release.

Note: A Statement is automatically closed when it is garbage collected. When a Statement is closed, its current ResultSet, if one exists, is also closed.

Exceptions
SQLException if a database-access error occurs.


 Statement.execute

Statement.execute

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean execute( String sql ) throws SQLException
Parameters
sql
any SQL statement
Returns
true if the next result is a ResultSet; false if it is an update count or there are no more results
Description
Execute a SQL statement that may return multiple results. Under some (uncommon) situations a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this, unless you're executing a stored procedure that you know may return multiple results, or unless you're dynamically executing an unknown SQL string. The "execute", "getMoreResults", "getResultSet" and "getUpdateCount" methods let you navigate through multiple results. The "execute" method executes a SQL statement and indicates the form of the first result. You can then use getResultSet or getUpdateCount to retrieve the result, and getMoreResults to move to any subsequent result(s).

Exceptions
SQLException if a database-access error occurs.
See Also
getResultSet, getUpdateCount, getMoreResults


 Statement.executeQuery

Statement.executeQuery

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet executeQuery( String sql ) throws SQLException
Parameters
sql
typically this is a static SQL SELECT statement
Returns
a ResultSet that contains the data produced by the query; never null
Description
Execute a SQL statement that returns a single ResultSet.

Exceptions
SQLException if a database-access error occurs.


 Statement.executeUpdate

Statement.executeUpdate

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int executeUpdate( String sql ) throws SQLException
Parameters
sql
a SQL INSERT, UPDATE or DELETE statement or a SQL statement that returns nothing
Returns
either the row count for INSERT, UPDATE or DELETE or 0 for SQL statements that return nothing
Description
Execute a SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements that return nothing such as SQL DDL statements can be executed.

Exceptions
SQLException if a database-access error occurs.


 Statement.getMaxFieldSize

Statement.getMaxFieldSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxFieldSize() throws SQLException
Returns
the current max column size limit; zero means unlimited
Description
The maxFieldSize limit (in bytes) is the maximum amount of data returned for any column value; it only applies to BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR columns. If the limit is exceeded, the excess data is silently discarded.

Exceptions
SQLException if a database-access error occurs.


 Statement.getMaxRows

Statement.getMaxRows

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getMaxRows() throws SQLException
Returns
the current max row limit; zero means unlimited
Description
The maxRows limit is the maximum number of rows that a ResultSet can contain. If the limit is exceeded, the excess rows are silently dropped.

Exceptions
SQLException if a database-access error occurs.


 Statement.getMoreResults

Statement.getMoreResults

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean getMoreResults() throws SQLException
Returns
true if the next result is a ResultSet; false if it is an update count or there are no more results
Description
getMoreResults moves to a Statement's next result. It returns true if this result is a ResultSet. getMoreResults also implicitly closes any current ResultSet obtained with getResultSet. There are no more results when (!getMoreResults() && (getUpdateCount() == -1)

Exceptions
SQLException if a database-access error occurs.
See Also
execute


 Statement.getQueryTimeout

Statement.getQueryTimeout

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getQueryTimeout() throws SQLException
Returns
the current query timeout limit in seconds; zero means unlimited
Description
The queryTimeout limit is the number of seconds the driver will wait for a Statement to execute. If the limit is exceeded, a SQLException is thrown.

Exceptions
SQLException if a database-access error occurs.


 Statement.getResultSet

Statement.getResultSet

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract ResultSet getResultSet() throws SQLException
Returns
the current result as a ResultSet; null if the result is an update count or there are no more results
Description
getResultSet returns the current result as a ResultSet. It should only be called once per result.

Exceptions
SQLException if a database-access error occurs.
See Also
execute


 Statement.getUpdateCount

Statement.getUpdateCount

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getUpdateCount() throws SQLException
Returns
the current result as an update count; -1 if it is a ResultSet or there are no more results
Description
getUpdateCount returns the current result as an update count; if the result is a ResultSet or there are no more results, -1 is returned. It should only be called once per result.

Exceptions
SQLException if a database-access error occurs.
See Also
execute


 Statement.getWarnings

Statement.getWarnings

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract SQLWarning getWarnings() throws SQLException
Returns
the first SQLWarning or null
Description
The first warning reported by calls on this Statement is returned. A Statment's execute methods clear its SQLWarning chain. Subsequent Statement warnings will be chained to this SQLWarning.

The warning chain is automatically cleared each time a statement is (re)executed.

Note: If you are processing a ResultSet then any warnings associated with ResultSet reads will be chained on the ResultSet object.

Exceptions
SQLException if a database-access error occurs.


 Statement.setCursorName

Statement.setCursorName

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setCursorName( String name ) throws SQLException
Parameters
name
the new cursor name.
Description
setCursorname defines the SQL cursor name that will be used by subsequent Statement execute methods. This name can then be used in SQL positioned update/delete statements to identify the current row in the ResultSet generated by this statement. If the database doesn't support positioned update/delete, this method is a noop.

Note: By definition, positioned update/delete execution must be done by a different Statement than the one which generated the ResultSet being used for positioning. Also, cursor names must be unique within a Connection.

Exceptions
SQLException if a database-access error occurs.


 Statement.setEscapeProcessing

Statement.setEscapeProcessing

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setEscapeProcessing( boolean enable ) throws SQLException
Parameters
enable
true to enable; false to disable
Description
If escape scanning is on (the default), the driver will do escape substitution before sending the SQL to the database. Note: Since prepared statements have usually been parsed prior to making this call, disabling escape processing for prepared statements will like have no affect.

Exceptions
SQLException if a database-access error occurs.


 Statement.setMaxFieldSize

Statement.setMaxFieldSize

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setMaxFieldSize( int max ) throws SQLException
Parameters
max
the new max column size limit; zero means unlimited
Description
The maxFieldSize limit (in bytes) is set to limit the size of data that can be returned for any column value; it only applies to BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR fields. If the limit is exceeded, the excess data is silently discarded. For maximum portability use values greater than 256.

Exceptions
SQLException if a database-access error occurs.


 Statement.setMaxRows

Statement.setMaxRows

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setMaxRows( int max ) throws SQLException
Parameters
max
the new max rows limit; zero means unlimited
Description
The maxRows limit is set to limit the number of rows that any ResultSet can contain. If the limit is exceeded, the excess rows are silently dropped.

Exceptions
SQLException if a database-access error occurs.


 Statement.setQueryTimeout

Statement.setQueryTimeout

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void setQueryTimeout( int seconds ) throws SQLException
Parameters
seconds
the new query timeout limit in seconds; zero means unlimited
Description
The queryTimeout limit is the number of seconds the driver will wait for a Statement to execute. If the limit is exceeded, a SQLException is thrown.

Exceptions
SQLException if a database-access error occurs.


 Class Time

Class java.sql.Time

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Date
           |
           +----java.sql.Time

public class Time
extends Date

This class is a thin wrapper around java.util.Date that allows JDBC to identify this as a SQL TIME value. It adds formatting and parsing operations to support the JDBC escape syntax for time values.


 Time Members

Time Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Time(int, int, int) | Construct a Time Object
Time(long) | Construct a Time using a milliseconds time value

Methods
Name | Description
getDate() | Returns the day of the month represented by this date.
getDay() | Returns the day of the week represented by this date.
getMonth() | Returns the month represented by this date.
getYear() | Returns the year represented by this date, minus 1900.
setDate(int) | Sets the day of the month of this date to the specified value.
setMonth(int) | Sets the month of this date to the specified value.
setTime(long) | Set a Time using a milliseconds time value
setYear(int) | Sets the year of this date to be the specified value plus 1900.
toString() | Format a time in JDBC date escape format
valueOf(String) | Convert a string in JDBC time escape format to a Time value


 Time.Time

Time.Time

Syntax 1
public Time( int hour, int minute, int second )
Parameters
hour
0 to 23
minute
0 to 59
second
0 to 59
Description
Construct a Time Object

Syntax 2
public Time( long time )
Parameters
time
milliseconds since January 1, 1970, 00:00:00 GMT
Description
Construct a Time using a milliseconds time value


 Time.getDate

Time.getDate

Syntax
public int getDate()
Description
Returns the day of the month represented by this date.

Overrides
getDate in class Date


 Time.getDay

Time.getDay

Syntax
public int getDay()
Description
Returns the day of the week represented by this date.

Overrides
getDay in class Date


 Time.getMonth

Time.getMonth

Syntax
public int getMonth()
Description
Returns the month represented by this date.

Overrides
getMonth in class Date


 Time.getYear

Time.getYear

Syntax
public int getYear()
Description
Returns the year represented by this date, minus 1900.

Overrides
getYear in class Date


 Time.setDate

Time.setDate

Syntax
public void setDate( int i )
Description
Sets the day of the month of this date to the specified value.

Overrides
setDate in class Date


 Time.setMonth

Time.setMonth

Syntax
public void setMonth( int i )
Description
Sets the month of this date to the specified value.

Overrides
setMonth in class Date


 Time.setTime

Time.setTime

Syntax
public void setTime( long time )
Parameters
time
milliseconds since January 1, 1970, 00:00:00 GMT
Description
Set a Time using a milliseconds time value

Overrides
setTime in class Date


 Time.setYear

Time.setYear

Syntax
public void setYear( int i )
Description
Sets the year of this date to be the specified value plus 1900.

Overrides
setYear in class Date


 Time.toString

Time.toString

Syntax
public String toString()
Returns
a String in hh:mm:ss format
Description
Format a time in JDBC date escape format

Overrides
toString in class Date


 Time.valueOf

Time.valueOf

Syntax
public static Time valueOf( String s )
Parameters
s
time in format "hh:mm:ss"
Returns
corresponding Time
Description
Convert a string in JDBC time escape format to a Time value


 Class Timestamp

Class java.sql.Timestamp

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Date
           |
           +----java.sql.Timestamp

public class Timestamp
extends Date

This class is a thin wrapper around java.util.Date that allows JDBC to identify this as a SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP nanos value and provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.

Note: This type is a composite of a java.util.Date and a separate nanos value. Only integral seconds are stored in the java.util.Date component. The fractional seconds - the nanos - are separate. The getTime method will only return integral seconds. If a time value that includes the fractional seconds is desired you must convert nanos to milliseconds (nanos/1000000) and add this to the getTime value. Also note that the hashcode() method uses the underlying java.util.Data implementation and therefore does not include nanos in its computation.


 Timestamp Members

Timestamp Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Timestamp(int, int, int, int, int, int, int) | Construct a Timestamp Object
Timestamp(long) | Construct a Timestamp using a milliseconds time value.

Methods
Name | Description
after(Timestamp) | Is this timestamp later than the timestamp argument?
before(Timestamp) | Is this timestamp earlier than the timestamp argument?
equals(Timestamp) | Test Timestamp values for equality
getNanos() | Get the Timestamp's nanos value
setNanos(int) | Set the Timestamp's nanos value
toString() | Format a timestamp in JDBC timestamp escape format
valueOf(String) | Convert a string in JDBC timestamp escape format to a Timestamp value


 Timestamp.Timestamp

Timestamp.Timestamp

Syntax 1
public Timestamp( int year, int month, int date, int hour, int minute, int second, int nano )
Parameters
year
year-1900
month
0 to 11
day
1 to 31
hour
0 to 23
minute
0 to 59
second
0 to 59
nano
0 to 999,999,999
Description
Construct a Timestamp Object

Syntax 2
public Timestamp( long time )
Parameters
time
milliseconds since January 1, 1970, 00:00:00 GMT
Description
Construct a Timestamp using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos value.


 Timestamp.after

Timestamp.after

Syntax
public boolean after( Timestamp ts )
Parameters
ts
the Timestamp value to compare with
Description
Is this timestamp later than the timestamp argument?


 Timestamp.before

Timestamp.before

Syntax
public boolean before( Timestamp ts )
Parameters
ts
the Timestamp value to compare with
Description
Is this timestamp earlier than the timestamp argument?


 Timestamp.equals

Timestamp.equals

Syntax
public boolean equals( Timestamp ts )
Parameters
ts
the Timestamp value to compare with
Description
Test Timestamp values for equality


 Timestamp.getNanos

Timestamp.getNanos

Syntax
public int getNanos()
Returns
the Timestamp's fractional seconds component
Description
Get the Timestamp's nanos value


 Timestamp.setNanos

Timestamp.setNanos

Syntax
public void setNanos( int n )
Parameters
n
the new fractional seconds component
Description
Set the Timestamp's nanos value


 Timestamp.toString

Timestamp.toString

Syntax
public String toString()
Returns
a String in yyyy-mm-dd hh:mm:ss.fffffffff format
Description
Format a timestamp in JDBC timestamp escape format

Overrides
toString in class Date


 Timestamp.valueOf

Timestamp.valueOf

Syntax
public static Timestamp valueOf( String s )
Parameters
s
timestamp in format "yyyy-mm-dd hh:mm:ss.fffffffff"
Returns
corresponding Timestamp
Description
Convert a string in JDBC timestamp escape format to a Timestamp value


 Class Types

Class java.sql.Types

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.sql.Types

public class Types
extends Object

This class defines constants that are used to identify SQL types. The actual type constant values are equivalent to those in XOPEN.


 Types Members

Types Members

Class Overview | This Package | All Packages

Fields
Name | Description
BIGINT |
BINARY |
BIT |
CHAR |
DATE |
DECIMAL |
DOUBLE |
FLOAT |
INTEGER |
LONGVARBINARY |
LONGVARCHAR |
NULL |
NUMERIC |
OTHER | OTHER indicates that the SQL type is database specific and gets mapped to a Java object which can be accessed via getObject and setObject.
REAL |
SMALLINT |
TIME |
TIMESTAMP |
TINYINT |
VARBINARY |
VARCHAR |


 Types.BIGINT

Types.BIGINT

Syntax
public static final int BIGINT


 Types.BINARY

Types.BINARY

Syntax
public static final int BINARY


 Types.BIT

Types.BIT

Syntax
public static final int BIT


 Types.CHAR

Types.CHAR

Syntax
public static final int CHAR


 Types.DATE

Types.DATE

Syntax
public static final int DATE


 Types.DECIMAL

Types.DECIMAL

Syntax
public static final int DECIMAL


 Types.DOUBLE

Types.DOUBLE

Syntax
public static final int DOUBLE


 Types.FLOAT

Types.FLOAT

Syntax
public static final int FLOAT


 Types.INTEGER

Types.INTEGER

Syntax
public static final int INTEGER


 Types.LONGVARBINARY

Types.LONGVARBINARY

Syntax
public static final int LONGVARBINARY


 Types.LONGVARCHAR

Types.LONGVARCHAR

Syntax
public static final int LONGVARCHAR


 Types.NULL

Types.NULL

Syntax
public static final int NULL


 Types.NUMERIC

Types.NUMERIC

Syntax
public static final int NUMERIC


 Types.OTHER

Types.OTHER

Syntax
public static final int OTHER
Description
OTHER indicates that the SQL type is database specific and gets mapped to a Java object which can be accessed via getObject and setObject.


 Types.REAL

Types.REAL

Syntax
public static final int REAL


 Types.SMALLINT

Types.SMALLINT

Syntax
public static final int SMALLINT


 Types.TIME

Types.TIME

Syntax
public static final int TIME


 Types.TIMESTAMP

Types.TIMESTAMP

Syntax
public static final int TIMESTAMP


 Types.TINYINT

Types.TINYINT

Syntax
public static final int TINYINT


 Types.VARBINARY

Types.VARBINARY

Syntax
public static final int VARBINARY


 Types.VARCHAR

Types.VARCHAR

Syntax
public static final int VARCHAR


 Package java.text

Package java.text

All Packages

Interfaces

  • CharacterIterator

    • Classes

  • BreakIterator
  • ChoiceFormat
  • CollationElementIterator
  • CollationKey
  • Collator
  • DateFormat
  • DateFormatSymbols
  • DecimalFormat
  • DecimalFormatSymbols
  • FieldPosition
  • Format
  • MessageFormat
  • NumberFormat
  • ParsePosition
  • RuleBasedCollator
  • SimpleDateFormat
  • StringCharacterIterator

    • Exceptions

  • ParseException


 Class BreakIterator

Class java.text.BreakIterator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.BreakIterator

public abstract class BreakIterator
extends Object
implements Cloneable, Serializable

The BreakIterator class implements methods for finding the location of boundaries in text. Instances of BreakIterator maintain a current position and scan over text returning the index of characters where boundaries occur. Internally, BreakIterator scans text using a CharacterIterator, and is thus able to scan text held by any object implementing that protocol. A StringCharacterIterator is used to scan String objects passed to setText.

You use the factory methods provided by this class to create instances of various types of break iterators. In particular, use getWordIterator, getLineIterator, getSentenceIterator, and getCharacterIterator to create BreakIterators that perform word, line, sentence, and character boundary analysis respectively. A single BreakIterator can work only on one unit (word, line, sentence, and so on). You must use a different iterator for each unit boundary analysis you wish to perform.

Line boundary analysis determines where a text string can be broken when line-wrapping. The mechanism correctly handles punctuation and hyphenated words.

Sentence boundary analysis allows selection with correct interpretation of periods within numbers and abbreviations, and trailing punctuation marks such as quotation marks and parentheses.

Word boundary analysis is used by search and replace functions, as well as within text editing applications that allow the user to select words with a double click. Word selection provides correct interpretation of punctuation marks within and following words. Characters that are not part of a word, such as symbols or punctuation marks, have word-breaks on both sides.

Character boundary analysis allows users to interact with characters as they expect to, for example, when moving the cursor through a text string. Character boundary analysis provides correct navigation of through character strings, regardless of how the character is stored. For example, an accented character might be stored as a base character and a diacritical mark. What users consider to be a character can differ between languages.

BreakIterator is intended for use with natural languages only. Do not use this class to tokenize a programming language.

Examples:

Creating and using text boundaries

 public static void main(String args[]) {
      if (args.length == 1) {
          String stringToExamine = args[0];
          //print each word in order
          BreakIterator boundary = BreakIterator.getWordInstance();
          boundary.setText(stringToExamine);
          printEachForward(boundary, stringToExamine);
          //print each sentence in reverse order
          boundary = BreakIterator.getSentenceInstance(Locale.US);
          boundary.setText(stringToExamine);
          printEachBackward(boundary, stringToExamine);
          printFirst(boundary, stringToExamine);
          printLast(boundary, stringToExamine);
      }
 }
Print each element in order
 public static void printEachForward(BreakIterator boundary, String source) {
     int start = boundary.first();
     for (int end = boundary.next();
          end != BreakIterator.DONE;
          start = end, end = boundary.next()) {
          System.out.println(source.substring(start,end));
     }
 }
Print each element in reverse order
 public static void printEachBackward(BreakIterator boundary, String source) {
     int end = boundary.last();
     for (int start = boundary.previous();
          start != BreakIterator.DONE;
          end = start, start = boundary.previous()) {
         System.out.println(source.substring(start,end));
     }
 }
Print first element
 public static void printFirst(BreakIterator boundary, String source) {
     int start = boundary.first();
     int end = boundary.next();
     System.out.println(source.substring(start,end));
 }
Print last element
 public static void printLast(BreakIterator boundary, String source) {
     int end = boundary.last();
     int start = boundary.previous();
     System.out.println(source.substring(start,end));
 }
Print the element at a specified position
 public static void printAt(BreakIterator boundary, int pos, String source) {
     int end = boundary.following(pos);
     int start = boundary.previous();
     System.out.println(source.substring(start,end));
 }

See Also:
CharacterIterator


 BreakIterator Members

BreakIterator Members

Class Overview | This Package | All Packages

Fields
Name | Description
DONE | DONE is returned by previous() and next() after all valid boundaries have been returned.

Constructors
Name | Description
BreakIterator() | Constructor.

Methods
Name | Description
clone() | Create a copy of this boundary
current() | Return character index of the text boundary that was most recently returned by next(), previous(), first(), or last()
first() | Return the first boundary.
following(int) | Return the first boundary following the specified offset.
getAvailableLocales() | Get the set of Locales for which TextBoundaries are installed
getCharacterInstance() | Create BreakIterator for character-breaks using default locale Returns an instance of a BreakIterator implementing character breaks.
getCharacterInstance(Locale) | Create BreakIterator for character-breaks using specified locale Returns an instance of a BreakIterator implementing character breaks.
getLineInstance() | Create BreakIterator for line-breaks using default locale.
getLineInstance(Locale) | Create BreakIterator for line-breaks using default locale.
getSentenceInstance() | Create BreakIterator for sentence-breaks using default locale Returns an instance of a BreakIterator implementing sentence breaks.
getSentenceInstance(Locale) | Create BreakIterator for sentence-breaks using specified locale Returns an instance of a BreakIterator implementing sentence breaks.
getText() | Get the text being scanned
getWordInstance() | Create BreakIterator for word-breaks using default locale.
getWordInstance(Locale) | Create BreakIterator for word-breaks using default locale.
last() | Return the last boundary.
next() | Return the boundary following the current boundary.
next(int) | Return the nth boundary from the current boundary
previous() | Return the boundary preceding the current boundary.
setText(CharacterIterator) | Set a new text for scanning.
setText(String) | Set a new text string to be scanned.


 BreakIterator.DONE

BreakIterator.DONE

Syntax
public static final int DONE
Description
DONE is returned by previous() and next() after all valid boundaries have been returned.


 BreakIterator.BreakIterator

BreakIterator.BreakIterator

Syntax
protected BreakIterator()
Description
Constructor. BreakIterator is stateless and has no default behavior.


 BreakIterator.clone

BreakIterator.clone

Syntax
public Object clone()
Returns
A copy of this
Description
Create a copy of this boundary

Overrides
clone in class Object


 BreakIterator.current

BreakIterator.current

Syntax
public abstract int current()
Returns
The boundary most recently returned.
Description
Return character index of the text boundary that was most recently returned by next(), previous(), first(), or last()


 BreakIterator.first

BreakIterator.first

Syntax
public abstract int first()
Returns
The character index of the first text boundary.
Description
Return the first boundary. The iterator's current position is set to the first boundary.


 BreakIterator.following

BreakIterator.following

Syntax
public abstract int following( int offset )
Parameters
offset
the offset to begin scanning. Valid values are determined by the CharacterIterator passed to setText(). Invalid values cause an IllegalArgumentException to be thrown.
Returns
The first boundary after the specified offset.
Description
Return the first boundary following the specified offset. The value returned is always greater than the offset or the value BreakIterator.DONE


 BreakIterator.getAvailableLocales

BreakIterator.getAvailableLocales

Syntax
public static synchronized Locale[] getAvailableLocales()
Returns
available locales
Description
Get the set of Locales for which TextBoundaries are installed


 BreakIterator.getCharacterInstance

BreakIterator.getCharacterInstance

Syntax 1
public static BreakIterator getCharacterInstance()
Returns
A BreakIterator for character-breaks
Description
Create BreakIterator for character-breaks using default locale Returns an instance of a BreakIterator implementing character breaks. Character breaks are boundaries of combining character sequences.

See Also
getDefault

Syntax 2
public static BreakIterator getCharacterInstance( Locale where )
Parameters
where
the local. If a specific character break is not avaliable for the specified local, a default character break is returned.
Returns
A BreakIterator for character-breaks
Description
Create BreakIterator for character-breaks using specified locale Returns an instance of a BreakIterator implementing character breaks. Character breaks are boundaries of combining character sequences.


 BreakIterator.getLineInstance

BreakIterator.getLineInstance

Syntax 1
public static BreakIterator getLineInstance()
Returns
A BreakIterator for line-breaks
Description
Create BreakIterator for line-breaks using default locale. Returns an instance of a BreakIterator implementing line breaks. Line breaks are logically possible line breaks, actual line breaks are usually determined based on display width. LineBreak is usefull for word wrapping text.

See Also
getDefault

Syntax 2
public static BreakIterator getLineInstance( Locale where )
Parameters
where
the local. If a specific LineBreak is not avaliable for the specified local, a default LineBreak is returned.
Returns
A BreakIterator for line-breaks
Description
Create BreakIterator for line-breaks using default locale. Returns an instance of a BreakIterator implementing line breaks. Line breaks are logically possible line breaks, actual line breaks are usually determined based on display width. LineBreak is usefull for word wrapping text.


 BreakIterator.getSentenceInstance

BreakIterator.getSentenceInstance

Syntax 1
public static BreakIterator getSentenceInstance()
Returns
A BreakIterator for sentence-breaks
Description
Create BreakIterator for sentence-breaks using default locale Returns an instance of a BreakIterator implementing sentence breaks.

See Also
getDefault

Syntax 2
public static BreakIterator getSentenceInstance( Locale where )
Parameters
where
the local. If a specific SentenceBreak is not avaliable for the specified local, a default SentenceBreak is returned.
Returns
A BreakIterator for sentence-breaks
Description
Create BreakIterator for sentence-breaks using specified locale Returns an instance of a BreakIterator implementing sentence breaks.


 BreakIterator.getText

BreakIterator.getText

Syntax
public abstract CharacterIterator getText()
Returns
the text being scanned
Description
Get the text being scanned


 BreakIterator.getWordInstance

BreakIterator.getWordInstance

Syntax 1
public static BreakIterator getWordInstance()
Returns
A BreakIterator for word-breaks
Description
Create BreakIterator for word-breaks using default locale. Returns an instance of a BreakIterator implementing word breaks. WordBreak is usefull for word selection (ex. double click)

See Also
getDefault

Syntax 2
public static BreakIterator getWordInstance( Locale where )
Parameters
where
the local. If a specific WordBreak is not avaliable for the specified local, a default WordBreak is returned.
Returns
A BreakIterator for word-breaks
Description
Create BreakIterator for word-breaks using default locale. Returns an instance of a BreakIterator implementing word breaks. WordBreak is usefull for word selection (ex. double click)


 BreakIterator.last

BreakIterator.last

Syntax
public abstract int last()
Returns
The character index of the last text boundary.
Description
Return the last boundary. The iterator's current position is set to the last boundary.


 BreakIterator.next

BreakIterator.next

Syntax 1
public abstract int next( int n )
Parameters
n
which boundary to return. A value of 0 does nothing. Negative values move to previous boundaries and positive values move to later boundaries.
Returns
The index of the nth boundary from the current position.
Description
Return the nth boundary from the current boundary

Syntax 2
public abstract int next()
Returns
The character index of the next text boundary or DONE if all boundaries have been returned. Equivalent to next(1).
Description
Return the boundary following the current boundary.


 BreakIterator.previous

BreakIterator.previous

Syntax
public abstract int previous()
Returns
The character index of the previous text boundary or DONE if all boundaries have been returned.
Description
Return the boundary preceding the current boundary.


 BreakIterator.setText

BreakIterator.setText

Syntax 1
public void setText( String newText )
Parameters
newText
new text to scan.
Description
Set a new text string to be scanned. The current scan position is reset to first().

Syntax 2
public abstract void setText( CharacterIterator newText )
Parameters
newText
new text to scan.
Description
Set a new text for scanning. The current scan position is reset to first().


 Interface CharacterIterator

Interface java.text.CharacterIterator

Interface Members | This Package | All Packages

public interface CharacterIterator
extends Cloneable

This interface defines a protocol for bidirectional iteration over text. The iterator iterates over a bounded sequence of characters. Characters are indexed with values beginning with the value returned by getBeginIndex and continuing through the value returned by getEndIndex()-1. The index of the current character can be retrieved by calling getIndex. Calling setIndex will move the iterator to a new position within the sequence of characters. If at any time the iterator's current index moves outside the range of getBeginIndex and getEndIndex, previous() and next() will return DONE, signaling that the iterator has reached the end of the sequence.

Examples:

Traverse the text from start to finish

 public void traverseForward(CharacterIterator iter) {
     for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
         processChar(c);
     }
 }
Traverse the text backwards, from end to start
 public void traverseBackward(CharacterIterator iter) {
     for(char c = iter.last(); c != CharacterIterator.DONE; c = iter.prev()) {
         processChar(c);
     }
 }
Traverse both forward and backward from a given position in the text. Calls to notBoundary() in this example represents some additional stopping criteria.
 public void traverseOut(CharacterIterator iter, int pos) {
     for (char c = iter.setIndex(pos);
          c != CharacterIterator.DONE && notBoundary(c);
          c = iter.next()) {}
 int end = iter.getIndex();
 for (char c = iter.setIndex(pos);
     c != CharacterIterator.DONE && notBoundary(c);
     c = iter.prev()) {}
 int start = iter.getIndex();
 processSection(start,end);
 }

See Also:
StringCharacterIterator


 CharacterIterator Members

CharacterIterator Members

Interface Overview | This Package | All Packages

Fields
Name | Description
DONE | Constant that is returned when the iterator has reached either the end or the beginning of the text.

Methods
Name | Description
clone() | Create a copy of this iterator
current() | Get the character at the current position (as returned by getIndex()).
first() | Set the position to getBeginIndex() and return the character at that position.
getBeginIndex() | Return the start index of the text.
getEndIndex() | Return the end index of the text.
getIndex() | Return the current index.
last() | Set the position to getEndIndex()-1, return the character at that position.
next() | Increment the iterator's index by one and return the character at the new index.
previous() | Decrement the iterator's index by one and return the character at the new index.
setIndex(int) | Set the position to the specified position in the text and return that character.


 CharacterIterator.DONE

CharacterIterator.DONE

Interface Overview | Interface Members | This Package | All Packages

Syntax
public static final char DONE
Description
Constant that is returned when the iterator has reached either the end or the beginning of the text. The unicode 2.0 standard states that '\\uFFFF' is an invalid unicode value and should not occur in any valid unicode string.


 CharacterIterator.clone

CharacterIterator.clone

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object clone()
Returns
A copy of this
Description
Create a copy of this iterator

Overrides
clone in class Object


 CharacterIterator.current

CharacterIterator.current

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char current()
Returns
the character at the current position or DONE if the current position is off the end of the text.
Description
Get the character at the current position (as returned by getIndex()).

See Also
getIndex


 CharacterIterator.first

CharacterIterator.first

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char first()
Returns
the first character in the text
Description
Set the position to getBeginIndex() and return the character at that position.

See Also
getBeginIndex


 CharacterIterator.getBeginIndex

CharacterIterator.getBeginIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getBeginIndex()
Returns
the index at which the text begins.
Description
Return the start index of the text.


 CharacterIterator.getEndIndex

CharacterIterator.getEndIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getEndIndex()
Returns
the index at which the text end.
Description
Return the end index of the text. This index is the index of the first character following the end of the text.


 CharacterIterator.getIndex

CharacterIterator.getIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract int getIndex()
Returns
the current index.
Description
Return the current index.


 CharacterIterator.last

CharacterIterator.last

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char last()
Returns
the last character in the text
Description
Set the position to getEndIndex()-1, return the character at that position.

See Also
getEndIndex


 CharacterIterator.next

CharacterIterator.next

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char next()
Returns
the character at the new position or DONE if the current position is off the end of the text.
Description
Increment the iterator's index by one and return the character at the new index. If the resulting index is greater or equal to getEndIndex(), the current index is reset to getEndIndex() and a value of DONE is returned.


 CharacterIterator.previous

CharacterIterator.previous

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char previous()
Returns
the character at the new position or DONE if the current position is off the end of the text.
Description
Decrement the iterator's index by one and return the character at the new index. If the resulting index is less than getBeginIndex(), the current index is reset to getBeginIndex() and a value of DONE is returned.


 CharacterIterator.setIndex

CharacterIterator.setIndex

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract char setIndex( int position )
Parameters
position
the position within the text. Valid values range from getBeginIndex() to getEndIndex() - 1. An IllegalArgumentException is thrown if an invalid value is supplied.
Returns
the character at the specified position.
Description
Set the position to the specified position in the text and return that character.


 Class ChoiceFormat

Class java.text.ChoiceFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.NumberFormat
                   |
                   +----java.text.ChoiceFormat

public class ChoiceFormat
extends NumberFormat

A ChoiceFormat allows you to attach a format to a range of numbers. It is generally used in a MessageFormat for handling plurals. The choice is specified with an ascending list of doubles, where each item specifies a half-open interval up to the next item:

 X matches j if and only if limit[j] <= X < limit[j+1]
If there is no match, then either the first or last index is used, depending on whether the number (X) is too low or too high.

Note: ChoiceFormat differs from the other Format classes in that you create a ChoiceFormat object with a constructor (not with a getInstance style factory method). The factory methods aren't necessary because ChoiceFormat doesn't require any complex setup for a given locale. In fact, ChoiceFormat doesn't implement any locale specific behavior.

When creating a ChoiceFormat, you must specify an array of formats and an array of limits. The length of these arrays must be the same. For example,

  •      limits = {1,2,3,4,5,6,7}
formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}

     limits = {0, 1, ChoiceFormat.nextDouble(1)}
formats = {"no files", "one file", "many files"}
(nextDouble can be used to get the next higher double, to
     make the half-open interval.)

Here is a simple example that shows formatting and parsing:

 double[] limits = {1,2,3,4,5,6,7};
 String[] monthNames = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
 ChoiceFormat form = new ChoiceFormat(limits, monthNames);
 ParsePosition status = new ParsePosition(0);
 for (double i = 0.0; i <= 8.0; ++i) {
     status.setIndex(0);
     System.out.println(i + " -> " + form.format(i) + " -> "
                              + form.parse(form.format(i),status));
 }
Here is a more complex example, with a pattern format:
 double[] filelimits = {0,1,2};
 String[] filepart = {"are no files","is one file","are {2} files"};
 ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
 Format[] testFormats = {fileform, null, NumberFormat.getInstance()};
 MessageFormat pattform = new MessageFormat("There {0} on {1}");
 pattform.setFormats(testFormats);
 Object[] testArgs = {null, "ADisk", null};
 for (int i = 0; i < 4; ++i) {
     testArgs[0] = new Integer(i);
     testArgs[2] = testArgs[0];
     System.out.println(pattform.format(testArgs));
 }

See Also:
DecimalFormat, MessageFormat


 ChoiceFormat Members

ChoiceFormat Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ChoiceFormat(double[], String[]) | Constructs with the limits and the corresponding formats.
ChoiceFormat(String) | Constructs with limits and corresponding formats based on the pattern.

Methods
Name | Description
applyPattern(String) | Sets the pattern.
clone() | Overrides Cloneable
equals(Object) | Equality comparision between two
format(double, StringBuffer, FieldPosition) | Specialization of format.
format(long, StringBuffer, FieldPosition) | Specialization of format.
getFormats() | Get the formats passed in the constructor.
getLimits() | Get the limits passed in the constructor.
hashCode() | Generates a hash code for the message format object.
nextDouble(double) | Finds the least double greater than d.
nextDouble(double, boolean) |
parse(String, ParsePosition) | Returns a Long if possible (e.g.
previousDouble(double) | Finds the greatest double less than d.
setChoices(double[], String[]) | Set the choices to be used in formatting.
toPattern() | Gets the pattern.


 ChoiceFormat.ChoiceFormat

ChoiceFormat.ChoiceFormat

Syntax 1
public ChoiceFormat( String newPattern )
Description
Constructs with limits and corresponding formats based on the pattern.

Syntax 2
public ChoiceFormat( double limits[], String formats[] )
Description
Constructs with the limits and the corresponding formats.

See Also
setChoices


 ChoiceFormat.applyPattern

ChoiceFormat.applyPattern

Syntax
public void applyPattern( String newPattern )
Parameters
newPattern
See the class description.
Description
Sets the pattern.


 ChoiceFormat.clone

ChoiceFormat.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class NumberFormat


 ChoiceFormat.equals

ChoiceFormat.equals

Syntax
public boolean equals( Object obj )
Description
Equality comparision between two

Overrides
equals in class NumberFormat


 ChoiceFormat.format

ChoiceFormat.format

Syntax 1
public StringBuffer format( long number, StringBuffer toAppendTo, FieldPosition status )
Description
Specialization of format. This method really calls format(double, StringBuffer, FieldPosition) thus the range of longs that are supported is only equal to the range that can be stored by double. This will never be a practical limitation.

Overrides
format in class NumberFormat

Syntax 2
public StringBuffer format( double number, StringBuffer toAppendTo, FieldPosition status )
Description
Specialization of format.

Overrides
format in class NumberFormat


 ChoiceFormat.getFormats

ChoiceFormat.getFormats

Syntax
public Object[] getFormats()
Returns
the formats.
Description
Get the formats passed in the constructor.


 ChoiceFormat.getLimits

ChoiceFormat.getLimits

Syntax
public double[] getLimits()
Returns
the limits.
Description
Get the limits passed in the constructor.


 ChoiceFormat.hashCode

ChoiceFormat.hashCode

Syntax
public int hashCode()
Description
Generates a hash code for the message format object.

Overrides
hashCode in class NumberFormat


 ChoiceFormat.nextDouble

ChoiceFormat.nextDouble

Syntax
public static final double nextDouble( double d )
Description
Finds the least double greater than d. If NaN, returns same value.

Used to make half-open intervals.

See Also
previousDouble


 ChoiceFormat.nextDouble

ChoiceFormat.nextDouble

Syntax
public static double nextDouble( double d, boolean positive )


 ChoiceFormat.parse

ChoiceFormat.parse

Syntax
public Number parse( String text, ParsePosition status )
Description
Returns a Long if possible (e.g.

Overrides
parse in class NumberFormat


 ChoiceFormat.previousDouble

ChoiceFormat.previousDouble

Syntax
public static final double previousDouble( double d )
Description
Finds the greatest double less than d. If NaN, returns same value.

See Also
nextDouble


 ChoiceFormat.setChoices

ChoiceFormat.setChoices

Syntax
public void setChoices( double limits[], String formats[] )
Parameters
limits
contains the top value that you want parsed with that format,and should be in ascending sorted order. When formatting X, the choice will be the i, where limit[i] <= X < limit[i+1].
formats
are the formats you want to use for each limit. They can be either Format objects or Strings. When formatting with object Y, if the object is a NumberFormat, then ((NumberFormat) Y).format(X) is called. Otherwise Y.toString() is called.
Description
Set the choices to be used in formatting.


 ChoiceFormat.toPattern

ChoiceFormat.toPattern

Syntax
public String toPattern()
Description
Gets the pattern.


 Class CollationElementIterator

Class java.text.CollationElementIterator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.CollationElementIterator

public final class CollationElementIterator
extends Object

The CollationElementIterator class is used as an iterator to walk through each character of an international string. Use the iterator to return the ordering priority of the positioned character. The ordering priority of a character, which we refer to as a key, defines how a character is collated in the given collation object.

For example, consider the following in Spanish:

 "ca" -> the first key is key('c') and second key is key('a').
 "cha" -> the first key is key('ch') and second key is key('a').
And in German,
 "äb"-> the first key is key('a'), the second key is key('e'), and
 the third key is key('b').
The key of a character is an integer composed of primary order(short), secondary order(byte), and tertiary order(byte). Java strictly defines the size and signedness of its primitive data types. Therefore, the static functions primaryOrder, secondaryOrder, and tertiaryOrder return int, short, and short respectively to ensure the correctness of the key value.

Example of the iterator usage,

 // get the first key of the string
 String str = "This is a test";
 CollationElementIterator c =
     new CollationElementIterator(str, 0, str.length(),
                                  Collator.getInstance());
 int primaryOrder = CollationElementIterator.primaryOrder(c->next());

CollationElementIterator.next returns the collation order of the next character. A collation order consists of primary order, secondary order and tertiary order. The data type of the collation order is int. The first 16 bits of a collation order is its primary order; the next 8 bits is the secondary order and the last 8 bits is the tertiary order.

See Also:
Collator, RuleBasedCollator


 CollationElementIterator Members

CollationElementIterator Members

Class Overview | This Package | All Packages

Fields
Name | Description
NULLORDER | Null order which indicates the end of string is reached by the cursor.

Methods
Name | Description
next() | Get the ordering priority of the next character in the string.
primaryOrder(int) | Get the primary order of a collation order.
reset() | Resets the cursor to the beginning of the string.
secondaryOrder(int) | Get the secondary order of a collation order.
tertiaryOrder(int) | Get the tertiary order of a collation order.


 CollationElementIterator.NULLORDER

CollationElementIterator.NULLORDER

Syntax
public static final int NULLORDER
Description
Null order which indicates the end of string is reached by the cursor.


 CollationElementIterator.next

CollationElementIterator.next

Syntax
public int next()
Returns
the next character's ordering. Returns NULLORDER if the end of string is reached.
Description
Get the ordering priority of the next character in the string.


 CollationElementIterator.primaryOrder

CollationElementIterator.primaryOrder

Syntax
public static final int primaryOrder( int order )
Parameters
order
the collation order
Returns
the primary order of a collation order.
Description
Get the primary order of a collation order.


 CollationElementIterator.reset

CollationElementIterator.reset

Syntax
public void reset()
Description
Resets the cursor to the beginning of the string.


 CollationElementIterator.secondaryOrder

CollationElementIterator.secondaryOrder

Syntax
public static final short secondaryOrder( int order )
Parameters
order
the collation order
Returns
the secondary order of a collation order.
Description
Get the secondary order of a collation order.


 CollationElementIterator.tertiaryOrder

CollationElementIterator.tertiaryOrder

Syntax
public static final short tertiaryOrder( int order )
Parameters
order
the collation order
Returns
the tertiary order of a collation order.
Description
Get the tertiary order of a collation order.


 Class CollationKey

Class java.text.CollationKey

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.CollationKey

public final class CollationKey
extends Object

A CollationKey represents a String under the rules of a specific Collator object. Comparing two CollationKeys returns the relative order of the Strings they represent. Using CollationKeys to compare Strings is generally faster than using Collator.compare. Thus, when the Strings must be compared multiple times, for example when sorting a list of Strings. It's more efficient to use CollationKeys.

You can not create CollationKeys directly. Rather, generate them by calling Collator.getCollationKey. You can only compare CollationKeys generated from the same Collator object.

Generating a CollationKey for a String involves examining the entire String and converting it to series of bits that can be compared bitwise. This allows fast comparisons once the keys are generated. The cost of generating keys is recouped in faster comparisons when Strings need to be compared many times. On the other hand, the result of a comparison is often determined by the first couple of characters of each String. Collator.compare examines only as many characters as it needs which allows it to be faster when doing single comparisons.

The following example shows how CollationKeys might be used to sort a list of Strings.

 // Create an array of CollationKeys for the Strings to be sorted.
 Collator myCollator = Collator.getInstance();
 CollationKey[] keys = new CollationKey[3];
 keys[0] = myCollator.getCollationKey("Tom");
 keys[1] = myCollator.getCollationKey("Dick");
 keys[2] = myCollator.getCollationKey("Harry");
 sort( keys );

 //...

 // Inside body of sort routine, compare keys this way
 if( keys[i].compareTo( keys[j] ) > 0 )
    // swap keys[i] and keys[j]

 //...

 // Finally, when we've returned from sort.
 System.out.println( keys[0].getSourceString() );
 System.out.println( keys[1].getSourceString() );
 System.out.println( keys[2].getSourceString() );

See Also:
Collator, RuleBasedCollator


 CollationKey Members

CollationKey Members

Class Overview | This Package | All Packages

Methods
Name | Description
compareTo(CollationKey) | Compare this CollationKey to the target CollationKey.
equals(Object) | Compare this CollationKey and the target CollationKey for equality.
getSourceString() | Returns the String that this CollationKey represents.
hashCode() | Creates a hash code for this CollationKey.
toByteArray() | Converts the CollationKey to a sequence of bits.


 CollationKey.compareTo

CollationKey.compareTo

Syntax
public int compareTo( CollationKey target )
Parameters
target
target CollationKey
Returns
Returns an integer value. Value is less than zero if this is less than target, value is zero if this and target are equal and value is greater than zero if this is greater than target.
Description
Compare this CollationKey to the target CollationKey. The collation rules of the Collator object which created these keys are applied. Note: CollationKeys created by different Collators can not be compared.

See Also
compare


 CollationKey.equals

CollationKey.equals

Syntax
public boolean equals( Object target )
Parameters
target
the CollationKey to compare to.
Returns
Returns true if two objects are equal, false otherwise.
Description
Compare this CollationKey and the target CollationKey for equality. The collation rules of the Collator object which created these keys are applied. Note: CollationKeys created by different Collators can not be compared.

Overrides
equals in class Object


 CollationKey.getSourceString

CollationKey.getSourceString

Syntax
public String getSourceString()
Description
Returns the String that this CollationKey represents.


 CollationKey.hashCode

CollationKey.hashCode

Syntax
public int hashCode()
Returns
the hash value based on the string's collation order.
Description
Creates a hash code for this CollationKey. The hash value is calculated on the key itself, not the String from which the key was created. Thus if x and y are CollationKeys, then x.hashCode(x) == y.hashCode() if x.equals(y) is true. This allows language-sensitive comparison in a hash table. See the CollatinKey class description for an example.

Overrides
hashCode in class Object


 CollationKey.toByteArray

CollationKey.toByteArray

Syntax
public byte[] toByteArray()
Description
Converts the CollationKey to a sequence of bits. If two CollationKeys could be legitimately compared, then one could compare the byte arrays for each of those keys to obtain the same result. Byte arrays are organized most significant byte first.


 Class Collator

Class java.text.Collator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Collator

public abstract class Collator
extends Object
implements Cloneable, Serializable

The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

Collator is an abstract base class. Subclasses implement specific collation strategies. One subclass, RuleBasedCollator, is currently provided with the JDK and is applicable to a wide set of languages. Other subclasses may be created to handle more specialized needs.

Like other locale-sensitive classes, you can use the static factory method, getInstance, to obtain the appropriate Collator object for a given locale. You will only need to look at the subclasses of Collator if you need to understand the details of a particular collation strategy or if you need to modify that strategy.

The following example shows how to compare two strings using the Collator for the default locale.

 // Compare two strings in the default locale
 Collator myCollator = Collator.getInstance();
 if( myCollator.compare("abc", "ABC") < 0 )
     System.out.println("abc is less than ABC");
 else
     System.out.println("abc is greater than or equal to ABC");

You can set a Collator's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY, SECONDARY, TERTIARY, and IDENTICAL. The exact assignment of strengths to language features is locale dependant. For example, in Czech, "e" and "f" are considered primary differences, while "e" and "ê" are secondary differences, "e" and "E" are tertiary differences and "e" and "e" are identical. The following shows how both case and accents could be ignored for US English.

 //Get the Collator for US English and set its strength to PRIMARY
 Collator usCollator = Collator.getInstance(Locale.US);
 usCollator.setStrength(Collator.PRIMARY);
 if( usCollator.compare("abc", "ABC") == 0 ) {
     System.out.println("Strings are equivalent");
 }

For comparing Strings exactly once, the compare method provides the best performance. When sorting a list of Strings however, it is generally necessary to compare each String multiple times. In this case, CollationKeys provide better performance. The CollationKey class converts a String to a series of bits that can be compared bitwise against other CollationKeys. A CollationKey is created by a Collator object for a given String.
Note: CollationKeys from different Collators can not be compared. See the class description for CollationKey for an example using CollationKeys.

See Also:
RuleBasedCollator, CollationKey, CollationElementIterator, Locale


 Collator Members

Collator Members

Class Overview | This Package | All Packages

Fields
Name | Description
CANONICAL_DECOMPOSITION | Decomposition mode value.
FULL_DECOMPOSITION | Decomposition mode value.
IDENTICAL | Collator strength value.
NO_DECOMPOSITION | Decomposition mode value.
PRIMARY | Collator strength value.
SECONDARY | Collator strength value.
TERTIARY | Collator strength value.

Constructors
Name | Description
Collator() | Default constructor.

Methods
Name | Description
clone() | Overrides Cloneable
compare(String, String) | Compares the source string to the target string according to the collation rules for this Collator.
equals(Object) | Compares the equality of two Collators.
equals(String, String) | Convenience method for comparing the equality of two strings based on this Collator's collation rules.
getAvailableLocales() | Get the set of Locales for which Collators are installed.
getCollationKey(String) | Transforms the String into a series of bits that can be compared bitwise to other CollationKeys.
getDecomposition() | Get the decomposition mode of this Collator.
getInstance() | Gets the Collator for the current default locale.
getInstance(Locale) | Gets the Collator for the desired locale.
getStrength() | Returns this Collator's strength property.
hashCode() | Generates the hash code for this Collator.
setDecomposition(int) | Set the decomposition mode of this Collator.
setStrength(int) | Sets this Collator's strength property.


 Collator.CANONICAL_DECOMPOSITION

Collator.CANONICAL_DECOMPOSITION

Syntax
public static final int CANONICAL_DECOMPOSITION
Description
Decomposition mode value. With CANONICAL_DECOMPOSITION set, characters that are canonical variants according to Unicode 2.0 will be decomposed for collation. This is the default setting and should be used to get correct collation of accented characters.

See Also
getDecomposition, setDecomposition


 Collator.FULL_DECOMPOSITION

Collator.FULL_DECOMPOSITION

Syntax
public static final int FULL_DECOMPOSITION
Description
Decomposition mode value. With FULL_DECOMPOSITION set, both Unicode canonical variants and Unicode compatibility variants will be decomposed for collation. This causes not only accented characters to be collated, but also characters that have special formats to be collated with their norminal form. For example, the half-width and full-width ASCII and Katakana characters are then collated together. FULL_DECOMPOSITION is the most complete and therefore the slowest decomposition mode.

See Also
getDecomposition, setDecomposition


 Collator.IDENTICAL

Collator.IDENTICAL

Syntax
public static final int IDENTICAL
Description
Collator strength value. When set, all differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for characters with equivalent Unicode spellings ("ä" vs "a?") to be considered IDENTICAL.


 Collator.NO_DECOMPOSITION

Collator.NO_DECOMPOSITION

Syntax
public static final int NO_DECOMPOSITION
Description
Decomposition mode value. With NO_DECOMPOSITION set, accented characters will not be decomposed for collation. This provides the fastest collation but will only produce correct results for languages that do not use accents.

See Also
getDecomposition, setDecomposition


 Collator.PRIMARY

Collator.PRIMARY

Syntax
public static final int PRIMARY
Description
Collator strength value. When set, only PRIMARY differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for different base letters ("a" vs "b") to be considered a PRIMARY difference.

See Also
setStrength, getStrength


 Collator.SECONDARY

Collator.SECONDARY

Syntax
public static final int SECONDARY
Description
Collator strength value. When set, only SECONDARY and above differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for different accented forms of the same base letter ("a" vs "ä") to be considered a SECONDARY difference.

See Also
setStrength, getStrength


 Collator.TERTIARY

Collator.TERTIARY

Syntax
public static final int TERTIARY
Description
Collator strength value. When set, only TERTIARY and above differences are considered significant during comparison. The assignment of strengths to language features is locale dependant. A common example is for case differences ("a" vs "A") to be considered a TERTIARY difference.

See Also
setStrength, getStrength


 Collator.Collator

Collator.Collator

Syntax
protected Collator()
Description
Default constructor. This constructor is protected so subclasses can get access to it. Users typically create a Collator sub-class by calling the factory method getInstance.

See Also
getInstance


 Collator.clone

Collator.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Object


 Collator.compare

Collator.compare

Syntax
public abstract int compare( String source, String target )
Parameters
source
the source string.
target
the target string.
Returns
Returns an integer value. Value is less than zero if source is less than target, value is zero if source and target are equal, value is greater than zero if source is greater than target.
Description
Compares the source string to the target string according to the collation rules for this Collator. Returns an integer less than, equal to or greater than zero depending on whether the source String is less than, equal to or greater than the target string. See the Collator class description for an example of use.

For a one time comparison, this method has the best performance. If a given String will be involved in multiple comparisons, CollationKey.compareTo has the best performance. See the Collator class description for an example using CollationKeys.

See Also
CollationKey, getCollationKey


 Collator.equals

Collator.equals

Syntax
public boolean equals( String source, String target )
Parameters
source
the source string to be compared with.
target
the target string to be compared with.
Returns
true if the strings are equal according to the collation rules. false, otherwise.
Description
Convenience method for comparing the equality of two strings based on this Collator's collation rules.

See Also
compare


 Collator.equals

Collator.equals

Syntax
public boolean equals( Object that )
Parameters
that
the Collator to be compared with this.
Returns
true if this Collator is the same as that Collator; false otherwise.
Description
Compares the equality of two Collators.

Overrides
equals in class Object


 Collator.getAvailableLocales

Collator.getAvailableLocales

Syntax
public static synchronized Locale[] getAvailableLocales()
Returns
the list of available locales which collators are installed.
Description
Get the set of Locales for which Collators are installed.


 Collator.getCollationKey

Collator.getCollationKey

Syntax
public abstract CollationKey getCollationKey( String source )
Parameters
source
the string to be transformed into a collation key.
Returns
the CollationKey for the given String based on this Collator's collation rules. If the source String is null, a null CollationKey is returned.
Description
Transforms the String into a series of bits that can be compared bitwise to other CollationKeys. CollationKeys provide better performance than Collator.compare when Strings are involved in multiple comparisons. See the Collator class description for an example using CollationKeys.

See Also
CollationKey, compare


 Collator.getDecomposition

Collator.getDecomposition

Syntax
public synchronized int getDecomposition()
Returns
the decomposition mode
Description
Get the decomposition mode of this Collator. Decomposition mode determines how Unicode composed characters are handled. Adjusting decomposition mode allows the user to select between faster and more complete collation behavior.

The three values for decomposition mode are:

  • NO_DECOMPOSITION,
  • CANONICAL_DECOMPOSITION
  • FULL_DECOMPOSITION.
See the documentation for these three constants for a description of their meaning.

See Also
setDecomposition, NO_DECOMPOSITION, CANONICAL_DECOMPOSITION, FULL_DECOMPOSITION


 Collator.getInstance

Collator.getInstance

Syntax 1
public static synchronized Collator getInstance()
Returns
the Collator for the default locale.(for example, en_US)
Description
Gets the Collator for the current default locale. The default locale is determined by java.util.Locale.getDefault.

See Also
getDefault

Syntax 2
public static synchronized Collator getInstance( Locale desiredLocale )
Parameters
desiredLocale
the desired locale.
Returns
the Collator for the desired locale.
Description
Gets the Collator for the desired locale.

See Also
Locale, ResourceBundle


 Collator.getStrength

Collator.getStrength

Syntax
public synchronized int getStrength()
Returns
this Collator's current strength property.
Description
Returns this Collator's strength property. The strength property determines the minimum level of difference considered significant during comparison. See the Collator class description for an example of use.

See Also
setStrength, PRIMARY, SECONDARY, TERTIARY, IDENTICAL


 Collator.hashCode

Collator.hashCode

Syntax
public abstract synchronized int hashCode()
Description
Generates the hash code for this Collator.

Overrides
hashCode in class Object


 Collator.setDecomposition

Collator.setDecomposition

Syntax
public synchronized void setDecomposition( int decompositionMode )
Parameters
the
new decomposition mode
Description
Set the decomposition mode of this Collator. See getDecomposition for a description of decomposition mode.

Exceptions
IllegalArgumentException If the given value is not a valid decomposition mode.
See Also
getDecomposition, NO_DECOMPOSITION, CANONICAL_DECOMPOSITION, FULL_DECOMPOSITION


 Collator.setStrength

Collator.setStrength

Syntax
public synchronized void setStrength( int newStrength )
Parameters
the
new strength value.
Description
Sets this Collator's strength property. The strength property determines the minimum level of difference considered significant during comparison. See the Collator class description for an example of use.

Exceptions
IllegalArgumentException If the new strength value is not one of PRIMARY, SECONDARY, TERTIARY or IDENTICAL.
See Also
getStrength, PRIMARY, SECONDARY, TERTIARY, IDENTICAL


 Class DateFormat

Class java.text.DateFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.DateFormat

public abstract class DateFormat
extends Format
implements Cloneable

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., millis -> text), parsing (text -> millis), and normalization. Formats/Parses a date or time, which is the standard millis since 24:00 GMT, Jan 1, 1970

DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given loacle and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in the method descriptions.

DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.

To format a date for the current Locale, use one of the static factory methods:

  myString = DateFormat.getDateInstance().format(myDate);

If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

  DateFormat df = DateFormat.getDateInstance();
  for (int i = 0; i < a.length; ++i) {
    output.println(df.format(myDate[i]) + "; ");
  }

To format a number for a different Locale, specify it in the call to getDateInstance().

  DateFormat df = DateFormat.getDateInstance(Locale.FRANCE);

You can use a DateFormat to parse also.

  myDate = df.parse(myString);

Use getDate to get the normal date format for that country. There are other static factory methods available. Use getTime to get the time format for that country. Use getDateTime to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:

  • SHORT is completely numeric, such as 12.13.52 or 3:30pm
  • MEDIUM is longer, such as Jan 12, 1952
  • LONG is longer, such as January 12, 1952 or 3:30:32pm
  • FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

You can also set the time zone on the format if you wish. If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to

  • pregressively parse through pieces of a string.
  • align any particular field, or find out where it is for selection on the screen.

See Also:
Format, NumberFormat, SimpleDateFormat, Calendar, GregorianCalendar, TimeZone


 DateFormat Members

DateFormat Members

Class Overview | This Package | All Packages

Fields
Name | Description
AM_PM_FIELD | Useful constant for AM_PM field alignment.
calendar | The calendar that DateFormat uses to produce the time field values needed to implement date/time formatting.
DATE_FIELD | Useful constant for DATE field alignment.
DAY_OF_WEEK_FIELD | Useful constant for DAY_OF_WEEK field alignment.
DAY_OF_WEEK_IN_MONTH_FIELD | Useful constant for DAY_OF_WEEK_IN_MONTH field alignment.
DAY_OF_YEAR_FIELD | Useful constant for DAY_OF_YEAR field alignment.
DEFAULT | Constant for default style pattern.
ERA_FIELD | Useful constant for ERA field alignment.
FULL | Constant for full style pattern.
HOUR0_FIELD | Useful constant for zero-based HOUR field alignment.
HOUR1_FIELD | Useful constant for one-based HOUR field alignment.
HOUR_OF_DAY0_FIELD | Useful constant for zero-based HOUR_OF_DAY field alignment.
HOUR_OF_DAY1_FIELD | Useful constant for one-based HOUR_OF_DAY field alignment.
LONG | Constant for long style pattern.
MEDIUM | Constant for medium style pattern.
MILLISECOND_FIELD | Useful constant for MILLISECOND field alignment.
MINUTE_FIELD | Useful constant for MINUTE field alignment.
MONTH_FIELD | Useful constant for MONTH field alignment.
numberFormat | The number formatter that DateFormat uses to format numbers in dates and times.
SECOND_FIELD | Useful constant for SECOND field alignment.
SHORT | Constant for short style pattern.
TIMEZONE_FIELD | Useful constant for TIMEZONE field alignment.
WEEK_OF_MONTH_FIELD | Useful constant for WEEK_OF_MONTH field alignment.
WEEK_OF_YEAR_FIELD | Useful constant for WEEK_OF_YEAR field alignment.
YEAR_FIELD | Useful constant for YEAR field alignment.

Constructors
Name | Description
DateFormat() |

Methods
Name | Description
clone() | Overrides Cloneable
equals(Object) | Overrides equals
format(Date) | Formats a Date into a date/time string.
format(Date, StringBuffer, FieldPosition) | Formats a Date into a date/time string.
format(Object, StringBuffer, FieldPosition) | Overrides Format.
getAvailableLocales() | Gets the set of locales for which DateFormats are installed.
getCalendar() | Gets the calendar associated with this date/time formatter.
getDateInstance() | Gets the date formatter with the default formatting style for the default locale.
getDateInstance(int) | Gets the date formatter with the given formatting style for the default locale.
getDateInstance(int, Locale) | Gets the date formatter with the given formatting style for the given locale.
getDateTimeInstance() | Gets the date/time formatter with the default formatting style for the default locale.
getDateTimeInstance(int, int) | Gets the date/time formatter with the given date and time formatting styles for the default locale.
getDateTimeInstance(int, int, Locale) | Gets the date/time formatter with the given formatting styles for the given locale.
getInstance() | Get a default date/time formatter that uses the SHORT style for both the date and the time.
getNumberFormat() | Gets the number formatter which this date/time formatter uses to format and parse a time.
getTimeInstance() | Gets the time formatter with the default formatting style for the default locale.
getTimeInstance(int) | Gets the time formatter with the given formatting style for the default locale.
getTimeInstance(int, Locale) | Gets the time formatter with the given formatting style for the given locale.
getTimeZone() | Gets the time zone.
hashCode() | Overrides hashCode
isLenient() | Tell whether date/time parsing is to be lenient.
parse(String) | Parse a date/time string.
parse(String, ParsePosition) | Parse a date/time string according to the given parse position.
parseObject(String, ParsePosition) | Parse a date/time string into an Object.
setCalendar(Calendar) | Set the calendar to be used by this date format.
setLenient(boolean) | Specify whether or not date/time parsing is to be lenient.
setNumberFormat(NumberFormat) | Allows you to set the number formatter.
setTimeZone(TimeZone) | Sets the time zone for the calendar of this DateFormat object.


 DateFormat.AM_PM_FIELD

DateFormat.AM_PM_FIELD

Syntax
public static final int AM_PM_FIELD
Description
Useful constant for AM_PM field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.calendar

DateFormat.calendar

Syntax
protected Calendar calendar
Description
The calendar that DateFormat uses to produce the time field values needed to implement date/time formatting. Subclasses should initialize this to the default calendar for the locale associated with this DateFormat.


 DateFormat.DATE_FIELD

DateFormat.DATE_FIELD

Syntax
public static final int DATE_FIELD
Description
Useful constant for DATE field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.DAY_OF_WEEK_FIELD

DateFormat.DAY_OF_WEEK_FIELD

Syntax
public static final int DAY_OF_WEEK_FIELD
Description
Useful constant for DAY_OF_WEEK field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD

DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD

Syntax
public static final int DAY_OF_WEEK_IN_MONTH_FIELD
Description
Useful constant for DAY_OF_WEEK_IN_MONTH field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.DAY_OF_YEAR_FIELD

DateFormat.DAY_OF_YEAR_FIELD

Syntax
public static final int DAY_OF_YEAR_FIELD
Description
Useful constant for DAY_OF_YEAR field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.DEFAULT

DateFormat.DEFAULT

Syntax
public static final int DEFAULT
Description
Constant for default style pattern.


 DateFormat.ERA_FIELD

DateFormat.ERA_FIELD

Syntax
public static final int ERA_FIELD
Description
Useful constant for ERA field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.FULL

DateFormat.FULL

Syntax
public static final int FULL
Description
Constant for full style pattern.


 DateFormat.HOUR0_FIELD

DateFormat.HOUR0_FIELD

Syntax
public static final int HOUR0_FIELD
Description
Useful constant for zero-based HOUR field alignment. Used in FieldPosition of date/time formatting. HOUR0_FIELD is used for the zero-based 12-hour clock. For example, 11:30 PM + 1 hour results in 00:30 AM.


 DateFormat.HOUR1_FIELD

DateFormat.HOUR1_FIELD

Syntax
public static final int HOUR1_FIELD
Description
Useful constant for one-based HOUR field alignment. Used in FieldPosition of date/time formatting. HOUR1_FIELD is used for the one-based 12-hour clock. For example, 11:30 PM + 1 hour results in 12:30 AM.


 DateFormat.HOUR_OF_DAY0_FIELD

DateFormat.HOUR_OF_DAY0_FIELD

Syntax
public static final int HOUR_OF_DAY0_FIELD
Description
Useful constant for zero-based HOUR_OF_DAY field alignment. Used in FieldPosition of date/time formatting. HOUR_OF_DAY0_FIELD is used for the zero-based 24-hour clock. For example, 23:59 + 01:00 results in 00:59.


 DateFormat.HOUR_OF_DAY1_FIELD

DateFormat.HOUR_OF_DAY1_FIELD

Syntax
public static final int HOUR_OF_DAY1_FIELD
Description
Useful constant for one-based HOUR_OF_DAY field alignment. Used in FieldPosition of date/time formatting. HOUR_OF_DAY1_FIELD is used for the one-based 24-hour clock. For example, 23:59 + 01:00 results in 24:59.


 DateFormat.LONG

DateFormat.LONG

Syntax
public static final int LONG
Description
Constant for long style pattern.


 DateFormat.MEDIUM

DateFormat.MEDIUM

Syntax
public static final int MEDIUM
Description
Constant for medium style pattern.


 DateFormat.MILLISECOND_FIELD

DateFormat.MILLISECOND_FIELD

Syntax
public static final int MILLISECOND_FIELD
Description
Useful constant for MILLISECOND field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.MINUTE_FIELD

DateFormat.MINUTE_FIELD

Syntax
public static final int MINUTE_FIELD
Description
Useful constant for MINUTE field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.MONTH_FIELD

DateFormat.MONTH_FIELD

Syntax
public static final int MONTH_FIELD
Description
Useful constant for MONTH field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.numberFormat

DateFormat.numberFormat

Syntax
protected NumberFormat numberFormat
Description
The number formatter that DateFormat uses to format numbers in dates and times. Subclasses should initialize this to the default number format for the locale associated with this DateFormat.


 DateFormat.SECOND_FIELD

DateFormat.SECOND_FIELD

Syntax
public static final int SECOND_FIELD
Description
Useful constant for SECOND field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.SHORT

DateFormat.SHORT

Syntax
public static final int SHORT
Description
Constant for short style pattern.


 DateFormat.TIMEZONE_FIELD

DateFormat.TIMEZONE_FIELD

Syntax
public static final int TIMEZONE_FIELD
Description
Useful constant for TIMEZONE field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.WEEK_OF_MONTH_FIELD

DateFormat.WEEK_OF_MONTH_FIELD

Syntax
public static final int WEEK_OF_MONTH_FIELD
Description
Useful constant for WEEK_OF_MONTH field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.WEEK_OF_YEAR_FIELD

DateFormat.WEEK_OF_YEAR_FIELD

Syntax
public static final int WEEK_OF_YEAR_FIELD
Description
Useful constant for WEEK_OF_YEAR field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.YEAR_FIELD

DateFormat.YEAR_FIELD

Syntax
public static final int YEAR_FIELD
Description
Useful constant for YEAR field alignment. Used in FieldPosition of date/time formatting.


 DateFormat.DateFormat

DateFormat.DateFormat

Syntax
protected DateFormat()


 DateFormat.clone

DateFormat.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Format


 DateFormat.equals

DateFormat.equals

Syntax
public boolean equals( Object obj )
Description
Overrides equals

Overrides
equals in class Object


 DateFormat.format

DateFormat.format

Syntax 1
public final StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition )
Parameters
obj
must be a Number or a Date.
toAppendTo
the string buffer for the returning time string.
status
the formatting status. On input: an alignment field, if desired. On output: the offsets of the alignment field.
Returns
the formatted time string.
Description
Overrides Format. Formats a time object into a time string. Examples of time objects are a time value expressed in milliseconds and a Date object.

Overrides
format in class Format
See Also
Format

Syntax 2
public abstract StringBuffer format( Date date, StringBuffer toAppendTo, FieldPosition fieldPosition )
Parameters
date
a Date to be formatted into a date/time string.
toAppendTo
the string buffer for the returning date/time string.
status
the formatting status. On input: an alignment field, if desired. On output: the offsets of the alignment field. For example, given a time text "1996.07.10 AD at 15:08:56 PDT", if the given status.field is DateFormat.YEAR_FIELD, the offsets status.beginIndex and status.getEndIndex will be set to 0 and 4, respectively. Notice that if the same time field appears more than once in a pattern, the status will be set for the first occurence of that time field. For instance, formatting a Date to the time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD, the offsets status.beginIndex and status.getEndIndex will be set to 5 and 8, respectively, for the first occurence of the timezone pattern character 'z'.
Returns
the formatted date/time string.
Description
Formats a Date into a date/time string.

Syntax 3
public final String format( Date date )
Parameters
date
the time value to be formatted into a time string.
Returns
the formatted time string.
Description
Formats a Date into a date/time string.


 DateFormat.getAvailableLocales

DateFormat.getAvailableLocales

Syntax
public static Locale[] getAvailableLocales()
Returns
the set of locales for which DateFormats are installed.
Description
Gets the set of locales for which DateFormats are installed.


 DateFormat.getCalendar

DateFormat.getCalendar

Syntax
public Calendar getCalendar()
Returns
the calendar associated with this date/time formatter.
Description
Gets the calendar associated with this date/time formatter.


 DateFormat.getDateInstance

DateFormat.getDateInstance

Syntax 1
public static final DateFormat getDateInstance()
Returns
a date formatter.
Description
Gets the date formatter with the default formatting style for the default locale.

Syntax 2
public static final DateFormat getDateInstance( int style )
Parameters
style
the given formatting style. For example, SHORT for "M/d/yy" in the US locale.
Returns
a date formatter.
Description
Gets the date formatter with the given formatting style for the default locale.

Syntax 3
public static final DateFormat getDateInstance( int style, Locale aLocale )
Parameters
style
the given formatting style. For example, SHORT for "M/d/yy" in the US locale.
inLocale
the given locale.
Returns
a date formatter.
Description
Gets the date formatter with the given formatting style for the given locale.


 DateFormat.getDateTimeInstance

DateFormat.getDateTimeInstance

Syntax 1
public static final DateFormat getDateTimeInstance()
Returns
a date/time formatter.
Description
Gets the date/time formatter with the default formatting style for the default locale.

Syntax 2
public static final DateFormat getDateTimeInstance( int dateStyle, int timeStyle )
Parameters
dateStyle
the given date formatting style. For example, SHORT for "M/d/yy" in the US locale.
timeStyle
the given time formatting style. For example, SHORT for "h:mm a" in the US locale.
Returns
a date/time formatter.
Description
Gets the date/time formatter with the given date and time formatting styles for the default locale.

Syntax 3
public static final DateFormat getDateTimeInstance( int dateStyle, int timeStyle, Locale aLocale )
Parameters
dateStyle
the given date formatting style.
timeStyle
the given time formatting style.
inLocale
the given locale.
Returns
a date/time formatter.
Description
Gets the date/time formatter with the given formatting styles for the given locale.


 DateFormat.getInstance

DateFormat.getInstance

Syntax
public static final DateFormat getInstance()
Description
Get a default date/time formatter that uses the SHORT style for both the date and the time.


 DateFormat.getNumberFormat

DateFormat.getNumberFormat

Syntax
public NumberFormat getNumberFormat()
Returns
the number formatter which this date/time formatter uses.
Description
Gets the number formatter which this date/time formatter uses to format and parse a time.


 DateFormat.getTimeInstance

DateFormat.getTimeInstance

Syntax 1
public static final DateFormat getTimeInstance()
Returns
a time formatter.
Description
Gets the time formatter with the default formatting style for the default locale.

Syntax 2
public static final DateFormat getTimeInstance( int style )
Parameters
style
the given formatting style. For example, SHORT for "h:mm a" in the US locale.
Returns
a time formatter.
Description
Gets the time formatter with the given formatting style for the default locale.

Syntax 3
public static final DateFormat getTimeInstance( int style, Locale aLocale )
Parameters
style
the given formatting style. For example, SHORT for "h:mm a" in the US locale.
inLocale
the given locale.
Returns
a time formatter.
Description
Gets the time formatter with the given formatting style for the given locale.


 DateFormat.getTimeZone

DateFormat.getTimeZone

Syntax
public TimeZone getTimeZone()
Returns
the time zone associated with the calendar of DateFormat.
Description
Gets the time zone.


 DateFormat.hashCode

DateFormat.hashCode

Syntax
public int hashCode()
Description
Overrides hashCode

Overrides
hashCode in class Object


 DateFormat.isLenient

DateFormat.isLenient

Syntax
public boolean isLenient()
Description
Tell whether date/time parsing is to be lenient.


 DateFormat.parse

DateFormat.parse

Syntax 1
public Date parse( String text ) throws ParseException
Description
Parse a date/time string.

Exceptions
ParseException If the given string cannot be parsed as a date.
See Also
parse

Syntax 2
public abstract Date parse( String text, ParsePosition pos )
Parameters
text
The date/time string to be parsed
pos
On input, the position at which to start parsing; on output, the position at which parsing terminated, or the start position if the parse failed.
Returns
A Date, or null if the input could not be parsed
Description
Parse a date/time string according to the given parse position. For example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date that is equivalent to Date(837039928046).

By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

See Also
setLenient


 DateFormat.parseObject

DateFormat.parseObject

Syntax
public Object parseObject( String source, ParsePosition pos )
Description
Parse a date/time string into an Object. This convenience method simply calls parse(String, ParsePosition).

Overrides
parseObject in class Format
See Also
parse


 DateFormat.setCalendar

DateFormat.setCalendar

Syntax
public void setCalendar( Calendar newCalendar )
Description
Set the calendar to be used by this date format. Initially, the default calendar for the specified or default locale is used.


 DateFormat.setLenient

DateFormat.setLenient

Syntax
public void setLenient( boolean lenient )
Description
Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

See Also
setLenient


 DateFormat.setNumberFormat

DateFormat.setNumberFormat

Syntax
public void setNumberFormat( NumberFormat newNumberFormat )
Parameters
newNumberFormat
the given new NumberFormat.
Description
Allows you to set the number formatter.


 DateFormat.setTimeZone

DateFormat.setTimeZone

Syntax
public void setTimeZone( TimeZone zone )
Parameters
zone
the given new time zone.
Description
Sets the time zone for the calendar of this DateFormat object.


 Class DateFormatSymbols

Class java.text.DateFormatSymbols

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.DateFormatSymbols

public class DateFormatSymbols
extends Object
implements Serializable, Cloneable

DateFormatSymbols is a public class for encapsulating localizable date-time formatting data, such as the names of the months, the names of the days of the week, and the time zone data. DateFormat and SimpleDateFormat both use DateFormatSymbols to encapsulate this information.

Typically you shouldn't use DateFormatSymbols directly. Rather, you are encouraged to create a date-time formatter with the DateFormat class's factory methods: getTimeInstance, getDateInstance, or getDateTimeInstance. These methods automatically create a DateFormatSymbols for the formatter so that you don't have to. After the formatter is created, you may modify its format pattern using the setPattern method. For more information about creating formatters using DateFormat's factory methods, see DateFormat.

If you decide to create a date-time formatter with a specific format pattern for a specific locale, you can do so with:

 new SimpleDateFormat(aPattern, new DateFormatSymbols(aLocale)).

DateFormatSymbols objects are clonable. When you obtain a DateFormatSymbols object, feel free to modify the date-time formatting data. For instance, you can replace the localized date-time format pattern characters with the ones that you feel easy to remember. Or you can change the representative cities to your favorite ones.

New DateFormatSymbols subclasses may be added to support SimpleDateFormat for date-time formatting for additional locales.

See Also:
DateFormat, SimpleDateFormat, SimpleTimeZone


 DateFormatSymbols Members

DateFormatSymbols Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DateFormatSymbols() | Construct a DateFormatSymbols object by loading format data from resources for the default locale.
DateFormatSymbols(Locale) | Construct a DateFormatSymbols object by loading format data from resources for the given locale.

Methods
Name | Description
clone() | Overrides Cloneable
equals(Object) | Override equals
getAmPmStrings() | Gets ampm strings.
getEras() | Gets era strings.
getLocalPatternChars() | Gets localized date-time pattern characters.
getMonths() | Gets month strings.
getShortMonths() | Gets short month strings.
getShortWeekdays() | Gets short weekday strings.
getWeekdays() | Gets weekday strings.
getZoneStrings() | Gets timezone strings.
hashCode() | Override hashCode.
setAmPmStrings(String[]) | Sets ampm strings.
setEras(String[]) | Sets era strings.
setLocalPatternChars(String) | Sets localized date-time pattern characters.
setMonths(String[]) | Sets month strings.
setShortMonths(String[]) | Sets short month strings.
setShortWeekdays(String[]) | Sets short weekday strings.
setWeekdays(String[]) | Sets weekday strings.
setZoneStrings(String[][]) | Sets timezone strings.


 DateFormatSymbols.DateFormatSymbols

DateFormatSymbols.DateFormatSymbols

Syntax 1
public DateFormatSymbols()
Description
Construct a DateFormatSymbols object by loading format data from resources for the default locale.

Exceptions
MissingResourceException if the resources for the default locale cannot be found or cannot be loaded.

Syntax 2
public DateFormatSymbols( Locale locale )
Description
Construct a DateFormatSymbols object by loading format data from resources for the given locale.

Exceptions
MissingResourceException if the resources for the specified locale cannot be found or cannot be loaded.


 DateFormatSymbols.clone

DateFormatSymbols.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Object


 DateFormatSymbols.equals

DateFormatSymbols.equals

Syntax
public boolean equals( Object obj )
Description
Override equals

Overrides
equals in class Object


 DateFormatSymbols.getAmPmStrings

DateFormatSymbols.getAmPmStrings

Syntax
public String[] getAmPmStrings()
Returns
the weekday strings.
Description
Gets ampm strings. For example: "AM" and "PM".


 DateFormatSymbols.getEras

DateFormatSymbols.getEras

Syntax
public String[] getEras()
Returns
the era strings.
Description
Gets era strings. For example: "AD" and "BC".


 DateFormatSymbols.getLocalPatternChars

DateFormatSymbols.getLocalPatternChars

Syntax
public String getLocalPatternChars()
Returns
the localized date-time pattern characters.
Description
Gets localized date-time pattern characters. For example: 'u', 't', etc.


 DateFormatSymbols.getMonths

DateFormatSymbols.getMonths

Syntax
public String[] getMonths()
Returns
the month strings.
Description
Gets month strings. For example: "January", "February", etc.


 DateFormatSymbols.getShortMonths

DateFormatSymbols.getShortMonths

Syntax
public String[] getShortMonths()
Returns
the short month strings.
Description
Gets short month strings. For example: "Jan", "Feb", etc.


 DateFormatSymbols.getShortWeekdays

DateFormatSymbols.getShortWeekdays

Syntax
public String[] getShortWeekdays()
Returns
the short weekday strings.
Description
Gets short weekday strings. For example: "Sun", "Mon", etc.


 DateFormatSymbols.getWeekdays

DateFormatSymbols.getWeekdays

Syntax
public String[] getWeekdays()
Returns
the weekday strings.
Description
Gets weekday strings. For example: "Sunday", "Monday", etc.


 DateFormatSymbols.getZoneStrings

DateFormatSymbols.getZoneStrings

Syntax
public String[][] getZoneStrings()
Returns
the timezone strings.
Description
Gets timezone strings.


 DateFormatSymbols.hashCode

DateFormatSymbols.hashCode

Syntax
public int hashCode()
Description
Override hashCode. Generates a hash code for the DateFormatSymbols object.

Overrides
hashCode in class Object


 DateFormatSymbols.setAmPmStrings

DateFormatSymbols.setAmPmStrings

Syntax
public void setAmPmStrings( String newAmpms[] )
Parameters
newAmpms
the new ampm strings.
Description
Sets ampm strings. For example: "AM" and "PM".


 DateFormatSymbols.setEras

DateFormatSymbols.setEras

Syntax
public void setEras( String newEras[] )
Parameters
newEras
the new era strings.
Description
Sets era strings. For example: "AD" and "BC".


 DateFormatSymbols.setLocalPatternChars

DateFormatSymbols.setLocalPatternChars

Syntax
public void setLocalPatternChars( String newLocalPatternChars )
Parameters
newLocalPatternChars
the new localized date-time pattern characters.
Description
Sets localized date-time pattern characters. For example: 'u', 't', etc.


 DateFormatSymbols.setMonths

DateFormatSymbols.setMonths

Syntax
public void setMonths( String newMonths[] )
Parameters
newMonths
the new month strings.
Description
Sets month strings. For example: "January", "February", etc.


 DateFormatSymbols.setShortMonths

DateFormatSymbols.setShortMonths

Syntax
public void setShortMonths( String newShortMonths[] )
Parameters
newShortMonths
the new short month strings.
Description
Sets short month strings. For example: "Jan", "Feb", etc.


 DateFormatSymbols.setShortWeekdays

DateFormatSymbols.setShortWeekdays

Syntax
public void setShortWeekdays( String newShortWeekdays[] )
Parameters
newShortWeekdays
the new short weekday strings.
Description
Sets short weekday strings. For example: "Sun", "Mon", etc.


 DateFormatSymbols.setWeekdays

DateFormatSymbols.setWeekdays

Syntax
public void setWeekdays( String newWeekdays[] )
Parameters
newWeekdays
the new weekday strings.
Description
Sets weekday strings. For example: "Sunday", "Monday", etc.


 DateFormatSymbols.setZoneStrings

DateFormatSymbols.setZoneStrings

Syntax
public void setZoneStrings( String newZoneStrings[][] )
Parameters
newZoneStrings
the new timezone strings.
Description
Sets timezone strings.


 Class DecimalFormat

Class java.text.DecimalFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.NumberFormat
                   |
                   +----java.text.DecimalFormat

public class DecimalFormat
extends NumberFormat

DecimalFormat is a concrete subclass of NumberFormat for formatting decimal numbers. This class allows for a variety of parameters, and localization to Western, Arabic, or Indic numbers.

Normally, you get the proper NumberFormat for a specific locale (including the default locale) using one of NumberFormat's factory methods such as getInstance. You may then modify it from there (after testing to make sure it is a DecimalFormat, of course!)

Either the prefixes or the suffixes must be different for the parse to distinguish positive from negative. Parsing will be unreliable if the digits, thousands or decimal separators are the same, or if any of them occur in the prefixes or suffixes.

Special cases:

NaN is formatted as a single character, typically \\uFFFD.

+/-Infinity is formatted as a single character, typically \\u221E, plus the positive and negative pre/suffixes.

Note: this class is designed for common users; for very large or small numbers, use a format that can express exponential values.

Example:

 // normally we would have a GUI with a menu for this
 Locale[] locales = NumberFormat.getAvailableLocales();
 double myNumber = -1234.56;
 NumberFormat form;
 // just for fun, we print out a number with the locale number, currency
 // and percent format for each locale we can.
 for (int j = 0; j < 3; ++j) {
     System.out.println("FORMAT");
     for (int i = 0; i < locales.length; ++i) {
         if (locales[i].getCountry().length() == 0) {
            // skip language-only
            continue;
         }
         System.out.print(locales[i].getDisplayName());
         switch (j) {
         default:
             form = NumberFormat.getInstance(locales[i]); break;
         case 1:
             form = NumberFormat.getCurrencyInstance(locales[i]); break;
         case 0:
             form = NumberFormat.getPercentInstance(locales[i]); break;
         }
         try {
             System.out.print(": " + ((DecimalFormat)form).toPattern()
                          + " -> " + form.format(myNumber));
         } catch (IllegalArgumentException iae) { }
         try {
             System.out.println(" -> " + form.parse(form.format(myNumber)));
         } catch (ParseException pe) { }
     }
 }
The following shows the structure of the pattern.
 pattern    := subpattern{;subpattern}
 subpattern := {prefix}integer{.fraction}{suffix}
 prefix     := '\\u0000'..'\\uFFFD' - specialCharacters
 suffix     := '\\u0000'..'\\uFFFD' - specialCharacters
 integer    := '#'* '0'* '0'
 fraction   := '0'* '#'*
 Notation:
  X*       0 or more instances of X
  (X | Y)  either X or Y.
  X..Y     any character from X up to Y, inclusive.
  S - T    characters in S, except those in T
The first subpattern is for positive numbers. The second (optional) subpattern is for negative numbers. (In both cases, ',' can occur inside the integer portion--it is just too messy to indicate in BNF.)

Here are the special characters used in the parts of the subpattern, with notes on their usage.

 Symbol Meaning
 0      a digit
 #      a digit, zero shows as absent
 .      placeholder for decimal separator
 ,      placeholder for grouping separator.
 ;      separates formats.
 -      default negative prefix.
 %      divide by 100 and show as percentage
 X      any other characters can be used in the prefix or suffix
 '      used to quote special characters in a prefix or suffix.

Notes

If there is no explicit negative subpattern, - is prefixed to the positive form. That is, "0.00" alone is equivalent to "0.00;-0.00".

Illegal formats, such as "#.#.#" or mixing '_' and '*' in the same format, will cause an ParseException to be thrown. From that ParseException, you can find the place in the string where the error occurred.

The grouping separator is commonly used for thousands, but in some countries for ten-thousands. The interval is a constant number of digits between the grouping characters, such as 100,000,000 or 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".

This class only handles localized digits where the 10 digits are contiguous in Unicode, from 0 to 9. Other digits sets (such as superscripts) would need a different subclass.

See Also:
Format, NumberFormat, ChoiceFormat


 DecimalFormat Members

DecimalFormat Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DecimalFormat() | Create a DecimalFormat using the default pattern and symbols for the default locale.
DecimalFormat(String) | Create a DecimalFormat from the given pattern and the symbols for the default locale.
DecimalFormat(String, DecimalFormatSymbols) | Create a DecimalFormat from the given pattern and symbols.

Methods
Name | Description
applyLocalizedPattern(String) | Apply the given pattern to this Format object.
applyPattern(String) | Apply the given pattern to this Format object.
clone() | Standard override; no change in semantics.
equals(Object) | Overrides equals
format(double, StringBuffer, FieldPosition) | Specialization of format.
format(long, StringBuffer, FieldPosition) | Specialization of format.
getDecimalFormatSymbols() | Returns the decimal format symbols, which is generally not changed by the programmer or user.
getGroupingSize() | Return the grouping size.
getMultiplier() | Get the multiplier for use in percent, permill, etc.
getNegativePrefix() | Get the negative prefix.
getNegativeSuffix() | Get the negative suffix.
getPositivePrefix() | Get the positive prefix.
getPositiveSuffix() | Get the positive suffix.
hashCode() | Overrides hashCode
isDecimalSeparatorAlwaysShown() | Allows you to get the behavior of the decimal separator with integers.
parse(String, ParsePosition) | Returns a Long if possible (e.g.
setDecimalFormatSymbols(DecimalFormatSymbols) | Sets the decimal format symbols, which is generally not changed by the programmer or user.
setDecimalSeparatorAlwaysShown(boolean) | Allows you to set the behavior of the decimal separator with integers.
setGroupingSize(int) | Set the grouping size.
setMultiplier(int) | Set the multiplier for use in percent, permill, etc.
setNegativePrefix(String) | Set the negative prefix.
setNegativeSuffix(String) | Set the positive suffix.
setPositivePrefix(String) | Set the positive prefix.
setPositiveSuffix(String) | Set the positive suffix.
toLocalizedPattern() | Synthesizes a localized pattern string that represents the current state of this Format object.
toPattern() | Synthesizes a pattern string that represents the current state of this Format object.


 DecimalFormat.DecimalFormat

DecimalFormat.DecimalFormat

Syntax 1
public DecimalFormat()
Description
Create a DecimalFormat using the default pattern and symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale.

See Also
getInstance, getNumberInstance, getCurrencyInstance, getPercentInstance

Syntax 2
public DecimalFormat( String pattern )
Parameters
pattern
A non-localized pattern string.
Description
Create a DecimalFormat from the given pattern and the symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale.

Exceptions
IllegalArgumentException if the given pattern is invalid.
See Also
getInstance, getNumberInstance, getCurrencyInstance, getPercentInstance

Syntax 3
public DecimalFormat( String pattern, DecimalFormatSymbols symbols )
Parameters
pattern
a non-localized pattern string
symbols
the set of symbols to be used
Description
Create a DecimalFormat from the given pattern and symbols. Use this constructor when you need to completely customize the behavior of the format.

To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getInstance or getCurrencyInstance. If you need only minor adjustments to a standard format, you can modify the format returned by a NumberFormat factory method.

Exceptions
IllegalArgumentException if the given pattern is invalid
See Also
getInstance, getNumberInstance, getCurrencyInstance, getPercentInstance, DecimalFormatSymbols


 DecimalFormat.applyLocalizedPattern

DecimalFormat.applyLocalizedPattern

Syntax
public void applyLocalizedPattern( String pattern )
Description
Apply the given pattern to this Format object. The pattern is assumed to be in a localized notation. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine, since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers, use a second pattern, separated by a semicolon

Example "#,#00.0#" -> 1,234.56

This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 fraction digits.

Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses.

In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern.


 DecimalFormat.applyPattern

DecimalFormat.applyPattern

Syntax
public void applyPattern( String pattern )
Description
Apply the given pattern to this Format object. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine, since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers, use a second pattern, separated by a semicolon

Example "#,#00.0#" -> 1,234.56

This means a minimum of 2 integer digits, 1 fraction digit, and a maximum of 2 fraction digits.

Example: "#,#00.0#;(#,#00.0#)" for negatives in parantheses.

In negative patterns, the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern.


 DecimalFormat.clone

DecimalFormat.clone

Syntax
public Object clone()
Description
Standard override; no change in semantics.

Overrides
clone in class NumberFormat


 DecimalFormat.equals

DecimalFormat.equals

Syntax
public boolean equals( Object obj )
Description
Overrides equals

Overrides
equals in class NumberFormat


 DecimalFormat.format

DecimalFormat.format

Syntax 1
public StringBuffer format( double number, StringBuffer result, FieldPosition fieldPosition )
Description
Specialization of format.

Overrides
format in class NumberFormat

Syntax 2
public StringBuffer format( long number, StringBuffer result, FieldPosition fieldPosition )
Description
Specialization of format.

Overrides
format in class NumberFormat


 DecimalFormat.getDecimalFormatSymbols

DecimalFormat.getDecimalFormatSymbols

Syntax
public DecimalFormatSymbols getDecimalFormatSymbols()
Returns
desired DecimalFormatSymbols
Description
Returns the decimal format symbols, which is generally not changed by the programmer or user.

See Also
DecimalFormatSymbols


 DecimalFormat.getGroupingSize

DecimalFormat.getGroupingSize

Syntax
public int getGroupingSize()
Description
Return the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3.

See Also
setGroupingSize, isGroupingUsed, getGroupingSeparator


 DecimalFormat.getMultiplier

DecimalFormat.getMultiplier

Syntax
public int getMultiplier()
Description
Get the multiplier for use in percent, permill, etc. For a percentage, set the suffixes to have "%" and the multiplier to be 100. (For Arabic, use arabic percent symbol). For a permill, set the suffixes to have "?" and the multiplier to be 1000.

Examples: with 100, 1.23 -> "123", and "123" -> 1.23


 DecimalFormat.getNegativePrefix

DecimalFormat.getNegativePrefix

Syntax
public String getNegativePrefix()
Description
Get the negative prefix.

Examples: -123, ($123) (with negative suffix), sFr-123


 DecimalFormat.getNegativeSuffix

DecimalFormat.getNegativeSuffix

Syntax
public String getNegativeSuffix()
Description
Get the negative suffix.

Examples: -123%, ($123) (with positive suffixes)


 DecimalFormat.getPositivePrefix

DecimalFormat.getPositivePrefix

Syntax
public String getPositivePrefix()
Description
Get the positive prefix.

Examples: +123, $123, sFr123


 DecimalFormat.getPositiveSuffix

DecimalFormat.getPositiveSuffix

Syntax
public String getPositiveSuffix()
Description
Get the positive suffix.

Example: 123%


 DecimalFormat.hashCode

DecimalFormat.hashCode

Syntax
public int hashCode()
Description
Overrides hashCode

Overrides
hashCode in class NumberFormat


 DecimalFormat.isDecimalSeparatorAlwaysShown

DecimalFormat.isDecimalSeparatorAlwaysShown

Syntax
public boolean isDecimalSeparatorAlwaysShown()
Description
Allows you to get the behavior of the decimal separator with integers. (The decimal separator will always appear with decimals.)

Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345


 DecimalFormat.parse

DecimalFormat.parse

Syntax
public Number parse( String text, ParsePosition status )
Description
Returns a Long if possible (e.g.

Overrides
parse in class NumberFormat


 DecimalFormat.setDecimalFormatSymbols

DecimalFormat.setDecimalFormatSymbols

Syntax
public void setDecimalFormatSymbols( DecimalFormatSymbols newSymbols )
Parameters
newSymbols
desired DecimalFormatSymbols
Description
Sets the decimal format symbols, which is generally not changed by the programmer or user.

See Also
DecimalFormatSymbols


 DecimalFormat.setDecimalSeparatorAlwaysShown

DecimalFormat.setDecimalSeparatorAlwaysShown

Syntax
public void setDecimalSeparatorAlwaysShown( boolean newValue )
Description
Allows you to set the behavior of the decimal separator with integers. (The decimal separator will always appear with decimals.)

Example: Decimal ON: 12345 -> 12345.; OFF: 12345 -> 12345


 DecimalFormat.setGroupingSize

DecimalFormat.setGroupingSize

Syntax
public void setGroupingSize( int newValue )
Description
Set the grouping size. Grouping size is the number of digits between grouping separators in the integer portion of a number. For example, in the number "123,456.78", the grouping size is 3.

See Also
getGroupingSize, setGroupingUsed, setGroupingSeparator


 DecimalFormat.setMultiplier

DecimalFormat.setMultiplier

Syntax
public void setMultiplier( int newValue )
Description
Set the multiplier for use in percent, permill, etc. For a percentage, set the suffixes to have "%" and the multiplier to be 100. (For Arabic, use arabic percent symbol). For a permill, set the suffixes to have "?" and the multiplier to be 1000.

Examples: with 100, 1.23 -> "123", and "123" -> 1.23


 DecimalFormat.setNegativePrefix

DecimalFormat.setNegativePrefix

Syntax
public void setNegativePrefix( String newValue )
Description
Set the negative prefix.

Examples: -123, ($123) (with negative suffix), sFr-123


 DecimalFormat.setNegativeSuffix

DecimalFormat.setNegativeSuffix

Syntax
public void setNegativeSuffix( String newValue )
Description
Set the positive suffix.

Examples: 123%


 DecimalFormat.setPositivePrefix

DecimalFormat.setPositivePrefix

Syntax
public void setPositivePrefix( String newValue )
Description
Set the positive prefix.

Examples: +123, $123, sFr123


 DecimalFormat.setPositiveSuffix

DecimalFormat.setPositiveSuffix

Syntax
public void setPositiveSuffix( String newValue )
Description
Set the positive suffix.

Example: 123%


 DecimalFormat.toLocalizedPattern

DecimalFormat.toLocalizedPattern

Syntax
public String toLocalizedPattern()
Description
Synthesizes a localized pattern string that represents the current state of this Format object.

See Also
applyPattern


 DecimalFormat.toPattern

DecimalFormat.toPattern

Syntax
public String toPattern()
Description
Synthesizes a pattern string that represents the current state of this Format object.

See Also
applyPattern


 Class DecimalFormatSymbols

Class java.text.DecimalFormatSymbols

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.DecimalFormatSymbols

public final class DecimalFormatSymbols
extends Object
implements Cloneable, Serializable

This class represents the set of symbols (such as the decimal separator, the grouping separator, and so on) needed by DecimalFormat to format numbers. DecimalFormat creates for itself an instance of DecimalFormatSymbols from its locale data. If you need to change any of these symbols, you can get the DecimalFormatSymbols object from your DecimalFormat and modify it.

See Also:
Locale, DecimalFormat


 DecimalFormatSymbols Members

DecimalFormatSymbols Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DecimalFormatSymbols() | Create a DecimalFormatSymbols object for the default locale.
DecimalFormatSymbols(Locale) | Create a DecimalFormatSymbols object for the given locale.

Methods
Name | Description
clone() | Standard override.
equals(Object) | Override equals
getDecimalSeparator() | character used for decimal sign.
getDigit() | character used for a digit in a pattern.
getGroupingSeparator() | character used for thousands separator.
getInfinity() | character used to represent infinity.
getMinusSign() | character used to represent minus sign.
getNaN() | character used to represent NaN.
getPatternSeparator() | character used to separate positive and negative subpatterns in a pattern.
getPercent() | character used for percent sign.
getPerMill() | character used for mille percent sign.
getZeroDigit() | character used for zero.
hashCode() | Override hashCode
setDecimalSeparator(char) |
setDigit(char) |
setGroupingSeparator(char) |
setInfinity(String) |
setMinusSign(char) |
setNaN(String) |
setPatternSeparator(char) |
setPercent(char) |
setPerMill(char) |
setZeroDigit(char) |


 DecimalFormatSymbols.DecimalFormatSymbols

DecimalFormatSymbols.DecimalFormatSymbols

Syntax 1
public DecimalFormatSymbols()
Description
Create a DecimalFormatSymbols object for the default locale.

Syntax 2
public DecimalFormatSymbols( Locale locale )
Description
Create a DecimalFormatSymbols object for the given locale.


 DecimalFormatSymbols.clone

DecimalFormatSymbols.clone

Syntax
public Object clone()
Description
Standard override.

Overrides
clone in class Object


 DecimalFormatSymbols.equals

DecimalFormatSymbols.equals

Syntax
public boolean equals( Object obj )
Description
Override equals

Overrides
equals in class Object


 DecimalFormatSymbols.getDecimalSeparator

DecimalFormatSymbols.getDecimalSeparator

Syntax
public char getDecimalSeparator()
Description
character used for decimal sign. Different for French, etc.


 DecimalFormatSymbols.getDigit

DecimalFormatSymbols.getDigit

Syntax
public char getDigit()
Description
character used for a digit in a pattern.


 DecimalFormatSymbols.getGroupingSeparator

DecimalFormatSymbols.getGroupingSeparator

Syntax
public char getGroupingSeparator()
Description
character used for thousands separator. Different for French, etc.


 DecimalFormatSymbols.getInfinity

DecimalFormatSymbols.getInfinity

Syntax
public String getInfinity()
Description
character used to represent infinity. Almost always left unchanged.


 DecimalFormatSymbols.getMinusSign

DecimalFormatSymbols.getMinusSign

Syntax
public char getMinusSign()
Description
character used to represent minus sign. If no explicit negative format is specified, one is formed by prefixing minusSign to the positive format.


 DecimalFormatSymbols.getNaN

DecimalFormatSymbols.getNaN

Syntax
public String getNaN()
Description
character used to represent NaN. Almost always left unchanged.


 DecimalFormatSymbols.getPatternSeparator

DecimalFormatSymbols.getPatternSeparator

Syntax
public char getPatternSeparator()
Description
character used to separate positive and negative subpatterns in a pattern.


 DecimalFormatSymbols.getPercent

DecimalFormatSymbols.getPercent

Syntax
public char getPercent()
Description
character used for percent sign. Different for Arabic, etc.


 DecimalFormatSymbols.getPerMill

DecimalFormatSymbols.getPerMill

Syntax
public char getPerMill()
Description
character used for mille percent sign. Different for Arabic, etc.


 DecimalFormatSymbols.getZeroDigit

DecimalFormatSymbols.getZeroDigit

Syntax
public char getZeroDigit()
Description
character used for zero. Different for Arabic, etc.


 DecimalFormatSymbols.hashCode

DecimalFormatSymbols.hashCode

Syntax
public int hashCode()
Description
Override hashCode

Overrides
hashCode in class Object


 DecimalFormatSymbols.setDecimalSeparator

DecimalFormatSymbols.setDecimalSeparator

Syntax
public void setDecimalSeparator( char decimalSeparator )


 DecimalFormatSymbols.setDigit

DecimalFormatSymbols.setDigit

Syntax
public void setDigit( char digit )


 DecimalFormatSymbols.setGroupingSeparator

DecimalFormatSymbols.setGroupingSeparator

Syntax
public void setGroupingSeparator( char groupingSeparator )


 DecimalFormatSymbols.setInfinity

DecimalFormatSymbols.setInfinity

Syntax
public void setInfinity( String infinity )


 DecimalFormatSymbols.setMinusSign

DecimalFormatSymbols.setMinusSign

Syntax
public void setMinusSign( char minusSign )


 DecimalFormatSymbols.setNaN

DecimalFormatSymbols.setNaN

Syntax
public void setNaN( String NaN )


 DecimalFormatSymbols.setPatternSeparator

DecimalFormatSymbols.setPatternSeparator

Syntax
public void setPatternSeparator( char patternSeparator )


 DecimalFormatSymbols.setPercent

DecimalFormatSymbols.setPercent

Syntax
public void setPercent( char percent )


 DecimalFormatSymbols.setPerMill

DecimalFormatSymbols.setPerMill

Syntax
public void setPerMill( char perMill )


 DecimalFormatSymbols.setZeroDigit

DecimalFormatSymbols.setZeroDigit

Syntax
public void setZeroDigit( char zeroDigit )


 Class FieldPosition

Class java.text.FieldPosition

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.FieldPosition

public class FieldPosition
extends Object

FieldPosition is a simple class used by Format and its subclasses to identify fields in formatted output. Fields are identified by constants, whose names typically end with _FIELD, defined in the various subclasses of Format. See ERA_FIELD and its friends in DateFormat for an example.

FieldPosition keeps track of the position of the field within the formatted output with two indices: the index of the first character of the field and the index of the last character of the field.

One version of the format method in the various Format classes requires a FieldPosition object as an argument. You use this format method to perform partial formatting or to get information about the formatted output (such as the position of a field).

See Also:
Format


 FieldPosition Members

FieldPosition Members

Class Overview | This Package | All Packages

Constructors
Name | Description
FieldPosition(int) | Creates a FieldPosition object for the given field.

Methods
Name | Description
getBeginIndex() | Retrieve the index of the first character in the requested field.
getEndIndex() | Retrieve the index of the character following the last character in the requested field.
getField() | Retrieve the field identifier.


 FieldPosition.FieldPosition

FieldPosition.FieldPosition

Syntax
public FieldPosition( int field )
Description
Creates a FieldPosition object for the given field. Fields are identified by constants, whose names typically end with _FIELD, in the various subclasses of Format.

See Also
INTEGER_FIELD, FRACTION_FIELD, YEAR_FIELD, MONTH_FIELD


 FieldPosition.getBeginIndex

FieldPosition.getBeginIndex

Syntax
public int getBeginIndex()
Description
Retrieve the index of the first character in the requested field.


 FieldPosition.getEndIndex

FieldPosition.getEndIndex

Syntax
public int getEndIndex()
Description
Retrieve the index of the character following the last character in the requested field.


 FieldPosition.getField

FieldPosition.getField

Syntax
public int getField()
Description
Retrieve the field identifier.


 Class Format

Class java.text.Format

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format

public abstract class Format
extends Object
implements Serializable, Cloneable

Format is an abstract base class for formatting locale-sensitive information such as dates, messages, and numbers.

Format defines the programming interface for formatting locale-sensitive objects into Strings (the format method) and for parsing Strings back into objects (the parseObject method). Any String formatted by format is guaranteed to be parseable by parseObject.

If formatting is unsuccessful because the Format object cannot format the type of object specified, format throws an IllegalArgumentException. Otherwise, if there is something illformed about the object, format returns the Unicode replacement character \\uFFFD.

If there is no match when parsing, parseObject(String) throws a ParseException, and parseObject(String, ParsePosition) leaves the ParsePosition index member unchanged and returns null.

Subclassing: The JDK provides three concrete subclasses of Format-- DateFormat, MessageFormat, and NumberFormat--for formatting dates, messages, and numbers, respectively.

Concrete subclasses must implement these two methods:

  1. format(Object obj, StringBuffer toAppendTo, FieldPosition pos)
  2. parseObject (String source, ParsePosition pos)

Most subclasses will also implement the following two methods:

  1. getInstance for getting a useful format object appropriate for the current locale
  2. getInstance(Locale) for getting a useful format object appropriate for the specified locale
In addition, some subclasses may also choose to implement other getXxxxInstance methods for more specialized control. For example, the NumberFormat class provides getPercentInstance and getCurrencyInstance methods for getting specialized number formatters.

Subclasses of Format that allow programmers to create objects for locales (with getInstance(Locale) for example) must also implement the following class method:

 public static Locale[] getAvailableLocales()

And finally subclasses may define a set of constants to identify the various fields in the formatted output. These constants are used to create a FieldPosition object which identifies what information is contained in the field and its position in the formatted result. These constants should be named item_FIELD where item identifies the field. For examples of these constants, see ERA_FIELD and its friends in DateFormat.

See Also:
ParsePosition, FieldPosition, NumberFormat, DateFormat, MessageFormat


 Format Members

Format Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Format() |

Methods
Name | Description
clone() | Creates a new object of the same class as this object.
format(Object) | Formats an object to produce a string.
format(Object, StringBuffer, FieldPosition) | Formats an object to produce a string.
parseObject(String) | Parses a string to produce an object.
parseObject(String, ParsePosition) | Parses a string to produce an object.


 Format.Format

Format.Format

Syntax
public Format()


 Format.clone

Format.clone

Syntax
public Object clone()
Description
Creates a new object of the same class as this object.

Overrides
clone in class Object


 Format.format

Format.format

Syntax 1
public final String format( Object obj )
Parameters
obj
The object to format
Returns
Formatted string.
Description
Formats an object to produce a string.

Subclasses will override the StringBuffer version of format.

Exceptions
IllegalArgumentException when the Format cannot format the type of object.
See Also
MessageFormat, format

Syntax 2
public abstract StringBuffer format( Object obj, StringBuffer toAppendTo, FieldPosition pos )
Parameters
obj
The object to format
toAppendTo
where the text is to be appended
status
On input: an alignment field, if desired. On output: the offsets of the alignment field.
Returns
the value passed in as toAppendTo (this allows chaining, as with StringBuffer.append())
Description
Formats an object to produce a string. Subclasses will implement for particular object, such as:
 StringBuffer format (Number obj, StringBuffer toAppendTo)
 Number parse (String str)
These general routines allow polymorphic parsing and formatting for objects such as the MessageFormat.

Exceptions
IllegalArgumentException when the Format cannot format the given object.
See Also
MessageFormat, FieldPosition


 Format.parseObject

Format.parseObject

Syntax 1
public abstract Object parseObject( String source, ParsePosition status )
Parameters
ParsePosition
Input-Output parameter.

Before calling, set status.index to the offset you want to start parsing at in the source. After calling, status.index is the end of the text you parsed. If error occurs, index is unchanged.

When parsing, leading whitespace is discarded (with successful parse), while trailing whitespace is left as is.

Example: Parsing "_12_xy" (where _ represents a space) for a number, with index == 0 will result in the number 12, with status.index updated to 3 (just before the second space). Parsing a second time will result in a ParseException since "xy" is not a number, and leave index at 3.

Subclasses will typically supply specific parse methods that return different types of values. Since methods can't overload on return types, these will typically be named "parse", while this polymorphic method will always be called parseObject. Any parse method that does not take a status should throw ParseException when no text in the required format is at the start position.

Returns
Object parsed from string. In case of error, returns null.
Description
Parses a string to produce an object. Subclasses will typically implement for particular object, such as:
       String format (Number obj);
       String format (long obj);
       String format (double obj);
       Number parse (String str);

See Also
ParsePosition

Syntax 2
public Object parseObject( String source ) throws ParseException
Description
Parses a string to produce an object.

Exceptions
ParseException if the specified string is invalid.


 Class MessageFormat

Class java.text.MessageFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.MessageFormat

public class MessageFormat
extends Format

MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

Note: MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). The factory methods aren't necessary because MessageFormat doesn't require any complex setup for a given locale. In fact, MessageFormat doesn't implement any locale specific behavior at all. It just needs to be set up on a sentence by sentence basis.

Here are some examples of usage:

 Object[] arguments = {
     new Integer(7),
     new Date(System.currentTimeMillis()),
     "a disturbance in the Force"
 };
 String result = MessageFormat.format(
     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
     arguments);
 : At 12:30 PM on Jul 3, 2053, there was a disturbance
           in the Force on planet 7.
Typically, the message format will come from resources, and the arguments will be dynamically set at runtime.

Example 2:

 Object[] testArgs = {new Long(3), "MyDisk"};
 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");
 System.out.println(form.format(testArgs));
 // output, with different testArgs
 : The disk "MyDisk" contains 0 file(s).
 : The disk "MyDisk" contains 1 file(s).
 : The disk "MyDisk" contains 1,273 file(s).

The pattern is of the form:

 messageFormatPattern := string ( "{" messageFormatElement "}" string )*
 messageFormatElement := argument { "," elementFormat }
 elementFormat := "time" { "," datetimeStyle }
                | "date" { "," datetimeStyle }
                | "number" { "," numberStyle }
                | "choice" { "," choiceStyle }
 datetimeStyle := "short"
                  | "medium"
                  | "long"
                  | "full"
                  | dateFormatPattern
 numberStyle := "currency"
               | "percent"
               | "integer"
               | numberFormatPattern
 choiceStyle := choiceFormatPattern
If there is no elementFormat, then the argument must be a string, which is substituted. If there is no dateTimeStyle or numberStyle, then the default format is used (for example, NumberFormat.getInstance, DateFormat.getTimeInstance, or DateFormat.getInstance).

In strings, single quotes can be used to quote the "{" (curly brace) if necessary. A real single quote is represented by ''. Inside a messageFormatElement, quotes are not removed. For example, {1,number,$'#',##} will produce a number format with the pound-sign quoted, with a result such as: "$#31,45".

If a pattern is used, then unquoted braces in the pattern, if any, must match: that is, "ab {0} de" and "ab '}' de" are ok, but "ab {0'}' de" and "ab } de" are not.

The argument is a number from 0 to 9, which corresponds to the arguments presented in an array to be formatted.

It is ok to have unused arguments in the array. With missing arguments or arguments that are not of the right class for the specified format, a ParseException is thrown. First, format checks to see if a Format object has been specified for the argument with the setFormats method. If so, then format uses that Format object to format the argument. Otherwise, the argument is formatted based on the object's type. If the argument is a Number, then format uses NumberFormat.getInstance to format the argument; if the argument is a Date, then format uses DateFormat.getDateTimeInstance to format the argument. Otherwise, it uses the toString method.

For more sophisticated patterns, you can use a ChoiceFormat to get output such as:

 MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
 double[] filelimits = {0,1,2};
 String[] filepart = {"no files","one file","{0,number} files"};
 ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
 form.setFormat(1,fileform); // NOT zero, see below
 Object[] testArgs = {new Long(12373), "MyDisk"};
 System.out.println(form.format(testArgs));
 // output, with different testArgs
 output: The disk "MyDisk" contains no files.
 output: The disk "MyDisk" contains one file.
 output: The disk "MyDisk" contains 1,273 files.
You can either do this programmatically, as in the above example, or by using a pattern (see ChoiceFormat for more information) as in:
 form.applyPattern(
    "There {0,choice,0#are no files|1#is one file|1#are {0,number,integer} files}.");

Note: As we see above, the string produced by a ChoiceFormat in MessageFormat is treated specially; occurances of '{' are used to indicated subformats, and cause recursion. If you create both a MessageFormat and ChoiceFormat programmatically (instead of using the string patterns), then be careful not to produce a format that recurses on itself, which will cause an infinite loop.

Note: formats are numbered by order of variable in the string. This is not the same as the argument numbering! For example: with "abc{2}def{3}ghi{0}...",

  • format0 affects the first variable {2}
  • format1 affects the second variable {3}
  • format2 affects the second variable {0}
  • and so on.

See Also:
Locale, Format, NumberFormat, DecimalFormat, ChoiceFormat


 MessageFormat Members

MessageFormat Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MessageFormat(String) | Constructs with the specified pattern.

Methods
Name | Description
applyPattern(String) | Sets the pattern.
clone() | Overrides Cloneable
equals(Object) | Equality comparision between two message format objects
format(Object, StringBuffer, FieldPosition) | Formats an object to produce a string.
format(Object[], StringBuffer, FieldPosition) | Returns pattern with formatted objects.
format(String, Object[]) | Convenience routine.
getFormats() | Gets formats that were set with setFormats.
getLocale() | Gets the locale.
hashCode() | Generates a hash code for the message format object.
parse(String) | Parses the string.
parse(String, ParsePosition) | Parses the string.
parseObject(String, ParsePosition) | Parses the string.
setFormat(int, Format) | Sets formats individually to use on parameters.
setFormats(Format[]) | Sets formats to use on parameters.
setLocale(Locale) | Constructs with the specified pattern and formats for the arguments in that pattern.
toPattern() | Gets the pattern.


 MessageFormat.MessageFormat

MessageFormat.MessageFormat

Syntax
public MessageFormat( String pattern )
Description
Constructs with the specified pattern.

See Also
applyPattern


 MessageFormat.applyPattern

MessageFormat.applyPattern

Syntax
public void applyPattern( String newPattern )
Description
Sets the pattern. See the class description.


 MessageFormat.clone

MessageFormat.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Format


 MessageFormat.equals

MessageFormat.equals

Syntax
public boolean equals( Object obj )
Description
Equality comparision between two message format objects

Overrides
equals in class Object


 MessageFormat.format

MessageFormat.format

Syntax 1
public final StringBuffer format( Object source[], StringBuffer result, FieldPosition ignore )
Parameters
source
an array of objects to be formatted & substituted.
result
where text is appended.
ignore
no useful status is returned.
Description
Returns pattern with formatted objects.

Syntax 2
public static String format( String pattern, Object arguments[] )
Description
Convenience routine. Avoids explicit creation of MessageFormat, but doesn't allow future optimizations.

Syntax 3
public final StringBuffer format( Object source, StringBuffer result, FieldPosition ignore )
Description
Formats an object to produce a string.

Overrides
format in class Format


 MessageFormat.getFormats

MessageFormat.getFormats

Syntax
public Format[] getFormats()
Description
Gets formats that were set with setFormats. See the class description about format numbering.


 MessageFormat.getLocale

MessageFormat.getLocale

Syntax
public Locale getLocale()
Description
Gets the locale. This locale is used for fetching default number or date format information.


 MessageFormat.hashCode

MessageFormat.hashCode

Syntax
public int hashCode()
Description
Generates a hash code for the message format object.

Overrides
hashCode in class Object


 MessageFormat.parse

MessageFormat.parse

Syntax 1
public Object[] parse( String source, ParsePosition status )
Description
Parses the string.

Caveats: The parse may fail in a number of circumstances. For example:

  • If one of the arguments does not occur in the pattern.
  • If the format of an argument is loses information, such as with a choice format where a large number formats to "many".
  • Does not yet handle recursion (where the substituted strings contain {n} references.)
  • Will not always find a match (or the correct match) if some part of the parse is ambiguous. For example, if the pattern "{1},{2}" is used with the string arguments {"a,b", "c"}, it will format as "a,b,c". When the result is parsed, it will return {"a", "b,c"}.
  • If a single argument is formatted twice in the string, then the later parse wins.

Syntax 2
public Object[] parse( String source ) throws ParseException
Description
Parses the string. Does not yet handle recursion (where the substituted strings contain {n} references.)

Exceptions
ParseException if the string can't be parsed.


 MessageFormat.parseObject

MessageFormat.parseObject

Syntax
public Object parseObject( String text, ParsePosition status )
Description
Parses the string. Does not yet handle recursion (where the substituted strings contain %n references.)

Overrides
parseObject in class Format


 MessageFormat.setFormat

MessageFormat.setFormat

Syntax
public void setFormat( int variable, Format newFormat )
Description
Sets formats individually to use on parameters. See the class description about format numbering.


 MessageFormat.setFormats

MessageFormat.setFormats

Syntax
public void setFormats( Format newFormats[] )
Description
Sets formats to use on parameters. See the class description about format numbering.


 MessageFormat.setLocale

MessageFormat.setLocale

Syntax
public void setLocale( Locale theLocale )
Description
Constructs with the specified pattern and formats for the arguments in that pattern.

See Also
applyPattern


 MessageFormat.toPattern

MessageFormat.toPattern

Syntax
public String toPattern()
Description
Gets the pattern. See the class description.


 Class NumberFormat

Class java.text.NumberFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.NumberFormat

public abstract class NumberFormat
extends Format
implements Cloneable

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are.

NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.

To format a number for the current Locale, use one of the factory class methods:

  myString = NumberFormat.getInstance().format(myNumber);
If you are formatting multiple numbers, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
 NumberFormat nf = NumberFormat.getInstance();
 for (int i = 0; i < a.length; ++i) {
     output.println(nf.format(myNumber[i]) + "; ");
 }
To format a number for a different Locale, specify it in the call to getInstance.
 NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
 myNumber = nf.parse(myString);
Use getInstance or getNumberInstance to get the normal number format. Use getCurrencyInstance to get the currency number format. And use getPercentInstance to get a format for displaying percentages. With this format, a fraction like 0.53 is displayed as 53%.

You can also control the display of numbers with such methods as setMinimumFractionDigits. If you want even more control over the format or parsing, or want to give your users more control, you can try casting the NumberFormat you get from the factory methods to a DecimalNumberFormat. This will work for the vast majority of locales; just remember to put it in a try block in case you encounter an unusual one.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to:

  • progressively parse through pieces of a string
  • align the decimal point and other areas
For example, you can align numbers in two ways:
  1. If you are using a monospaced font with spacing for alignment, you can pass the FieldPosition in your format call, with field = INTEGER_FIELD. On output, getEndIndex will be set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) spaces at the front of the string.
  2. If you are using proportional fonts, instead of padding with spaces, measure the width of the string in pixels from the start to getEndIndex. Then move the pen by (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. It also works where there is no decimal, but possibly additional characters at the end, e.g. with parentheses in negative numbers: "(12)" for -12.

See Also:
DecimalFormat, ChoiceFormat


 NumberFormat Members

NumberFormat Members

Class Overview | This Package | All Packages

Fields
Name | Description
FRACTION_FIELD | Field constant used to construct a FieldPosition object.
INTEGER_FIELD | Field constant used to construct a FieldPosition object.

Constructors
Name | Description
NumberFormat() |

Methods
Name | Description
clone() | Overrides Cloneable
equals(Object) | Overrides equals
format(double) | Specialization of format.
format(double, StringBuffer, FieldPosition) | Specialization of format.
format(long) | Specialization of format.
format(long, StringBuffer, FieldPosition) | Specialization of format.
format(Object, StringBuffer, FieldPosition) | Formats an object to produce a string.
getAvailableLocales() | Get the set of Locales for which NumberFormats are installed
getCurrencyInstance() | Returns a currency format for the current default locale.
getCurrencyInstance(Locale) | Returns a currency format for the specified locale.
getInstance() | Returns the default number format for the current default locale.
getInstance(Locale) | Returns the default number format for the specified locale.
getMaximumFractionDigits() | Returns the maximum number of digits allowed in the fraction portion of a number.
getMaximumIntegerDigits() | Returns the maximum number of digits allowed in the integer portion of a number.
getMinimumFractionDigits() | Returns the minimum number of digits allowed in the fraction portion of a number.
getMinimumIntegerDigits() | Returns the minimum number of digits allowed in the integer portion of a number.
getNumberInstance() | Returns a general-purpose number format for the current default locale.
getNumberInstance(Locale) | Returns a general-purpose number format for the specified locale.
getPercentInstance() | Returns a percentage format for the current default locale.
getPercentInstance(Locale) | Returns a percentage format for the specified locale.
hashCode() | Overrides hashCode
isGroupingUsed() | Returns true if grouping is used in this format.
isParseIntegerOnly() | Returns true if this format will parse numbers as integers only.
parse(String) | Convenience method.
parse(String, ParsePosition) | Returns a Long if possible (e.g.
parseObject(String, ParsePosition) | Parses a string to produce an object.
setGroupingUsed(boolean) | Set whether or not grouping will be used in this format.
setMaximumFractionDigits(int) | Sets the maximum number of digits allowed in the fraction portion of a number.
setMaximumIntegerDigits(int) | Sets the maximum number of digits allowed in the integer portion of a number.
setMinimumFractionDigits(int) | Sets the minimum number of digits allowed in the fraction portion of a number.
setMinimumIntegerDigits(int) | Sets the minimum number of digits allowed in the integer portion of a number.
setParseIntegerOnly(boolean) | Sets whether or not numbers should be parsed as integers only.


 NumberFormat.FRACTION_FIELD

NumberFormat.FRACTION_FIELD

Syntax
public static final int FRACTION_FIELD
Description
Field constant used to construct a FieldPosition object. Signifies that the position of the fraction part of a formatted number should be returned.

See Also
FieldPosition


 NumberFormat.INTEGER_FIELD

NumberFormat.INTEGER_FIELD

Syntax
public static final int INTEGER_FIELD
Description
Field constant used to construct a FieldPosition object. Signifies that the position of the integer part of a formatted number should be returned.

See Also
FieldPosition


 NumberFormat.NumberFormat

NumberFormat.NumberFormat

Syntax
public NumberFormat()


 NumberFormat.clone

NumberFormat.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Format


 NumberFormat.equals

NumberFormat.equals

Syntax
public boolean equals( Object obj )
Description
Overrides equals

Overrides
equals in class Object


 NumberFormat.format

NumberFormat.format

Syntax
public final StringBuffer format( Object number, StringBuffer toAppendTo, FieldPosition pos )
Description
Formats an object to produce a string.

Overrides
format in class Format


 NumberFormat.format

NumberFormat.format

Syntax 1
public final String format( double number )
Description
Specialization of format.

See Also
format

Syntax 2
public final String format( long number )
Description
Specialization of format.

See Also
format

Syntax 3
public abstract StringBuffer format( double number, StringBuffer toAppendTo, FieldPosition pos )
Description
Specialization of format.

See Also
format

Syntax 4
public abstract StringBuffer format( long number, StringBuffer toAppendTo, FieldPosition pos )
Description
Specialization of format.

See Also
format


 NumberFormat.getAvailableLocales

NumberFormat.getAvailableLocales

Syntax
public static Locale[] getAvailableLocales()
Returns
available locales
Description
Get the set of Locales for which NumberFormats are installed


 NumberFormat.getCurrencyInstance

NumberFormat.getCurrencyInstance

Syntax 1
public static final NumberFormat getCurrencyInstance()
Description
Returns a currency format for the current default locale.

Syntax 2
public static NumberFormat getCurrencyInstance( Locale inLocale )
Description
Returns a currency format for the specified locale.


 NumberFormat.getInstance

NumberFormat.getInstance

Syntax 1
public static final NumberFormat getInstance()
Description
Returns the default number format for the current default locale. The default format is one of the styles provided by the other factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. Exactly which one is locale dependant.

Syntax 2
public static NumberFormat getInstance( Locale inLocale )
Description
Returns the default number format for the specified locale. The default format is one of the styles provided by the other factory methods: getNumberInstance, getCurrencyInstance or getPercentInstance. Exactly which one is locale dependant.


 NumberFormat.getMaximumFractionDigits

NumberFormat.getMaximumFractionDigits

Syntax
public int getMaximumFractionDigits()
Description
Returns the maximum number of digits allowed in the fraction portion of a number.

See Also
setMaximumFractionDigits


 NumberFormat.getMaximumIntegerDigits

NumberFormat.getMaximumIntegerDigits

Syntax
public int getMaximumIntegerDigits()
Description
Returns the maximum number of digits allowed in the integer portion of a number.

See Also
setMaximumIntegerDigits


 NumberFormat.getMinimumFractionDigits

NumberFormat.getMinimumFractionDigits

Syntax
public int getMinimumFractionDigits()
Description
Returns the minimum number of digits allowed in the fraction portion of a number.

See Also
setMinimumFractionDigits


 NumberFormat.getMinimumIntegerDigits

NumberFormat.getMinimumIntegerDigits

Syntax
public int getMinimumIntegerDigits()
Description
Returns the minimum number of digits allowed in the integer portion of a number.

See Also
setMinimumIntegerDigits


 NumberFormat.getNumberInstance

NumberFormat.getNumberInstance

Syntax 1
public static final NumberFormat getNumberInstance()
Description
Returns a general-purpose number format for the current default locale.

Syntax 2
public static NumberFormat getNumberInstance( Locale inLocale )
Description
Returns a general-purpose number format for the specified locale.


 NumberFormat.getPercentInstance

NumberFormat.getPercentInstance

Syntax 1
public static final NumberFormat getPercentInstance()
Description
Returns a percentage format for the current default locale.

Syntax 2
public static NumberFormat getPercentInstance( Locale inLocale )
Description
Returns a percentage format for the specified locale.


 NumberFormat.hashCode

NumberFormat.hashCode

Syntax
public int hashCode()
Description
Overrides hashCode

Overrides
hashCode in class Object


 NumberFormat.isGroupingUsed

NumberFormat.isGroupingUsed

Syntax
public boolean isGroupingUsed()
Description
Returns true if grouping is used in this format. For example, in the English locale, with grouping on, the number 1234567 might be formatted as "1,234,567". The grouping separator as well as the size of each group is locale dependant and is determined by sub-classes of NumberFormat.

See Also
setGroupingUsed


 NumberFormat.isParseIntegerOnly

NumberFormat.isParseIntegerOnly

Syntax
public boolean isParseIntegerOnly()
Description
Returns true if this format will parse numbers as integers only. For example in the English locale, with ParseIntegerOnly true, the string "1234." would be parsed as the integer value 1234 and parsing would stop at the "." character. Of course, the exact format accepted by the parse operation is locale dependant and determined by sub-classes of NumberFormat.


 NumberFormat.parse

NumberFormat.parse

Syntax 1
public abstract Number parse( String text, ParsePosition parsePosition )
Description
Returns a Long if possible (e.g. within range [Long.MIN_VALUE, Long.MAX_VALUE], and with no decimals), otherwise a Double. If IntegerOnly is set, will stop at a decimal point (or equivalent; e.g. for rational numbers "1 2/3", will stop after the 1). Does not throw an exception; if no object can be parsed, index is unchanged!

See Also
isParseIntegerOnly, parseObject

Syntax 2
public Number parse( String text ) throws ParseException
Description
Convenience method.

Exceptions
ParseException if the specified string is invalid.
See Also
format


 NumberFormat.parseObject

NumberFormat.parseObject

Syntax
public final Object parseObject( String source, ParsePosition parsePosition )
Description
Parses a string to produce an object.

Overrides
parseObject in class Format


 NumberFormat.setGroupingUsed

NumberFormat.setGroupingUsed

Syntax
public void setGroupingUsed( boolean newValue )
Description
Set whether or not grouping will be used in this format.

See Also
isGroupingUsed


 NumberFormat.setMaximumFractionDigits

NumberFormat.setMaximumFractionDigits

Syntax
public void setMaximumFractionDigits( int newValue )
Description
Sets the maximum number of digits allowed in the fraction portion of a number. maximumFractionDigits must be >= minimumFractionDigits. If the new value for maximumFractionDigits is less than the current value of minimumFractionDigits, then minimumFractionDigits will also be set to the new value.

See Also
getMaximumFractionDigits


 NumberFormat.setMaximumIntegerDigits

NumberFormat.setMaximumIntegerDigits

Syntax
public void setMaximumIntegerDigits( int newValue )
Description
Sets the maximum number of digits allowed in the integer portion of a number. maximumIntegerDigits must be >= minimumIntegerDigits. If the new value for maximumIntegerDigits is less than the current value of minimumIntegerDigits, then minimumIntegerDigits will also be set to the new value.

See Also
getMaximumIntegerDigits


 NumberFormat.setMinimumFractionDigits

NumberFormat.setMinimumFractionDigits

Syntax
public void setMinimumFractionDigits( int newValue )
Description
Sets the minimum number of digits allowed in the fraction portion of a number. minimumFractionDigits must be <= maximumFractionDigits. If the new value for minimumFractionDigits exceeds the current value of maximumFractionDigits, then maximumIntegerDigits will also be set to the new value

See Also
getMinimumFractionDigits


 NumberFormat.setMinimumIntegerDigits

NumberFormat.setMinimumIntegerDigits

Syntax
public void setMinimumIntegerDigits( int newValue )
Description
Sets the minimum number of digits allowed in the integer portion of a number. minimumIntegerDigits must be <= maximumIntegerDigits. If the new value for minimumIntegerDigits exceeds the current value of maximumIntegerDigits, then maximumIntegerDigits will also be set to the new value

See Also
getMinimumIntegerDigits


 NumberFormat.setParseIntegerOnly

NumberFormat.setParseIntegerOnly

Syntax
public void setParseIntegerOnly( boolean value )
Description
Sets whether or not numbers should be parsed as integers only.

See Also
isParseIntegerOnly


 Class ParseException

Class java.text.ParseException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.text.ParseException

public class ParseException
extends Exception

Signals that an error has been has been reached unexpectedly while parsing.

See Also:
Exception, Format, FieldPosition


 ParseException Members

ParseException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ParseException(String, int) | Constructs a ParseException with the specified detail message and offset.

Methods
Name | Description
getErrorOffset() | Returns the position where the error was found.


 ParseException.ParseException

ParseException.ParseException

Syntax
public ParseException( String s, int errorOffset )
Parameters
s
the detail message
errorOffset
the position where the error is found while parsing.
Description
Constructs a ParseException with the specified detail message and offset. A detail message is a String that describes this particular exception.


 ParseException.getErrorOffset

ParseException.getErrorOffset

Syntax
public int getErrorOffset()
Description
Returns the position where the error was found.


 Class ParsePosition

Class java.text.ParsePosition

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.ParsePosition

public class ParsePosition
extends Object

ParsePosition is a simple class used by Format and its subclasses to keep track of the current position during parsing. The parseObject method in the various Format classes requires a ParsePosition object as an argument.

By design, as you parse through a string with different formats, you can use the same ParsePosition, since the index parameter records the current position.

See Also:
Format


 ParsePosition Members

ParsePosition Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ParsePosition(int) | Create a new ParsePosition with the given initial index.

Methods
Name | Description
getIndex() | Retrieve the current parse position.
setIndex(int) | Set the current parse position.


 ParsePosition.ParsePosition

ParsePosition.ParsePosition

Syntax
public ParsePosition( int index )
Description
Create a new ParsePosition with the given initial index.


 ParsePosition.getIndex

ParsePosition.getIndex

Syntax
public int getIndex()
Description
Retrieve the current parse position. On input to a parse method, this is the index of the character at which parsing will begin; on output, it is the index of the character following the last character parsed.


 ParsePosition.setIndex

ParsePosition.setIndex

Syntax
public void setIndex( int index )
Description
Set the current parse position.


 Class RuleBasedCollator

Class java.text.RuleBasedCollator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Collator
           |
           +----java.text.RuleBasedCollator

public class RuleBasedCollator
extends Collator

The RuleBasedCollator class is a concrete subclass of Collator that provides a simple, data-driven, table collator. With this class you can create a customized table-based Collator. RuleBasedCollator maps characters to sort keys.

RuleBasedCollator has the following restrictions for efficiency (other subclasses may be used for more complex languages) :

  1. The French secondary ordering is applied to the whole collator object.
  2. All non-mentioned Unicode characters are at the end of the collation order.
  3. Private use characters are treated as identical. The private use area in Unicode is 0xE800-0xF8FF.

The collation table is composed of a list of collation rules, where each rule is of three forms:

    < modifier >
    < relation > < text-argument >
    < reset > < text-argument >
The following demonstrates how to create your own collation rules:
  • Text-Argument: A text-argument is any sequence of characters, excluding special characters (that is, whitespace characters and the characters used in modifier, relation and reset). If those characters are desired, you can put them in single quotes (e.g. ampersand => '&').
  • Modifier: There is a single modifier which is used to specify that all accents (secondary differences) are backwards.

    '@' : Indicates that accents are sorted backwards, as in French.

  • Relation: The relations are the following:
    • '<' : Greater, as a letter difference (primary)
    • ';' : Greater, as an accent difference (secondary)
    • ',' : Greater, as a case difference (tertiary)
    • '=' : Equal
  • Reset: There is a single reset which is used primarily for contractions and expansions, but which can also be used to add a modification at the end of a set of rules.

    '&' : Indicates that the next rule follows the position to where the reset text-argument would be sorted.

This sounds more complicated than it is in practice. For example, the following are equivalent ways of expressing the same thing:

 a < b < c
 a < b & b < c
 a < c & a < b
Notice that the order is important, as the subsequent item goes immediately after the text-argument. The following are not equivalent:
 a < b & a < c
 a < c & a < b
Either the text-argument must already be present in the sequence, or some initial substring of the text-argument must be present. (e.g. "a < b & ae < e" is valid since "a" is present in the sequence before "ae" is reset). In this latter case, "ae" is not entered and treated as a single character; instead, "e" is sorted as if it were expanded to two characters: "a" followed by an "e". This difference appears in natural languages: in traditional Spanish "ch" is treated as though it contracts to a single character (expressed as "c < ch < d"), while in traditional German "ä" (a-umlaut) is treated as though it expands to two characters (expressed as "a & ae ; ä < b").

Ignorable Characters

For ignorable characters, the first rule must start with a relation (the examples we have used above are really fragments; "a < b" really should be "< a < b"). If, however, the first relation is not "<", then all the text-arguments up to the first "<" are ignorable. For example, ", - < a < b" makes "-" an ignorable character, as we saw earlier in the word "black-birds". In the samples for different languages, you see that most accents are ignorable.

Normalization and Accents

The Collator object automatically normalizes text internally to separate accents from base characters where possible. This is done both when processing the rules, and when comparing two strings. Collator also uses the Unicode canonical mapping to ensure that combining sequences are sorted properly (for more information, see The Unicode Standard, Version 2.0.)

Errors

The following are errors:

  • A text-argument not preceded by either a reset or relation character (e.g. "a < b c < d").
  • A relation or reset character not followed by a text-argument (e.g. "a < , b").
  • A reset where the text-argument (or an initial substring of the text-argument) is not already in the sequence. (e.g. "a < b & e < f")
If you produce one of these errors, a RuleBasedCollator throws a ParseException.

Examples

Simple: "< a < b < c < d"

Norwegian: "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J < k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T < u,U< v,V< w,W< x,X< y,Y< z,Z < å=a?,Å=A? ;aa,AA< æ,Æ< ø,Ø"

Normally, to create a rule-based Collator object, you will use Collator's factory method getInstance. However, to create a rule-based Collator object with specialized rules tailored to your needs, you construct the RuleBasedCollator with the rules contained in a String object. For example:

 String Simple = "< a < b < c < d";
 RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
Or:
 String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
                 "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
                 "< u,U< v,V< w,W< x,X< y,Y< z,Z" +
                 "< å=a?,Å=A?" +
                 ";aa,AA< æ,Æ< ø,Ø";
 RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);

Combining Collators is as simple as concatenating strings. Here's an example that combines two Collators from two different locales:

 // Create an en_US Collator object
 RuleBasedCollator en_USCollator = (RuleBasedCollator)
     Collator.getInstance(new Locale("en", "US", ""));
 // Create a da_DK Collator object
 RuleBasedCollator da_DKCollator = (RuleBasedCollator)
     Collator.getInstance(new Locale("da", "DK", ""));
 // Combine the two
 // First, get the collation rules from en_USCollator
 String en_USRules = en_USCollator.getRules();
 // Second, get the collation rules from da_DKCollator
 String da_DKRules = da_DKCollator.getRules();
 RuleBasedCollator newCollator =
     new RuleBasedCollator(en_USRules + da_DKRules);
 // newCollator has the combined rules

Another more interesting example would be to make changes on an existing table to create a new Collator object. For example, add "& C < ch, cH, Ch, CH" to the en_USCollator object to create your own:

 // Create a new Collator object with additional rules
 String addRules = "& C < ch, cH, Ch, CH";
 RuleBasedCollator myCollator =
     new RuleBasedCollator(en_USCollator + addRules);
 // myCollator contains the new rules

The following example demonstrates how to change the order of non-spacing accents,

 // old rule
 String oldRules = "=?;?;?;?"    // main accents
                 + ";?;?;?;?"    // main accents
                 + ";?;?;?;?"    // main accents
                 + ";?;?;?;?"    // main accents
                 + ";?;?;?;?"    // main accents
                 + "< a , A ; ae, AE ; æ , Æ"
                 + "< b , B < c, C < e, E & C < d, D";
 // change the order of accent characters
 String addOn = "& ? ; ? ; ?";
 RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);

The last example shows how to put new primary ordering in before the default setting. For example, in Japanese Collator, you can either sort English characters before or after Japanese characters,

 // get en_US Collator rules
 RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator.getInstance(Locale.US);
 // add a few Japanese character to sort before English characters
 // suppose the last character before the first base letter 'a' in
 // the English collation rule is ?
 String jaString = "& ? < ?, ? < ?, ?";
 RuleBasedCollator myJapaneseCollator = new
     RuleBasedCollator(en_USCollator.getRules() + jaString);

See Also:
Collator, CollationElementIterator


 RuleBasedCollator Members

RuleBasedCollator Members

Class Overview | This Package | All Packages

Constructors
Name | Description
RuleBasedCollator(String) | RuleBasedCollator constructor.

Methods
Name | Description
clone() | Standard override; no change in semantics.
compare(String, String) | Compares the character data stored in two different strings based on the collation rules.
equals(Object) | Compares the equality of two collation objects.
getCollationElementIterator(String) | Return a CollationElementIterator for the given String.
getCollationKey(String) | Transforms the string into a series of characters that can be compared with CollationKey.compareTo.
getRules() | Gets the table-based rules for the collation object.
hashCode() | Generates the hash code for the table-based collation object


 RuleBasedCollator.RuleBasedCollator

RuleBasedCollator.RuleBasedCollator

Syntax
public RuleBasedCollator( String rules ) throws ParseException
Parameters
rules
the collation rules to build the collation table from.
Description
RuleBasedCollator constructor. This takes the table rules and builds a collation table out of them. Please see RuleBasedCollator class description for more details on the collation rule syntax.

Exceptions
ParseException A format exception will be thrown if the build process of the rules fails. For example, build rule "a < b c < d" will cause the constructor to throw the ParseException.
See Also
Locale


 RuleBasedCollator.clone

RuleBasedCollator.clone

Syntax
public Object clone()
Description
Standard override; no change in semantics.

Overrides
clone in class Collator


 RuleBasedCollator.compare

RuleBasedCollator.compare

Syntax
public int compare( String source, String target )
Description
Compares the character data stored in two different strings based on the collation rules. Returns information about whether a string is less than, greater than or equal to another string in a language. This can be overriden in a subclass.

Overrides
compare in class Collator


 RuleBasedCollator.equals

RuleBasedCollator.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the table-based collation object to be compared with this.
Returns
true if the current table-based collation object is the same as the table-based collation object obj; false otherwise.
Description
Compares the equality of two collation objects.

Overrides
equals in class Collator


 RuleBasedCollator.getCollationElementIterator

RuleBasedCollator.getCollationElementIterator

Syntax
public CollationElementIterator getCollationElementIterator( String source )
Description
Return a CollationElementIterator for the given String.

See Also
CollationElementIterator


 RuleBasedCollator.getCollationKey

RuleBasedCollator.getCollationKey

Syntax
public CollationKey getCollationKey( String source )
Description
Transforms the string into a series of characters that can be compared with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey. It can be overriden in a subclass.

Overrides
getCollationKey in class Collator


 RuleBasedCollator.getRules

RuleBasedCollator.getRules

Syntax
public String getRules()
Returns
returns the collation rules that the table collation object was created from.
Description
Gets the table-based rules for the collation object.


 RuleBasedCollator.hashCode

RuleBasedCollator.hashCode

Syntax
public int hashCode()
Description
Generates the hash code for the table-based collation object

Overrides
hashCode in class Collator


 Class SimpleDateFormat

Class java.text.SimpleDateFormat

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.Format
           |
           +----java.text.DateFormat
                   |
                   +----java.text.SimpleDateFormat

public class SimpleDateFormat
extends DateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (millis -> text), parsing (text -> millis), and normalization.

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat. Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. For more information on using these methods, see DateFormat.

Time Format Syntax:

To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:

 Symbol   Meaning                 Presentation        Example
 ------   -------                 ------------        -------
 G        era designator          (Text)              AD
 y        year                    (Number)            1996
 M        month in year           (Text & Number)     July & 07
 d        day in month            (Number)            10
 h        hour in am/pm (1~12)    (Number)            12
 H        hour in day (0~23)      (Number)            0
 m        minute in hour          (Number)            30
 s        second in minute        (Number)            55
 S        millisecond             (Number)            978
 E        day in week             (Text)              Tuesday
 D        day in year             (Number)            189
 F        day of week in month    (Number)            2 (2nd Wed in July)
 w        week in year            (Number)            27
 W        week in month           (Number)            2
 a        am/pm marker            (Text)              PM
 k        hour in day (1~24)      (Number)            24
 K        hour in am/pm (0~11)    (Number)            0
 z        time zone               (Text)              Pacific Standard Time
 '        escape for text
 ''        single quote                              '
The count of pattern letters determine the format.

(Text): 4 or more pattern letters--use full form, < 4--use short or abbreviated form if one exists.

(Number): the minimum number of digits. Shorter numbers are zero-padded to this amount. Year is handled specially; that is, if the count of 'y' is 2, the Year will be truncated to 2 digits.

(Text & Number): 3 or over, use text, otherwise use number.

Any characters in the pattern that are not in the ranges of ['a'..'z'] and ['A'..'Z'] will be treated as quoted text. For instance, characters like ':', '.', ' ', '#' and '@' will appear in the resulting time text even they are not embraced within single quotes.

A pattern containing any invalid pattern letter will result in a thrown exception during formatting or parsing.

Examples Using the US Locale:

 Format Pattern                         Result
 --------------                         -------
 "yyyy.MM.dd G 'at' hh:mm:ss z"    ->>  1996.07.10 AD at 15:08:56 PDT
 "EEE, MMM d, ''yy"                ->>  Wed, July 10, '96
 "h:mm a"                          ->>  12:08 PM
 "hh 'o''''clock' a, zzzz"         ->>  12 o'clock PM, Pacific Daylight Time
 "K:mm a, z"                       ->>  0:00 PM, PST
 "yyyyy.MMMMM.dd GGG hh:mm aaa"    ->>  1996.July.10 AD 12:08 PM
Code Sample:

 SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, "PST");
 pdt.setStartRule(DateFields.APRIL, 1, DateFields.SUNDAY, 2*60*60*1000);
 pdt.setEndRule(DateFields.OCTOBER, -1, DateFields.SUNDAY, 2*60*60*1000);
 // Format the current time.
 SimpleDateFormat formatter
     = new SimpleDateFormat ("yyyy.mm.dd e 'at' hh:mm:ss a zzz");
 Date currentTime_1 = new Date();
 String dateString = formatter.format(currentTime_1);
 // Parse the previous string back into a Date.
 ParsePosition pos = new ParsePosition(0);
 Date currentTime_2 = formatter.parse(dateString, pos);
In the example, the time value currentTime_2 obtained from parsing will be equal to currentTime_1. However, they may not be equal if the am/pm marker 'a' is left out from the format pattern while the "hour in am/pm" pattern symbol is used. This information loss can happen when formatting the time in PM.

For time zones that have no names, use strings GMT+hours:minutes or GMT-hours:minutes.

The calendar defines what is the first day of the week, the first week of the year, whether hours are zero based or not (0 vs 12 or 24), and the time zone. There is one common decimal format to handle all the numbers; the digit count is handled programmatically according to the pattern.

See Also:
Calendar, GregorianCalendar, TimeZone, DateFormat, DateFormatSymbols, DecimalFormat


 SimpleDateFormat Members

SimpleDateFormat Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SimpleDateFormat() | Construct a SimpleDateFormat using the default pattern for the default locale.
SimpleDateFormat(String) | Construct a SimpleDateFormat using the given pattern in the default locale.
SimpleDateFormat(String, DateFormatSymbols) | Construct a SimpleDateFormat using the given pattern and locale-specific symbol data.
SimpleDateFormat(String, Locale) | Construct a SimpleDateFormat using the given pattern and locale.

Methods
Name | Description
applyLocalizedPattern(String) | Apply the given localized pattern string to this date format.
applyPattern(String) | Apply the given unlocalized pattern string to this date format.
clone() | Overrides Cloneable
equals(Object) | Override equals.
format(Date, StringBuffer, FieldPosition) | Overrides DateFormat Formats a date or time, which is the standard millis since 24:00 GMT, Jan 1, 1970.
getDateFormatSymbols() | Gets the date/time formatting data.
hashCode() | Override hashCode.
parse(String, ParsePosition) | Overrides DateFormat
setDateFormatSymbols(DateFormatSymbols) | Allows you to set the date/time formatting data.
toLocalizedPattern() | Return a localized pattern string describing this date format.
toPattern() | Return a pattern string describing this date format.


 SimpleDateFormat.SimpleDateFormat

SimpleDateFormat.SimpleDateFormat

Syntax 1
public SimpleDateFormat()
Description
Construct a SimpleDateFormat using the default pattern for the default locale. Note: Not all locales support SimpleDateFormat; for full generality, use the factory methods in the DateFormat class.

See Also
DateFormat

Syntax 2
public SimpleDateFormat( String pattern )
Description
Construct a SimpleDateFormat using the given pattern in the default locale. Note: Not all locales support SimpleDateFormat; for full generality, use the factory methods in the DateFormat class.

Syntax 3
public SimpleDateFormat( String pattern, Locale loc )
Description
Construct a SimpleDateFormat using the given pattern and locale. Note: Not all locales support SimpleDateFormat; for full generality, use the factory methods in the DateFormat class.

Syntax 4
public SimpleDateFormat( String pattern, DateFormatSymbols formatData )
Description
Construct a SimpleDateFormat using the given pattern and locale-specific symbol data.


 SimpleDateFormat.applyLocalizedPattern

SimpleDateFormat.applyLocalizedPattern

Syntax
public void applyLocalizedPattern( String pattern )
Description
Apply the given localized pattern string to this date format.


 SimpleDateFormat.applyPattern

SimpleDateFormat.applyPattern

Syntax
public void applyPattern( String pattern )
Description
Apply the given unlocalized pattern string to this date format.


 SimpleDateFormat.clone

SimpleDateFormat.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class DateFormat


 SimpleDateFormat.equals

SimpleDateFormat.equals

Syntax
public boolean equals( Object obj )
Description
Override equals.

Overrides
equals in class DateFormat


 SimpleDateFormat.format

SimpleDateFormat.format

Syntax
public StringBuffer format( Date date, StringBuffer toAppendTo, FieldPosition pos )
Parameters
date
the date-time value to be formatted into a date-time string.
toAppendTo
where the new date-time text is to be appended.
pos
the formatting position. On input: an alignment field, if desired. On output: the offsets of the alignment field.
Returns
the formatted date-time string.
Description
Overrides DateFormat

Formats a date or time, which is the standard millis since 24:00 GMT, Jan 1, 1970.

Example: using the US locale: "yyyy.MM.dd e 'at' HH:mm:ss zzz" ->> 1996.07.10 AD at 15:08:56 PDT

Overrides
format in class DateFormat
See Also
DateFormat


 SimpleDateFormat.getDateFormatSymbols

SimpleDateFormat.getDateFormatSymbols

Syntax
public DateFormatSymbols getDateFormatSymbols()
Returns
a copy of the date-time formatting data associated with this date-time formatter.
Description
Gets the date/time formatting data.


 SimpleDateFormat.hashCode

SimpleDateFormat.hashCode

Syntax
public int hashCode()
Description
Override hashCode. Generates the hash code for the SimpleDateFormat object

Overrides
hashCode in class DateFormat


 SimpleDateFormat.parse

SimpleDateFormat.parse

Syntax
public Date parse( String text, ParsePosition pos )
Description
Overrides DateFormat

Overrides
parse in class DateFormat
See Also
DateFormat


 SimpleDateFormat.setDateFormatSymbols

SimpleDateFormat.setDateFormatSymbols

Syntax
public void setDateFormatSymbols( DateFormatSymbols newFormatSymbols )
Parameters
newFormatData
the given date-time formatting data.
Description
Allows you to set the date/time formatting data.


 SimpleDateFormat.toLocalizedPattern

SimpleDateFormat.toLocalizedPattern

Syntax
public String toLocalizedPattern()
Description
Return a localized pattern string describing this date format.


 SimpleDateFormat.toPattern

SimpleDateFormat.toPattern

Syntax
public String toPattern()
Description
Return a pattern string describing this date format.


 Class StringCharacterIterator

Class java.text.StringCharacterIterator

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.text.StringCharacterIterator

public final class StringCharacterIterator
extends Object
implements CharacterIterator

StringCharacterIterator implements the CharacterIterater protocol for a String. The StringCharacterIterator class iterates over the entire String.

Examples:

Traverse the text from start to finish

 public void traverseForward(CharacterIterator iter) {
     for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
         processChar(c);
     }
 }
Traverse the text backwards, from end to start
 public void traverseBackward(CharacterIterator iter) {
     for (char c = iter.last(); c != CharacterIterator.DONE; c = iter.prev()) {
         processChar(c);
     }
 }
Traverse both forward and backward from a given position in the text.
 public void traverseOut(CharacterIterator iter, int pos) {
     for (char c = iter.setIndex(pos);
          c != CharacterIterator.DONE && notBoundary(c);
          c = iter.next()) {}
     int end = iter.getIndex();
     for (char c = iter.setIndex(pos);
          c != CharacterIterator.DONE && notBoundary(c);
          c = iter.prev()) {}
     int start = iter.getIndex();
     processSection(iter.getText.subString(start,end);
 }


 StringCharacterIterator Members

StringCharacterIterator Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringCharacterIterator(String) | Construct an iterator with an initial index of 0.
StringCharacterIterator(String, int) | Construct an iterator with the specified initial index.
StringCharacterIterator(String, int, int, int) | Construct an iterator over the given range of the given string, with the index set at the specified position.

Methods
Name | Description
clone() | Create a copy of this boundary
current() | Get the character at the current position (as returned by getIndex()).
equals(Object) | Compares the equality of two StringCharacterIterator objects.
first() | Set the position to getBeginIndex() and return the character at that position.
getBeginIndex() | Return the start index of the text.
getEndIndex() | Return the end index of the text.
getIndex() | Return the current index.
hashCode() | Compute a hashcode for this enumeration
last() | Set the position to getEndIndex() and return the character at that position.
next() | Increment the iterator's index by one and return the character at the new index.
previous() | Decrement the iterator's index by one and return the character at the new index.
setIndex(int) | Set the position to specified position in the text and return that character.


 StringCharacterIterator.StringCharacterIterator

StringCharacterIterator.StringCharacterIterator

Syntax 1
public StringCharacterIterator( String text )
Description
Construct an iterator with an initial index of 0.

Syntax 2
public StringCharacterIterator( String text, int pos )
Parameters
text
The String to be iterated over
pos
Initial iterator position
Description
Construct an iterator with the specified initial index.

Syntax 3
public StringCharacterIterator( String text, int begin, int end, int pos )
Parameters
text
The String to be iterated over
begin
Index of the first character
end
Index of the character following the last character
pos
Initial iterator position
Description
Construct an iterator over the given range of the given string, with the index set at the specified position.


 StringCharacterIterator.clone

StringCharacterIterator.clone

Syntax
public Object clone()
Returns
A copy of this
Description
Create a copy of this boundary

Overrides
clone in class Object


 StringCharacterIterator.current

StringCharacterIterator.current

Syntax
public char current()
Returns
the character at the current position or DONE if the current position is off the end of the text.
Description
Get the character at the current position (as returned by getIndex()).


 StringCharacterIterator.equals

StringCharacterIterator.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the StringCharacterIterator object to be compared with.
Returns
true if the given obj is the same as this StringCharacterIterator object; false otherwise.
Description
Compares the equality of two StringCharacterIterator objects.

Overrides
equals in class Object


 StringCharacterIterator.first

StringCharacterIterator.first

Syntax
public char first()
Description
Set the position to getBeginIndex() and return the character at that position.


 StringCharacterIterator.getBeginIndex

StringCharacterIterator.getBeginIndex

Syntax
public int getBeginIndex()
Returns
the index at which the text begins.
Description
Return the start index of the text.


 StringCharacterIterator.getEndIndex

StringCharacterIterator.getEndIndex

Syntax
public int getEndIndex()
Returns
the index at which the text end.
Description
Return the end index of the text. This index is the index of the first character following the end of the text.


 StringCharacterIterator.getIndex

StringCharacterIterator.getIndex

Syntax
public int getIndex()
Returns
the current index.
Description
Return the current index.


 StringCharacterIterator.hashCode

StringCharacterIterator.hashCode

Syntax
public int hashCode()
Returns
A hash code
Description
Compute a hashcode for this enumeration

Overrides
hashCode in class Object


 StringCharacterIterator.last

StringCharacterIterator.last

Syntax
public char last()
Description
Set the position to getEndIndex() and return the character at that position.


 StringCharacterIterator.next

StringCharacterIterator.next

Syntax
public char next()
Returns
the character at the new position or DONE if the current position is off the end of the text.
Description
Increment the iterator's index by one and return the character at the new index. If the resulting index is greater or equal to getEndIndex(), the current index is reset to getEndIndex() and a value of DONE is returned.


 StringCharacterIterator.previous

StringCharacterIterator.previous

Syntax
public char previous()
Returns
the character at the new position or DONE if the current position is off the end of the text.
Description
Decrement the iterator's index by one and return the character at the new index. If the resulting index is less than getBeginIndex(), the current index is reset to getBeginIndex() and a value of DONE is returned.


 StringCharacterIterator.setIndex

StringCharacterIterator.setIndex

Syntax
public char setIndex( int p )
Description
Set the position to specified position in the text and return that character.


 Package java.util

Package java.util

All Packages

Interfaces

  • Enumeration
  • EventListener
  • Observer

    • Classes

  • BitSet
  • Calendar
  • Date
  • Dictionary
  • EventObject
  • GregorianCalendar
  • Hashtable
  • ListResourceBundle
  • Locale
  • Observable
  • Properties
  • PropertyResourceBundle
  • Random
  • ResourceBundle
  • SimpleTimeZone
  • Stack
  • StringTokenizer
  • TimeZone
  • Vector

    • Exceptions

  • EmptyStackException
  • MissingResourceException
  • NoSuchElementException
  • TooManyListenersException


 Class BitSet

Class java.util.BitSet

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.BitSet

public final class BitSet
extends Object
implements Cloneable, Serializable

A set of bits. The set automatically grows as more bits are needed.


 BitSet Members

BitSet Members

Class Overview | This Package | All Packages

Constructors
Name | Description
BitSet() | Creates an empty set.
BitSet(int) | Creates an empty set with the specified size.

Methods
Name | Description
and(BitSet) | Logically ANDs this bit set with the specified set of bits.
clear(int) | Clears a bit.
clone() | Clones the BitSet.
equals(Object) | Compares this object against the specified object.
get(int) | Gets a bit.
hashCode() | Gets the hashcode.
or(BitSet) | Logically ORs this bit set with the specified set of bits.
set(int) | Sets a bit.
size() | Calculates and returns the set's size in bits.
toString() | Converts the BitSet to a String.
xor(BitSet) | Logically XORs this bit set with the specified set of bits.


 BitSet.BitSet

BitSet.BitSet

Syntax 1
public BitSet()
Description
Creates an empty set.

Syntax 2
public BitSet( int nbits )
Parameters
nbits
the size of the set
Description
Creates an empty set with the specified size.


 BitSet.and

BitSet.and

Syntax
public void and( BitSet set )
Parameters
set
the bit set to be ANDed with
Description
Logically ANDs this bit set with the specified set of bits.


 BitSet.clear

BitSet.clear

Syntax
public void clear( int bit )
Parameters
bit
the bit to be cleared
Description
Clears a bit.


 BitSet.clone

BitSet.clone

Syntax
public Object clone()
Description
Clones the BitSet.

Overrides
clone in class Object


 BitSet.equals

BitSet.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with
Returns
true if the objects are the same; false otherwise.
Description
Compares this object against the specified object.

Overrides
equals in class Object


 BitSet.get

BitSet.get

Syntax
public boolean get( int bit )
Parameters
bit
the bit to be gotten
Description
Gets a bit.


 BitSet.hashCode

BitSet.hashCode

Syntax
public int hashCode()
Description
Gets the hashcode.

Overrides
hashCode in class Object


 BitSet.or

BitSet.or

Syntax
public void or( BitSet set )
Parameters
set
the bit set to be ORed with
Description
Logically ORs this bit set with the specified set of bits.


 BitSet.set

BitSet.set

Syntax
public void set( int bit )
Parameters
bit
the bit to be set
Description
Sets a bit.


 BitSet.size

BitSet.size

Syntax
public int size()
Description
Calculates and returns the set's size in bits. The maximum element in the set is the size - 1st element.


 BitSet.toString

BitSet.toString

Syntax
public String toString()
Description
Converts the BitSet to a String.

Overrides
toString in class Object


 BitSet.xor

BitSet.xor

Syntax
public void xor( BitSet set )
Parameters
set
the bit set to be XORed with
Description
Logically XORs this bit set with the specified set of bits.


 Class Calendar

Class java.util.Calendar

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Calendar

public abstract class Calendar
extends Object
implements Serializable, Cloneable

Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision. See java.util.Date for information about the Date class.)

Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The JDK provides one concrete subclass of Calendar: GregorianCalendar. Future subclasses could represent the various types of lunar calendars in use in many parts of the world.

Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a GregorianCalendar object whose time fields have been initialized with the current date and time:

 Calendar rightNow = Calendar.getInstance();

A Calendar object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional).

When computing a Date from time fields, two special circumstances may arise: there may be insufficient information to compute the Date (such as only year and month but no day in the month), or there may be inconsistent information (such as "Tuesday, July 15, 1996" -- July 15, 1996 is actually a Monday).

Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar, the default for a field is the same as that of the start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.

Inconsistent information. The calendar will give preference to the combinations of fields in the following order (and disregard other inconsistent information).

 month + day-of-month
 month + week-of-month + day-of-week
 month + day-of-week-of-month + day-of-week
 day-of-year
 day-of-week + week-of-year
 hour-of-day
 ampm + hour-of-ampm

Note: for some non-Gregorian calendars, different fields may be necessary for complete disambiguation. For example, a full specification of the historial Arabic astronomical calendar requires year, month, day-of-month and day-of-week in some cases.

Note: There are certain possible ambiguities in interpretation of certain singular times, which are resolved in the following ways:

  1. 24:00:00 "belongs" to the following day. That is, 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970
  2. Although historically not precise, midnight also belongs to "am", and noon belongs to "pm", so on the same day, 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm

The date or time format strings are not part of the definition of a calendar, as those must be modifiable or overridable by the user at runtime. Use java.text.DateFormat to format dates.

Calendar provides an API for field "rolling", where fields can be incremented or decremented, but wrap around. For example, rolling the month up in the date "September 12, 1996" results in "October 12, 1996".

Calendar also provides a date arithmetic function for adding the specified (signed) amount of time to a particular time field. For example, subtracting 5 days from the date "September 12, 1996" results in "September 7, 1996".

See Also:
Date, GregorianCalendar, TimeZone, DateFormat


 Calendar Members

Calendar Members

Class Overview | This Package | All Packages

Fields
Name | Description
AM | Useful constant for hour in 12-hour clock.
AM_PM | Useful constant for date and time.
APRIL | Useful constant for month.
areFieldsSet | The flag which tells if the time fields are set for the calendar.
AUGUST | Useful constant for month.
DATE | Useful constant for date and time.
DAY_OF_MONTH | Useful constant for date and time.
DAY_OF_WEEK | Useful constant for date and time.
DAY_OF_WEEK_IN_MONTH | Useful constant for date and time.
DAY_OF_YEAR | Useful constant for date and time.
DECEMBER | Useful constant for month.
DST_OFFSET | Useful constant for date and time.
ERA | Useful constant for date and time.
FEBRUARY | Useful constant for month.
FIELD_COUNT | Useful constant for date and time.
fields | The time fields containing values into which the millis is computed.
FRIDAY | Useful constant for days of week.
HOUR | Useful constant for date and time.
HOUR_OF_DAY | Useful constant for date and time.
isSet | The flags which tell if a specified time field for the calendar is set.
isTimeSet | The flag which indicates if the current time is set for the calendar.
JANUARY | Useful constant for month.
JULY | Useful constant for month.
JUNE | Useful constant for month.
MARCH | Useful constant for month.
MAY | Useful constant for month.
MILLISECOND | Useful constant for date and time.
MINUTE | Useful constant for date and time.
MONDAY | Useful constant for days of week.
MONTH | Useful constant for date and time.
NOVEMBER | Useful constant for month.
OCTOBER | Useful constant for month.
PM | Useful constant for hour in 12-hour clock.
SATURDAY | Useful constant for days of week.
SECOND | Useful constant for date and time.
SEPTEMBER | Useful constant for month.
SUNDAY | Useful constant for days of week.
THURSDAY | Useful constant for days of week.
time | The current time set for the calendar.
TUESDAY | Useful constant for days of week.
UNDECIMBER | Useful constant for month.
WEDNESDAY | Useful constant for days of week.
WEEK_OF_MONTH | Useful constant for date and time.
WEEK_OF_YEAR | Useful constant for date and time.
YEAR | Useful constant for date and time.
ZONE_OFFSET | Useful constant for date and time.

Constructors
Name | Description
Calendar() | Constructs a Calendar with the default time zone as returned by TimeZone.getDefault(), and the default locale.
Calendar(TimeZone, Locale) | Constructs a Calendar with the given time zone and locale.

Methods
Name | Description
add(int, int) | Date Arithmetic function.
after(Object) | Compares the time field records.
before(Object) | Compares the time field records.
clear() | Clears the values of all the time fields.
clear(int) | Clears the value in the given time field.
clone() | Overrides Cloneable
complete() | Fills in any unset fields in the time field list.
computeFields() | Converts UTC as milliseconds to time field values.
computeTime() | Converts Calendar's time field values to UTC as milliseconds.
equals(Object) | Compares the time field records.
get(int) | Gets the value for a given time field.
getAvailableLocales() | Gets the set of locales for which Calendars are installed.
getFirstDayOfWeek() | Gets what the first day of the week is; e.g., Sunday in US, Monday in France.
getGreatestMinimum(int) | Gets the highest minimum value for the given field if varies.
getInstance() | Gets a Calendar using the default timezone and locale.
getInstance(Locale) | Gets a Calendar using the default timezone and given locale.
getInstance(TimeZone) | Gets a Calendar using the given timezone and default locale.
getInstance(TimeZone, Locale) | Gets a Calendar using the given timezone and given locale.
getLeastMaximum(int) | Gets the lowest maximum value for the given field if varies.
getMaximum(int) | Gets the maximum value for the given time field.
getMinimalDaysInFirstWeek() | Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, getMinimalDaysInFirstWeek returns 1.
getMinimum(int) | Gets the minimum value for the given time field.
getTime() | Gets this Calendar's current time.
getTimeInMillis() | Gets this Calendar's current time as a long.
getTimeZone() | Gets the time zone.
internalGet(int) | Gets the value for a given time field.
isLenient() | Tell whether date/time interpretation is to be lenient.
isSet(int) | Determines if the given time field has a value set.
roll(int, boolean) | Time Field Rolling function.
set(int, int) | Sets the time field with the given value.
set(int, int, int) | Sets the values for the fields year, month, and date.
set(int, int, int, int, int) | Sets the values for the fields year, month, date, hour, and minute.
set(int, int, int, int, int, int) | Sets the values for the fields year, month, date, hour, minute, and second.
setFirstDayOfWeek(int) | Sets what the first day of the week is; e.g., Sunday in US, Monday in France.
setLenient(boolean) | Specify whether or not date/time interpretation is to be lenient.
setMinimalDaysInFirstWeek(int) | Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call the method with value 1.
setTime(Date) | Sets this Calendar's current time with the given Date.
setTimeInMillis(long) | Sets this Calendar's current time from the given long value.
setTimeZone(TimeZone) | Sets the time zone with the given time zone value.


 Calendar.AM

Calendar.AM

Syntax
public static final int AM
Description
Useful constant for hour in 12-hour clock. Used in GregorianCalendar.


 Calendar.AM_PM

Calendar.AM_PM

Syntax
public static final int AM_PM
Description
Useful constant for date and time. Used in time fields.


 Calendar.APRIL

Calendar.APRIL

Syntax
public static final int APRIL
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.areFieldsSet

Calendar.areFieldsSet

Syntax
protected boolean areFieldsSet
Description
The flag which tells if the time fields are set for the calendar.


 Calendar.AUGUST

Calendar.AUGUST

Syntax
public static final int AUGUST
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.DATE

Calendar.DATE

Syntax
public static final int DATE
Description
Useful constant for date and time. Used in time fields. DATE is the time field name for day-of-month.


 Calendar.DAY_OF_MONTH

Calendar.DAY_OF_MONTH

Syntax
public static final int DAY_OF_MONTH
Description
Useful constant for date and time. Used in time fields. This is a synonym for DATE.


 Calendar.DAY_OF_WEEK

Calendar.DAY_OF_WEEK

Syntax
public static final int DAY_OF_WEEK
Description
Useful constant for date and time. Used in time fields.


 Calendar.DAY_OF_WEEK_IN_MONTH

Calendar.DAY_OF_WEEK_IN_MONTH

Syntax
public static final int DAY_OF_WEEK_IN_MONTH
Description
Useful constant for date and time. Used in time fields.


 Calendar.DAY_OF_YEAR

Calendar.DAY_OF_YEAR

Syntax
public static final int DAY_OF_YEAR
Description
Useful constant for date and time. Used in time fields.


 Calendar.DECEMBER

Calendar.DECEMBER

Syntax
public static final int DECEMBER
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.DST_OFFSET

Calendar.DST_OFFSET

Syntax
public static final int DST_OFFSET
Description
Useful constant for date and time. Used in time fields.


 Calendar.ERA

Calendar.ERA

Syntax
public static final int ERA
Description
Useful constant for date and time. Used in time fields. ERA is calendar specific.


 Calendar.FEBRUARY

Calendar.FEBRUARY

Syntax
public static final int FEBRUARY
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.FIELD_COUNT

Calendar.FIELD_COUNT

Syntax
public static final int FIELD_COUNT
Description
Useful constant for date and time. FIELD_COUNT is used for the time field array creation.


 Calendar.fields

Calendar.fields

Syntax
protected int fields[]
Description
The time fields containing values into which the millis is computed.


 Calendar.FRIDAY

Calendar.FRIDAY

Syntax
public static final int FRIDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.HOUR

Calendar.HOUR

Syntax
public static final int HOUR
Description
Useful constant for date and time. Used in time fields. HOUR is used for the 12-hour clock.


 Calendar.HOUR_OF_DAY

Calendar.HOUR_OF_DAY

Syntax
public static final int HOUR_OF_DAY
Description
Useful constant for date and time. Used in time fields. HOUR_OF_DAY is used for the 24-hour clock.


 Calendar.isSet

Calendar.isSet

Syntax
protected boolean isSet[]
Description
The flags which tell if a specified time field for the calendar is set.


 Calendar.isTimeSet

Calendar.isTimeSet

Syntax
protected boolean isTimeSet
Description
The flag which indicates if the current time is set for the calendar.


 Calendar.JANUARY

Calendar.JANUARY

Syntax
public static final int JANUARY
Description
Useful constant for month. Used in GregorianCalendar. Note: Calendar month is now 0-based.


 Calendar.JULY

Calendar.JULY

Syntax
public static final int JULY
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.JUNE

Calendar.JUNE

Syntax
public static final int JUNE
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.MARCH

Calendar.MARCH

Syntax
public static final int MARCH
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.MAY

Calendar.MAY

Syntax
public static final int MAY
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.MILLISECOND

Calendar.MILLISECOND

Syntax
public static final int MILLISECOND
Description
Useful constant for date and time. Used in time fields.


 Calendar.MINUTE

Calendar.MINUTE

Syntax
public static final int MINUTE
Description
Useful constant for date and time. Used in time fields.


 Calendar.MONDAY

Calendar.MONDAY

Syntax
public static final int MONDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.MONTH

Calendar.MONTH

Syntax
public static final int MONTH
Description
Useful constant for date and time. Used in time fields.


 Calendar.NOVEMBER

Calendar.NOVEMBER

Syntax
public static final int NOVEMBER
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.OCTOBER

Calendar.OCTOBER

Syntax
public static final int OCTOBER
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.PM

Calendar.PM

Syntax
public static final int PM
Description
Useful constant for hour in 12-hour clock. Used in GregorianCalendar.


 Calendar.SATURDAY

Calendar.SATURDAY

Syntax
public static final int SATURDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.SECOND

Calendar.SECOND

Syntax
public static final int SECOND
Description
Useful constant for date and time. Used in time fields.


 Calendar.SEPTEMBER

Calendar.SEPTEMBER

Syntax
public static final int SEPTEMBER
Description
Useful constant for month. Used in GregorianCalendar.


 Calendar.SUNDAY

Calendar.SUNDAY

Syntax
public static final int SUNDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.THURSDAY

Calendar.THURSDAY

Syntax
public static final int THURSDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.time

Calendar.time

Syntax
protected long time
Description
The current time set for the calendar.


 Calendar.TUESDAY

Calendar.TUESDAY

Syntax
public static final int TUESDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.UNDECIMBER

Calendar.UNDECIMBER

Syntax
public static final int UNDECIMBER
Description
Useful constant for month. Used in GregorianCalendar. UNDECIMBER is an artifical name. This 13th month is for lunar calendars.


 Calendar.WEDNESDAY

Calendar.WEDNESDAY

Syntax
public static final int WEDNESDAY
Description
Useful constant for days of week. Used in GregorianCalendar.


 Calendar.WEEK_OF_MONTH

Calendar.WEEK_OF_MONTH

Syntax
public static final int WEEK_OF_MONTH
Description
Useful constant for date and time. Used in time fields.


 Calendar.WEEK_OF_YEAR

Calendar.WEEK_OF_YEAR

Syntax
public static final int WEEK_OF_YEAR
Description
Useful constant for date and time. Used in time fields.


 Calendar.YEAR

Calendar.YEAR

Syntax
public static final int YEAR
Description
Useful constant for date and time. Used in time fields.


 Calendar.ZONE_OFFSET

Calendar.ZONE_OFFSET

Syntax
public static final int ZONE_OFFSET
Description
Useful constant for date and time. Used in time fields.


 Calendar.Calendar

Calendar.Calendar

Syntax 1
protected Calendar()
Description
Constructs a Calendar with the default time zone as returned by TimeZone.getDefault(), and the default locale.

See Also
getDefault

Syntax 2
protected Calendar( TimeZone zone, Locale aLocale )
Parameters
zone
the given time zone.
Description
Constructs a Calendar with the given time zone and locale.


 Calendar.add

Calendar.add

Syntax
public abstract void add( int field, int amount )
Parameters
field
the time field.
amount
the amount of date or time to be added to the field.
Description
Date Arithmetic function. Adds the specified (signed) amount of time to the given time field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

add(Calendar.DATE, -5).


 Calendar.after

Calendar.after

Syntax
public abstract boolean after( Object when )
Parameters
when
the Calendar to be compared with this Calendar.
Returns
true if the current time of this Calendar is after the time of Calendar when; false otherwise.
Description
Compares the time field records. Equivalent to comparing result of conversion to UTC.


 Calendar.before

Calendar.before

Syntax
public abstract boolean before( Object when )
Parameters
when
the Calendar to be compared with this Calendar.
Returns
true if the current time of this Calendar is before the time of Calendar when; false otherwise.
Description
Compares the time field records. Equivalent to comparing result of conversion to UTC.


 Calendar.clear

Calendar.clear

Syntax 1
public final void clear()
Description
Clears the values of all the time fields.

Syntax 2
public final void clear( int field )
Parameters
field
the time field to be cleared.
Description
Clears the value in the given time field.


 Calendar.clone

Calendar.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Object


 Calendar.complete

Calendar.complete

Syntax
protected void complete()
Description
Fills in any unset fields in the time field list.


 Calendar.computeFields

Calendar.computeFields

Syntax
protected abstract void computeFields()
Description
Converts UTC as milliseconds to time field values. This allows you to sync up the time field values with a new time that is set for the calendar.


 Calendar.computeTime

Calendar.computeTime

Syntax
protected abstract void computeTime()
Description
Converts Calendar's time field values to UTC as milliseconds.


 Calendar.equals

Calendar.equals

Syntax
public abstract boolean equals( Object when )
Parameters
when
the Calendar to be compared with this Calendar.
Returns
true if the current time of this Calendar is equal to the time of Calendar when; false otherwise.
Description
Compares the time field records. Equivalent to comparing result of conversion to UTC.

Overrides
equals in class Object


 Calendar.get

Calendar.get

Syntax
public final int get( int field )
Parameters
field
the given time field.
Returns
the value for the given time field.
Description
Gets the value for a given time field.


 Calendar.getAvailableLocales

Calendar.getAvailableLocales

Syntax
public static synchronized Locale[] getAvailableLocales()
Returns
the set of locales for which Calendars are installed.
Description
Gets the set of locales for which Calendars are installed.


 Calendar.getFirstDayOfWeek

Calendar.getFirstDayOfWeek

Syntax
public int getFirstDayOfWeek()
Returns
the first day of the week.
Description
Gets what the first day of the week is; e.g., Sunday in US, Monday in France.


 Calendar.getGreatestMinimum

Calendar.getGreatestMinimum

Syntax
public abstract int getGreatestMinimum( int field )
Parameters
field
the given time field.
Returns
the highest minimum value for the given time field.
Description
Gets the highest minimum value for the given field if varies. Otherwise same as getMinimum(). For Gregorian, no difference.


 Calendar.getInstance

Calendar.getInstance

Syntax 1
public static synchronized Calendar getInstance()
Returns
a Calendar.
Description
Gets a Calendar using the default timezone and locale.

Syntax 2
public static synchronized Calendar getInstance( TimeZone zone )
Parameters
zone
the given timezone.
Returns
a Calendar.
Description
Gets a Calendar using the given timezone and default locale.

Syntax 3
public static synchronized Calendar getInstance( Locale aLocale )
Parameters
aLocale
the given locale.
Returns
a Calendar.
Description
Gets a Calendar using the default timezone and given locale.

Syntax 4
public static synchronized Calendar getInstance( TimeZone zone, Locale aLocale )
Parameters
zone
the given timezone.
aLocale
the given locale.
Returns
a Calendar.
Description
Gets a Calendar using the given timezone and given locale.


 Calendar.getLeastMaximum

Calendar.getLeastMaximum

Syntax
public abstract int getLeastMaximum( int field )
Parameters
field
the given time field.
Returns
the lowest maximum value for the given time field.
Description
Gets the lowest maximum value for the given field if varies. Otherwise same as getMaximum(). e.g., for Gregorian DAY_OF_MONTH, 28.


 Calendar.getMaximum

Calendar.getMaximum

Syntax
public abstract int getMaximum( int field )
Parameters
field
the given time field.
Returns
the maximum value for the given time field.
Description
Gets the maximum value for the given time field. e.g. for Gregorian DAY_OF_MONTH, 31.


 Calendar.getMinimalDaysInFirstWeek

Calendar.getMinimalDaysInFirstWeek

Syntax
public int getMinimalDaysInFirstWeek()
Returns
the minimal days required in the first week of the year.
Description
Gets what the minimal days required in the first week of the year are; e.g., if the first week is defined as one that contains the first day of the first month of a year, getMinimalDaysInFirstWeek returns 1. If the minimal days required must be a full week, getMinimalDaysInFirstWeek returns 7.


 Calendar.getMinimum

Calendar.getMinimum

Syntax
public abstract int getMinimum( int field )
Parameters
field
the given time field.
Returns
the minimum value for the given time field.
Description
Gets the minimum value for the given time field. e.g., for Gregorian DAY_OF_MONTH, 1.


 Calendar.getTime

Calendar.getTime

Syntax
public final Date getTime()
Returns
the current time.
Description
Gets this Calendar's current time.


 Calendar.getTimeInMillis

Calendar.getTimeInMillis

Syntax
protected long getTimeInMillis()
Returns
the current time as milliseconds from the epoch.
Description
Gets this Calendar's current time as a long.


 Calendar.getTimeZone

Calendar.getTimeZone

Syntax
public TimeZone getTimeZone()
Returns
the time zone object associated with this calendar.
Description
Gets the time zone.


 Calendar.internalGet

Calendar.internalGet

Syntax
protected final int internalGet( int field )
Parameters
field
the given time field.
Returns
the value for the given time field.
Description
Gets the value for a given time field. This is an internal fast time field value getter for the subclasses.


 Calendar.isLenient

Calendar.isLenient

Syntax
public boolean isLenient()
Description
Tell whether date/time interpretation is to be lenient.


 Calendar.isSet

Calendar.isSet

Syntax
public final boolean isSet( int field )
Returns
true if the given time field has a value set; false otherwise.
Description
Determines if the given time field has a value set.


 Calendar.roll

Calendar.roll

Syntax
public abstract void roll( int field, boolean up )
Parameters
field
the time field.
up
indicates if the value of the specified time field is to be rolled up or rolled down. Use true if rolling up, false otherwise.
Description
Time Field Rolling function. Rolls (up/down) a single unit of time on the given time field. For example, to roll the current date up by one day, you can achieve it by calling:

roll(Calendar.DATE, true). When rolling on the year or Calendar.YEAR field, it will roll the year value in the range between 1 and the value returned by calling getMaximum(Calendar.YEAR). When rolling on the month or Calendar.MONTH field, other fields like date might conflict and, need to be changed. For instance, rolling the month on the date 01/31/96 will result in 03/02/96. When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will roll the hour value in the range between 0 and 23, which is zero-based.


 Calendar.set

Calendar.set

Syntax 1
public final void set( int field, int value )
Parameters
field
the given time field.
value
the value to be set for the given time field.
Description
Sets the time field with the given value.

Syntax 2
public final void set( int year, int month, int date )
Parameters
year
the value used to set the YEAR time field.
month
the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field.
Description
Sets the values for the fields year, month, and date.

Syntax 3
public final void set( int year, int month, int date, int hour, int minute )
Parameters
year
the value used to set the YEAR time field.
month
the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field.
hour
the value used to set the HOUR_OF_DAY time field.
minute
the value used to set the MINUTE time field.
Description
Sets the values for the fields year, month, date, hour, and minute.

Syntax 4
public final void set( int year, int month, int date, int hour, int minute, int second )
Parameters
year
the value used to set the YEAR time field.
month
the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field.
hour
the value used to set the HOUR_OF_DAY time field.
minute
the value used to set the MINUTE time field.
second
the value used to set the SECOND time field.
Description
Sets the values for the fields year, month, date, hour, minute, and second.


 Calendar.setFirstDayOfWeek

Calendar.setFirstDayOfWeek

Syntax
public void setFirstDayOfWeek( int value )
Parameters
value
the given first day of the week.
Description
Sets what the first day of the week is; e.g., Sunday in US, Monday in France.


 Calendar.setLenient

Calendar.setLenient

Syntax
public void setLenient( boolean lenient )
Description
Specify whether or not date/time interpretation is to be lenient. With lenient interpretation, a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict interpretation, such dates will cause an exception to be thrown.

See Also
setLenient


 Calendar.setMinimalDaysInFirstWeek

Calendar.setMinimalDaysInFirstWeek

Syntax
public void setMinimalDaysInFirstWeek( int value )
Parameters
value
the given minimal days required in the first week of the year.
Description
Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call the method with value 1. If it must be a full week, use value 7.


 Calendar.setTime

Calendar.setTime

Syntax
public final void setTime( Date date )
Parameters
date
the given Date.
Description
Sets this Calendar's current time with the given Date.


 Calendar.setTimeInMillis

Calendar.setTimeInMillis

Syntax
protected void setTimeInMillis( long millis )
Parameters
date
the new time in milliseconds from the epoch.
Description
Sets this Calendar's current time from the given long value.


 Calendar.setTimeZone

Calendar.setTimeZone

Syntax
public void setTimeZone( TimeZone value )
Parameters
value
the given time zone.
Description
Sets the time zone with the given time zone value.


 Class Date

Class java.util.Date

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Date

public class Date
extends Object
implements Serializable, Cloneable

The class Date represents a specific instant in time, with millisecond precision.

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the "civil" name for the standard; UT is the "scientific" name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth's rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the U.S. Naval Observatory, particularly the Directorate of Time at:

    http://tycho.usno.navy.mil

and their definitions of "Systems of Time" at:

    http://tycho.usno.navy.mil/systime.html

In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used:

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer form 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 60; the value 60 occurs only for leap seconds and even then only in Java implementations that actually track leap seconds correctly.

In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.

See Also:
DateFormat, Calendar, TimeZone


 Date Members

Date Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Date() | Allocates a Date object and initializes it so that it represents the time at which it was allocated measured to the nearest millisecond.
Date(int, int, int) | Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments. Deprecated.
Date(int, int, int, int, int) | Allocates a Date object and initializes it so that it represents the specified hour and minute, local time, of the date specified by the year, month, date, hrs, and min arguments. Deprecated.
Date(int, int, int, int, int, int) | Allocates a Date object and initializes it so that it represents the specified hour, minute, and second, local time of the date specified by the year, month, date, hrs, min, and sec arguments. Deprecated.
Date(long) | Allocates a Date object and initializes it to represent the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.
Date(String) | Allocates a Date object and initializes it so that it represents the date and time indicated by the string s, which is interpreted as if by the parse method. Deprecated.

Methods
Name | Description
after(Date) | Tests if this date is after the specified date.
before(Date) | Tests if this date is before the specified date.
equals(Object) | Compares two dates.
getDate() | Returns the day of the month represented by this date. Deprecated.
getDay() | Returns the day of the week represented by this date. Deprecated.
getHours() | Returns the hour represented by this date. Deprecated.
getMinutes() | Returns the number of minutes past the hour represented by this date. Deprecated.
getMonth() | Returns the month represented by this date. Deprecated.
getSeconds() | Returns the number of seconds past the minute represented by this date. Deprecated.
getTime() | Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
getTimezoneOffset() | Returns the local time-zone offset. Deprecated.
getYear() | Returns the year represented by this date, minus 1900. Deprecated.
hashCode() | Returns a hash code value for this object.
parse(String) | Given a string representing a time, parse it and return the time value. Deprecated.
setDate(int) | Sets the day of the month of this date to the specified value. Deprecated.
setHours(int) | Sets the hour of this date to the specified value. Deprecated.
setMinutes(int) | Sets the minutes of this date to the specified value. Deprecated.
setMonth(int) | Sets the month of this date to the specified value. Deprecated.
setSeconds(int) | Sets the seconds of this date to the specified value. Deprecated.
setTime(long) | Sets this date to represent the specified number of milliseconds since January 1, 1970 00:00:00 GMT.
setYear(int) | Sets the year of this date to be the specified value plus 1900. Deprecated.
toGMTString() | Creates a string representation of this date. Deprecated.
toLocaleString() | Creates a string representation of this date in an implementation-dependent form. Deprecated.
toString() | Creates a canonical string representation of the date.
UTC(int, int, int, int, int, int) | Determines the date and time based on the arguments. Deprecated.


 Date.Date

Date.Date

Syntax 1
public Date()
Description
Allocates a Date object and initializes it so that it represents the time at which it was allocated measured to the nearest millisecond.

See Also
currentTimeMillis

Syntax 2
public Date( long date )
Parameters
date
the milliseconds since January 1, 1970, 00:00:00 GMT.
Description
Allocates a Date object and initializes it to represent the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.

See Also
currentTimeMillis

Syntax 3
public Date( int year, int month, int date )
Parameters
year
the year minus 1900.
month
the month between 0-11.
date
the day of the month between 1-31.
Description
Note: Date() is deprecated.

Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.

See Also
Calendar

Syntax 4
public Date( int year, int month, int date, int hrs, int min )
Parameters
year
the year minus 1900.
month
the month between 0-11.
date
the day of the month between 1-31.
hrs
the hours between 0-23.
min
the minutes between 0-59.
Description
Note: Date() is deprecated.

Allocates a Date object and initializes it so that it represents the specified hour and minute, local time, of the date specified by the year, month, date, hrs, and min arguments.

See Also
Calendar

Syntax 5
public Date( int year, int month, int date, int hrs, int min, int sec )
Parameters
year
the year minus 1900.
month
the month between 0-11.
date
the day of the month between 1-31.
hrs
the hours between 0-23.
min
the minutes between 0-59.
sec
the seconds between 0-59.
Description
Note: Date() is deprecated.

Allocates a Date object and initializes it so that it represents the specified hour, minute, and second, local time of the date specified by the year, month, date, hrs, min, and sec arguments.

See Also
Calendar

Syntax 6
public Date( String s )
Parameters
s
a string representation of the date.
Description
Note: Date() is deprecated.

Allocates a Date object and initializes it so that it represents the date and time indicated by the string s, which is interpreted as if by the parse method.

See Also
DateFormat, parse


 Date.after

Date.after

Syntax
public boolean after( Date when )
Parameters
when
a date.
Returns
true if this date is after the argument date; false otherwise.
Description
Tests if this date is after the specified date.


 Date.before

Date.before

Syntax
public boolean before( Date when )
Parameters
when
a date.
Returns
true if this date is before the argument date; false otherwise.
Description
Tests if this date is before the specified date.


 Date.equals

Date.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the object to compare with.
Returns
true if the objects are the same; false otherwise.
Description
Compares two dates. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.

Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.

Overrides
equals in class Object
See Also
getTime


 Date.getDate

Date.getDate

Syntax
public int getDate()
Returns
the day of the month represented by this date.
Description
Note: getDate() is deprecated.

Returns the day of the month represented by this date. The value returned is between 1 and 31.

See Also
Calendar


 Date.getDay

Date.getDay

Syntax
public int getDay()
Returns
the day of the week represented by this date.
Description
Note: getDay() is deprecated.

Returns the day of the week represented by this date. The value returned is between 0 and 6, where 0 represents Sunday.

See Also
Calendar


 Date.getHours

Date.getHours

Syntax
public int getHours()
Returns
the hour represented by this date.
Description
Note: getHours() is deprecated.

Returns the hour represented by this date. The value returned is between 0 and 23, where 0 represents midnight.

See Also
Calendar


 Date.getMinutes

Date.getMinutes

Syntax
public int getMinutes()
Returns
the number of minutes past the hour represented by this date.
Description
Note: getMinutes() is deprecated.

Returns the number of minutes past the hour represented by this date. The value returned is between 0 and 59.

See Also
Calendar


 Date.getMonth

Date.getMonth

Syntax
public int getMonth()
Returns
the month represented by this date.
Description
Note: getMonth() is deprecated.

Returns the month represented by this date. The value returned is between 0 and 11, with the value 0 representing January.

See Also
Calendar


 Date.getSeconds

Date.getSeconds

Syntax
public int getSeconds()
Returns
the number of seconds past the minute represented by this date.
Description
Note: getSeconds() is deprecated.

Returns the number of seconds past the minute represented by this date. The value returned is between 0 and 60. The value 60 can only occur on those Java Virtual Machines that take leap seconds into account.

See Also
Calendar


 Date.getTime

Date.getTime

Syntax
public long getTime()
Returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
Description
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.


 Date.getTimezoneOffset

Date.getTimezoneOffset

Syntax
public int getTimezoneOffset()
Returns
the time-zone offset, in minutes, for the current locale.
Description
Note: getTimezoneOffset() is deprecated.

Returns the local time-zone offset. The time-zone offset is the number of minutes that must be added to GMT to give the local time zone. This value includes the correction, if necessary, for daylight saving time.

See Also
Calendar, TimeZone


 Date.getYear

Date.getYear

Syntax
public int getYear()
Returns
the year represented by this date, minus 1900.
Description
Note: getYear() is deprecated.

Returns the year represented by this date, minus 1900.

See Also
Calendar


 Date.hashCode

Date.hashCode

Syntax
public int hashCode()
Returns
a hash code value for this object.
Description
Returns a hash code value for this object.

Overrides
hashCode in class Object


 Date.parse

Date.parse

Syntax
public static long parse( String s )
Parameters
s
a string to be parsed as a date.
Returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the string argument.
Description
Note: parse() is deprecated.

Given a string representing a time, parse it and return the time value. This method recognizes most standard syntaxes.

It accepts many syntaxes; in particular, it recognizes the IETF standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also understands the continental U.S. time-zone abbreviations, but for general use, a time-zone offset should be used: "Sat, 12 Aug 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If no time zone is specified, the local time zone is assumed. GMT and UTC are considered equivalent.

See Also
DateFormat


 Date.setDate

Date.setDate

Syntax
public void setDate( int date )
Parameters
date
the day of the month value between 1-31.
Description
Note: setDate() is deprecated.

Sets the day of the month of this date to the specified value.

See Also
Calendar


 Date.setHours

Date.setHours

Syntax
public void setHours( int hours )
Parameters
hours
the hour value.
Description
Note: setHours() is deprecated.

Sets the hour of this date to the specified value.

See Also
Calendar


 Date.setMinutes

Date.setMinutes

Syntax
public void setMinutes( int minutes )
Parameters
minutes
the value of the minutes.
Description
Note: setMinutes() is deprecated.

Sets the minutes of this date to the specified value.

See Also
Calendar


 Date.setMonth

Date.setMonth

Syntax
public void setMonth( int month )
Parameters
month
the month value between 0-11.
Description
Note: setMonth() is deprecated.

Sets the month of this date to the specified value.

See Also
Calendar


 Date.setSeconds

Date.setSeconds

Syntax
public void setSeconds( int seconds )
Parameters
seconds
the seconds value.
Description
Note: setSeconds() is deprecated.

Sets the seconds of this date to the specified value.

See Also
Calendar


 Date.setTime

Date.setTime

Syntax
public void setTime( long time )
Parameters
time
the number of milliseconds.
Description
Sets this date to represent the specified number of milliseconds since January 1, 1970 00:00:00 GMT.


 Date.setYear

Date.setYear

Syntax
public void setYear( int year )
Parameters
year
the year value.
Description
Note: setYear() is deprecated.

Sets the year of this date to be the specified value plus 1900.

See Also
Calendar


 Date.toGMTString

Date.toGMTString

Syntax
public String toGMTString()
Returns
a string representation of this date, using the Internet GMT conventions.
Description
Note: toGMTString() is deprecated.

Creates a string representation of this date. The result is of the form:

    "12 Aug 1995 02:30:00 GMT"

in which the day of the month is always one or two digits. The other fields have exactly the width shown. The time zone is always given as "GMT".

See Also
DateFormat


 Date.toLocaleString

Date.toLocaleString

Syntax
public String toLocaleString()
Returns
a string representation of this date, using the locale conventions.
Description
Note: toLocaleString() is deprecated.

Creates a string representation of this date in an implementation-dependent form. The intent is that the form should be familiar to the user of the Java application, wherever it may happen to be running. The intent is comparable to that of the "%c" format supported by the strftime() function of ISO C.

See Also
DateFormat


 Date.toString

Date.toString

Syntax
public String toString()
Returns
a string representation of this date.
Description
Creates a canonical string representation of the date. The result is of the form "Sat Aug 12 02:30:00 PDT 1995".

Overrides
toString in class Object


 Date.UTC

Date.UTC

Syntax
public static long UTC( int year, int month, int date, int hrs, int min, int sec )
Parameters
year
the year minus 1900.
month
the month between 0-11.
date
the day of the month between 1-31.
hrs
the hours between 0-23.
min
the minutes between 0-59.
sec
the seconds between 0-59.
Returns
the number of seconds since January 1, 1970, 00:00:00 GMT for the date and time specified by the arguments.
Description
Note: UTC() is deprecated.

Determines the date and time based on the arguments. The arguments are interpreted in UTC, not in the local time zone

See Also
Calendar


 Class Dictionary

Class java.util.Dictionary

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Dictionary

public abstract class Dictionary
extends Object

The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Any non-null object can be used as a key and as a value.

As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

See Also:
equals, hashCode, Hashtable


 Dictionary Members

Dictionary Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Dictionary() |

Methods
Name | Description
elements() | Returns an enumeration of the values in this dictionary.
get(Object) | Returns the value to which the key is mapped in this dictionary.
isEmpty() | Tests if this dictionary maps no keys to value.
keys() | Returns an enumeration of the keys in this dictionary.
put(Object, Object) | Maps the specified key to the specified value in this dictionary.
remove(Object) | Removes the key (and its corresponding value) from this dictionary.
size() | Returns the number of keys in this dictionary.


 Dictionary.Dictionary

Dictionary.Dictionary

Syntax
public Dictionary()


 Dictionary.elements

Dictionary.elements

Syntax
public abstract Enumeration elements()
Returns
an enumeration of the values in this dictionary.
Description
Returns an enumeration of the values in this dictionary. the Enumeration methods on the returned object to fetch the elements sequentially.

See Also
keys, Enumeration


 Dictionary.get

Dictionary.get

Syntax
public abstract Object get( Object key )
Parameters
key
a key in this dictionary. null if the key is not mapped to any value in this dictionary.
Returns
the value to which the key is mapped in this dictionary;
Description
Returns the value to which the key is mapped in this dictionary.

See Also
put


 Dictionary.isEmpty

Dictionary.isEmpty

Syntax
public abstract boolean isEmpty()
Returns
true if this dictionary maps no keys to values; false otherwise.
Description
Tests if this dictionary maps no keys to value.


 Dictionary.keys

Dictionary.keys

Syntax
public abstract Enumeration keys()
Returns
an enumeration of the keys in this dictionary.
Description
Returns an enumeration of the keys in this dictionary.

See Also
elements, Enumeration


 Dictionary.put

Dictionary.put

Syntax
public abstract Object put( Object key, Object value )
Parameters
key
the hashtable key.
value
the value.
Returns
the previous value to which the key was mapped in this dictionary, or null if the key did not have a previous mapping.
Description
Maps the specified key to the specified value in this dictionary. Neither the key nor the value can be null.

The value can be retrieved by calling the get method with a key that is equal to the original key.

Exceptions
NullPointerException if the key or value is null.
See Also
equals, get


 Dictionary.remove

Dictionary.remove

Syntax
public abstract Object remove( Object key )
Parameters
key
the key that needs to be removed.
Returns
the value to which the key had been mapped in this dictionary, or null if the key did not have a mapping.
Description
Removes the key (and its corresponding value) from this dictionary. This method does nothing if the key is not in this dictionary.


 Dictionary.size

Dictionary.size

Syntax
public abstract int size()
Returns
the number of keys in this dictionary.
Description
Returns the number of keys in this dictionary.


 Class EmptyStackException

Class java.util.EmptyStackException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.util.EmptyStackException

public class EmptyStackException
extends RuntimeException

Thrown by methods in the Stack class to indicate that the stack is empty.

See Also:
Stack


 EmptyStackException Members

EmptyStackException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
EmptyStackException() | Constructs a new EmptyStackException with no detail message.


 EmptyStackException.EmptyStackException

EmptyStackException.EmptyStackException

Syntax
public EmptyStackException()
Description
Constructs a new EmptyStackException with no detail message.


 Interface Enumeration

Interface java.util.Enumeration

Interface Members | This Package | All Packages

public interface Enumeration

An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

For example, to print all elements of a vector v:

     for (Enumeration e = v.elements() ; e.hasMoreElements() ;) {
         System.out.println(e.nextElement());

     }

Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable. Enumerations are also used to specify the input streams to a SequenceInputStream.

See Also:
SequenceInputStream, nextElement, Hashtable, elements, keys, Vector, elements


 Enumeration Members

Enumeration Members

Interface Overview | This Package | All Packages

Methods
Name | Description
hasMoreElements() | Tests if this enumeration contains more elements.
nextElement() | Returns the next element of this enumeration.


 Enumeration.hasMoreElements

Enumeration.hasMoreElements

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract boolean hasMoreElements()
Returns
true if this enumeration contains more elements; false otherwise.
Description
Tests if this enumeration contains more elements.


 Enumeration.nextElement

Enumeration.nextElement

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract Object nextElement()
Returns
the next element of this enumeration.
Description
Returns the next element of this enumeration.

Exceptions
NoSuchElementException if no more elements exist.


 Interface EventListener

Interface java.util.EventListener

This Package | All Packages

public interface EventListener

A tagging interface that all event listener interfaces must extend


 Class EventObject

Class java.util.EventObject

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.EventObject

public class EventObject
extends Object
implements Serializable


 EventObject Members

EventObject Members

Class Overview | This Package | All Packages

Fields
Name | Description
source |

Constructors
Name | Description
EventObject(Object) |

Methods
Name | Description
getSource() |
toString() | Returns a string representation of the object.


 EventObject.source

EventObject.source

Syntax
protected transient Object source


 EventObject.EventObject

EventObject.EventObject

Syntax
public EventObject( Object source )


 EventObject.getSource

EventObject.getSource

Syntax
public Object getSource()


 EventObject.toString

EventObject.toString

Syntax
public String toString()
Description
Returns a string representation of the object.

Overrides
toString in class Object


 Class GregorianCalendar

Class java.util.GregorianCalendar

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Calendar
           |
           +----java.util.GregorianCalendar

public class GregorianCalendar
extends Calendar

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world.

The standard (Gregorian) calendar has 2 eras, BC and AD.

This implementation handles a single discontinuity, which corresponds by default to the date the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others). This cutover date may be changed by the caller.

Prior to the institution of the Gregorian calendar, New Year's Day was March 25. To avoid confusion, this calendar always uses January 1. A manual adjustment may be made if desired for dates that are prior to the Gregorian changeover and which fall between January 1 and March 24.

Example:

     // get the supported ids for GMT-08:00 (Pacific Standard Time)
 String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
     // if no ids were returned, something is wrong. get out.
 if (ids.length == 0)
     System.exit(0);
     // begin output
 System.out.println("Current Time");
     // create a Pacific Standard Time time zone
 SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
     // set up rules for daylight savings time
 pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
 pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
     // create a GregorianCalendar with the Pacific Daylight time zone
    // and the current date and time
 Calendar calendar = new GregorianCalendar(pdt);
 Date trialTime = new Date();
 calendar.setTime(trialTime);
    // print out a bunch of interesting things
 System.out.println("ERA: " + calendar.get(Calendar.ERA));
 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
 System.out.println("DATE: " + calendar.get(Calendar.DATE));
 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
 System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
 System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println("DAY_OF_WEEK_IN_MONTH: "
                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
 System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
 System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
 System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
 System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
 System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
 System.out.println("ZONE_OFFSET: "
                    + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
 System.out.println("DST_OFFSET: "
                    + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
 System.out.println("Current Time, with hour reset to 3");
 calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
 calendar.set(Calendar.HOUR, 3);
 System.out.println("ERA: " + calendar.get(Calendar.ERA));
 System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
 System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
 System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
 System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
 System.out.println("DATE: " + calendar.get(Calendar.DATE));
 System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
 System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
 System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println("DAY_OF_WEEK_IN_MONTH: "
                    + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
 System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
 System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
 System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
 System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
 System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
 System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
 System.out.println("ZONE_OFFSET: "
        + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
 System.out.println("DST_OFFSET: "
        + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours

See Also:
Calendar, TimeZone


 GregorianCalendar Members

GregorianCalendar Members

Class Overview | This Package | All Packages

Fields
Name | Description
AD | Useful constant for GregorianCalendar.
BC | Useful constant for GregorianCalendar.

Constructors
Name | Description
GregorianCalendar() | Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
GregorianCalendar(int, int, int) | Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
GregorianCalendar(int, int, int, int, int) | Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(int, int, int, int, int, int) | Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(Locale) | Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone) | Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
GregorianCalendar(TimeZone, Locale) | Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Methods
Name | Description
add(int, int) | Overrides Calendar Date Arithmetic function.
after(Object) | Overrides Calendar Compares the time field records.
before(Object) | Overrides Calendar Compares the time field records.
clone() | Overrides Cloneable
computeFields() | Overrides Calendar Converts UTC as milliseconds to time field values.
computeTime() | Overrides Calendar Converts time field values to UTC as milliseconds.
equals(Object) | Overrides Calendar Compares the time field records.
getGreatestMinimum(int) | Returns highest minimum value for the given field if varies.
getGregorianChange() | Gets the Gregorian Calendar change date.
getLeastMaximum(int) | Returns lowest maximum value for the given field if varies.
getMaximum(int) | Returns maximum value for the given field.
getMinimum(int) | Returns minimum value for the given field.
hashCode() | Override hashCode.
isLeapYear(int) | Determines if the given year is a leap year.
roll(int, boolean) | Overrides Calendar Time Field Rolling function.
setGregorianChange(Date) | Sets the GregorianCalendar change date.


 GregorianCalendar.AD

GregorianCalendar.AD

Syntax
public static final int AD
Description
Useful constant for GregorianCalendar.


 GregorianCalendar.BC

GregorianCalendar.BC

Syntax
public static final int BC
Description
Useful constant for GregorianCalendar.


 GregorianCalendar.GregorianCalendar

GregorianCalendar.GregorianCalendar

Syntax 1
public GregorianCalendar()
Description
Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.

Syntax 2
public GregorianCalendar( TimeZone zone )
Parameters
zone
the given time zone.
Description
Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.

Syntax 3
public GregorianCalendar( Locale aLocale )
Parameters
aLocale
the given locale.
Description
Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.

Syntax 4
public GregorianCalendar( TimeZone zone, Locale aLocale )
Parameters
zone
the given time zone.
aLocale
the given locale.
Description
Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Syntax 5
public GregorianCalendar( int year, int month, int date )
Parameters
year
the value used to set the YEAR time field in the calendar.
month
the value used to set the MONTH time field in the calendar. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field in the calendar.
Description
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

Syntax 6
public GregorianCalendar( int year, int month, int date, int hour, int minute )
Parameters
year
the value used to set the YEAR time field in the calendar.
month
the value used to set the MONTH time field in the calendar. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field in the calendar.
hour
the value used to set the HOUR_OF_DAY time field in the calendar.
minute
the value used to set the MINUTE time field in the calendar.
Description
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.

Syntax 7
public GregorianCalendar( int year, int month, int date, int hour, int minute, int second )
Parameters
year
the value used to set the YEAR time field in the calendar.
month
the value used to set the MONTH time field in the calendar. Month value is 0-based. e.g., 0 for January.
date
the value used to set the DATE time field in the calendar.
hour
the value used to set the HOUR_OF_DAY time field in the calendar.
minute
the value used to set the MINUTE time field in the calendar.
second
the value used to set the SECOND time field in the calendar.
Description
Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.


 GregorianCalendar.add

GregorianCalendar.add

Syntax
public void add( int field, int amount )
Parameters
field
the time field.
amount
the amount of date or time to be added to the field.
Description
Overrides Calendar Date Arithmetic function. Adds the specified (signed) amount of time to the given time field, based on the calendar's rules.

Exceptions
IllegalArgumentException if an unknown field is given.
Overrides
add in class Calendar


 GregorianCalendar.after

GregorianCalendar.after

Syntax
public boolean after( Object when )
Description
Overrides Calendar Compares the time field records. Equivalent to comparing result of conversion to UTC. Please see Calendar.after for descriptions on parameters and the return value.

Overrides
after in class Calendar


 GregorianCalendar.before

GregorianCalendar.before

Syntax
public boolean before( Object when )
Description
Overrides Calendar Compares the time field records. Equivalent to comparing result of conversion to UTC. Please see Calendar.before for descriptions on parameters and the return value.

Overrides
before in class Calendar


 GregorianCalendar.clone

GregorianCalendar.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Calendar


 GregorianCalendar.computeFields

GregorianCalendar.computeFields

Syntax
protected void computeFields()
Description
Overrides Calendar Converts UTC as milliseconds to time field values.

Overrides
computeFields in class Calendar


 GregorianCalendar.computeTime

GregorianCalendar.computeTime

Syntax
protected void computeTime()
Description
Overrides Calendar Converts time field values to UTC as milliseconds.

Exceptions
IllegalArgumentException if an unknown field is given.
Overrides
computeTime in class Calendar


 GregorianCalendar.equals

GregorianCalendar.equals

Syntax
public boolean equals( Object obj )
Description
Overrides Calendar Compares the time field records. Equivalent to comparing result of conversion to UTC. Please see Calendar.equals for descriptions on parameters and the return value.

Overrides
equals in class Calendar


 GregorianCalendar.getGreatestMinimum

GregorianCalendar.getGreatestMinimum

Syntax
public int getGreatestMinimum( int field )
Description
Returns highest minimum value for the given field if varies. Otherwise same as getMinimum(). For Gregorian, no difference. Please see Calendar.getGreatestMinimum for descriptions on parameters and the return value.

Overrides
getGreatestMinimum in class Calendar


 GregorianCalendar.getGregorianChange

GregorianCalendar.getGregorianChange

Syntax
public final Date getGregorianChange()
Returns
the Gregorian cutover time for this calendar.
Description
Gets the Gregorian Calendar change date. This is the point when the switch from Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October 15, 1582. Previous to this time and date will be Julian dates.


 GregorianCalendar.getLeastMaximum

GregorianCalendar.getLeastMaximum

Syntax
public int getLeastMaximum( int field )
Description
Returns lowest maximum value for the given field if varies. Otherwise same as getMaximum(). For Gregorian DAY_OF_MONTH, 28 Please see Calendar.getLeastMaximum for descriptions on parameters and the return value.

Overrides
getLeastMaximum in class Calendar


 GregorianCalendar.getMaximum

GregorianCalendar.getMaximum

Syntax
public int getMaximum( int field )
Description
Returns maximum value for the given field. e.g. for Gregorian DAY_OF_MONTH, 31 Please see Calendar.getMaximum for descriptions on parameters and the return value.

Overrides
getMaximum in class Calendar


 GregorianCalendar.getMinimum

GregorianCalendar.getMinimum

Syntax
public int getMinimum( int field )
Description
Returns minimum value for the given field. e.g. for Gregorian DAY_OF_MONTH, 1 Please see Calendar.getMinimum for descriptions on parameters and the return value.

Overrides
getMinimum in class Calendar


 GregorianCalendar.hashCode

GregorianCalendar.hashCode

Syntax
public synchronized int hashCode()
Description
Override hashCode. Generates the hash code for the GregorianCalendar object

Overrides
hashCode in class Object


 GregorianCalendar.isLeapYear

GregorianCalendar.isLeapYear

Syntax
public boolean isLeapYear( int year )
Parameters
year
the given year.
Returns
true if the given year is a leap year; false otherwise.
Description
Determines if the given year is a leap year. Returns true if the given year is a leap year.


 GregorianCalendar.roll

GregorianCalendar.roll

Syntax
public void roll( int field, boolean up )
Parameters
field
the time field.
up
Indicates if rolling up or rolling down the field value.
Description
Overrides Calendar Time Field Rolling function. Rolls (up/down) a single unit of time on the given time field.

Exceptions
IllegalArgumentException if an unknown field value is given.
Overrides
roll in class Calendar


 GregorianCalendar.setGregorianChange

GregorianCalendar.setGregorianChange

Syntax
public void setGregorianChange( Date date )
Parameters
date
the given Gregorian cutover date.
Description
Sets the GregorianCalendar change date. This is the point when the switch from Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October 15, 1582. Previous to this time and date will be Julian dates.


 Class Hashtable

Class java.util.Hashtable

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Dictionary
           |
           +----java.util.Hashtable

public class Hashtable
extends Dictionary
implements Cloneable, Serializable

This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

An instance of Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.

If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

     Hashtable numbers = new Hashtable();
     numbers.put("one", new Integer(1));
     numbers.put("two", new Integer(2));
     numbers.put("three", new Integer(3));

To retrieve a number, use the following code:

     Integer n = (Integer)numbers.get("two");
     if (n != null) {
         System.out.println("two = " + n);
     }

See Also:
equals, hashCode, rehash


 Hashtable Members

Hashtable Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Hashtable() | Constructs a new, empty hashtable with a default capacity and load factor.
Hashtable(int) | Constructs a new, empty hashtable with the specified initial capacity and default load factor.
Hashtable(int, float) | Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.

Methods
Name | Description
clear() | Clears this hashtable so that it contains no keys.
clone() | Creates a shallow copy of this hashtable.
contains(Object) | Tests if some key maps into the specified value in this hashtable.
containsKey(Object) | Tests if the specified object is a key in this hashtable.
elements() | Returns an enumeration of the values in this hashtable.
get(Object) | Returns the value to which the specified key is mapped in this hashtable.
isEmpty() | Tests if this hashtable maps no keys to values.
keys() | Returns an enumeration of the keys in this hashtable.
put(Object, Object) | Maps the specified key to the specified value in this hashtable.
rehash() | Rehashes the contents of the hashtable into a hashtable with a larger capacity.
remove(Object) | Removes the key (and its corresponding value) from this hashtable.
size() | Returns the number of keys in this hashtable.
toString() | Returns a rather long string representation of this hashtable.


 Hashtable.Hashtable

Hashtable.Hashtable

Syntax 1
public Hashtable( int initialCapacity, float loadFactor )
Parameters
initialCapacity
the initial capacity of the hashtable.
loadFactor
a number between 0.0 and 1.0.
Description
Constructs a new, empty hashtable with the specified initial capacity and the specified load factor.

Exceptions
IllegalArgumentException if the initial capacity is less than or equal to zero, or if the load factor is less than or equal to zero.

Syntax 2
public Hashtable( int initialCapacity )
Parameters
initialCapacity
the initial capacity of the hashtable.
Description
Constructs a new, empty hashtable with the specified initial capacity and default load factor.

Syntax 3
public Hashtable()
Description
Constructs a new, empty hashtable with a default capacity and load factor.


 Hashtable.clear

Hashtable.clear

Syntax
public synchronized void clear()
Description
Clears this hashtable so that it contains no keys.


 Hashtable.clone

Hashtable.clone

Syntax
public synchronized Object clone()
Returns
a clone of the hashtable.
Description
Creates a shallow copy of this hashtable. The keys and values themselves are not cloned. This is a relatively expensive operation.

Overrides
clone in class Object


 Hashtable.contains

Hashtable.contains

Syntax
public synchronized boolean contains( Object value )
Parameters
value
a value to search for.
Returns
true if some key maps to the value argument in this hashtable; false otherwise.
Description
Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method.

Exceptions
NullPointerException if the value is null.
See Also
containsKey


 Hashtable.containsKey

Hashtable.containsKey

Syntax
public synchronized boolean containsKey( Object key )
Parameters
key
possible key.
Returns
true if the specified object is a key in this hashtable; false otherwise.
Description
Tests if the specified object is a key in this hashtable.

See Also
contains


 Hashtable.elements

Hashtable.elements

Syntax
public synchronized Enumeration elements()
Returns
an enumeration of the values in this hashtable.
Description
Returns an enumeration of the values in this hashtable. Use the Enumeration methods on the returned object to fetch the elements sequentially.

Overrides
elements in class Dictionary
See Also
Enumeration, keys


 Hashtable.get

Hashtable.get

Syntax
public synchronized Object get( Object key )
Parameters
key
a key in the hashtable.
Returns
the value to which the key is mapped in this hashtable; null if the key is not mapped to any value in this hashtable.
Description
Returns the value to which the specified key is mapped in this hashtable.

Overrides
get in class Dictionary
See Also
put


 Hashtable.isEmpty

Hashtable.isEmpty

Syntax
public boolean isEmpty()
Returns
true if this hashtable maps no keys to values; false otherwise.
Description
Tests if this hashtable maps no keys to values.

Overrides
isEmpty in class Dictionary


 Hashtable.keys

Hashtable.keys

Syntax
public synchronized Enumeration keys()
Returns
an enumeration of the keys in this hashtable.
Description
Returns an enumeration of the keys in this hashtable.

Overrides
keys in class Dictionary
See Also
Enumeration, elements


 Hashtable.put

Hashtable.put

Syntax
public synchronized Object put( Object key, Object value )
Parameters
key
the hashtable key.
value
the value.
Returns
the previous value of the specified key in this hashtable, or null if it did not have one.
Description
Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null.

The value can be retrieved by calling the get method with a key that is equal to the original key.

Exceptions
NullPointerException if the key or value is null.
Overrides
put in class Dictionary
See Also
equals, get


 Hashtable.rehash

Hashtable.rehash

Syntax
protected void rehash()
Description
Rehashes the contents of the hashtable into a hashtable with a larger capacity. This method is called automatically when the number of keys in the hashtable exceeds this hashtable's capacity and load factor.


 Hashtable.remove

Hashtable.remove

Syntax
public synchronized Object remove( Object key )
Parameters
key
the key that needs to be removed.
Returns
the value to which the key had been mapped in this hashtable, or null if the key did not have a mapping.
Description
Removes the key (and its corresponding value) from this hashtable. This method does nothing if the key is not in the hashtable.

Overrides
remove in class Dictionary


 Hashtable.size

Hashtable.size

Syntax
public int size()
Returns
the number of keys in this hashtable.
Description
Returns the number of keys in this hashtable.

Overrides
size in class Dictionary


 Hashtable.toString

Hashtable.toString

Syntax
public synchronized String toString()
Returns
a string representation of this hashtable.
Description
Returns a rather long string representation of this hashtable.

Overrides
toString in class Object


 Class ListResourceBundle

Class java.util.ListResourceBundle

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.ResourceBundle
           |
           +----java.util.ListResourceBundle

public abstract class ListResourceBundle
extends ResourceBundle

ListResourceBundle is a abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list. See ResourceBundle for more information about resource bundles in general.

Subclasses must override getContents and provide an array, where each item in the array is a pair of objects. The first element of each pair is a String key, and the second is the value associated with that key.

In the following example, the keys are of the form "s1"... The actual keys are entirely up to your choice, so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive. MyResource is the default version of the bundle family, and MyResource_fr is the french version:

 //====================
 class MyResource extends ListResourceBundle {
     public Object[][] getContents() {
         return contents;
     }
     static final Object[][] contents = {
     // LOCALIZE THIS
         {"s1", "3"},		// starting value in choice field
         {"s2", "MyDisk"},	// starting value in string field
         {"s3", "3 Mar 96"},	// starting value in date field
         {"s4", "The disk '{1}' contained {0} on {2}."},	// initial pattern
         {"s5", "0"},		// first choice number
         {"s6", "no files"},	// first choice value
         {"s7", "1"},		// second choice number
         {"s8", "one file"},	// second choice value
         {"s9", "2"},		// third choice number
         {"s10", "{0}|3 files"},	// third choice value
         {"s11", "format threw an exception: {0}"},	// generic exception message
         {"s12", "ERROR"},	// what to show in field in case of error
         {"s14", "Result"},	// label for formatted stuff
         {"s13", "Dialog"},	// standard font
         {"s15", "Pattern"},	// label for standard pattern
         {"s16", new Dimension(1,5)}	// real object, not just string
     // END OF MATERIAL TO LOCALIZE
     };
 }
 //====================
 class MyResource_fr  extends ListResourceBundle {
     public Object[][] getContents() {
         return contents;
}
     static final Object[][] contents = {
     // LOCALIZE THIS
         {"s1", "3"},		// starting value in choice field
         {"s2", "MonDisk"},	// starting value in string field
         {"s3", "3 Mar 96"},	// starting value in date field
         {"s4", "Le disk '{1}' a {0} a {2}."},	// initial pattern
         {"s5", "0"},		// first choice number
         {"s6", "pas de files"},	// first choice value
         {"s7", "1"},		// second choice number
         {"s8", "une file"},	// second choice value
         {"s9", "2"},		// third choice number
         {"s10", "{0}|3 files"},	// third choice value
         {"s11", "Le format a jete une exception: {0}"},	// generic exception message
         {"s12", "ERROR"},	// what to show in field in case of error
         {"s14", "Resulte"},	// label for formatted stuff
         {"s13", "Dialogue"},	// standard font
         {"s15", "Pattern"},	// label for standard pattern
         {"s16", new Dimension(1,3)}	// real object, not just string
     // END OF MATERIAL TO LOCALIZE
     };
 }

See Also:
ResourceBundle, PropertyResourceBundle


 ListResourceBundle Members

ListResourceBundle Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ListResourceBundle() |

Methods
Name | Description
getContents() | See class description.
getKeys() | Implementation of ResourceBundle.getKeys.
handleGetObject(String) | Override of ResourceBundle, same semantics


 ListResourceBundle.ListResourceBundle

ListResourceBundle.ListResourceBundle

Syntax
public ListResourceBundle()


 ListResourceBundle.getContents

ListResourceBundle.getContents

Syntax
protected abstract Object[][] getContents()
Description
See class description.


 ListResourceBundle.getKeys

ListResourceBundle.getKeys

Syntax
public Enumeration getKeys()
Description
Implementation of ResourceBundle.getKeys.

Overrides
getKeys in class ResourceBundle


 ListResourceBundle.handleGetObject

ListResourceBundle.handleGetObject

Syntax
public final Object handleGetObject( String key )
Description
Override of ResourceBundle, same semantics

Overrides
handleGetObject in class ResourceBundle


 Class Locale

Class java.util.Locale

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Locale

public final class Locale
extends Object
implements Cloneable, Serializable

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.

You create a Locale object using one of the two constructors in this class:

 Locale(String language, String country)
 Locale(String language, String country, String variant)
The first argument to both constructors is a valid ISO Language Code. These codes are the lower-case two-letter codes as defined by ISO-639. You can find a full list of these codes at a number of sites, such as:
http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt

The second argument to both constructors is a valid ISO Country Code. These codes are the upper-case two-letter codes as defined by ISO-3166. You can find a full list of these codes at a number of sites, such as:
http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html

The second constructor requires a third argument--the Variant. The Variant codes are vendor and browser-specific. For example, use WIN for Windows, MAC for Macintosh, and POSIX for POSIX. Where there are two variants, separate them with an underscore, and put the most important one first. For example, a Traditional Spanish collation might be referenced, with "ES", "ES", "Traditional_WIN".

Because a Locale object is just an identifier for a region, no validity check is performed when you construct a Locale. If you want to see whether particular resources are available for the Locale you construct, you must query those resources. For example, ask the NumberFormat for the locales it supports using its getAvailableLocales method.
Note: When you ask for a resource for a particular locale, you get back the best available match, not necessarily precisely what you asked for. For more information, look at ResourceBundle.

The Locale class provides a number of convenient constants that you can use to create Locale objects for commonly used locales. For example, the following creates a Locale object for the United States:

 Locale.US

Once you've created a Locale you can query it for information about itself. Use getCountry to get the ISO Country Code and getLanguage to get the ISO Language Code. You can use getDisplayCountry to get the name of the country suitable for displaying to the user. Similarly, you can use getDisplayLanguage to get the name of the language suitable for displaying to the user. Interestingly, the getDisplayXXX methods are themselves locale-sensitive and have two versions: one that uses the default locale and one that uses the locale specified as an argument.

The JDK provides a number of classes that perform locale-sensitive operations. For example, the NumberFormat class formats numbers, currency, or percentages in a locale-sensitive manner. Classes such as NumberFormat have a number of convenience methods for creating a default object of that type. For example, the NumberFormat class provides these three convenience methods for creating a default NumberFormat object:

 NumberFormat.getInstance()
 NumberFormat.getCurrencyInstance()
 NumberFormat.getPercentInstance()
These methods have two variants; one with an explicit locale and one without; the latter using the default locale.
 NumberFormat.getInstance(myLocale)
 NumberFormat.getCurrencyInstance(myLocale)
 NumberFormat.getPercentInstance(myLocale)
A Locale is the mechanism for identifying the kind of object (NumberFormat) that you would like to get. The locale is just a mechanism for identifying objects, not a container for the objects themselves.

Each class that performs locale-sensitive operations allows you to get all the available objects of that type. You can sift through these objects by language, country, or variant, and use the display names to present a menu to the user. For example, you can create a menu of all the collation objects suitable for a given language. Such classes must implement these three class methods:

 public static Locale[] getAvailableLocales()
 public static String getDisplayName(Locale objectLocale,
                                     Locale displayLocale)
 public static final String getDisplayName(Locale objectLocale)
     // getDisplayName will throw MissingResourceException if the locale
     // is not one of the available locales.

See Also:
ResourceBundle, Format, NumberFormat, Collation


 Locale Members

Locale Members

Class Overview | This Package | All Packages

Fields
Name | Description
CANADA | Useful constant for country.
CANADA_FRENCH | Useful constant for country.
CHINA | Useful constant for country.
CHINESE | Useful constant for language.
ENGLISH | Useful constant for language.
FRANCE | Useful constant for country.
FRENCH | Useful constant for language.
GERMAN | Useful constant for language.
GERMANY | Useful constant for country.
ITALIAN | Useful constant for language.
ITALY | Useful constant for country.
JAPAN | Useful constant for country.
JAPANESE | Useful constant for language.
KOREA | Useful constant for country.
KOREAN | Useful constant for language.
PRC | Useful constant for country.
SIMPLIFIED_CHINESE | Useful constant for language.
TAIWAN | Useful constant for region.
TRADITIONAL_CHINESE | Useful constant for language.
UK | Useful constant for country.
US | Useful constant for country.

Constructors
Name | Description
Locale(String, String) | Construct a locale from language, country.
Locale(String, String, String) | Construct a locale from language, country, variant.

Methods
Name | Description
clone() | Overrides Cloneable
equals(Object) | Compares two Objects for equality.
getCountry() | Getter for programmatic name of field, an uppercased two-letter ISO-3166 code.
getDefault() | Common method of getting the current default Locale.
getDisplayCountry() | Getter for display of field to user.
getDisplayCountry(Locale) | Getter for display of field to user.
getDisplayLanguage() | Getter for display of field to user.
getDisplayLanguage(Locale) | Getter for display of field to user.
getDisplayName() | Getter for display of the entire locale to user.
getDisplayName(Locale) | Getter for display of the entire locale to user.
getDisplayVariant() | Getter for display of field to user.
getDisplayVariant(Locale) | Getter for display of field to user If the localized name is not found, returns the variant code.
getISO3Country() | Getter for the three-letter ISO country abbreviation of the locale.
getISO3Language() | Getter for the three-letter ISO language abbreviation of the locale.
getLanguage() | Getter for programmatic name of field, an lowercased two-letter ISO-639 code.
getVariant() | Getter for programmatic name of field.
hashCode() | Override hashCode.
setDefault(Locale) | Sets the default.
toString() | Getter for the programmatic name of the entire locale, with the language, country and variant separated by underbars.


 Locale.CANADA

Locale.CANADA

Syntax
public static final Locale CANADA
Description
Useful constant for country.


 Locale.CANADA_FRENCH

Locale.CANADA_FRENCH

Syntax
public static final Locale CANADA_FRENCH
Description
Useful constant for country.


 Locale.CHINA

Locale.CHINA

Syntax
public static final Locale CHINA
Description
Useful constant for country.


 Locale.CHINESE

Locale.CHINESE

Syntax
public static final Locale CHINESE
Description
Useful constant for language.


 Locale.ENGLISH

Locale.ENGLISH

Syntax
public static final Locale ENGLISH
Description
Useful constant for language.


 Locale.FRANCE

Locale.FRANCE

Syntax
public static final Locale FRANCE
Description
Useful constant for country.


 Locale.FRENCH

Locale.FRENCH

Syntax
public static final Locale FRENCH
Description
Useful constant for language.


 Locale.GERMAN

Locale.GERMAN

Syntax
public static final Locale GERMAN
Description
Useful constant for language.


 Locale.GERMANY

Locale.GERMANY

Syntax
public static final Locale GERMANY
Description
Useful constant for country.


 Locale.ITALIAN

Locale.ITALIAN

Syntax
public static final Locale ITALIAN
Description
Useful constant for language.


 Locale.ITALY

Locale.ITALY

Syntax
public static final Locale ITALY
Description
Useful constant for country.


 Locale.JAPAN

Locale.JAPAN

Syntax
public static final Locale JAPAN
Description
Useful constant for country.


 Locale.JAPANESE

Locale.JAPANESE

Syntax
public static final Locale JAPANESE
Description
Useful constant for language.


 Locale.KOREA

Locale.KOREA

Syntax
public static final Locale KOREA
Description
Useful constant for country.


 Locale.KOREAN

Locale.KOREAN

Syntax
public static final Locale KOREAN
Description
Useful constant for language.


 Locale.PRC

Locale.PRC

Syntax
public static final Locale PRC
Description
Useful constant for country.


 Locale.SIMPLIFIED_CHINESE

Locale.SIMPLIFIED_CHINESE

Syntax
public static final Locale SIMPLIFIED_CHINESE
Description
Useful constant for language.


 Locale.TAIWAN

Locale.TAIWAN

Syntax
public static final Locale TAIWAN
Description
Useful constant for region.


 Locale.TRADITIONAL_CHINESE

Locale.TRADITIONAL_CHINESE

Syntax
public static final Locale TRADITIONAL_CHINESE
Description
Useful constant for language.


 Locale.UK

Locale.UK

Syntax
public static final Locale UK
Description
Useful constant for country.


 Locale.US

Locale.US

Syntax
public static final Locale US
Description
Useful constant for country.


 Locale.Locale

Locale.Locale

Syntax 1
public Locale( String language, String country, String variant )
Parameters
language
lowercase two-letter ISO-639 code.
country
uppercase two-letter ISO-3166 code.
variant
vendor and browser specific code. See class description.
Description
Construct a locale from language, country, variant.

Syntax 2
public Locale( String language, String country )
Parameters
language
lowercase two-letter ISO-639 code.
country
uppercase two-letter ISO-3166 code.
Description
Construct a locale from language, country.


 Locale.clone

Locale.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Object


 Locale.equals

Locale.equals

Syntax
public boolean equals( Object obj )
Description
Compares two Objects for equality.

Overrides
equals in class Object


 Locale.getCountry

Locale.getCountry

Syntax
public String getCountry()
Description
Getter for programmatic name of field, an uppercased two-letter ISO-3166 code.

See Also
getDisplayCountry


 Locale.getDefault

Locale.getDefault

Syntax
public static synchronized Locale getDefault()
Description
Common method of getting the current default Locale. Used for the presentation: menus, dialogs, etc. Generally set once when your applet or application is initialized, then never reset. (If you do reset the default locale, you probably want to reload your GUI, so that the change is reflected in your interface.)

More advanced programs will allow users to use different locales for different fields, e.g. in a spreadsheet.
Note that the initial setting will match the host system.


 Locale.getDisplayCountry

Locale.getDisplayCountry

Syntax 1
public final String getDisplayCountry()
Description
Getter for display of field to user. If the localized name is not found, returns the ISO code. The default locale is used for the presentation language.

Syntax 2
public String getDisplayCountry( Locale inLocale )
Parameters
inLocale
specifies the desired user language.
Description
Getter for display of field to user. If the localized name is not found, returns the ISO code.


 Locale.getDisplayLanguage

Locale.getDisplayLanguage

Syntax 1
public final String getDisplayLanguage()
Description
Getter for display of field to user. If the localized name is not found, returns the ISO code. The desired user language is from the default locale.

Syntax 2
public String getDisplayLanguage( Locale inLocale )
Parameters
inLocale
specifies the desired user language.
Description
Getter for display of field to user. If the localized name is not found, returns the ISO codes. Example: "English (UK)", "Deutch", "Germany"


 Locale.getDisplayName

Locale.getDisplayName

Syntax 1
public final String getDisplayName()
Description
Getter for display of the entire locale to user. If the localized name is not found, uses the ISO codes. The default locale is used for the presentation language.

Syntax 2
public String getDisplayName( Locale inLocale )
Parameters
inLocale
specifies the desired user language.
Description
Getter for display of the entire locale to user. If the localized name is not found, uses the ISO codes


 Locale.getDisplayVariant

Locale.getDisplayVariant

Syntax 1
public final String getDisplayVariant()
Description
Getter for display of field to user. If the localized name is not found, returns the variant code. The default locale is used for the presentation language.

Syntax 2
public String getDisplayVariant( Locale inLocale )
Parameters
inLocale
specifies the desired user language.
Description
Getter for display of field to user If the localized name is not found, returns the variant code.


 Locale.getISO3Country

Locale.getISO3Country

Syntax
public String getISO3Country() throws MissingResourceException
Description
Getter for the three-letter ISO country abbreviation of the locale.

Exceptions
MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.


 Locale.getISO3Language

Locale.getISO3Language

Syntax
public String getISO3Language() throws MissingResourceException
Description
Getter for the three-letter ISO language abbreviation of the locale.

Exceptions
MissingResourceException Throws MissingResourceException if the three-letter language abbreviation is not available for this locale.


 Locale.getLanguage

Locale.getLanguage

Syntax
public String getLanguage()
Description
Getter for programmatic name of field, an lowercased two-letter ISO-639 code.

See Also
getDisplayLanguage


 Locale.getVariant

Locale.getVariant

Syntax
public String getVariant()
Description
Getter for programmatic name of field.

See Also
getDisplayVariant


 Locale.hashCode

Locale.hashCode

Syntax
public synchronized int hashCode()
Description
Override hashCode. Since Locales are often used in hashtables, caches the value for speed.

Overrides
hashCode in class Object


 Locale.setDefault

Locale.setDefault

Syntax
public static synchronized void setDefault( Locale newLocale )
Parameters
newLocale
Locale to set to.
Description
Sets the default. Normally set once at the beginning of applet or application, then never reset. setDefault does not reset the host locale.


 Locale.toString

Locale.toString

Syntax
public final String toString()
Description
Getter for the programmatic name of the entire locale, with the language, country and variant separated by underbars. If a field is missing, at most one underbar will occur. Example: "EN", "DE_DE", "EN_US_WIN", "DE_POSIX", "FR_MAC"

Overrides
toString in class Object
See Also
getDisplayName


 Class MissingResourceException

Class java.util.MissingResourceException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.util.MissingResourceException

public class MissingResourceException
extends RuntimeException

Signals that a resource is missing.

See Also:
Exception, ResourceBundle


 MissingResourceException Members

MissingResourceException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
MissingResourceException(String, String, String) | Constructs a MissingResourceException with the specified information.

Methods
Name | Description
getClassName() | Gets parameter passed by constructor.
getKey() | Gets parameter passed by constructor.


 MissingResourceException.MissingResourceException

MissingResourceException.MissingResourceException

Syntax
public MissingResourceException( String s, String className, String key )
Parameters
s
the detail message
classname
the name of the resource class
key
the key for the missing resource.
Description
Constructs a MissingResourceException with the specified information. A detail message is a String that describes this particular exception.


 MissingResourceException.getClassName

MissingResourceException.getClassName

Syntax
public String getClassName()
Description
Gets parameter passed by constructor.


 MissingResourceException.getKey

MissingResourceException.getKey

Syntax
public String getKey()
Description
Gets parameter passed by constructor.


 Class NoSuchElementException

Class java.util.NoSuchElementException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.lang.RuntimeException
                           |
                           +----java.util.NoSuchElementException

public class NoSuchElementException
extends RuntimeException

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

See Also:
Enumeration, nextElement


 NoSuchElementException Members

NoSuchElementException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
NoSuchElementException() | Constructs a NoSuchElementException with no detail message.
NoSuchElementException(String) | Constructs a NoSuchElementException with the specified detail message.


 NoSuchElementException.NoSuchElementException

NoSuchElementException.NoSuchElementException

Syntax 1
public NoSuchElementException()
Description
Constructs a NoSuchElementException with no detail message.

Syntax 2
public NoSuchElementException( String s )
Parameters
s
the detail message.
Description
Constructs a NoSuchElementException with the specified detail message.


 Class Observable

Class java.util.Observable

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Observable

public class Observable
extends Object

This class represents an observable object, or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed.

An observable object can have one or more observers. After an observable instance changes, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

See Also:
notifyObservers, notifyObservers, Observer, update


 Observable Members

Observable Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Observable() | Construct an Observable with zero Observers

Methods
Name | Description
addObserver(Observer) | Adds an observer to the set of observers for this object.
clearChanged() | Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change.
countObservers() | Returns the number of observers of this object.
deleteObserver(Observer) | Deletes an observer from the set of observers of this object.
deleteObservers() | Clears the observer list so that this object no longer has any observers.
hasChanged() | Tests if this object has changed.
notifyObservers() | If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.
notifyObservers(Object) | If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.
setChanged() | Indicates that this object has changed.


 Observable.Observable

Observable.Observable

Syntax
public Observable()
Description
Construct an Observable with zero Observers


 Observable.addObserver

Observable.addObserver

Syntax
public synchronized void addObserver( Observer o )
Parameters
o
an observer to be added.
Description
Adds an observer to the set of observers for this object.


 Observable.clearChanged

Observable.clearChanged

Syntax
protected synchronized void clearChanged()
Description
Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change. This method is called automatically by the notifyObservers methods.

See Also
notifyObservers, notifyObservers


 Observable.countObservers

Observable.countObservers

Syntax
public synchronized int countObservers()
Returns
the number of observers of this object.
Description
Returns the number of observers of this object.


 Observable.deleteObserver

Observable.deleteObserver

Syntax
public synchronized void deleteObserver( Observer o )
Parameters
o
the observer to be deleted.
Description
Deletes an observer from the set of observers of this object.


 Observable.deleteObservers

Observable.deleteObservers

Syntax
public synchronized void deleteObservers()
Description
Clears the observer list so that this object no longer has any observers.


 Observable.hasChanged

Observable.hasChanged

Syntax
public synchronized boolean hasChanged()
Returns
true if the setChanged method has been called more recently than the clearChanged method on this object; false otherwise.
Description
Tests if this object has changed.

See Also
clearChanged, setChanged


 Observable.notifyObservers

Observable.notifyObservers

Syntax 1
public void notifyObservers()
Description
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

Each observer has its update method called with two arguments: this observable object and null.

See Also
clearChanged, hasChanged, update

Syntax 2
public void notifyObservers( Object arg )
Parameters
arg
any object.
Description
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

Each observer has its update method called with two arguments: this observable object and the arg argument.

See Also
clearChanged, hasChanged, update


 Observable.setChanged

Observable.setChanged

Syntax
protected synchronized void setChanged()
Description
Indicates that this object has changed.


 Interface Observer

Interface java.util.Observer

Interface Members | This Package | All Packages

public interface Observer

A class can implement the Observer interface when it wants to be informed of changes in observable objects.

See Also:
Observable


 Observer Members

Observer Members

Interface Overview | This Package | All Packages

Methods
Name | Description
update(Observable, Object) | This method is called whenever the observed object is changed.


 Observer.update

Observer.update

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void update( Observable o, Object arg )
Parameters
o
the observable object.
arg
an argument passed to the notifyObservers method.
Description
This method is called whenever the observed object is changed. An application calls an observable object's notifyObservers method to have all the object's observers notified of the change.


 Class Properties

Class java.util.Properties

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Dictionary
           |
           +----java.util.Hashtable
                   |
                   +----java.util.Properties

public class Properties
extends Hashtable

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list.


 Properties Members

Properties Members

Class Overview | This Package | All Packages

Fields
Name | Description
defaults | A property list that contains default values for any keys not found in this property list.

Constructors
Name | Description
Properties() | Creates an empty property list with no default values.
Properties(Properties) | Creates an empty property list with the specified defaults.

Methods
Name | Description
getProperty(String) | Searches for the property with the specified key in this property list.
getProperty(String, String) | Searches for the property with the specified key in this property list.
list(PrintStream) | Prints this property list out to the specified output stream.
list(PrintWriter) | Prints this property list out to the specified output stream.
load(InputStream) | Reads a property list from an input stream.
propertyNames() | Returns an enumeration of all the keys in this property list, including the keys in the default property list.
save(OutputStream, String) | Stores this property list to the specified output stream.


 Properties.defaults

Properties.defaults

Syntax
protected Properties defaults
Description
A property list that contains default values for any keys not found in this property list.


 Properties.Properties

Properties.Properties

Syntax 1
public Properties()
Description
Creates an empty property list with no default values.

Syntax 2
public Properties( Properties defaults )
Parameters
defaults
the defaults.
Description
Creates an empty property list with the specified defaults.


 Properties.getProperty

Properties.getProperty

Syntax 1
public String getProperty( String key )
Parameters
key
the property key.
Returns
the value in this property list with the specified key value.
Description
Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns null if the property is not found.

See Also
defaults

Syntax 2
public String getProperty( String key, String defaultValue )
Parameters
key
the hashtable key.
defaultValue
a default value.
Returns
the value in this property list with the specified key value.
Description
Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns the default value argument if the property is not found.

See Also
defaults


 Properties.list

Properties.list

Syntax 1
public void list( PrintStream out )
Parameters
out
an output stream.
Description
Prints this property list out to the specified output stream. This method is useful for debugging.

Syntax 2
public void list( PrintWriter out )
Parameters
out
an output stream.
Description
Prints this property list out to the specified output stream. This method is useful for debugging.


 Properties.load

Properties.load

Syntax
public synchronized void load( InputStream in ) throws IOException
Parameters
in
the input stream.
Description
Reads a property list from an input stream.

Exceptions
IOException if an error occurred when reading from the input stream.


 Properties.propertyNames

Properties.propertyNames

Syntax
public Enumeration propertyNames()
Returns
an enumeration of all the keys in this property list, including the keys in the default property list.
Description
Returns an enumeration of all the keys in this property list, including the keys in the default property list.

See Also
Enumeration, defaults


 Properties.save

Properties.save

Syntax
public synchronized void save( OutputStream out, String header )
Parameters
out
an output stream.
header
a description of the property list.
Description
Stores this property list to the specified output stream. The string header is printed as a comment at the beginning of the stream.


 Class PropertyResourceBundle

Class java.util.PropertyResourceBundle

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.ResourceBundle
           |
           +----java.util.PropertyResourceBundle

public class PropertyResourceBundle
extends ResourceBundle

PropertyResourceBundle is an abstract subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file. See ResourceBundle for more information about resource bundles in general.

The property file contains the keys that you use in your source code in calls to ResourceBundle.getString and similar methods, and their corresponding values, etc. The name of the property file indicates the resource bundle's family and locale.

In the following example, the keys are of the form "s1"... The actual keys are entirely up to your choice, so long as they are the same as the keys you use in your program to retrieve the objects from the bundle. Keys are case-sensitive.

 s1=3
 s2=MeinDisk
 s3=3 Mar 96
 s4=Der disk '{1}' a {0} a {2}.
 s5=0
 s6=keine Datein
 s7=1
 s8=ein Datei
 s9=2
 s10={0}|3 Datein
 s11=Der Format worf ein Exception: {0}
 s12=ERROR
 s14=Resulte
 s13=Dialogue
 s15=Pattern
 s16=1,3

See Also:
ResourceBundle, ListResourceBundle


 PropertyResourceBundle Members

PropertyResourceBundle Members

Class Overview | This Package | All Packages

Constructors
Name | Description
PropertyResourceBundle(InputStream) | Creates a property resource

Methods
Name | Description
getKeys() | Implementation of ResourceBundle.getKeys.
handleGetObject(String) | Override of ResourceBundle, same semantics


 PropertyResourceBundle.PropertyResourceBundle

PropertyResourceBundle.PropertyResourceBundle

Syntax
public PropertyResourceBundle( InputStream stream ) throws IOException
Parameters
file
property file to read from.
Description
Creates a property resource


 PropertyResourceBundle.getKeys

PropertyResourceBundle.getKeys

Syntax
public Enumeration getKeys()
Description
Implementation of ResourceBundle.getKeys.

Overrides
getKeys in class ResourceBundle


 PropertyResourceBundle.handleGetObject

PropertyResourceBundle.handleGetObject

Syntax
public Object handleGetObject( String key )
Description
Override of ResourceBundle, same semantics

Overrides
handleGetObject in class ResourceBundle


 Class Random

Class java.util.Random

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Random

public class Random
extends Object
implements Serializable

An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

Many applications will find the random method in class Math simpler to use.

See Also:
random


 Random Members

Random Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Random() | Creates a new random number generator.
Random(long) | Creates a new random number generator using a single long seed.

Methods
Name | Description
next(int) | Generates the next pseudorandom number.
nextBytes(byte[]) | Generates a user specified number of random bytes.
nextDouble() | Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
nextFloat() | Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
nextGaussian() | Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
nextInt() | Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
nextLong() | Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.
setSeed(long) | Sets the seed of this random number generator using a single long seed.


 Random.Random

Random.Random

Syntax 1
public Random()
Description
Creates a new random number generator. Its seed is initialized to a value based on the current time.

See Also
currentTimeMillis

Syntax 2
public Random( long seed )
Parameters
seed
the initial seed.
Description
Creates a new random number generator using a single long seed.

See Also
setSeed


 Random.next

Random.next

Syntax
protected synchronized int next( int bits )
Parameters
bits
random bits
Returns
the next pseudorandom value from this random number generator's sequence.
Description
Generates the next pseudorandom number. Subclass should override this, as this is used by all other methods.


 Random.nextBytes

Random.nextBytes

Syntax
public void nextBytes( byte bytes[] )
Description
Generates a user specified number of random bytes.


 Random.nextDouble

Random.nextDouble

Syntax
public double nextDouble()
Returns
the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
Description
Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.


 Random.nextFloat

Random.nextFloat

Syntax
public float nextFloat()
Returns
the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
Description
Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.


 Random.nextGaussian

Random.nextGaussian

Syntax
public synchronized double nextGaussian()
Returns
the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
Description
Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.


 Random.nextInt

Random.nextInt

Syntax
public int nextInt()
Returns
the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
Description
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.


 Random.nextLong

Random.nextLong

Syntax
public long nextLong()
Returns
the next pseudorandom, uniformly distributed long value from this random number generator's sequence.
Description
Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.


 Random.setSeed

Random.setSeed

Syntax
public synchronized void setSeed( long seed )
Parameters
seed
the initial seed.
Description
Sets the seed of this random number generator using a single long seed.


 Class ResourceBundle

Class java.util.ResourceBundle

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.ResourceBundle

public abstract class ResourceBundle
extends Object

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows you to write programs that can:

  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locales

One resource bundle is, conceptually, a set of related classes that inherit from ResourceBundle. Each related subclass of ResourceBundle has the same base name plus an additional component that identifies its locale. For example, suppose your resource bundle is named MyResources. The first class you are likely to write is the default resource bundle which simply has the same name as its family--MyResources. You can also provide as many related locale-specific classes as you need: for example, perhaps you would provide a German one named MyResources_de.

Each related subclass of ResourceBundle contains the same items, but the items have been translated for the locale represented by that ResourceBundle subclass. For example, both MyResources and MyResources_de may have a String that's used on a button for confirming operations. In MyResources the String may contain OK and in MyResources_de it may contain Gut.

If there are different resources for different countries, you can make specializations: for example, MyResources_de_CH for Switzerland. If you want to only modify some of the resources in the specialization, you can do so.

When your program needs a locale-specific object, it loads the ResourceBundle class using the getBundle method:

 ResourceBundle myResources =
      ResourceBundle.getBundle("MyResources", currentLocale);
The first argument specifies the family name of the resource bundle that contains the object in question. The second argument indicates the desired locale. getBundle uses these two arguments to construct the name of the ResourceBundle subclass it should load as follows.

The resource bundle lookup searches for classes with various suffixes on the basis of (1) the desired locale and (2) the default locale (baseclass), in the following order from lower-level (more specific) to parent-level (less specific):

baseclass + "_" + language1 + "_" + country1 + "_" + variant1
baseclass + "_" + language1 + "_" + country1
baseclass + "_" + language1
baseclass
baseclass + "_" + language2 + "_" + country2 + "_" + variant2
baseclass + "_" + language2 + "_" + country2
baseclass + "_" + language2

The result of the lookup is a class, but that class may be backed by a property file on disk. If a lookup fails, getBundle() throws a MissingResourceException.

The baseclass must be fully qualified (for example, myPackage.MyResources, not just MyResources). It must also be accessable by your code; it cannot be a class that is private to the package where ResourceBundle.getBundle is called.

Note: ResourceBundle are used internally in accessing NumberFormats, Collations, and so on. The lookup strategy is the same.

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here's an example of a ListResourceBundle that contains two key/value pairs:

 class MyResource extends ListResourceBundle {
      public Object[][] getContents() {
              return contents;
      }
      static final Object[][] contents = {
      // LOCALIZE THIS
              {"OkKey", "OK"},
              {"CancelKey", "Cancel"},
      // END OF MATERIAL TO LOCALIZE
      };
 }
Keys are always Strings. In this example, the keys are OkKey and CancelKey. In the above example, the values are also Strings--OK and Cancel--but they don't have to be. The values can be any type of object.

You retrieve an object from resource bundle using the appropriate getter method. Because OkKey and CancelKey are both strings, you would use getString to retrieve them:

 button1 = new Button(myResourceBundle.getString("OkKey"));
 button2 = new Button(myResourceBundle.getString("CancelKey"));
The getter methods all require the key as an argument and return the object if found. If the object is not found, the getter method throws a MissingResourceException.

Besides getString; ResourceBundle supports a number of other methods for getting different types of objects such as getStringArray. If you don't have an object that matches one of these methods, you can use getObject and cast the result to the appropriate type. For example:

 int[] myIntegers = (int[]) myResources.getObject("intList");

NOTE: You should always supply a baseclass with no suffixes. This will be the class of "last resort", if a locale is requested that does not exist. For example, below we have a class MyResources. It happens to contain US strings, so we don't have to have an explicit MyResource_en or MyResource_en_US.

The JDK provides two subclasses of ResourceBundle, ListResourceBundle and PropertyResourceBundle, that provide a fairly simple way to create resources. (Once serialization is fully integrated, we will provide another way.) As you saw briefly in a prevous example, ListResourceBundle manages its resource as a List of key/value pairs. PropertyResourceBundle uses a properties file to manage its resources.

If ListResourceBundle or PropertyResourceBundle do not suit your needs, you can write your own ResourceBundle subclass. Your subclasses must overrde two methods: handleGetObject and getKeys().

The following is a very simple example of a ResourceBundle subclass that manages only a few resources (for a larger number of resources you would probably use a Hashtable). Notice that if the key is not found, handleGetObject must return null. Notice also that you don't need to supply a value if a "parent-level" ResourceBundle handles the same key with the same value (look at uk below).

Example:

 abstract class MyResources extends ResourceBundle {
     public Object handleGetObject(String key) {
         if (key.equals("okKey")) return "Ok";
         if (key.equals("cancelKey")) return "Cancel";
        return null;
     }
 }
 abstract class MyResources_de extends MyResources {
     public Object handleGetObject(String key) {
         if (key.equals("okKey")) return "Gut";
         if (key.equals("cancelKey")) return "Vernichten";
         return null;
     }
 }
 abstract class MyResources_uk extends MyResources {
     public Object handleGetObject(String key) {
         // don't need okKey, since parent level handles it.
         if (key.equals("cancelKey")) return "Dispose";
            return null;
     }
 }
You do not have to restrict yourself to using a single family of ResourceBundles. For example, you could have a set of bundles for exception messages, ExceptionResources (ExceptionResources_fr, ExceptionResources_de, ...), and one for widgets, WidgetResource (WidgetResources_fr, WidgetResources_de, ...); breaking up the resources however you like.

See Also:
ListResourceBundle, PropertyResourceBundle, MissingResourceException


 ResourceBundle Members

ResourceBundle Members

Class Overview | This Package | All Packages

Fields
Name | Description
parent | The parent bundle is consulted by getObject when this bundle does not contain a particular resource.

Constructors
Name | Description
ResourceBundle() |

Methods
Name | Description
getBundle(String) | Get the appropriate ResourceBundle subclass.
getBundle(String, Locale) | Get the appropriate ResourceBundle subclass.
getKeys() | Return an enumeration of the keys.
getObject(String) | Get an object from a ResourceBundle.
getString(String) | Get an object from a ResourceBundle.
getStringArray(String) | Get an object from a ResourceBundle.
handleGetObject(String) | Get an object from a ResourceBundle.
setParent(ResourceBundle) | Set the parent bundle of this bundle.


 ResourceBundle.parent

ResourceBundle.parent

Syntax
protected ResourceBundle parent
Description
The parent bundle is consulted by getObject when this bundle does not contain a particular resource.


 ResourceBundle.ResourceBundle

ResourceBundle.ResourceBundle

Syntax
public ResourceBundle()


 ResourceBundle.getBundle

ResourceBundle.getBundle

Syntax 1
public static final ResourceBundle getBundle( String baseName ) throws MissingResourceException
Parameters
baseName
see class description.
Description
Get the appropriate ResourceBundle subclass.

Syntax 2
public static final ResourceBundle getBundle( String baseName, Locale locale )
Parameters
baseName
see class description.
locale
see class description.
Description
Get the appropriate ResourceBundle subclass.


 ResourceBundle.getKeys

ResourceBundle.getKeys

Syntax
public abstract Enumeration getKeys()
Description
Return an enumeration of the keys. NOTE: Subclasses must override.


 ResourceBundle.getObject

ResourceBundle.getObject

Syntax
public final Object getObject( String key ) throws MissingResourceException
Parameters
key
see class description.
Description
Get an object from a ResourceBundle.


 ResourceBundle.getString

ResourceBundle.getString

Syntax
public final String getString( String key ) throws MissingResourceException
Parameters
key
see class description.
Description
Get an object from a ResourceBundle.
Convenience method to save casting.


 ResourceBundle.getStringArray

ResourceBundle.getStringArray

Syntax
public final String[] getStringArray( String key ) throws MissingResourceException
Parameters
key
see class description.
Description
Get an object from a ResourceBundle.
Convenience method to save casting.


 ResourceBundle.handleGetObject

ResourceBundle.handleGetObject

Syntax
protected abstract Object handleGetObject( String key ) throws MissingResourceException
Parameters
key
see class description.
Description
Get an object from a ResourceBundle. NOTE: Subclasses must override.


 ResourceBundle.setParent

ResourceBundle.setParent

Syntax
protected void setParent( ResourceBundle parent )
Parameters
parent
this bundle's parent bundle.
Description
Set the parent bundle of this bundle. The parent bundle is searched by getObject when this bundle does not contain a particular resource.


 Class SimpleTimeZone

Class java.util.SimpleTimeZone

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.TimeZone
           |
           +----java.util.SimpleTimeZone

public class SimpleTimeZone
extends TimeZone

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar. This simple class does not handle historical changes, and has limited rules.

Use a negative value for dayOfWeekInMonth to indicate that SimpleTimeZone should count from the end of the month backwards. For example, Daylight Savings Time ends at the last (dayOfWeekInMonth = -1) Sunday in October, at 2 AM in standard time.

See Also:
Calendar, GregorianCalendar, TimeZone


 SimpleTimeZone Members

SimpleTimeZone Members

Class Overview | This Package | All Packages

Constructors
Name | Description
SimpleTimeZone(int, String) | Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone ID.
SimpleTimeZone(int, String, int, int, int, int, int, int, int, int) | Constructs a SimpleTimeZone with the given base time zone offset from GMT, time zone ID, time to start and end the daylight time.

Methods
Name | Description
clone() | Overrides Cloneable
equals(Object) | Compares the equality of two SimpleTimeZone objects.
getOffset(int, int, int, int, int, int) | Overrides TimeZone Gets offset, for current date, modified in case of daylight savings.
getRawOffset() | Overrides TimeZone Gets the GMT offset for this time zone.
hashCode() | Override hashCode.
inDaylightTime(Date) | Overrides TimeZone Queries if the given date is in Daylight Savings Time.
setEndRule(int, int, int, int) | Sets the daylight savings ending rule.
setRawOffset(int) | Overrides TimeZone Sets the base time zone offset to GMT.
setStartRule(int, int, int, int) | Sets the daylight savings starting rule.
setStartYear(int) | Sets the daylight savings starting year.
useDaylightTime() | Overrides TimeZone Queries if this time zone uses Daylight Savings Time.


 SimpleTimeZone.SimpleTimeZone

SimpleTimeZone.SimpleTimeZone

Syntax 1
public SimpleTimeZone( int rawOffset, String ID )
Parameters
rawOffset
the given base time zone offset to GMT.
ID
the time zone ID which is obtained from TimeZone.getAvailableIDs.
Description
Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone ID. Timezone IDs can be obtained from TimeZone.getAvailableIDs. Normally you should use TimeZone.getDefault to construct a TimeZone.

Syntax 2
public SimpleTimeZone( int rawOffset, String ID, int startMonth, int startDayOfWeekInMonth, int startDayOfWeek, int startTime, int endMonth, int endDayOfWeekInMonth, int endDayOfWeek, int endTime )
Parameters
rawOffset
the given base time zone offset to GMT.
ID
the time zone ID which is obtained from TimeZone.getAvailableIDs.
startMonth
the daylight savings starting month. Month is 0-based. eg, 0 for January.
startDayOfWeekInMonth
the daylight savings starting day-of-week-in-month. Please see the member description for an example.
startDayOfWeek
the daylight savings starting day-of-week. Please see the member description for an example.
startTime
the daylight savings starting time. Please see the member description for an example.
endMonth
the daylight savings ending month. Month is 0-based. eg, 0 for January.
endDayOfWeekInMonth
the daylight savings ending day-of-week-in-month. Please see the member description for an example.
endDayOfWeek
the daylight savings ending day-of-week. Please see the member description for an example.
endTime
the daylight savings ending time. Please see the member description for an example.
Description
Constructs a SimpleTimeZone with the given base time zone offset from GMT, time zone ID, time to start and end the daylight time. Timezone IDs can be obtained from TimeZone.getAvailableIDs. Normally you should use TimeZone.getDefault to create a TimeZone. For a time zone that does not use daylight saving time, do not use this constructor; instead you should use SimpleTimeZone(rawOffset, ID).


 SimpleTimeZone.clone

SimpleTimeZone.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class TimeZone


 SimpleTimeZone.equals

SimpleTimeZone.equals

Syntax
public boolean equals( Object obj )
Parameters
obj
the SimpleTimeZone object to be compared with.
Returns
true if the given obj is the same as this SimpleTimeZone object; false otherwise.
Description
Compares the equality of two SimpleTimeZone objects.

Overrides
equals in class Object


 SimpleTimeZone.getOffset

SimpleTimeZone.getOffset

Syntax
public int getOffset( int era, int year, int month, int day, int dayOfWeek, int millis )
Description
Overrides TimeZone Gets offset, for current date, modified in case of daylight savings. This is the offset to add *to* UTC to get local time. Please see TimeZone.getOffset for descriptions on parameters.

Overrides
getOffset in class TimeZone


 SimpleTimeZone.getRawOffset

SimpleTimeZone.getRawOffset

Syntax
public int getRawOffset()
Description
Overrides TimeZone Gets the GMT offset for this time zone.

Overrides
getRawOffset in class TimeZone


 SimpleTimeZone.hashCode

SimpleTimeZone.hashCode

Syntax
public synchronized int hashCode()
Description
Override hashCode. Generates the hash code for the SimpleDateFormat object

Overrides
hashCode in class Object


 SimpleTimeZone.inDaylightTime

SimpleTimeZone.inDaylightTime

Syntax
public boolean inDaylightTime( Date date )
Description
Overrides TimeZone Queries if the given date is in Daylight Savings Time.

Overrides
inDaylightTime in class TimeZone


 SimpleTimeZone.setEndRule

SimpleTimeZone.setEndRule

Syntax
public void setEndRule( int month, int dayOfWeekInMonth, int dayOfWeek, int time )
Parameters
month
the daylight savings ending month. Month is 0-based. eg, 0 for January.
dayOfWeekInMonth
the daylight savings ending day-of-week-in-month. Please see the member description for an example.
dayOfWeek
the daylight savings ending day-of-week. Please see the member description for an example.
time
the daylight savings ending time. Please see the member description for an example.
Description
Sets the daylight savings ending rule. For example, Daylight Savings Time ends at the last (-1) Sunday in October, at 2 AM in standard time. Therefore, you can set the end rule by calling: setEndRule(TimeFields.OCTOBER, -1, TimeFields.SUNDAY, 2*60*60*1000);


 SimpleTimeZone.setRawOffset

SimpleTimeZone.setRawOffset

Syntax
public void setRawOffset( int offsetMillis )
Description
Overrides TimeZone Sets the base time zone offset to GMT. This is the offset to add *to* UTC to get local time. Please see TimeZone.setRawOffset for descriptions on the parameter.

Overrides
setRawOffset in class TimeZone


 SimpleTimeZone.setStartRule

SimpleTimeZone.setStartRule

Syntax
public void setStartRule( int month, int dayOfWeekInMonth, int dayOfWeek, int time )
Parameters
month
the daylight savings starting month. Month is 0-based. eg, 0 for January.
dayOfWeekInMonth
the daylight savings starting day-of-week-in-month. Please see the member description for an example.
dayOfWeek
the daylight savings starting day-of-week. Please see the member description for an example.
time
the daylight savings starting time. Please see the member description for an example.
Description
Sets the daylight savings starting rule. For example, Daylight Savings Time starts at the first Sunday in April, at 2 AM in standard time. Therefore, you can set the start rule by calling: setStartRule(TimeFields.APRIL, 1, TimeFields.SUNDAY, 2*60*60*1000);


 SimpleTimeZone.setStartYear

SimpleTimeZone.setStartYear

Syntax
public void setStartYear( int year )
Parameters
year
the daylight savings starting year.
Description
Sets the daylight savings starting year.


 SimpleTimeZone.useDaylightTime

SimpleTimeZone.useDaylightTime

Syntax
public boolean useDaylightTime()
Description
Overrides TimeZone Queries if this time zone uses Daylight Savings Time.

Overrides
useDaylightTime in class TimeZone


 Class Stack

Class java.util.Stack

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Vector
           |
           +----java.util.Stack

public class Stack
extends Vector

The Stack class represents a last-in-first-out (LIFO) stack of objects.


 Stack Members

Stack Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Stack() |

Methods
Name | Description
empty() | Tests if this stack is empty.
peek() | Looks at the object at the top of this stack without removing it from the stack.
pop() | Removes the object at the top of this stack and returns that object as the value of this function.
push(Object) | Pushes an item onto the top of this stack.
search(Object) | Returns where an object is on this stack.


 Stack.Stack

Stack.Stack

Syntax
public Stack()


 Stack.empty

Stack.empty

Syntax
public boolean empty()
Returns
true if this stack is empty; false otherwise.
Description
Tests if this stack is empty.


 Stack.peek

Stack.peek

Syntax
public synchronized Object peek()
Returns
the object at the top of this stack.
Description
Looks at the object at the top of this stack without removing it from the stack.

Exceptions
EmptyStackException if this stack is empty.


 Stack.pop

Stack.pop

Syntax
public synchronized Object pop()
Returns
The object at the top of this stack.
Description
Removes the object at the top of this stack and returns that object as the value of this function.

Exceptions
EmptyStackException if this stack is empty.


 Stack.push

Stack.push

Syntax
public Object push( Object item )
Parameters
item
the item to be pushed onto this stack.
Returns
the item argument.
Description
Pushes an item onto the top of this stack.


 Stack.search

Stack.search

Syntax
public synchronized int search( Object o )
Parameters
o
the desired object.
Returns
the distance from the top of the stack where the object is] located; the return value -1 indicates that the object is not on the stack.
Description
Returns where an object is on this stack.


 Class StringTokenizer

Class java.util.StringTokenizer

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.StringTokenizer

public class StringTokenizer
extends Object
implements Enumeration

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnTokens flag having the value true or false:

  • If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
  • If the flag is true, delimiter characters are considered to be tokens. A token is either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

The following is one example of the use of the tokenizer. The code:

     StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         println(st.nextToken());
     }

prints the following output:

     this
     is
     a
     test

See Also:
StreamTokenizer


 StringTokenizer Members

StringTokenizer Members

Class Overview | This Package | All Packages

Constructors
Name | Description
StringTokenizer(String) | Constructs a string tokenizer for the specified string.
StringTokenizer(String, String) | Constructs a string tokenizer for the specified string.
StringTokenizer(String, String, boolean) | Constructs a string tokenizer for the specified string.

Methods
Name | Description
countTokens() | Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.
hasMoreElements() | Returns the same value as the hasMoreTokens method.
hasMoreTokens() | Tests if there are more tokens available from this tokenizer's string.
nextElement() | Returns the same value as the nextToken method, except that its declared return value is Object rather than String.
nextToken() | Returns the next token from this string tokenizer.
nextToken(String) | Returns the next token in this string tokenizer's string.


 StringTokenizer.StringTokenizer

StringTokenizer.StringTokenizer

Syntax 1
public StringTokenizer( String str, String delim, boolean returnTokens )
Parameters
str
a string to be parsed.
delim
the delimiters.
returnTokens
flag indicating whether to return the delimiters as tokens.
Description
Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens.

If the returnTokens flag is true, then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag is false, the delimiter characters are skipped and only serve as separators between tokens.

Syntax 2
public StringTokenizer( String str, String delim )
Parameters
str
a string to be parsed.
delim
the delimiters.
Description
Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens.

Syntax 3
public StringTokenizer( String str )
Parameters
str
a string to be parsed.
Description
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is "\t\n\r": the space character, the tab character, the newline character, and the carriage-return character.


 StringTokenizer.countTokens

StringTokenizer.countTokens

Syntax
public int countTokens()
Returns
the number of tokens remaining in the string using the current delimiter set.
Description
Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

See Also
nextToken


 StringTokenizer.hasMoreElements

StringTokenizer.hasMoreElements

Syntax
public boolean hasMoreElements()
Returns
true if there are more tokens; false otherwise.
Description
Returns the same value as the hasMoreTokens method. It exists so that this class can implement the Enumeration interface.

See Also
Enumeration, hasMoreTokens


 StringTokenizer.hasMoreTokens

StringTokenizer.hasMoreTokens

Syntax
public boolean hasMoreTokens()
Returns
true if there are more tokens available from this tokenizer's string; false otherwise.
Description
Tests if there are more tokens available from this tokenizer's string.


 StringTokenizer.nextElement

StringTokenizer.nextElement

Syntax
public Object nextElement()
Returns
the next token in the string.
Description
Returns the same value as the nextToken method, except that its declared return value is Object rather than String. It exists so that this class can implement the Enumeration interface.

Exceptions
NoSuchElementException if there are no more tokens in this tokenizer's string.
See Also
Enumeration, nextToken


 StringTokenizer.nextToken

StringTokenizer.nextToken

Syntax 1
public String nextToken()
Returns
the next token from this string tokenizer.
Description
Returns the next token from this string tokenizer.

Exceptions
NoSuchElementException if there are no more tokens in this tokenizer's string.

Syntax 2
public String nextToken( String delim )
Parameters
delim
the new delimiters.
Returns
the next token, after switching to the new delimiter set.
Description
Returns the next token in this string tokenizer's string. The new delimiter set remains the default after this call.

Exceptions
NoSuchElementException if there are no more tokens in this tokenizer's string.


 Class TimeZone

Class java.util.TimeZone

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.TimeZone

public abstract class TimeZone
extends Object
implements Serializable, Cloneable

TimeZone represents a time zone offset, and also figures out daylight savings.

Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.

You can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the Pacific Standard Time zone is "PST". So, you can get a PST TimeZone object with:

 TimeZone tz = TimeZone.getTimeZone("PST");
You can use getAvailableIDs method to iterate through all the supported time zone IDs. You can then choose a supported ID to get a favorite TimeZone.

See Also:
Calendar, GregorianCalendar, SimpleTimeZone


 TimeZone Members

TimeZone Members

Class Overview | This Package | All Packages

Constructors
Name | Description
TimeZone() |

Methods
Name | Description
clone() | Overrides Cloneable
getAvailableIDs() | Gets all the available IDs supported.
getAvailableIDs(int) | Gets the available IDs according to the given time zone offset.
getDefault() | Gets the default TimeZone for this host.
getID() | Gets the ID of this time zone.
getOffset(int, int, int, int, int, int) | Gets the time zone offset, for current date, modified in case of daylight savings.
getRawOffset() | Gets unmodified offset, NOT modified in case of daylight savings.
getTimeZone(String) | Gets the TimeZone for the given ID.
inDaylightTime(Date) | Queries if the given date is in Daylight Savings Time in this time zone.
setDefault(TimeZone) | Sets time zone to using the given TimeZone.
setID(String) | Sets the time zone ID.
setRawOffset(int) | Sets the base time zone offset to GMT.
useDaylightTime() | Queries if this time zone uses Daylight Savings Time.


 TimeZone.TimeZone

TimeZone.TimeZone

Syntax
public TimeZone()


 TimeZone.clone

TimeZone.clone

Syntax
public Object clone()
Description
Overrides Cloneable

Overrides
clone in class Object


 TimeZone.getAvailableIDs

TimeZone.getAvailableIDs

Syntax 1
public static synchronized String[] getAvailableIDs( int rawOffset )
Parameters
rawOffset
the given time zone GMT offset.
Returns
an array of IDs, where the time zone for that ID has the specified GMT offset. For example, {"Phoenix", "Denver"}, since both have GMT-07:00, but differ in daylight savings behavior.
Description
Gets the available IDs according to the given time zone offset.

Syntax 2
public static synchronized String[] getAvailableIDs()
Returns
an array of IDs.
Description
Gets all the available IDs supported.


 TimeZone.getDefault

TimeZone.getDefault

Syntax
public static synchronized TimeZone getDefault()
Returns
a default TimeZone.
Description
Gets the default TimeZone for this host.


 TimeZone.getID

TimeZone.getID

Syntax
public String getID()
Returns
the ID of this time zone.
Description
Gets the ID of this time zone.


 TimeZone.getOffset

TimeZone.getOffset

Syntax
public abstract int getOffset( int era, int year, int month, int day, int dayOfWeek, int milliseconds )
Parameters
era
the era of the given date.
year
the year in the given date.
month
the month in the given date. Month is 0-based. e.g., 0 for January.
day
the day-in-month of the given date.
dayOfWeek
the day-of-week of the given date.
milliseconds
the millis in day.
Returns
the offset to add *to* GMT to get local time.
Description
Gets the time zone offset, for current date, modified in case of daylight savings. This is the offset to add *to* UTC to get local time.


 TimeZone.getRawOffset

TimeZone.getRawOffset

Syntax
public abstract int getRawOffset()
Returns
the unmodified offset to add *to* UTC to get local time.
Description
Gets unmodified offset, NOT modified in case of daylight savings. This is the offset to add *to* UTC to get local time.


 TimeZone.getTimeZone

TimeZone.getTimeZone

Syntax
public static synchronized TimeZone getTimeZone( String ID )
Parameters
ID
the given ID.
Returns
a TimeZone.
Description
Gets the TimeZone for the given ID.


 TimeZone.inDaylightTime

TimeZone.inDaylightTime

Syntax
public abstract boolean inDaylightTime( Date date )
Parameters
date
the given Date.
Returns
true if the given date is in Daylight Savings Time, false, otherwise.
Description
Queries if the given date is in Daylight Savings Time in this time zone.


 TimeZone.setDefault

TimeZone.setDefault

Syntax
public static synchronized void setDefault( TimeZone zone )
Parameters
zone
the given time zone.
Description
Sets time zone to using the given TimeZone.


 TimeZone.setID

TimeZone.setID

Syntax
public void setID( String ID )
Parameters
ID
the new time zone ID.
Description
Sets the time zone ID. This does not change any other data in the time zone object.


 TimeZone.setRawOffset

TimeZone.setRawOffset

Syntax
public abstract void setRawOffset( int offsetMillis )
Parameters
offsetMillis
the given base time zone offset to GMT.
Description
Sets the base time zone offset to GMT. This is the offset to add *to* UTC to get local time.


 TimeZone.useDaylightTime

TimeZone.useDaylightTime

Syntax
public abstract boolean useDaylightTime()
Returns
true if this time zone uses Daylight Savings Time, false, otherwise.
Description
Queries if this time zone uses Daylight Savings Time.


 Class TooManyListenersException

Class java.util.TooManyListenersException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.util.TooManyListenersException

public class TooManyListenersException
extends Exception

The TooManyListenersException Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.

The presence of a throws TooManyListenersException clause on any given concrete implementation of the normally multicast semantic void add < EventListenerType > () event listener registration pattern is used to annotate that interface as implementing a unicast Listener special case, that is, that one and only one Listener may be registered on the particular event listener source concurrently.

See Also:
EventObject, EventListener


 TooManyListenersException Members

TooManyListenersException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
TooManyListenersException() | Constructs a TooManyListenersException with no detail message.
TooManyListenersException(String) | Constructs a TooManyListenersException with the specified detail message.


 TooManyListenersException.TooManyListenersException

TooManyListenersException.TooManyListenersException

Syntax 1
public TooManyListenersException()
Description
Constructs a TooManyListenersException with no detail message. A detail message is a String that describes this particular exception.

Syntax 2
public TooManyListenersException( String s )
Parameters
s
the detail message
Description
Constructs a TooManyListenersException with the specified detail message. A detail message is a String that describes this particular exception.


 Class Vector

Class java.util.Vector

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.Vector

public class Vector
extends Object
implements Cloneable, Serializable

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.


 Vector Members

Vector Members

Class Overview | This Package | All Packages

Fields
Name | Description
capacityIncrement | The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity.
elementCount | The number of valid components in the vector.
elementData | The array buffer into which the components of the vector are stored.

Constructors
Name | Description
Vector() | Constructs an empty vector.
Vector(int) | Constructs an empty vector with the specified initial capacity.
Vector(int, int) | Constructs an empty vector with the specified initial capacity and capacity increment.

Methods
Name | Description
addElement(Object) | Adds the specified component to the end of this vector, increasing its size by one.
capacity() | Returns the current capacity of this vector.
clone() | Returns a clone of this vector.
contains(Object) | Tests if the specified object is a component in this vector.
copyInto(Object[]) | Copies the components of this vector into the specified array.
elementAt(int) | Returns the component at the specified index.
elements() | Returns an enumeration of the components of this vector.
ensureCapacity(int) | Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
firstElement() | Returns the first component of this vector.
indexOf(Object) | Searches for the first occurence of the given argument, testing for equality using the equals method.
indexOf(Object, int) | Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method.
insertElementAt(Object, int) | Inserts the specified object as a component in this vector at the specified index.
isEmpty() | Tests if this vector has no components.
lastElement() | Returns the last component of the vector.
lastIndexOf(Object) | Returns the index of the last occurrence of the specified object in this vector.
lastIndexOf(Object, int) | Searches backwards for the specified object, starting from the specified index, and returns an index to it.
removeAllElements() | Removes all components from this vector and sets its size to zero.
removeElement(Object) | Removes the first occurrence of the argument from this vector.
removeElementAt(int) | Deletes the component at the specified index.
setElementAt(Object, int) | Sets the component at the specified index of this vector to be the specified object.
setSize(int) | Sets the size of this vector.
size() | Returns the number of components in this vector.
toString() | Returns a string representation of this vector.
trimToSize() | Trims the capacity of this vector to be the vector's current size.


 Vector.capacityIncrement

Vector.capacityIncrement

Syntax
protected int capacityIncrement
Description
The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity is 0, the capacity of the vector is doubled each time it needs to grow.


 Vector.elementCount

Vector.elementCount

Syntax
protected int elementCount
Description
The number of valid components in the vector.


 Vector.elementData

Vector.elementData

Syntax
protected Object elementData[]
Description
The array buffer into which the components of the vector are stored. The capacity of the vector is the length of this array buffer.


 Vector.Vector

Vector.Vector

Syntax 1
public Vector( int initialCapacity, int capacityIncrement )
Parameters
initialCapacity
the initial capacity of the vector.
capacityIncrement
the amount by which the capacity is increased when the vector overflows.
Description
Constructs an empty vector with the specified initial capacity and capacity increment.

Syntax 2
public Vector( int initialCapacity )
Parameters
initialCapacity
the initial capacity of the vector.
Description
Constructs an empty vector with the specified initial capacity.

Syntax 3
public Vector()
Description
Constructs an empty vector.


 Vector.addElement

Vector.addElement

Syntax
public final synchronized void addElement( Object obj )
Parameters
obj
the component to be added.
Description
Adds the specified component to the end of this vector, increasing its size by one. The capacity of this vector is increased if its size becomes greater than its capacity.


 Vector.capacity

Vector.capacity

Syntax
public final int capacity()
Returns
the current capacity of this vector.
Description
Returns the current capacity of this vector.


 Vector.clone

Vector.clone

Syntax
public synchronized Object clone()
Returns
a clone of this vector.
Description
Returns a clone of this vector.

Overrides
clone in class Object


 Vector.contains

Vector.contains

Syntax
public final boolean contains( Object elem )
Parameters
elem
an object.
Returns
true if the specified object is a component in this vector; false otherwise.
Description
Tests if the specified object is a component in this vector.


 Vector.copyInto

Vector.copyInto

Syntax
public final synchronized void copyInto( Object anArray[] )
Parameters
anArray
the array into which the components get copied.
Description
Copies the components of this vector into the specified array. The array must be big enough to hold all the objects in this vector.


 Vector.elementAt

Vector.elementAt

Syntax
public final synchronized Object elementAt( int index )
Parameters
index
an index into this vector.
Returns
the component at the specified index.
Description
Returns the component at the specified index.

Exceptions
ArrayIndexOutOfBoundsException if an invalid index was given.


 Vector.elements

Vector.elements

Syntax
public final synchronized Enumeration elements()
Returns
an enumeration of the components of this vector.
Description
Returns an enumeration of the components of this vector.

See Also
Enumeration


 Vector.ensureCapacity

Vector.ensureCapacity

Syntax
public final synchronized void ensureCapacity( int minCapacity )
Parameters
minCapacity
the desired minimum capacity.
Description
Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.


 Vector.firstElement

Vector.firstElement

Syntax
public final synchronized Object firstElement()
Returns
the first component of this vector.
Description
Returns the first component of this vector.

Exceptions
NoSuchElementException if this vector has no components.


 Vector.indexOf

Vector.indexOf

Syntax 1
public final int indexOf( Object elem )
Parameters
elem
an object.
Returns
the index of the first occurrence of the argument in this vector; returns -1 if the object is not found.
Description
Searches for the first occurence of the given argument, testing for equality using the equals method.

See Also
equals

Syntax 2
public final synchronized int indexOf( Object elem, int index )
Parameters
elem
an object.
index
the index to start searching from.
Returns
the index of the first occurrence of the object argument in this vector at position index or later in the vector; returns -1 if the object is not found.
Description
Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method.

See Also
equals


 Vector.insertElementAt

Vector.insertElementAt

Syntax
public final synchronized void insertElementAt( Object obj, int index )
Parameters
obj
the component to insert.
index
where to insert the new component.
Description
Inserts the specified object as a component in this vector at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously.

The index must be a value greater than or equal to 0 and less than or equal to the current size of the vector.

Exceptions
ArrayIndexOutOfBoundsException if the index was invalid.
See Also
size


 Vector.isEmpty

Vector.isEmpty

Syntax
public final boolean isEmpty()
Returns
true if this vector has no components; false otherwise.
Description
Tests if this vector has no components.


 Vector.lastElement

Vector.lastElement

Syntax
public final synchronized Object lastElement()
Returns
the last component of the vector, i.e., the component at index size() - 1.
Description
Returns the last component of the vector.

Exceptions
NoSuchElementException if this vector is empty.


 Vector.lastIndexOf

Vector.lastIndexOf

Syntax 1
public final int lastIndexOf( Object elem )
Parameters
elem
the desired component.
Returns
the index of the last occurrence of the specified object in this vector; returns -1 if the object is not found.
Description
Returns the index of the last occurrence of the specified object in this vector.

Syntax 2
public final synchronized int lastIndexOf( Object elem, int index )
Parameters
elem
the desired component.
index
the index to start searching from.
Returns
the index of the last occurrence of the specified object in this vector at position less than index in the vector; -1 if the object is not found.
Description
Searches backwards for the specified object, starting from the specified index, and returns an index to it.


 Vector.removeAllElements

Vector.removeAllElements

Syntax
public final synchronized void removeAllElements()
Description
Removes all components from this vector and sets its size to zero.


 Vector.removeElement

Vector.removeElement

Syntax
public final synchronized boolean removeElement( Object obj )
Parameters
obj
the component to be removed.
Returns
true if the argument was a component of this vector; false otherwise.
Description
Removes the first occurrence of the argument from this vector. If the object is found in this vector, each component in the vector with an index greater or equal to the object's index is shifted downward to have an index one smaller than the value it had previously.


 Vector.removeElementAt

Vector.removeElementAt

Syntax
public final synchronized void removeElementAt( int index )
Parameters
index
the index of the object to remove.
Description
Deletes the component at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted downward to have an index one smaller than the value it had previously.

The index must be a value greater than or equal to 0 and less than the current size of the vector.

Exceptions
ArrayIndexOutOfBoundsException if the index was invalid.
See Also
size


 Vector.setElementAt

Vector.setElementAt

Syntax
public final synchronized void setElementAt( Object obj, int index )
Parameters
obj
what the component is to be set to.
index
the specified index.
Description
Sets the component at the specified index of this vector to be the specified object. The previous component at that position is discarded.

The index must be a value greater than or equal to 0 and less than the current size of the vector.

Exceptions
ArrayIndexOutOfBoundsException if the index was invalid.
See Also
size


 Vector.setSize

Vector.setSize

Syntax
public final synchronized void setSize( int newSize )
Parameters
newSize
the new size of this vector.
Description
Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.


 Vector.size

Vector.size

Syntax
public final int size()
Returns
the number of components in this vector.
Description
Returns the number of components in this vector.


 Vector.toString

Vector.toString

Syntax
public final synchronized String toString()
Returns
a string representation of this vector.
Description
Returns a string representation of this vector.

Overrides
toString in class Object


 Vector.trimToSize

Vector.trimToSize

Syntax
public final synchronized void trimToSize()
Description
Trims the capacity of this vector to be the vector's current size. An application can use this operation to minimize the storage of a vector.


 Package java.util.zip

Package java.util.zip

All Packages

Interfaces

  • Checksum

    • Classes

  • Adler32
  • CRC32
  • CheckedInputStream
  • CheckedOutputStream
  • Deflater
  • DeflaterOutputStream
  • GZIPInputStream
  • GZIPOutputStream
  • Inflater
  • InflaterInputStream
  • ZipEntry
  • ZipFile
  • ZipInputStream
  • ZipOutputStream

    • Exceptions

  • DataFormatException
  • ZipException


 Class Adler32

Class java.util.zip.Adler32

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.Adler32

public class Adler32
extends Object
implements Checksum

A class that can be used to compute the Adler-32 checksum of a data stream. An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed much faster.

See Also:
Checksum


 Adler32 Members

Adler32 Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Adler32() |

Methods
Name | Description
getValue() | Returns checksum value.
reset() | Resets checksum to initial value.
update(byte[]) | Updates checksum with specified array of bytes.
update(byte[], int, int) | Updates checksum with specified array of bytes.
update(int) | Updates checksum with specified byte.


 Adler32.Adler32

Adler32.Adler32

Syntax
public Adler32()


 Adler32.getValue

Adler32.getValue

Syntax
public long getValue()
Description
Returns checksum value.


 Adler32.reset

Adler32.reset

Syntax
public void reset()
Description
Resets checksum to initial value.


 Adler32.update

Adler32.update

Syntax 1
public void update( int b )
Description
Updates checksum with specified byte.

Syntax 2
public native void update( byte b[], int off, int len )
Description
Updates checksum with specified array of bytes.

Syntax 3
public void update( byte b[] )
Description
Updates checksum with specified array of bytes.


 Class CRC32

Class java.util.zip.CRC32

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.CRC32

public class CRC32
extends Object
implements Checksum

A class that can be used to compute the CRC-32 of a data stream.

See Also:
Checksum


 CRC32 Members

CRC32 Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CRC32() |

Methods
Name | Description
getValue() | Returns CRC-32 value.
reset() | Resets CRC-32 to initial value.
update(byte[]) | Updates CRC-32 with specified array of bytes.
update(byte[], int, int) | Updates CRC-32 with specified array of bytes.
update(int) | Updates CRC-32 with specified byte.


 CRC32.CRC32

CRC32.CRC32

Syntax
public CRC32()


 CRC32.getValue

CRC32.getValue

Syntax
public long getValue()
Description
Returns CRC-32 value.


 CRC32.reset

CRC32.reset

Syntax
public void reset()
Description
Resets CRC-32 to initial value.


 CRC32.update

CRC32.update

Syntax 1
public void update( int b )
Description
Updates CRC-32 with specified byte.

Syntax 2
public native void update( byte b[], int off, int len )
Description
Updates CRC-32 with specified array of bytes.

Syntax 3
public void update( byte b[] )
Description
Updates CRC-32 with specified array of bytes.


 Class CheckedInputStream

Class java.util.zip.CheckedInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.util.zip.CheckedInputStream

public class CheckedInputStream
extends FilterInputStream

An input stream that also maintains a checksum of the data being read. The checksum can then be used to verify the integrity of the input data.

See Also:
Checksum


 CheckedInputStream Members

CheckedInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CheckedInputStream(InputStream, Checksum) | Creates an input stream using the specified Checksum.

Methods
Name | Description
getChecksum() | Returns the Checksum for this input stream.
read() | Reads a byte.
read(byte[], int, int) | Reads into an array of bytes.
skip(long) | Skips specified number of bytes of input.


 CheckedInputStream.CheckedInputStream

CheckedInputStream.CheckedInputStream

Syntax
public CheckedInputStream( InputStream in, Checksum cksum )
Parameters
in
the input stream
cksum
the Checksum
Description
Creates an input stream using the specified Checksum.


 CheckedInputStream.getChecksum

CheckedInputStream.getChecksum

Syntax
public Checksum getChecksum()
Description
Returns the Checksum for this input stream.


 CheckedInputStream.read

CheckedInputStream.read

Syntax 1
public int read() throws IOException
Returns
the byte read, or -1 if the end of the stream is reached.
Description
Reads a byte. Will block if no input is available.

Exceptions
IOException if an I/O error has occurred
Overrides
read in class FilterInputStream

Syntax 2
public int read( byte buf[], int off, int len ) throws IOException
Parameters
buf
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, or -1 if the end of the stream is reached.
Description
Reads into an array of bytes. Will block until some input is available.

Exceptions
IOException if an I/O error has occurred
Overrides
read in class FilterInputStream


 CheckedInputStream.skip

CheckedInputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to skip
Returns
the actual number of bytes skipped
Description
Skips specified number of bytes of input.

Exceptions
IOException if an I/O error has occurred
Overrides
skip in class FilterInputStream


 Class CheckedOutputStream

Class java.util.zip.CheckedOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.util.zip.CheckedOutputStream

public class CheckedOutputStream
extends FilterOutputStream

An output stream that also maintains a checksum of the data being written. The checksum can then be used to verify the integrity of the output data.

See Also:
Checksum


 CheckedOutputStream Members

CheckedOutputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
CheckedOutputStream(OutputStream, Checksum) | Creates an output stream with the specified Checksum.

Methods
Name | Description
getChecksum() | Returns the Checksum for this output stream.
write(byte[], int, int) | Writes an array of bytes.
write(int) | Writes a byte.


 CheckedOutputStream.CheckedOutputStream

CheckedOutputStream.CheckedOutputStream

Syntax
public CheckedOutputStream( OutputStream out, Checksum cksum )
Parameters
out
the output stream
cksum
the checksum
Description
Creates an output stream with the specified Checksum.


 CheckedOutputStream.getChecksum

CheckedOutputStream.getChecksum

Syntax
public Checksum getChecksum()
Description
Returns the Checksum for this output stream.


 CheckedOutputStream.write

CheckedOutputStream.write

Syntax 1
public void write( int b ) throws IOException
Parameters
b
the byte to be written
Description
Writes a byte. Will block until the byte is actually written.

Exceptions
IOException if an I/O error has occurred
Overrides
write in class FilterOutputStream

Syntax 2
public void write( byte b[], int off, int len ) throws IOException
Parameters
buf
the data to be written
off
the start offset of the data
len
the number of bytes to be written
Description
Writes an array of bytes. Will block until the bytes are actually written.

Exceptions
IOException if an I/O error has occurred
Overrides
write in class FilterOutputStream


 Interface Checksum

Interface java.util.zip.Checksum

Interface Members | This Package | All Packages

public interface Checksum

An interface representing a data checksum.


 Checksum Members

Checksum Members

Interface Overview | This Package | All Packages

Methods
Name | Description
getValue() | Returns the current checksum value.
reset() | Resets the checksum to its initial value.
update(byte[], int, int) | Updates the current checksum with the specified array of bytes.
update(int) | Updates the current checksum with the specified byte.


 Checksum.getValue

Checksum.getValue

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract long getValue()
Description
Returns the current checksum value.


 Checksum.reset

Checksum.reset

Interface Overview | Interface Members | This Package | All Packages

Syntax
public abstract void reset()
Description
Resets the checksum to its initial value.


 Checksum.update

Checksum.update

Interface Overview | Interface Members | This Package | All Packages

Syntax 1
public abstract void update( int b )
Description
Updates the current checksum with the specified byte.

Syntax 2
public abstract void update( byte b[], int off, int len )
Description
Updates the current checksum with the specified array of bytes.


 Class DataFormatException

Class java.util.zip.DataFormatException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.util.zip.DataFormatException

public class DataFormatException
extends Exception

Signals that a data format error has occurred.


 DataFormatException Members

DataFormatException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
DataFormatException() | Constructs a DataFormatException with no detail message.
DataFormatException(String) | Constructs a DataFormatException with the specified detail message.


 DataFormatException.DataFormatException

DataFormatException.DataFormatException

Syntax 1
public DataFormatException()
Description
Constructs a DataFormatException with no detail message.

Syntax 2
public DataFormatException( String s )
Parameters
s
the String containing a detail message
Description
Constructs a DataFormatException with the specified detail message. A detail message is a String that describes this particular exception.


 Class Deflater

Class java.util.zip.Deflater

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.Deflater

public class Deflater
extends Object

This class provides support for general purpose decompression using the popular ZLIB compression library. The ZLIB compression library was initially developed as part of the PNG graphics standard and is not protected by patents. It is fully described in RFCs 1950, 1951, and 1952, which can be found at ftp://ds.internic.net/rfc in the files rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).

See Also:
Inflater


 Deflater Members

Deflater Members

Class Overview | This Package | All Packages

Fields
Name | Description
BEST_COMPRESSION | Compression level for best compression.
BEST_SPEED | Compression level for fastest compression.
DEFAULT_COMPRESSION | Default compression level.
DEFAULT_STRATEGY | Default compression strategy.
DEFLATED | Compression method for the deflate algorithm (the only one currently supported).
FILTERED | Compression strategy best used for data consisting mostly of small values with a somewhat random distribution.
HUFFMAN_ONLY | Compression strategy for Huffman coding only.
NO_COMPRESSION | Compression level for no compression.

Constructors
Name | Description
Deflater() | Creates a new compressor with the default compression level.
Deflater(int) | Creates a new compressor using the specified compression level.
Deflater(int, boolean) | Creates a new compressor using the specified compression level.

Methods
Name | Description
deflate(byte[]) | Fills specified buffer with compressed data.
deflate(byte[], int, int) | Fills specified buffer with compressed data.
end() | Discards unprocessed input and frees internal data.
finalize() | Frees the compressor when garbage is collected.
finish() | When called, indicates that compression should end with the current contents of the input buffer.
finished() | Returns true if the end of the compressed data output stream has been reached.
getAdler() | Returns the ADLER-32 value of the uncompressed data.
getTotalIn() | Returns the total number of bytes input so far.
getTotalOut() | Returns the total number of bytes output so far.
needsInput() | Returns true if the input data buffer is empty and setInput() should be called in order to provide more input.
reset() | Resets deflater so that a new set of input data can be processed.
setDictionary(byte[]) | Sets preset dictionary for compression.
setDictionary(byte[], int, int) | Sets preset dictionary for compression.
setInput(byte[]) | Sets input data for compression.
setInput(byte[], int, int) | Sets input data for compression.
setLevel(int) | Sets the current compression level to the specified value.
setStrategy(int) | Sets the compression strategy to the specified value.


 Deflater.BEST_COMPRESSION

Deflater.BEST_COMPRESSION

Syntax
public static final int BEST_COMPRESSION
Description
Compression level for best compression.


 Deflater.BEST_SPEED

Deflater.BEST_SPEED

Syntax
public static final int BEST_SPEED
Description
Compression level for fastest compression.


 Deflater.DEFAULT_COMPRESSION

Deflater.DEFAULT_COMPRESSION

Syntax
public static final int DEFAULT_COMPRESSION
Description
Default compression level.


 Deflater.DEFAULT_STRATEGY

Deflater.DEFAULT_STRATEGY

Syntax
public static final int DEFAULT_STRATEGY
Description
Default compression strategy.


 Deflater.DEFLATED

Deflater.DEFLATED

Syntax
public static final int DEFLATED
Description
Compression method for the deflate algorithm (the only one currently supported).


 Deflater.FILTERED

Deflater.FILTERED

Syntax
public static final int FILTERED
Description
Compression strategy best used for data consisting mostly of small values with a somewhat random distribution. Forces more Huffman coding and less string matching.


 Deflater.HUFFMAN_ONLY

Deflater.HUFFMAN_ONLY

Syntax
public static final int HUFFMAN_ONLY
Description
Compression strategy for Huffman coding only.


 Deflater.NO_COMPRESSION

Deflater.NO_COMPRESSION

Syntax
public static final int NO_COMPRESSION
Description
Compression level for no compression.


 Deflater.Deflater

Deflater.Deflater

Syntax 1
public Deflater( int level, boolean nowrap )
Parameters
level
the compression level (0-9)
nowrap
if true then use GZIP compatible compression
Description
Creates a new compressor using the specified compression level. If 'nowrap' is true then the ZLIB header and checksum fields will not be used in order to support the compression format used in both GZIP and PKZIP.

Syntax 2
public Deflater( int level )
Parameters
level
the compression level (0-9)
Description
Creates a new compressor using the specified compression level. Compressed data will be generated in ZLIB format.

Syntax 3
public Deflater()
Description
Creates a new compressor with the default compression level. Compressed data will be generated in ZLIB format.


 Deflater.deflate

Deflater.deflate

Syntax 1
public native synchronized int deflate( byte b[], int off, int len )
Parameters
b
the buffer for the compressed data
off
the start offset of the data
len
the maximum number of bytes of compressed data
Returns
the actual number of bytes of compressed data
Description
Fills specified buffer with compressed data. Returns actual number of bytes of compressed data. A return value of 0 indicates that needsInput() should be called in order to determine if more input data is required.

Syntax 2
public int deflate( byte b[] )
Parameters
b
the buffer for the compressed data
Returns
the actual number of bytes of compressed data
Description
Fills specified buffer with compressed data. Returns actual number of bytes of compressed data. A return value of 0 indicates that needsInput() should be called in order to determine if more input data is required.


 Deflater.end

Deflater.end

Syntax
public native synchronized void end()
Description
Discards unprocessed input and frees internal data.


 Deflater.finalize

Deflater.finalize

Syntax
protected void finalize()
Description
Frees the compressor when garbage is collected.

Overrides
finalize in class Object


 Deflater.finish

Deflater.finish

Syntax
public synchronized void finish()
Description
When called, indicates that compression should end with the current contents of the input buffer.


 Deflater.finished

Deflater.finished

Syntax
public synchronized boolean finished()
Description
Returns true if the end of the compressed data output stream has been reached.


 Deflater.getAdler

Deflater.getAdler

Syntax
public native synchronized int getAdler()
Description
Returns the ADLER-32 value of the uncompressed data.


 Deflater.getTotalIn

Deflater.getTotalIn

Syntax
public native synchronized int getTotalIn()
Description
Returns the total number of bytes input so far.


 Deflater.getTotalOut

Deflater.getTotalOut

Syntax
public native synchronized int getTotalOut()
Description
Returns the total number of bytes output so far.


 Deflater.needsInput

Deflater.needsInput

Syntax
public boolean needsInput()
Description
Returns true if the input data buffer is empty and setInput() should be called in order to provide more input.


 Deflater.reset

Deflater.reset

Syntax
public native synchronized void reset()
Description
Resets deflater so that a new set of input data can be processed. Keeps current compression level and strategy settings.


 Deflater.setDictionary

Deflater.setDictionary

Syntax 1
public native synchronized void setDictionary( byte b[], int off, int len )
Parameters
b
the dictionary data bytes
off
the start offset of the data
len
the length of the data
Description
Sets preset dictionary for compression. A preset dictionary is used when the history buffer can be predetermined. When the data is later uncompressed with Inflater.inflate(), Inflater.getAdler() can be called in order to get the Adler-32 value of the dictionary required for decompression.

See Also
inflate, getAdler

Syntax 2
public void setDictionary( byte b[] )
Parameters
b
the dictionary data bytes
Description
Sets preset dictionary for compression. A preset dictionary is used when the history buffer can be predetermined. When the data is later uncompressed with Inflater.inflate(), Inflater.getAdler() can be called in order to get the Adler-32 value of the dictionary required for decompression.

See Also
inflate, getAdler


 Deflater.setInput

Deflater.setInput

Syntax 1
public synchronized void setInput( byte b[], int off, int len )
Parameters
b
the input data bytes
off
the start offset of the data
len
the length of the data
Description
Sets input data for compression. This should be called whenever needsInput() returns true indicating that more input data is required.

See Also
needsInput

Syntax 2
public void setInput( byte b[] )
Parameters
b
the input data bytes
Description
Sets input data for compression. This should be called whenever needsInput() returns true indicating that more input data is required.

See Also
needsInput


 Deflater.setLevel

Deflater.setLevel

Syntax
public synchronized void setLevel( int Level )
Parameters
level
the new compression level (0-9)
Description
Sets the current compression level to the specified value.

Exceptions
IllegalArgumentException if the compression level is invalid


 Deflater.setStrategy

Deflater.setStrategy

Syntax
public synchronized void setStrategy( int strategy )
Parameters
strategy
the new compression strategy
Description
Sets the compression strategy to the specified value.

Exceptions
IllegalArgumentException if the compression strategy is invalid


 Class DeflaterOutputStream

Class java.util.zip.DeflaterOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.util.zip.DeflaterOutputStream

public class DeflaterOutputStream
extends FilterOutputStream

This class implements an output stream filter for compressing data in the "deflate" compression format. It is also used as the basis for other types of compression filters, such as GZIPOutputStream.

See Also:
Deflater


 DeflaterOutputStream Members

DeflaterOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | Output buffer for writing compressed data.
def | Compressor for this stream.

Constructors
Name | Description
DeflaterOutputStream(OutputStream) | Creates a new output stream with a defaul compressor and buffer size.
DeflaterOutputStream(OutputStream, Deflater) | Creates a new output stream with the specified compressor and a default buffer size.
DeflaterOutputStream(OutputStream, Deflater, int) | Creates a new output stream with the specified compressor and buffer size.

Methods
Name | Description
close() | Writes remaining compressed data to the output stream and closes the underlying stream.
deflate() | Writes next block of compressed data to the output stream.
finish() | Finishes writing compressed data to the output stream without closing the underlying stream.
write(byte[], int, int) | Writes an array of bytes to the compressed output stream.
write(int) | Writes a byte to the compressed output stream.


 DeflaterOutputStream.buf

DeflaterOutputStream.buf

Syntax
protected byte buf[]
Description
Output buffer for writing compressed data.


 DeflaterOutputStream.def

DeflaterOutputStream.def

Syntax
protected Deflater def
Description
Compressor for this stream.


 DeflaterOutputStream.DeflaterOutputStream

DeflaterOutputStream.DeflaterOutputStream

Syntax 1
public DeflaterOutputStream( OutputStream out, Deflater def, int size )
Parameters
out
the output stream
def
the compressor ("deflater")
len
the output buffer size
Description
Creates a new output stream with the specified compressor and buffer size.

Syntax 2
public DeflaterOutputStream( OutputStream out, Deflater def )
Parameters
out
the output stream
def
the compressor ("deflater")
Description
Creates a new output stream with the specified compressor and a default buffer size.

Syntax 3
public DeflaterOutputStream( OutputStream out )
Description
Creates a new output stream with a defaul compressor and buffer size.


 DeflaterOutputStream.close

DeflaterOutputStream.close

Syntax
public void close() throws IOException
Description
Writes remaining compressed data to the output stream and closes the underlying stream.

Exceptions
IOException if an I/O error has occurred
Overrides
close in class FilterOutputStream


 DeflaterOutputStream.deflate

DeflaterOutputStream.deflate

Syntax
protected void deflate() throws IOException
Description
Writes next block of compressed data to the output stream.


 DeflaterOutputStream.finish

DeflaterOutputStream.finish

Syntax
public void finish() throws IOException
Description
Finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Exceptions
IOException if an I/O error has occurred


 DeflaterOutputStream.write

DeflaterOutputStream.write

Syntax 1
public void write( int b ) throws IOException
Parameters
b
the byte to be written
Description
Writes a byte to the compressed output stream. This method will block until the byte can be written.

Exceptions
IOException if an I/O error has occurred
Overrides
write in class FilterOutputStream

Syntax 2
public void write( byte b[], int off, int len ) throws IOException
Parameters
buf
the data to be written
off
the start offset of the data
len
the length of the data
Description
Writes an array of bytes to the compressed output stream. This method will block until all the bytes are written.

Exceptions
IOException if an I/O error has occurred
Overrides
write in class FilterOutputStream


 Class GZIPInputStream

Class java.util.zip.GZIPInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.util.zip.InflaterInputStream
                           |
                           +----java.util.zip.GZIPInputStream

public class GZIPInputStream
extends InflaterInputStream

This class implements a stream filter for reading compressed data in the GZIP format.

See Also:
InflaterInputStream


 GZIPInputStream Members

GZIPInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
crc | CRC-32 for uncompressed data.
eos | Indicates end of input stream.
GZIP_MAGIC | GZIP header magic number.

Constructors
Name | Description
GZIPInputStream(InputStream) | Creates a new input stream with a default buffer size.
GZIPInputStream(InputStream, int) | Creates a new input stream with the specified buffer size.

Methods
Name | Description
close() | Closes the input stream.
read(byte[], int, int) | Reads uncompressed data into an array of bytes.


 GZIPInputStream.crc

GZIPInputStream.crc

Syntax
protected CRC32 crc
Description
CRC-32 for uncompressed data.


 GZIPInputStream.eos

GZIPInputStream.eos

Syntax
protected boolean eos
Description
Indicates end of input stream.


 GZIPInputStream.GZIP_MAGIC

GZIPInputStream.GZIP_MAGIC

Syntax
public static final int GZIP_MAGIC
Description
GZIP header magic number.


 GZIPInputStream.GZIPInputStream

GZIPInputStream.GZIPInputStream

Syntax 1
public GZIPInputStream( InputStream in, int size ) throws IOException
Parameters
in
the input stream
size
the input buffer size
Description
Creates a new input stream with the specified buffer size.

Exceptions
IOException if an I/O error has occurred

Syntax 2
public GZIPInputStream( InputStream in ) throws IOException
Parameters
in
the input stream
Description
Creates a new input stream with a default buffer size.

Exceptions
IOException if an I/O error has occurred


 GZIPInputStream.close

GZIPInputStream.close

Syntax
public void close() throws IOException
Description
Closes the input stream.

Exceptions
IOException if an I/O error has occurred
Overrides
close in class FilterInputStream


 GZIPInputStream.read

GZIPInputStream.read

Syntax
public int read( byte buf[], int off, int len ) throws IOException
Parameters
buf
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, or -1 if the end of the compressed input stream is reached
Description
Reads uncompressed data into an array of bytes. Blocks until enough input is available for decompression.

Exceptions
IOException if an I/O error has occurred or the compressed input data is corrupt
Overrides
read in class InflaterInputStream


 Class GZIPOutputStream

Class java.util.zip.GZIPOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.util.zip.DeflaterOutputStream
                           |
                           +----java.util.zip.GZIPOutputStream

public class GZIPOutputStream
extends DeflaterOutputStream

This class implements a stream filter for writing compressed data in the GZIP file format.


 GZIPOutputStream Members

GZIPOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
crc | CRC-32 of uncompressed data.

Constructors
Name | Description
GZIPOutputStream(OutputStream) | Creates a new output stream with a default buffer size.
GZIPOutputStream(OutputStream, int) | Creates a new output stream with the specified buffer size.

Methods
Name | Description
close() | Writes remaining compressed data to the output stream and closes the underlying stream.
finish() | Finishes writing compressed data to the output stream without closing the underlying stream.
write(byte[], int, int) | Writes array of bytes to the compressed output stream.


 GZIPOutputStream.crc

GZIPOutputStream.crc

Syntax
protected CRC32 crc
Description
CRC-32 of uncompressed data.


 GZIPOutputStream.GZIPOutputStream

GZIPOutputStream.GZIPOutputStream

Syntax 1
public GZIPOutputStream( OutputStream out, int size ) throws IOException
Parameters
out
the output stream
size
the output buffer size
Description
Creates a new output stream with the specified buffer size.

Exceptions
IOException If an I/O error has occurred.

Syntax 2
public GZIPOutputStream( OutputStream out ) throws IOException
Parameters
out
the output stream
Description
Creates a new output stream with a default buffer size.

Exceptions
IOException If an I/O error has occurred.


 GZIPOutputStream.close

GZIPOutputStream.close

Syntax
public void close() throws IOException
Description
Writes remaining compressed data to the output stream and closes the underlying stream.

Exceptions
IOException if an I/O error has occurred
Overrides
close in class DeflaterOutputStream


 GZIPOutputStream.finish

GZIPOutputStream.finish

Syntax
public void finish() throws IOException
Description
Finishes writing compressed data to the output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Exceptions
IOException if an I/O error has occurred
Overrides
finish in class DeflaterOutputStream


 GZIPOutputStream.write

GZIPOutputStream.write

Syntax
public synchronized void write( byte buf[], int off, int len ) throws IOException
Parameters
buf
the data to be written
off
the start offset of the data
len
the length of the data
Description
Writes array of bytes to the compressed output stream. This method will block until all the bytes are written.

Exceptions
IOException If an I/O error has occurred.
Overrides
write in class DeflaterOutputStream


 Class Inflater

Class java.util.zip.Inflater

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.Inflater

public class Inflater
extends Object

This class provides support for general purpose decompression using the popular ZLIB compression library. The ZLIB compression library was initially developed as part of the PNG graphics standard and is not protected by patents. It is fully described in RFCs 1950, 1951, and 1952, which can be found at ftp://ds.internic.net/rfc in the files rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).

See Also:
Deflater


 Inflater Members

Inflater Members

Class Overview | This Package | All Packages

Constructors
Name | Description
Inflater() | Creates a new decompressor.
Inflater(boolean) | Creates a new decompressor.

Methods
Name | Description
end() | Discards unprocessed input and frees internal data.
finalize() | Frees the decompressor when garbage is collected.
finished() | Return true if the end of the compressed data stream has been reached.
getAdler() | Returns the ADLER-32 value of the uncompressed data.
getRemaining() | Returns the total number of bytes remaining in the input buffer.
getTotalIn() | Returns the total number of bytes input so far.
getTotalOut() | Returns the total number of bytes output so far.
inflate(byte[]) | Uncompresses bytes into specified buffer.
inflate(byte[], int, int) | Uncompresses bytes into specified buffer.
needsDictionary() | Returns true if a preset dictionary is needed for decompression.
needsInput() | Returns true if no data remains in the input buffer.
reset() | Resets inflater so that a new set of input data can be processed.
setDictionary(byte[]) | Sets the preset dictionary to the given array of bytes.
setDictionary(byte[], int, int) | Sets the preset dictionary to the given array of bytes.
setInput(byte[]) | Sets input data for decompression.
setInput(byte[], int, int) | Sets input data for decompression.


 Inflater.Inflater

Inflater.Inflater

Syntax 1
public Inflater( boolean nowrap )
Parameters
nowrap
if true then support GZIP compatible compression
Description
Creates a new decompressor. If the parameter 'nowrap' is true then the ZLIB header and checksum fields will not be used in order to support the compression format used by both GZIP and PKZIP.

Syntax 2
public Inflater()
Description
Creates a new decompressor.


 Inflater.end

Inflater.end

Syntax
public native synchronized void end()
Description
Discards unprocessed input and frees internal data.


 Inflater.finalize

Inflater.finalize

Syntax
protected void finalize()
Description
Frees the decompressor when garbage is collected.

Overrides
finalize in class Object


 Inflater.finished

Inflater.finished

Syntax
public synchronized boolean finished()
Description
Return true if the end of the compressed data stream has been reached.


 Inflater.getAdler

Inflater.getAdler

Syntax
public native synchronized int getAdler()
Description
Returns the ADLER-32 value of the uncompressed data.


 Inflater.getRemaining

Inflater.getRemaining

Syntax
public synchronized int getRemaining()
Description
Returns the total number of bytes remaining in the input buffer. This can be used to find out what bytes still remain in the input buffer after decompression has finished.


 Inflater.getTotalIn

Inflater.getTotalIn

Syntax
public native synchronized int getTotalIn()
Description
Returns the total number of bytes input so far.


 Inflater.getTotalOut

Inflater.getTotalOut

Syntax
public native synchronized int getTotalOut()
Description
Returns the total number of bytes output so far.


 Inflater.inflate

Inflater.inflate

Syntax 1
public native synchronized int inflate( byte b[], int off, int len ) throws DataFormatException
Parameters
b
the buffer for the uncompressed data
off
the start offset of the data
len
the maximum number of uncompressed bytes
Returns
the actual number of uncompressed bytes
Description
Uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the later case, getAdler() can be used to get the Adler-32 value of the dictionary required.

Exceptions
DataFormatException if the compressed data format is invalid
See Also
needsInput, needsDictionary

Syntax 2
public int inflate( byte b[] ) throws DataFormatException
Parameters
b
the buffer for the uncompressed data
Returns
the actual number of uncompressed bytes
Description
Uncompresses bytes into specified buffer. Returns actual number of bytes uncompressed. A return value of 0 indicates that needsInput() or needsDictionary() should be called in order to determine if more input data or a preset dictionary is required. In the later case, getAdler() can be used to get the Adler-32 value of the dictionary required.

Exceptions
DataFormatException if the compressed data format is invalid
See Also
needsInput, needsDictionary


 Inflater.needsDictionary

Inflater.needsDictionary

Syntax
public synchronized boolean needsDictionary()
Description
Returns true if a preset dictionary is needed for decompression.

See Also
InflatesetDictionary


 Inflater.needsInput

Inflater.needsInput

Syntax
public synchronized boolean needsInput()
Description
Returns true if no data remains in the input buffer. This can be used to determine if #setInput should be called in order to provide more input.


 Inflater.reset

Inflater.reset

Syntax
public native synchronized void reset()
Description
Resets inflater so that a new set of input data can be processed.


 Inflater.setDictionary

Inflater.setDictionary

Syntax 1
public native synchronized void setDictionary( byte b[], int off, int len )
Parameters
b
the dictionary data bytes
off
the start offset of the data
len
the length of the data
Description
Sets the preset dictionary to the given array of bytes. Should be called when inflate() returns 0 and needsDictionary() returns true indicating that a preset dictionary is required. The method getAdler() can be used to get the Adler-32 value of the dictionary needed.

See Also
needsDictionary, getAdler

Syntax 2
public void setDictionary( byte b[] )
Parameters
b
the dictionary data bytes
Description
Sets the preset dictionary to the given array of bytes. Should be called when inflate() returns 0 and needsDictionary() returns true indicating that a preset dictionary is required. The method getAdler() can be used to get the Adler-32 value of the dictionary needed.

See Also
needsDictionary, getAdler


 Inflater.setInput

Inflater.setInput

Syntax 1
public synchronized void setInput( byte b[], int off, int len )
Parameters
b
the input data bytes
off
the start offset of the input data
len
the length of the input data
Description
Sets input data for decompression. Should be called whenever needsInput() returns true indicating that more input data is required.

See Also
needsInput

Syntax 2
public void setInput( byte b[] )
Parameters
b
the input data bytes
Description
Sets input data for decompression. Should be called whenever needsInput() returns true indicating that more input data is required.

See Also
needsInput


 Class InflaterInputStream

Class java.util.zip.InflaterInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.util.zip.InflaterInputStream

public class InflaterInputStream
extends FilterInputStream

This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream.

See Also:
Inflater


 InflaterInputStream Members

InflaterInputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
buf | Input buffer for decompression.
inf | Decompressor for this stream.
len | Length of input buffer.

Constructors
Name | Description
InflaterInputStream(InputStream) | Creates a new input stream with a default decompressor and buffer size.
InflaterInputStream(InputStream, Inflater) | Creates a new input stream with the specified decompressor and a default buffer size.
InflaterInputStream(InputStream, Inflater, int) | Creates a new input stream with the specified decompressor and buffer size.

Methods
Name | Description
fill() | Fills input buffer with more data to decompress.
read() | Reads a byte of uncompressed data.
read(byte[], int, int) | Reads uncompressed data into an array of bytes.
skip(long) | Skips specified number of bytes of uncompressed data.


 InflaterInputStream.buf

InflaterInputStream.buf

Syntax
protected byte buf[]
Description
Input buffer for decompression.


 InflaterInputStream.inf

InflaterInputStream.inf

Syntax
protected Inflater inf
Description
Decompressor for this stream.


 InflaterInputStream.len

InflaterInputStream.len

Syntax
protected int len
Description
Length of input buffer.


 InflaterInputStream.InflaterInputStream

InflaterInputStream.InflaterInputStream

Syntax 1
public InflaterInputStream( InputStream in, Inflater inf, int size )
Parameters
in
the input stream
inf
the decompressor ("inflater")
len
the input buffer size
Description
Creates a new input stream with the specified decompressor and buffer size.

Syntax 2
public InflaterInputStream( InputStream in, Inflater inf )
Parameters
in
the input stream
inf
the decompressor ("inflater")
Description
Creates a new input stream with the specified decompressor and a default buffer size.

Syntax 3
public InflaterInputStream( InputStream in )
Description
Creates a new input stream with a default decompressor and buffer size.


 InflaterInputStream.fill

InflaterInputStream.fill

Syntax
protected void fill() throws IOException
Description
Fills input buffer with more data to decompress.

Exceptions
IOException if an I/O error has occurred


 InflaterInputStream.read

InflaterInputStream.read

Syntax 1
public int read() throws IOException
Returns
the byte read, or -1 if end of compressed input is reached
Description
Reads a byte of uncompressed data. This method will block until enough input is available for decompression.

Exceptions
IOException if an I/O error has occurred
Overrides
read in class FilterInputStream

Syntax 2
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, or -1 if the end of the compressed input is reached or a preset dictionary is needed
Description
Reads uncompressed data into an array of bytes. This method will block until some input can be decompressed.

Exceptions
ZipException if a ZIP format error has occurred
Exceptions
IOException if an I/O error has occurred
Overrides
read in class FilterInputStream


 InflaterInputStream.skip

InflaterInputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to skip
Returns
the actual number of bytes skipped.
Description
Skips specified number of bytes of uncompressed data.

Exceptions
IOException if an I/O error has occurred
Overrides
skip in class FilterInputStream


 Class ZipEntry

Class java.util.zip.ZipEntry

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.ZipEntry

public class ZipEntry
extends Object
implements ZipConstants

This class is used to represent a ZIP file entry.


 ZipEntry Members

ZipEntry Members

Class Overview | This Package | All Packages

Fields
Name | Description
DEFLATED | Compression method for compressed (deflated) entries.
STORED | Compression method for uncompressed entries.

Constructors
Name | Description
ZipEntry(String) | Creates a new ZIP file entry with the specified name.

Methods
Name | Description
getComment() | Returns the comment string for the entry, or null if none.
getCompressedSize() | Returns the compressed size of the entry data, or -1 if not known.
getCrc() | Returns the CRC-32 checksum of the uncompressed entry data, or -1 if not known.
getExtra() | Returns the extra field data for the entry, or null if none.
getMethod() | Returns the compression method of the entry, or -1 if not specified.
getName() | Returns the name of the entry.
getSize() | Returns the uncompressed size of the entry data, or -1 if not known.
getTime() | Returns the modification time of the entry, or -1 if not specified.
isDirectory() | Returns true if this is a directory entry.
setComment(String) | Sets the optional comment string for the entry.
setCrc(long) | Sets the CRC-32 checksum of the uncompressed entry data.
setExtra(byte[]) | Sets the optional extra field data for the entry.
setMethod(int) | Sets the compression method for the entry.
setSize(long) | Sets the uncompressed size of the entry data.
setTime(long) | Sets the modification time of the entry.
toString() | Returns a string representation of the ZIP entry.


 ZipEntry.DEFLATED

ZipEntry.DEFLATED

Syntax
public static final int DEFLATED
Description
Compression method for compressed (deflated) entries.


 ZipEntry.STORED

ZipEntry.STORED

Syntax
public static final int STORED
Description
Compression method for uncompressed entries.


 ZipEntry.ZipEntry

ZipEntry.ZipEntry

Syntax
public ZipEntry( String name )
Parameters
name
the entry name
Description
Creates a new ZIP file entry with the specified name.

Exceptions
NullPointerException if the entry name is null
Exceptions
IllegalArgumentException if the entry name is longer than 0xFFFF bytes


 ZipEntry.getComment

ZipEntry.getComment

Syntax
public String getComment()
Description
Returns the comment string for the entry, or null if none.


 ZipEntry.getCompressedSize

ZipEntry.getCompressedSize

Syntax
public long getCompressedSize()
Description
Returns the compressed size of the entry data, or -1 if not known. In the case of a stored entry, the compressed size will be the same as the uncompressed size of the entry.


 ZipEntry.getCrc

ZipEntry.getCrc

Syntax
public long getCrc()
Description
Returns the CRC-32 checksum of the uncompressed entry data, or -1 if not known.


 ZipEntry.getExtra

ZipEntry.getExtra

Syntax
public byte[] getExtra()
Description
Returns the extra field data for the entry, or null if none.


 ZipEntry.getMethod

ZipEntry.getMethod

Syntax
public int getMethod()
Description
Returns the compression method of the entry, or -1 if not specified.


 ZipEntry.getName

ZipEntry.getName

Syntax
public String getName()
Description
Returns the name of the entry.


 ZipEntry.getSize

ZipEntry.getSize

Syntax
public long getSize()
Description
Returns the uncompressed size of the entry data, or -1 if not known.


 ZipEntry.getTime

ZipEntry.getTime

Syntax
public long getTime()
Description
Returns the modification time of the entry, or -1 if not specified.


 ZipEntry.isDirectory

ZipEntry.isDirectory

Syntax
public boolean isDirectory()
Description
Returns true if this is a directory entry. A directory entry is defined to be one whose name ends with a '/'.


 ZipEntry.setComment

ZipEntry.setComment

Syntax
public void setComment( String comment )
Parameters
comment
the comment string
Description
Sets the optional comment string for the entry.

Exceptions
IllegalArgumentException if the length of the specified comment string is greater than 0xFFFF bytes


 ZipEntry.setCrc

ZipEntry.setCrc

Syntax
public void setCrc( long crc )
Parameters
crc
the CRC-32 value
Description
Sets the CRC-32 checksum of the uncompressed entry data.

Exceptions
IllegalArgumentException if the specified CRC-32 value is less than 0 or greater than 0xFFFFFFFF


 ZipEntry.setExtra

ZipEntry.setExtra

Syntax
public void setExtra( byte extra[] )
Parameters
extra
the extra field data bytes
Description
Sets the optional extra field data for the entry.

Exceptions
IllegalArgumentException if the length of the specified extra field data is greater than 0xFFFFF bytes


 ZipEntry.setMethod

ZipEntry.setMethod

Syntax
public void setMethod( int method )
Parameters
method
the compression method, either STORED or DEFLATED
Description
Sets the compression method for the entry.

Exceptions
IllegalArgumentException if the specified compression method is invalid


 ZipEntry.setSize

ZipEntry.setSize

Syntax
public void setSize( long size )
Parameters
size
the uncompressed size in bytes
Description
Sets the uncompressed size of the entry data.

Exceptions
IllegalArgumentException if the specified size is less than 0 or greater than 0xFFFFFFFF bytes


 ZipEntry.setTime

ZipEntry.setTime

Syntax
public void setTime( long time )
Parameters
time
the entry modification time in number of milliseconds since the epoch
Description
Sets the modification time of the entry.


 ZipEntry.toString

ZipEntry.toString

Syntax
public String toString()
Description
Returns a string representation of the ZIP entry.

Overrides
toString in class Object


 Class ZipException

Class java.util.zip.ZipException

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.lang.Throwable
           |
           +----java.lang.Exception
                   |
                   +----java.io.IOException
                           |
                           +----java.util.zip.ZipException

public class ZipException
extends IOException


 ZipException Members

ZipException Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ZipException() |
ZipException(String) |


 ZipException.ZipException

ZipException.ZipException

Syntax 1
public ZipException()

Syntax 2
public ZipException( String s )


 Class ZipFile

Class java.util.zip.ZipFile

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.util.zip.ZipFile

public class ZipFile
extends Object
implements ZipConstants

This class can be used to read the contents of a ZIP file. It uses RandomAccessFile for quick access to ZIP file entries, and supports both compressed and uncompressed entries.


 ZipFile Members

ZipFile Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ZipFile(File) | Opens a ZIP file for reading given the specified File object.
ZipFile(String) | Opens a ZIP file for reading given the specified file name.

Methods
Name | Description
close() | Closes the ZIP file.
entries() | Returns an enumeration of the ZIP file entries.
getEntry(String) | Returns the ZIP file entry for the given path name.
getInputStream(ZipEntry) | Returns an input stream for reading the contents of the specified ZIP file entry.
getName() | Returns the path name of the ZIP file.


 ZipFile.ZipFile

ZipFile.ZipFile

Syntax 1
public ZipFile( String name ) throws IOException
Parameters
name
the name of the zip file
Description
Opens a ZIP file for reading given the specified file name.

Exceptions
ZipException if a ZIP format error has occurred
Exceptions
IOException if an I/O error has occurred

Syntax 2
public ZipFile( File file ) throws ZipException, IOException
Parameters
file
the ZIP file to be opened for reading
Description
Opens a ZIP file for reading given the specified File object.

Exceptions
ZipException if a ZIP error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipFile.close

ZipFile.close

Syntax
public void close() throws IOException
Description
Closes the ZIP file.


 ZipFile.entries

ZipFile.entries

Syntax
public Enumeration entries()
Description
Returns an enumeration of the ZIP file entries.


 ZipFile.getEntry

ZipFile.getEntry

Syntax
public ZipEntry getEntry( String name )
Parameters
name
the name of the entry
Returns
the ZIP file entry
Description
Returns the ZIP file entry for the given path name. Returns null if there is no entry corresponding to the given name.


 ZipFile.getInputStream

ZipFile.getInputStream

Syntax
public InputStream getInputStream( ZipEntry ze ) throws IOException
Parameters
ze
the zip file entry
Description
Returns an input stream for reading the contents of the specified ZIP file entry.

Exceptions
ZipException if a ZIP format error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipFile.getName

ZipFile.getName

Syntax
public String getName()
Description
Returns the path name of the ZIP file.


 Class ZipInputStream

Class java.util.zip.ZipInputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.InputStream
           |
           +----java.io.FilterInputStream
                   |
                   +----java.util.zip.InflaterInputStream
                           |
                           +----java.util.zip.ZipInputStream

public class ZipInputStream
extends InflaterInputStream
implements ZipConstants

This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.


 ZipInputStream Members

ZipInputStream Members

Class Overview | This Package | All Packages

Constructors
Name | Description
ZipInputStream(InputStream) | Creates a new ZIP input stream.

Methods
Name | Description
close() | Closes the ZIP input stream.
closeEntry() | Closes the current ZIP entry and positions the stream for reading the next entry.
getNextEntry() | Reads the next ZIP file entry and positions stream at the beginning of the entry data.
read(byte[], int, int) | Reads from the current ZIP entry into an array of bytes.
skip(long) | Skips specified number of bytes in the current ZIP entry.


 ZipInputStream.ZipInputStream

ZipInputStream.ZipInputStream

Syntax
public ZipInputStream( InputStream in )
Parameters
in
the actual input stream
Description
Creates a new ZIP input stream.


 ZipInputStream.close

ZipInputStream.close

Syntax
public void close() throws IOException
Description
Closes the ZIP input stream.

Exceptions
IOException if an I/O error has occurred
Overrides
close in class FilterInputStream


 ZipInputStream.closeEntry

ZipInputStream.closeEntry

Syntax
public void closeEntry() throws IOException
Description
Closes the current ZIP entry and positions the stream for reading the next entry.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipInputStream.getNextEntry

ZipInputStream.getNextEntry

Syntax
public ZipEntry getNextEntry() throws IOException
Description
Reads the next ZIP file entry and positions stream at the beginning of the entry data.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipInputStream.read

ZipInputStream.read

Syntax
public int read( byte b[], int off, int len ) throws IOException
Parameters
b
the buffer into which the data is read
off
the start offset of the data
len
the maximum number of bytes read
Returns
the actual number of bytes read, or -1 if the end of the entry is reached
Description
Reads from the current ZIP entry into an array of bytes. Blocks until some input is available.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred
Overrides
read in class InflaterInputStream


 ZipInputStream.skip

ZipInputStream.skip

Syntax
public long skip( long n ) throws IOException
Parameters
n
the number of bytes to skip
Returns
the actual number of bytes skipped
Description
Skips specified number of bytes in the current ZIP entry.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred
Overrides
skip in class InflaterInputStream


 Class ZipOutputStream

Class java.util.zip.ZipOutputStream

Class Members | This Package | All Packages
java.lang.Object
   |
   +----java.io.OutputStream
           |
           +----java.io.FilterOutputStream
                   |
                   +----java.util.zip.DeflaterOutputStream
                           |
                           +----java.util.zip.ZipOutputStream

public class ZipOutputStream
extends DeflaterOutputStream
implements ZipConstants

This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.


 ZipOutputStream Members

ZipOutputStream Members

Class Overview | This Package | All Packages

Fields
Name | Description
DEFLATED | Compression method for compressed (DEFLATED) entries.
STORED | Compression method for uncompressed (STORED) entries.

Constructors
Name | Description
ZipOutputStream(OutputStream) | Creates a new ZIP output stream.

Methods
Name | Description
close() | Closes the ZIP output stream as well as the stream being filtered.
closeEntry() | Closes the current ZIP entry and positions the stream for writing the next entry.
finish() | Finishes writing the contents of the ZIP output stream without closing the underlying stream.
putNextEntry(ZipEntry) | Begins writing a new ZIP file entry and positions the stream to the start of the entry data.
setComment(String) | Sets the ZIP file comment.
setLevel(int) | Sets the compression level for subsequent entries which are DEFLATED.
setMethod(int) | Sets the default compression method for subsequent entries.
write(byte[], int, int) | Writes an array of bytes to the current ZIP entry data.


 ZipOutputStream.DEFLATED

ZipOutputStream.DEFLATED

Syntax
public static final int DEFLATED
Description
Compression method for compressed (DEFLATED) entries.


 ZipOutputStream.STORED

ZipOutputStream.STORED

Syntax
public static final int STORED
Description
Compression method for uncompressed (STORED) entries.


 ZipOutputStream.ZipOutputStream

ZipOutputStream.ZipOutputStream

Syntax
public ZipOutputStream( OutputStream out )
Parameters
out
the actual output stream
Description
Creates a new ZIP output stream.


 ZipOutputStream.close

ZipOutputStream.close

Syntax
public void close() throws IOException
Description
Closes the ZIP output stream as well as the stream being filtered.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred
Overrides
close in class DeflaterOutputStream


 ZipOutputStream.closeEntry

ZipOutputStream.closeEntry

Syntax
public void closeEntry() throws IOException
Description
Closes the current ZIP entry and positions the stream for writing the next entry.

Exceptions
ZipException if a ZIP format error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipOutputStream.finish

ZipOutputStream.finish

Syntax
public void finish() throws IOException
Description
Finishes writing the contents of the ZIP output stream without closing the underlying stream. Use this method when applying multiple filters in succession to the same output stream.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O exception has occurred
Overrides
finish in class DeflaterOutputStream


 ZipOutputStream.putNextEntry

ZipOutputStream.putNextEntry

Syntax
public void putNextEntry( ZipEntry e ) throws IOException
Parameters
e
the ZIP entry to be written
Description
Begins writing a new ZIP file entry and positions the stream to the start of the entry data. Closes the current entry if still active. The default compression method will be used if no compression method was specified for the entry, and the current time will be used if the entry has no set modification time.

Exceptions
ZipException if a ZIP format error has occurred
Exceptions
IOException if an I/O error has occurred


 ZipOutputStream.setComment

ZipOutputStream.setComment

Syntax
public void setComment( String comment )
Parameters
comment
the comment string
Description
Sets the ZIP file comment.

Exceptions
IllegalArgumentException if the length of the specified ZIP file comment is greater than 0xFFFF bytes


 ZipOutputStream.setLevel

ZipOutputStream.setLevel

Syntax
public void setLevel( int level )
Parameters
level
the compression level (0-9)
Description
Sets the compression level for subsequent entries which are DEFLATED. The default setting is DEFAULT_COMPRESSION.

Exceptions
IllegalArgumentException if the compression level is invalid


 ZipOutputStream.setMethod

ZipOutputStream.setMethod

Syntax
public void setMethod( int method )
Parameters
method
the default compression method
Description
Sets the default compression method for subsequent entries. This default will be used whenever the compression method is not specified for an individual ZIP file entry, and is initially set to DEFLATED.

Exceptions
IllegalArgumentException if the specified compression method is invalid


 ZipOutputStream.write

ZipOutputStream.write

Syntax
public synchronized void write( byte b[], int off, int len ) throws IOException
Parameters
b
the data to be written
off
the start offset in the data
len
the number of bytes that are written
Description
Writes an array of bytes to the current ZIP entry data. This method will block until all the bytes are written.

Exceptions
ZipException if a ZIP file error has occurred
Exceptions
IOException if an I/O error has occurred
Overrides
write in class DeflaterOutputStream


Visual J++ Code Model

The COM interfaces that comprise the Visual J++ Code Model are described in this section. The interfaces provide access to information about the code in your current project. Much of this information is obtained by a background parser that runs under the Visual J++ development environment. This parser continually processes the code, rebuilding parse trees and symbol tables in response to every change. The Code Model interfaces expose the contents of these trees and tables in a format that provides easy programmatic access from any automation-capable language. The interfaces also permit callers to modify the code.

The Visual J++ Code Model is used by various parts of Visual J++, including the source code editor, the class browser, and various wizards and designers. It can also be used by third-party add-ins.

For detailed information, see the following interfaces:

  • IJavaBlockStatement

  • IJavaClass

  • IJavaClasses

  • IJavaCodeSense

  • IJavaCommentTags

  • IJavaCompileUnit

  • IJavaCompileUnitEvents

  • IJavaDocComment

  • IJavaField

  • IJavaImports

  • IjavaInitializer

  • IJavaInitializers

  • IJavaMember

  • IJavaMembers

  • IJavaMethod

  • IJavaPackage

  • IJavaPackages

  • IJavaSourceElement

  • IJavaSourceElements

  • IJavaStatement

See the following for information on:

  • JavaClassModifier, JavaClassModifiers

  • JavaMemberModifier, JavaMemberModifiers

  • JavaNameSearchFlag, JavaNameSearchFlags

  • JavaNamespaceFlag, JavaNamespaceFlags

  • JavaPrototypeFlag, JavaPrototypeFlags

  • JavaReferenceType

  • JavaStatementType


IJavaBlockStatement Interface

The IJavaBlockStatement interface represents a Java block statement (a statement delimited by braces and containing zero or more statements). It functions as a collection of statements.

IJavaBlockStatement : IJavaStatement

This interface defines the following members:

Member | Description
AddStatementText | Inserts a new statement at the given index.
Count | Returns the number of statements contained in this block.
Item | Returns the IJavaStatement at the given index.
RemoveStatementAt | Removes a statement from the block.


IJavaBlockStatement::AddStatementText

Inserts a new statement at the given index.

Syntax

HRESULT AddStatementText([in] BSTR bstrStatementText, [in] long nIndex);

Sub AddStatementText(ByVal bstrStatementText As String, ByVal nIndex As Long)

This syntax has these parts:

Parameters

bstrStatementText

String. Statement text.

nIndex

Long.


IJavaBlockStatement::Count

This property returns the number of statements contained in this block.

Syntax

[propget] HRESULT Count([out, retval] long* retval);


IJavaBlockStatement::Item

This function returns the IJavaStatement at the given index.

Syntax

HRESULT Item([in] VARIANT index, [out, retval] IJavaStatement** ppMember);

Function Item(ByVal index) As IJavaStatement

Parameters

index

Variant reference to IJavaStatement.


IJavaBlockStatement::RemoveStatementAt

Removes a statement from the block, specified by its index.

Syntax

HRESULT RemoveStatementAt([in] long nIndex);


IJavaClass Interface

The IJavaClass interface represents a Java class, interface, or delegate.

IJavaClass : IJavaSourceElement

This interface defines the following members:

Member | Description
AddField | Adds a field class member.
AddMethod | Adds a method class member.
CanOverride | Indicates whether the class can override the given method.
FullName | Represents the fully-qualified name of the class.
GetBlockRange | Returns the range of text containing the class.
GetBodyRange | Returns the text range containing the class’s body.
GetNameRange | Returns the start position and length of the range of text containing the class’s name.
Initializers | A collection of the initializers declared within the class.
InnerClasses | A collection of the inner classes declared within the class.
Interfaces | A collection of the interfaces that the class implements.
IsClass | Indicates whether the IJavaClass object represents a class.
IsDelegate | Indicates whether the IJavaClass object represents a delegate.
IsInterface | Indicates whether the IJavaClass object represents an interface.
IsSubclassOf | Traverses the superclass chain and compares the superclasses’ names with the given string.
Members | A collection of the members of the class, both fields and methods.
Modifiers | Provides access to the class’s modifiers.
Name | Represents the simple name of the class.
OverrideMethod | Inserts a method declaration and code stub for the given method.
Package | A reference to the package that contains the class.
RemoveMember | Removes a class member.
Superclass | Provides access to the IJavaClass object representing the class’s superclass.
Subclasses | A collection of all classes that inherit from this class.
SuperclassName | Provides access to the name of the class’s superclass.


IJavaClass::AddField

Use this method to add a field class member.

Syntax

HRESULT AddField(
[in] JavaMemberModifiers mods,
[in] BSTR pType,
[in] BSTR bstrName,
[in] BSTR bstrInitializer,
[in] long nIndex,
[out, retval] IJavaField** retval
);

Function AddField(ByVal mods As Long, ByVal pType As String, ByVal bstrName As String, ByVal bstrInitializer As String, ByVal nIndex As Long) As IJavaField

Parameters

mods

Modifiers for the new field.

pType

The type signature for the type of the new field.

bstrName

The name of the new field.

bstrInitializer

The initial value expression for the new field. May be NULL.

nIndex

The index of the existing member before which the new field should be inserted. To insert the new field at the end of the class, pass –1 as the index.


IJavaClass::AddMethod

Use this method to add a method class member.

Syntax

HRESULT AddMethod([in] JavaMemberModifiers mods, [in] BSTR bstrSignature,
[in] BSTR bstrName, [in] BSTR bstrFormalNames,
[in] BSTR bstrBodyText, [in] long nIndex,
[out, retval] IJavaMethod** retval);

Function AddMethod(ByVal mods As Long, ByVal bstrSignature As String, ByVal bstrName As String, ByVal bstrFormalNames As String, ByVal bstrBodyText As String, ByVal nIndex As Long) As IJavaMethod

Parameters

mods

Modifiers for the new method.

bstrSignature

The type signature for the new method, including parameter types and the return type.

bstrName

The name of the new method.

bstrFormalNames

A comma-separated list of the formal parameter names for the new method.

bstrBodyText

The text to be inserted as the body of the new method. May be NULL.

nIndex

The index of the existing member before which the new method should be inserted. To insert the new method at the end of the class, pass –1 as the index.

Remarks

To add a constructor to a class, call AddMethod() with no return type specified in the signature, and a name that is identical to the class name.


IJavaClass::CanOverride

Indicates whether the class can override the given method. This is determined by searching the class’s methods for a prototype matching the given method. If one is found, or if the given method cannot be overridden for other reasons (for example, it is a final method), VARIANT_FALSE is returned, indicating that a call to OverrideMethod would result in uncompileable code.

Syntax

[propget] HRESULT CanOverride([in] IJavaMethod* pMethod, [out, retval] VARIANT_BOOL* retval);

Property CanOverride(pMethod As IJavaMethod) As Boolean

Parameters

pMethod

The method to be overridden.


IJavaClass::FullName

The FullName property represents the fully-qualified name of the class, including its package name.

Syntax

HRESULT FullName([out, retval] BSTR* retval);

Property Get FullName As String


IJavaClass::GetBlockRange

This method returns the range of text containing the class, including all whitespace preceding the class declaration. These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetBlockRange([out] long* pnStart, [out] long* pnLength);

Sub GetBlockRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

TBD.

pnLength

TBD.


IJavaClass::GetBodyRange

This method returns the text range containing the class’s body. The range begins with left bracket "{" and ends with a right bracket "}". These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetBodyRange(
[out] long* pnStart,
[out] long* pnLength
);

Sub GetBodyRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

TBD.

pnLength

TBD.

Remarks

TBD.


IJavaClass::GetNameRange

This method returns the start position and length of the range of text containing the class’s name. These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetNameRange([out] long* pnStart, [out] long* pnLength);

Sub GetNameRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

Long. Starting position, in character units relative to the compile unit’s text buffer.

pnLength

Long. Length, in character units relative to the compile unit’s text buffer.

Remarks

TBD.


IJavaClass::Initializers

This property is a collection of the initializers declared within the class.

Syntax

HRESULT Initializers([out, retval] IJavaInitializers** retval);

Property Get Initializers As IJavaInitializers


IJavaClass::InnerClasses

This property is a collection of the inner classes declared within the class. This collection includes both nested top-level classes and member classes. It does not include local or anonymous classes.

Syntax

HRESULT InnerClasses([out, retval] IJavaClasses** retval);

Property Get InnerClasses As IJavaClasses


IJavaClass::Interfaces

This property is a collection of the interfaces that the class implements.

Syntax

HRESULT Interfaces([out, retval] IJavaClasses** retval);

Property Get Interfaces As IJavaClasses


IJavaClass::IsClass

This property indicates whether the IJavaClass object represents a class.

Syntax

HRESULT IsClass([out, retval] VARIANT_BOOL* retval);

Property Get IsClass As Boolean


IJavaClass::IsDelegate

This property indicates whether the IJavaClass object represents a delegate.

Syntax

HRESULT IsDelegate([out, retval] VARIANT_BOOL* retval);

Property Get IsDelegate As Boolean


IJavaClass::IsInterface

This property indicates whether the IJavaClass object represents an interface.

Syntax

HRESULT IsInterface([out, retval] VARIANT_BOOL* retval);

Property Get IsInterface As Boolean


IJavaClass::IsSubclassOf

Traverses the superclass chain and compares the superclasses’ names with the given string. If a match is found, returns VARIANT_TRUE. The given string can be a "fully-qualified" dotted name or not.

Syntax

[propget] HRESULT IsSubclassOf([in] BSTR bstrName, [out, retval] VARIANT_BOOL* retval);

Property IsSubclassOf(ByVal bstrName As String) As Boolean

Parameters

bstrName

The class name to check.


IJavaClass::Members

This property is a collection of the members of the class, both fields and methods. The collection can be filtered in various ways with the optional parameters passed when getting the property. The bstrName parameter allows you to retrieve members with a particular name. Passing VARIANT_TRUE for the fIncludeInherited parameter adds members from all superclasses to the collection. Passing an IJavaClass pointer in the pWhoIsAsking parameter will exclude members from the collection that are not accessable from the given class. Finally, flags from the JavaNamespaceFlags enumeration can be specified.

Syntax

[propget] HRESULT Members([in, defaultvalue("")] BSTR bstrName,
[in, defaultvalue(0)] VARIANT_BOOL fIncludeInherited,
[in, defaultvalue(0)] IJavaClass *pWhoIsAsking,
[in, defaultvalue(0)] JavaNamespaceFlags flags,
[out,retval] IJavaMembers **ppMembers
);

Property Members([ByVal bstrName As String], [ByVal fIncludeInherited As Boolean], [pWhoIsAsking As IJavaClass], [ByVal flags As Long]) As IJavaMembers

Parameters

bstrName

TBD.

fIncludeInherited

TBD.

pWhoIsAsking

TBD.

flags

TBD.


IJavaClass::Modifiers

This property provides access to the class’s modifiers.

Syntax

[propget] HRESULT Modifiers([out, retval] JavaMemberModifiers* retval);

[propput] HRESULT Modifiers([in] JavaMemberModifiers newval);

Property Modifiers As Long

Remarks

The modifiers are flag bits drawn from the following set:


IJavaClass::Name

These properties provide access to the name of the class. The Name property represents the simple name of the class. For example, in the class java.awt.Graphics, the Name property is "Graphics" and the FullName property is "java.awt.Graphics."

Syntax

[propget] HRESULT Name([out, retval] BSTR* retval);

[propput] HRESULT Name([in] BSTR newval);

Property Name As String


IJavaClass::OverrideMethod

Inserts a method declaration and code stub for the given method.

Syntax

HRESULT OverrideMethod([in] IJavaMethod* pMethod);

Sub OverrideMethod(pMethod As IJavaMethod)

Parameters

pMethod

The method to be overridden.


IJavaClass::Package

This property is a reference to the package that contains the class.

Syntax

HRESULT Package([out, retval] IJavaPackage** retval);

Property Get Package As IJavaPackage

Remarks

TBD.


IJavaClass::RemoveMember

Use this method to remove a class member.

Syntax

HRESULT RemoveMember([in] IJavaMember* pMember);

Sub RemoveMember(pMember As IJavaMember)

Parameters

pMember

The member to remove.


IJavaClass::Subclasses

This property is a collection of all classes that inherit from this class. All classes in installed packages (including those along the CLASSPATH) and in open Visual J++ projects are searched.

Syntax

[propget] HRESULT Subclasses([out, retval] IJavaClasses** retval);

Property Subclasses As IJavaClasses


IJavaClass::Superclass

This property provides access to the IJavaClass object representing the class’s superclass.

Syntax

[propget] HRESULT Superclass([out, retval] IJavaClass** retval);

[propput] HRESULT Superclass([in] IJavaClass* newval);

Property Superclass As IJavaClass


IJavaClass::SuperclassName

This property provides access to the name of the class’s superclass.

Syntax

[propget] HRESULT SuperclassName([out, retval] BSTR* retval);

[propput] HRESULT SuperclassName([in] BSTR newval);

Property SuperclassName As String


IJavaClasses Interface

This interface is used to enumerate classes in a compile unit or package, as well as interfaces, inner classes, and subclasses of a class.

IJavaClasses : IDispatch

This interface defines the following members:

Member | Description
Add | Inserts a class or interface into the collection by modifying the code that the collection describes.
Count | The number of classes in the collection.
Item | Returns an IJavaClass item from the collection.
Remove | Removes a class from the collection by modifying the code that the collection describes.


IJavaClasses::Add

Inserts a class or interface into the collection by modifying the code that the collection describes. The method’s parameters allow specification of the name of the new class, whether the class or interface keyword should be used, and the position at which to insert the class in the collection.

Syntax

HRESULT Add([in] BSTR bstrName, [in] VARIANT_BOOL bClass, [in] long nIndex, [out, retval] IJavaClass** retval);

Function Add(ByVal bstrName As String, ByVal bClass As Boolean, ByVal nIndex As Long) As IJavaClass

Parameters

bstrName

The name of the new class.

bClass

Indicates whether a new class or interface is to be inserted.

nIndex

The index of the existing class before which the new class is to be inserted. To insert the new class at the end of the collection, pass –1 as the index.


IJavaClasses::Count

The number of classes in the collection.

Syntax

[propget] HRESULT Count([out, retval] long* pCount);

Property Count As Long


IJavaClasses::Item

Returns an IJavaClass item from the collection. The VARIANT index provided specifies either the name of a class to search for, or an integer index.

Syntax

[id(0)] HRESULT Item([in] VARIANT index, [out, retval] IJavaClass** ppClass);

Function Item(ByVal index) As IJavaClass

Parameters

index

Variant. Class item index or name of a class.


IJavaClasses::Remove

Removes a class from the collection by modifying the code that the collection describes.

Syntax

HRESULT Remove([in] IJavaClass* pClass);

Sub Remove(pClass As IJavaClass)

Parameters

pClass

TBD.


IJavaCodeSense Interface

The IJavaCodeSense interface is the primary interface for the Visual J++ Code Model service, providing global Code Model operations. It is accessed by calling IServiceProvider::QueryService, with SID_SJavaCodeSense as the service ID:

hr = QueryService (SID_SJavaCodeSense, IID_IJavaCodeSense, &pICS)

This interface defines the following members:

Member | Description
Class | Returns a class object for the named class, searching relative to the given base directory.
CompileUnit | Provides access to a compile unit.
Package | Returns a package object for the named package, searching relative to the given base directory.
SourceElements | Provides access to a collection of one or more named Java source code elements.


IJavaCodeSense::Class

Returns a class object for the named class, searching relative to the given base directory.

Syntax

HRESULT Class(
IjavaClass*BSTR bstrName,
[in] BSTR bstrCurrentDirectory,
[in] DWORD dwFlags
);

Property Class(ByVal bstrClassName As String, ByVal bstrCurrentDirectory As String, ByVal dwFlags As Unsigned Long) As IJavaClass

Parameters

bstrClassName

Required String. Class name specification.

bstrCurrentDirectory

String. Current directory file specification.

dwFlags

TBD.

Remarks

Classes are identified by their names within the Java namespace (such as java.lang.String). An optional directory name parameter may be specified as a starting point for locating the requested class. This directory is substituted for “.” wherever it appears in the CLASSPATH.


IJavaCodeSense::CompileUnit

This property provides access to a compile unit (a file containing one or more classes).

Syntax

HRESULT CompileUnit(
[in]BSTR bstrFileName,
IJavaCompileUnit* retval
);

Property Get CompileUnit(FileName As String) As IJavaCompileUnit

Parameters

FileName

Required String. A full-path name identifying the file containing one or more classes.

Remarks

Compile units are identified by fully-qualified file names (for example, C:\MyClasses\Foo.java). The filename extension is optional. If a file with the .java extension does not exist, but a corresponding .class file does exist, the Java Code Model will use the .class file to obtain as much information as possible about the class.

Return Value

The value obtained from the returned HRESULT is one of the following:

Return value | Meaning
S_OK | Success


IJavaCodeSense::Package

Returns a package object for the named package, searching relative to the given base directory.

Syntax

HRESULT Package(
[in]BSTR bstrName
[in]VARIANT_BOOL fPublic
[in]BSTR bstrDir
[out, retval]IJavaPackage** retval
);

Property Get CompileUnit(FileName As String) As IJavaCompileUnit

Parameters

FileName

Required String. A full path name identifying the file containing one or more classes.

fPublic

Boolean. Determines if this property is public.

bstrDir

String. Base directory.

Remarks

Packages are identified by their names within the Java namespace (such as java.lang). An optional directory name parameter may be specified as a starting point for locating the requested package. This directory is substituted for “.” wherever it appears in the CLASSPATH.


IJavaCodeSense::SourceElements

This property provides access to a collection of one or more named Java source code elements (classes, methods, or fields).

Syntax

HRESULT SourceElements(
[in]BSTR bstrName
[in]JavaNameSearchFlags flags
[out, retval]IJavaSourceElements **retval
);

Property SourceElements(ByVal bstrName As String, ByVal flags As Long) As IjavaSourceElements

Parameters

bstrName

Required String. Class, method, or field.

flags

Long.

Remarks

If more than one element matches the specified name (for example, overloaded methods; classes in different packages), all such source elements are included in the returned collection.


IJavaCommentTags Interface

This is a generic interface to the four types of tag collections in a documentation comment (Links, Authors, Params, and Exceptions). It provides standard enumeration methods as well as Add/Remove methods for manipulating the content.

IJavaCommentTags : IDispatch

This interface defines the following members:

Member | Description
Add | Adds a new tag to the collection.
Count | Provides the number of tags in the collection.
Item | TBD
Remove | Removes a tag from the collection.


IJavaCommentTags::Add

Adds a new tag to the collection. The tag name will be the same as the others in the collection.

Syntax

HRESULT Add([in] BSTR bstrText, [in] long nIndex);

Sub Add(ByVal bstrText As String, ByVal nIndex As Long)

Parameters

bstrText

String. Tag name.

nIndex

TBD


IJavaCommentTags::Count

This property provides the number of tags in the collection.

Syntax

[propget] HRESULT Count([out, retval] long* retval);


IJavaCommentTags::Item

The VARIANT index provided specifies either an integer index in the collection or a name which searches the first word following the tag.

Syntax

HRESULT Item(
[in] VARIANT varIndex,
[out, retval] BSTR* retval

);

Function Item(ByVal varIndex) As String

Parameters

varIndex

Specifies either an integer index in the collection or a name.

Remarks

The named lookup is useful in the Params and Exceptions collections because the first word contains the name of the parameter or type of exception, which is subsequently documented.


IJavaCommentTags::Remove

Removes a tag from the collection. Either a string or an integer may be passed in the VARIANT parameter.

Syntax

HRESULT Remove([in] VARIANT varIndex);

Sub Remove(ByVal varIndex)

Parameters

varIndex

TBD.


IJavaCompileUnit Interface

This interface represents a Java compile unit (source file).

public interface IJavaCompileUnit extends Iunknown

The interface contains the following properties and methods:

Method | Description
Classes | Collection of the classes in the compile unit.
ClassFromType | Returns a class for a given type signature.
FindPackage | Returns the package with a specified name.
Imports | Collection of the compile unit’s imported package and class names.
Package | Provides access to the package containing this compile unit.
PackageName | Name of the package containing this compile unit.
PrimaryClassName | The name of the primary (public) class in this compile unit.
ProjectItem | The VJProjectItem that corresponds to the compile unit.
ReadOnly | Indicates whether the compile unit can be modified.
SaveChanges | Commits changes that have been made in the compile unit, unless the user has the file open for editing.
TextFromType | Converts a type signature to a type name in text format.
TypeFromText | Converts a type name in text format to a type signature.


IJavaCompileUnit::Classes

Provides access to the classes that are contained in the compile units of the package.

Syntax

HRESULT Classes(
[out, retval] IJavaClasses** retval
);

Property Classes As IJavaClasses


IJavaCompileUnit::ClassFromType

This property returns the class corresponding to the given type signature.

Syntax

HRESULT ClassFromType([in] BSTR bstrType, [out, retval] IJavaClass** retval);

Function ClassFromType(ByVal bstrType As String) As IJavaClass

Parameters

bstrType

The type signature.

Remarks

If the type signature represents a primitive type or an array type, the property access fails.


IJavaCompileUnit::FindPackage

This method returns the package that contains a class with the given name. The name resolution is performed relative to the namespace of the compile unit.

Syntax

HRESULT FindPackage([in] BSTR bstrName,
[out, retval] IJavaPackage** retval);

Function FindPackage(ByVal bstrName As String) As IJavaPackage

Parameters

bstrName

The name of the requested package.


IJavaCompileUnit::Imports

This property is a collection of the names of packages and classes that are imported by the compile unit. For a compiled .class file, this collection is always empty.

Syntax

HRESULT Imports(
[out, retval] IJavaImports** retval
);

Property Imports As IJavaImports


IJavaCompileUnit::Package

Provides access to the name of the IJavaPackage object representing the package for the compile unit.

Syntax

HRESULT Package([out, retval] IJavaPackage** retval);

Property Get Package As IJavaPackage


IJavaCompileUnit::PackageName

Provides access to the name of the compile unit’s package.

Syntax

HRESULT PackageName([out, retval] BSTR* retval);

Property Get PackageName As String


IJavaCompileUnit::PrimaryClassName

This property is the name of the primary class in the compile unit.

Syntax

HRESULT PrimaryClassName([out, retval] BSTR* retval);

Property Get PrimaryClassName As String

Remarks

This is the name of the class that matches the compile unit’s filename (typically, this is the public class in the compile unit).


IJavaCompileUnit::ProjectItem

This read-only property returns the VJProjectItem that corresponds to the IJavaCompileUnit, if there is one. This property may return Nothing if the IJavaCompileUnit does not represent a file of Java code that is part of the current Solution.

Property ProjectItem As VJExt._VJProjectItem


IJavaCompileUnit::ReadOnly

This property indicates whether the compile unit can be modified.

Syntax

HRESULT ReadOnly(
[out, retval] VARIANT_BOOL* retval

);

Property ReadOnly As Boolean

Remarks

A compile unit may be read-only if source code is not available.


IJavaCompileUnit::SaveChanges

This method causes any changes to the compile unit’s text buffer to be saved to disk.

Syntax

HRESULT SaveChanges();

Sub SaveChanges

Remarks

If the buffer is successfully saved, the method returns S_OK. If the buffer is currently locked for editing (for example, open in an editor window), the buffer is not saved, and the method returns S_FALSE. If the buffer cannot be saved for any other reason, the method fails.


IJavaCompileUnit::TextFromType

This property returns the textual (Java source code) representation of a type that corresponds to a type signature. The given type signature must conform to the Java signature format. A parameter specifies whether a class name appearing in the returned name should be expressed as a simple name or as a fully-qualified name.

Syntax

HRESULT TextFromType(
[in] JavaReferenceType jrt,
[in] IJavaCompileUnit* pUnitDest,
[in] BSTR bstrType,
[out, retval] BSTR* retval
);

Function TextFromType(ByVal jrt As JavaReferenceType, pUnitDest As IJavaCompileUnit, bstrType As String) As String

Parameters

jrt

The type of reference name requested.

JRT_NOCHANGE leave the class name exactly the way it appears in the source code.

JRT_SHORT return the simple class name, with no package name.

JRT_FULL return the full class name, including package name, if any.

JRT_MINIMAL return the shortest possible class name; if the class is imported by the compile unit, or is part of the same package as the compile unit, return the simple class name; otherwise, return the full class name.

pUnitDest

The compile unit in which the type name will be used. May be NULL.

bstrType

The type signature to be converted.


IJavaCompileUnit::TypeFromText

This property returns the type signature that corresponds to the textual (Java source code) representation of a type.

Syntax

TypeFromText([in] BSTR bstrText, [out, retval] BSTR* retval);

Function TypeFromText(ByVal bstrText As String) As String

Parameters

bstrText

The type name to be converted.

Remarks

The given textual type may represent a primitive type (such as char, short), a class type (for example, String), or an array type (such as int[]). The given textual type is interpreted relative to namespace of the compile unit, which includes all imported classes and all other classes in the compile unit’s package. The returned type signature conforms to the Java signature format, as defined in Section 2.2 of the Java Virtual Machine Specification.


IJavaCompileUnitEvents Interface

This is an outgoing (event) interface provided by the compile unit via the standard connection point mechanism. If you implement this interface, you can query the compile unit object for IID_IConnectionPointContainer, then call its FindConnectionPoint method with IID_IJavaCompileUnitEvents as the parameter. On the connection point interface returned, you can pass your event handler to the Advise method.

Note You can also register to receive this event from the CodeSense object, in which case your handler will receive events from all compile units.

This interface defines the following members:

Member | Description
OnCompileUnitChanged | Signals that the objects created by the parser may have changed.


IJavaCompileUnitEvents::OnCompileUnitChanged

This event is fired immediately after the CodeSense parser runs, and signals that the objects created by the parser may have changed. The parser runs only when information is requested from a CodeSense object, and the buffer has been changed since the last parse.

Syntax

HRESULT OnCompileUnitChanged(
[in]IJavaCompileUnit* pUnit);
};

Sub OnCompileUnitChanged(pUnit As IJavaCompileUnit)

Parameters

pUnit

The compile unit that has changed.

Remarks

TBD.


IJavaDocComment Interface

The IJavaDocComment interface represents the documentation comment for a class, field, or method.

IJavaDocComment : Idispatch

A documentation comment is delimited by /** and */, and immediately precedes the source element that it describes. For a description of the contents of documentation comments, refer to Chapter 18 of The Java Language Specification.

This interface defines the following members:

Member | Description
Authors | Provides access to the first of @author tags in the documentation comment.
Description | Provides access to all text preceding the first tag in the comment.
Exception | Provides access to the list of @exception tags in the documentation comment.
Links | Provides access to the list of @see tags in the documentation comment.
Params | Provides access to the list of @param tags in the documentation comment.
RemoveTag | Deletes a tag with the given name.
Return | Provides access to the @return tag in the documentation comment.
Summary | Provides access to the summary sentence of the documentation comment.
TagValue | Allows read/write access to the tag with the given name.
Text | Provides access to the complete text of the documentation comment.
Version | Provides access to the @version tag in the documentation comment.


IJavaDocComment::Authors

This collection provides access to the list of @author tags in the documentation comment.

Syntax

[propget] HRESULT Authors([out, retval] IJavaCommentTags** retval);


IJavaDocComment::Description

This property provides access to all text preceding the first tag in the comment, including the summary sentence.

Syntax

[propget] HRESULT Description([out, retval] BSTR* retval);

[propput] HRESULT Description([in] BSTR newval);

Property Description As String


IJavaDocComment::Exceptions

This collection provides access to the list of @exception tags in the documentation comment.

Syntax

[propget] HRESULT Exceptions([out, retval] IJavaCommentTags** retval);


IJavaDocComment::Links

This collection provides access to the list of @see tags in the documentation comment.

Syntax

[propget] HRESULT Links([out, retval] IJavaCommentTags** retval);


IJavaDocComment::Params

This collection provides access to the list of @param tags in the documentation comment.

Syntax

[propget] HRESULT Params([out, retval] IJavaCommentTags** retval);


IJavaDocComment::RemoveTag

This method deletes a tag with the given name.

Syntax

HRESULT RemoveTag([in] BSTR bstrTagName);


IJavaDocComment::Return

This property provides access to the @return tag in the documentation comment.

Syntax

[propget] HRESULT Return([out, retval] BSTR* retval);

[propput] HRESULT Return([in] BSTR newval);


IJavaDocComment::Summary

This property provides access to the summary sentence of the documentation comment.

Syntax

[propget] HRESULT Summary([out, retval] BSTR* retval);

Property Get Summary As String


IJavaDocComment::TagValue

This property allows read/write access to the tag with the given name.

Syntax

[propget] HRESULT TagValue([in] BSTR bstrTagName, [out, retval] BSTR* retval);

[propput] HRESULT TagValue([in] BSTR bstrTagName, [in] BSTR newval);


IJavaDocComment::Text

This property provides access to the complete text of the documentation comment. Leading spaces and asterisks are stripped from the beginning of each line.

Syntax

[propget] HRESULT Text([out, retval] BSTR* retval);

[propput] HRESULT Text([in] BSTR newval);

Property Text As String


IJavaDocComment::Version

This property provides access to the @version tag in the documentation comment.

Syntax

[propget] HRESULT Version([out, retval] BSTR* retval);

[propput] HRESULT Version([in] BSTR newval);


IJavaField Interface

The IJavaField interface represents a field of a class. IJavaField is derived from IJavaMember.

interface IJavaField : IJavaMember

This interface defines the following members:

Member | Description
InitialValue | Provides access to the field’s initial value expression.


IJavaField::InitialValue

This property provides access to the field’s initial value expression, if any. If the field has no initial value, the InitialValue property is NULL.

Syntax

[propget] HRESULT InitialValue([out, retval] BSTR* retval);

[propput] HRESULT InitialValue([in] BSTR newval);

Property InitialValue As String


IJavaImports Interface

The IJavaImports interface allows enumeration of the import statements in a compile unit.

IJavaImports : IDispatch

This interface defines the following members:

Member | Description
Add | Adds an import statement for the given package to the compile unit.
Count | Returns the number of import statements in the compile unit.
Item | Returns the name of the imported package or class at the given index.
Remove | Removes the given import statement from the compile unit.


IJavaImports::Add

Adds an import statement for the given package to the compile unit.

Syntax

HRESULT Add([in] BSTR bstrName);

Remarks

TBD.


IJavaImports::Count

This property returns the number of import statements in the compile unit.

Syntax

[propget] HRESULT Count([out, retval] long* pCount);


IJavaImports::Item

This property returns the name of the imported package or class at the given index.

Syntax

[id(0)] HRESULT Item([in] VARIANT index, [out, retval] BSTR* retval);


IJavaImports::Remove

Removes the given import statement from the compile unit.

Syntax

HRESULT Remove([in] BSTR bstrName);

Remarks

TBD.


IJavaInitializer Interface

The IJavaInitializer interface represents a static or instance initializer.

IJavaInitializer : IJavaSourceElement

This interface defines the following members:

Member | Description
Body | Allows enumeration of the statements that comprise the initializer.
Modifiers | Provides access to the initializer’s modifiers.


IJavaInitializer::Body

This property allows enumeration of the statements that comprise the initializer.

Syntax

[propget] HRESULT Body([out, retval] IJavaBlockStatement** retval);


IJavaInitializer::Modifiers

This property provides access to the initializer’s modifiers. The only relevant bit flag for an initializer is JMM_STATIC.

Syntax

[propget] HRESULT Modifiers([out, retval] JavaMemberModifiers* retval);


IJavaInitializers Interface

The IJavaInitializers interface allows enumeration of the class initializers.

IJavaInitializers : IDispatch

This interface defines the following members:

Member | Description
Count | Returns the number of initializers in the class.
Item | Returns the IJavaInitializer at the given index.


IJavaInitializers::Count

This property returns the number of initializers in the class.

Syntax

[propget] HRESULT Count([out, retval] long* pCount);


IJavaInitializers::Item

This property returns the IJavaInitializer at the given index.

Syntax

[id(0)] HRESULT Item([in] VARIANT index, [out, retval] IJavaInitializer** retval);

Remarks

TBD.


IJavaMember Interface

The IJavaMember interface represents a member (field or method) of a class.

IJavaMember : IJavaSourceElement

This interface defines the following members:

Member | Description
Class | Provides access to the class containing the member.
GetBlockRange | Returns the range of text containing the member.
GetNameRange | Returns the start position and length of the range of text containing the member’s name.
IsField | Indicates that the member is a field.
IsMethod | Indicates that the member is a method.
Modifiers | Provides access to the member’s modifiers.
Name | Provides access to the member’s name.
Type | Provides access to the member’s type.


IJavaMember::Class

This property provides access to the class containing the member.

Syntax

[propget] HRESULT Class([out, retval] IJavaClass** retval);

Property Class As IJavaClass


IJavaMember::GetBlockRange

This method returns the range of text containing the member, including all whitespace preceding the member declaration. These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetBlockRange([out] long* pnStart, [out] long* pnLength);

Sub GetBlockRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

TBD.

pnLength

TBD.


IJavaMember::GetNameRange

This method returns the start position and length of the range of text containing the member’s name. These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetNameRange([out] long* pnStart, [out] long* pnLength);

Sub GetNameRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

TBD.

pnLength

TBD.


IJavaMember::IsField

This property indicates that the member is a field.

Syntax

[propget] HRESULT IsField([out, retval] VARIANT_BOOL* retval);

Property IsField As Boolean


IJavaMember::IsMethod

This property indicates that the member is a method.

Syntax

[propget] HRESULT IsMethod([out, retval] VARIANT_BOOL* retval);

Property IsMethod As Boolean


IJavaMember::Modifiers

This property provides access to the member’s modifiers.

Syntax

[propget] HRESULT Modifiers([out, retval] JavaMemberModifiers* retval);

[propput] HRESULT Modifiers([in] JavaMemberModifiers newval);

Property Modifiers As Long

The modifiers are flag bits drawn from the following set:

  • JMM_PUBLIC

  • JMM_PROTECTED

  • JMM_PRIVATE

  • JMM_FINAL

  • JMM_STATIC

  • JMM_TRANSIENT (valid only for fields)

  • JMM_VOLATILE (valid only for fields)

  • JMM_ABSTRACT (valid only for methods)

  • JMM_SYNCHRONIZED (valid only for methods)

  • JMM_NATIVE (valid only for methods)


IJavaMember::Name

This property provides access to the member’s name.

Syntax

[propget] HRESULT Name([out, retval] BSTR* retval);

[propput] HRESULT Name([in] BSTR newval);

Property Name As String


IJavaMember::Type

This property provides access to the member’s type. For a method, the Type property indicates the method’s return type. The type is returned as a type signature string. If the member is a constructor method, the type signature will be an empty string.

Syntax

[propget] HRESULT Type([out, retval] BSTR* retval);

[propput] HRESULT Type([in] BSTR newval);

Property Type As String


IJavaMembers Interface

This interface is used to enumerate class members.

IJavaMembers : IDispatch

This interface defines the following members:

Member | Description
Count | The number of members in the collection.
Item | The VARIANT index provided specifies an integer index in the collection.
UniqueField | TBD


IJavaMembers::Count

The number of members in the collection.

Syntax

[propget] HRESULT Count([out, retval] long* pCount);

Property Count As Long


IJavaMembers::Item

The VARIANT index provided specifies an integer index in the collection.

Syntax

[id(0)] HRESULT Item([in] VARIANT index, [out, retval] IJavaMember** ppMember)

Function Item(ByVal index) As IJavaMember

Parameters

index

Variant. Integer index of the item in the collection.


IJavaMembers::UniqueField

If the collection represents all overloaded class members with the same name (differing only by their parameters), it will contain at most one field element, since there can only be one field with any given name. This method will return that field, if any.

Syntax

[propget] HRESULT UniqueField ([out,retval] IJavaField **ppField);

Property UniqueField As IJavaField


IJavaMethod Interface

The IJavaMethod interface represents a method of a class.

interface IJavaMethod : IJavaMember

This interface defines the following members:

Member | Description
AddFormal | Adds a new formal parameter to the method.
Body | Provides access to the block statement that comprises the body of the method.
Exceptions | A collection of the exceptions this method can throw.
FormalCount | Provides access to the count of the method’s formal parameters.
FormalNameAt | Provides access to the name of one of the method’s formal parameters.
FormalNames | Provides access to the method’s list of formal parameter names.
FormalTypeAt | Provides access to the type of one of the method’s formal parameters.
FormalTypes | Provides access to the method’s list of formal parameter types.
GetBodyRange | Returns the range of text containing the method's block statement.
IsConstructor | Indicates whether the method is a constructor.
RemoveFormal | Removes a formal prameter from the method.
RemoveFormalAt | Removes a formal parameter from the method using the index.


IJavaMethod::AddFormal

Adds a new formal parameter to the method.

Syntax

HRESULT AddFormal([in] BSTR pType, [in] BSTR bstrName, [in] long nIndex);

Sub AddFormal(ByVal pType As String, ByVal bstrName As String, ByVal nIndex As Long)

Parameters

pType

The type signature for the new formal parameter.

bstrName

The name of the new formal parameter.

nIndex

The index of the existing formal parameter after which to insert the new one. To insert a new parameter at the end of the list, pass –1 as the index.


IJavaMethod::Body

This property provides access to the block statement that comprises the body of the method.

Syntax

[propget] HRESULT Body([out, retval] IJavaBlockStatement** retval);

Property Body As IJavaBlockStatement


IJavaMethod::Exceptions

This property is a collection of the exceptions this method can throw.

Syntax

[propget] HRESULT Exceptions([out, retval] IJavaClasses** retval);

Property Exceptions As IJavaClasses


IJavaMethod::FormalCount

Provides access to the count of the method’s formal parameters.

Syntax

HRESULT FormalCount([out, retval] long* retval);

Property Get FormalCount As Long


IJavaMethod::FormalNameAt

Provides access to the name of one of the method’s formal parameters.

Syntax

[propget] HRESULT FormalNameAt([in] long nIndex, [out, retval] BSTR* retval);

[propput] HRESULT FormalNameAt([in] long nIndex, [in] BSTR newval);

Property FormalNameAt(ByVal nIndex As Long) As String

Parameters

nIndex

Long. Type.


IJavaMethod::FormalNames

Provides access to the method’s list of formal parameter names. The formal names are returned as a comma-separated list.

Syntax

HRESULT FormalNames([out, retval] BSTR* retval);

Property Get FormalNames As String


IJavaMethod::FormalTypeAt

Provides access to the type of one of the method’s formal parameters. The formal type is returned in type signature format.

Syntax

[propget] HRESULT FormalTypeAt([in] long nIndex, [out, retval] BSTR* retval);

[propput] HRESULT FormalTypeAt([in] long nIndex, [in] BSTR newval);

Property FormalTypeAt(ByVal nIndex As Long) As String

Parameters

nIndex

Long. Type.


IJavaMethod::FormalTypes

Provides access to the method’s list of formal parameter types. The formal types are returned in type signature format.

Syntax

HRESULT FormalTypes([out, retval] BSTR* retval);

Property Get FormalTypes As String


IJavaMethod::GetBodyRange

This method returns the range of text containing the method’s block statement, beginning with a left bracket "{" and ending with a right bracket "}." These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetBodyRange([out] long* pnStart, [out] long* pnLength);

Sub GetBodyRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

TBD.

pnLength

TBD.


IJavaMethod::IsConstructor

This property indicates whether the method is a constructor.

Syntax

Property get IsConstructor As Boolean.


IJavaMethod::RemoveFormal

Removes a formal parameter from the method.

Syntax

HRESULT RemoveFormal([in] BSTR bstrName);

Sub RemoveFormal(ByVal bstrName As String)

Parameters

bstrName

The name of the formal parameter to remove.


IJavaMethod::RemoveFormalAt

Removes a formal parameter from the method.

Syntax

HRESULT RemoveFormalAt([in] long nIndex);

Sub RemoveFormalAt(ByVal nIndex As Long)

Parameters

nIndex

The index of the formal parameter to remove.


IJavaPackage Interface

The IJavaPackage interface represents a Java package. A package is a directory in the file system or an installed archive, such as a .cab or .zip file. A package consists of a collection of compile units and a collection of subpackages. A package also has a name, and can have a parent package.

This interface defines the following members:

Member | Description
Classes | A collection of the classes in the package.
Name | Provides access to the name of the package in the Java namespace.
ParentPackage | Provides access to the parent package of the package.
SubPackages | A collection of the subpackages in the package.


IJavaPackage::Classes

This property is a collection of the classes in the package.

Classes(
[out, retval] IJavaClasses** retval
);

Property Classes As IJavaClasses


IJavaPackage::Name

This property provides access to the name of the package in the Java namespace. (For example, java.lang.)

Syntax

HRESULT Name(
[out, retval] BSTR* retval);

Property Name As String


IJavaPackage::ParentPackage

This property provides access to the parent package of the package.

Syntax

HRESULT ParentPackage(
[out, retval] IJavaPackage** retval
);

Property ParentPackage As IJavaPackage

The parent package is contained in the parent directory of the package directory. The parent package is NULL if the current package is a top-level package.


IJavaPackage::SubPackages

This property is a collection of the subpackages in the package.

Syntax

SubPackages(
[out, retval] IJavaPackages** retval
);

Property SubPackages As IJavaPackages


IJavaPackages Interface

This interface represents a collection of package collections.

This interface defines the following members:

Member | Description
Count | Returns the number of packages in the collection.
Item | Returns one package in the collection of packages.
PackageNamed | TBD


IJavaPackages::Count

This property returns the number of packages in the collection.

Syntax

HRESULT Count([out, retval] long* retval);

Property Get Count As Long


IJavaPackages::Item

This method returns one package in the collection of packages. The VARIANT index provides lookup by name or by integer index.

Syntax

HRESULT Item(
[in] VARIANT index,
[out, retval] IJavaPackage** retval
);

Function Item(ByVal index) As IJavaPackage

Parameters

byVal

Variant. By name or by integer index.


IJavaPackages::PackageNamed

Syntax

HRESULT PackageNamed(
[in] BSTR bstrName,
[out, retval] IJavaPackage **retval
);

Property PackageNamed(ByVal bstrName As String) As IJavaPackage

Parameters

bstrName

String. Package name.


IJavaSourceElement Interface

The IJavaSourceElement interface is a common interface shared by the interfaces that represent various elements appearing within a compile unit. These interfaces include IJavaClass, IJavaMember, and IJavaStatement.

IJavaSourceElement : Idispatch

This interface defines the following members:

Member | Description
CompileUnit | A reference to the compile unit that contains the source element.
DocComment | Provides access to the member’s documentation comment.
GetRange | Returns the start position and length of the range of text containing the source element.
IsValid | Indicates whether the source element object is valid.
Prototype | Returns a prototype string for the source element.


IJavaSourceElement::CompileUnit

This property is a reference to the compile unit that contains the source element.

Syntax

[propget] HRESULT CompileUnit([out, retval] IJavaCompileUnit** retval);

Property CompileUnit As IJavaCompileUnit


IJavaSourceElement::DocComment

This property provides access to the member’s documentation comment, if any.

Syntax

HRESULT DocComment([out, retval] IJavaDocComment** retval);

Property Get DocComment As IJavaDocComment


IJavaSourceElement::GetRange

This method returns the start position and length of the range of text containing the source element. These values are expressed in character units relative to the compile unit’s text buffer.

Syntax

HRESULT GetRange(
[out] long* pnStart,
[out] long* pnLength
);

Sub GetRange(pnStart As Long, pnLength As Long)

Parameters

pnStart

The start position of the source element’s text range.

pnLength

The number of characters in the source element’s text range.


IJavaSourceElement::IsValid

This property indicates whether the source element object is valid.

Syntax

[propget] HRESULT IsValid([out, retval] VARIANT_BOOL* retval);

Property Get IsValid As Boolean

Remarks

A source element object may be invalid if the compile unit has been changed since the source element was first accessed.


IJavaSourceElement::Prototype

This property returns a prototype string for the source element.

Syntax

HRESULT Prototype([in] JavaPrototypeFlags jpf, [out, retval] BSTR* retval);

Property Get Prototype(ByVal jpf As Long) As String

Parameters

jpf

Formatting flags for the prototype string

JPF_NONAME, JPF_CLASSNAME, and JPF_FULLNAME are mutually exclusive; the rest can be freely combined.

JPF_NONAME do not include the element’s name in the prototype.

JPF_CLASSNAME if the element is a member of a class, prepend the name of the class and a ‘.’ to the name.

JPF_FULLNAME also prepend the package name to the class name.

JPF_TYPE for class members, include the type of the field or return type of the method before its name.

JPF_PARAMTYPES for methods, include a list of parameter types in parentheses after the name.

JPF_PARAMNAMES also include the parameter names.

JPF_FULLTYPENAMES specifies fully-qualified names for reference types included in the prototype.

Remarks

The property takes a JavaPrototypeFlags parameter that describes which components of the prototype to include.


IJavaSourceElements Interface

The IJavaSourceElements interface allows enumeration of source elements. This collection is returned by the SourceElements property of the IJavaCodeSense interface.

interface IJavaSourceElements : Idispatch

This interface defines the following members:

Member | Description
Count | Returns the number of source elements in the collection.
Item | Returns the source element at the given index.


IJavaSourceElements::Count

This property returns the number of source elements in the collection.

Syntax

[propget] HRESULT Count([out, retval] long* pCount);

Property Count As Long


IJavaSourceElements::Item

This function returns the source element at the given index.

Syntax

[id(0)] HRESULT Item([in] VARIANT index, [out, retval] IJavaSourceElement** retval);

Function Item(ByVal index) As IJavaSourceElement

Parameters

index

TBD.


IJavaStatement Interface

The IJavaStatement interface represents a statement within a Java method or initializer.

IJavaStatement : IJavaSourceElement

This interface defines the following members:

Member | Description
StatementType | Indicates the type of statement.
Text | Provides access to the text of the statement.


IJavaStatement::StatementType

This property indicates the type of statement.

Syntax

[propget] HRESULT StatementType([out, retval] JavaStatementType* retval);

Property StatementType As JavaStatementType

The statement type is a value from among the following set:

  • JST_EMPTY

  • JST_BLOCK

  • JST_IF

  • JST_WHILE

  • JST_DO

  • JST_FOR

  • JST_SWITCH

  • JST_CASE

  • JST_TRY

  • JST_BREAK

  • JST_CONTINUE

  • JST_LABEL

  • JST_RETURN

  • JST_THROW

  • JST_SYNC

  • JST_EXPRESSION

  • JST_DECLARATION


IJavaStatement::Text

This property provides access to the text of the statement.

Syntax

[propget] HRESULT Text([out, retval] BSTR* retval);


JavaClassModifier, JavaClassModifiers

The following flags are associated with this enumeration:

JCM_PUBLIC
JCM_PRIVATE
JCM_PROTECTED
JCM_FINAL
JCM_ABSTRACT

typedef long JavaClassModifiers;


JavaMemberModifier, JavaMemberModifiers

The following flags are associated with this enumeration:

Flag | Equals
JMM_PUBLIC | 0x0001,
JMM_PRIVATE | 0x0002,
JMM_PROTECTED | 0x0004,
JMM_STATIC | 0x0008,
JMM_FINAL | 0x0010,
JMM_SYNCHRONIZED | 0x0020,
JMM_VOLATILE | 0x0040,
JMM_TRANSIENT | 0x0080,
JMM_NATIVE | 0x0100,
JMM_ABSTRACT | 0x0400,

   JavaMemberModifier;
   typedef long JavaMemberModifiers;


JavaNamespaceFlag, JavaNamespaceFlags

The following flags are associated with this enumeration:

JNF_TYPESONLY | Internal use only
JNF_STATICONLY | Only static class members
JNF_INVOLVED | Internal use only
JNF_IMPORT | Names that may appear in import statements
JNF_PACKAGE | Internal use only
JNF_INCLUDEPROTECTED | Internal use only
JNF_CONSTRUCTORSONLY | Constructors only


JavaNameSearchFlag, JavaNameSearchFlags

The following flags are associated with this enumeration:

JNSF_NOOPENPROJECTS | No open projects
JNSF_NOINSTALLEDPACKAGES | No installed packages
JNSF_NOCLASSES | No classes
JNSF_NOMEMBERS | No members


JavaPrototypeFlag, JavaPrototypeFlags

The following flags are associated with this enumeration:

JPF_NONAME | Mutually exclusive with JPF_CLASSNAME and JPF_FULLNAME
JPF_CLASSNAME |
JPF_FULLNAME | Includes JPF_CLASSNAME
JPF_TYPE |
JPF_PARAMTYPES |
JPF_PARAMNAMES |
JPF_FULLTYPENAMES |


JavaReferenceType

The following flags are associated with this enumeration:

Flag | Equals
JRT_NOCHANGE | 0,
JRT_SHORT | 1,
JRT_FULL | 2,
JRT_MINIMAL | 3,


JavaStatementType Enumeration

JavaStatementType

The following flags are associated with this enumeration:

Flag | Equals
JST_EMPTY | 0,
JST_BLOCK | 1,
JST_IF | 2,
JST_WHILE | 3,
JST_DO | 4,
JST_FOR | 5,
JST_SWITCH | 6,
JST_CASE | 7,
JST_TRY | 8,
JST_BREAK | 9,
JST_CONTINUE | 10,
JST_LABEL | 11,
JST_RETURN | 12,
JST_THROW | 13,
JST_SYNC | 14,
JST_EXPRESSION | 15,
JST_DECLARATION | 16,
JST_SWITCHLABEL | 17,
JST_LOCALCLASS | 18,


Extensibility in Visual J++

Additions to the Visual Studio extensibility object model are described in this section.

  • VJProject Object, VJProjects Collection

  • VJProjectItem Object, VJProjectItems Collection

  • VJProperty Object, VJProperties Collection

  • Events Object

  • VJProjectEvents Object, VJProjectItemsEvents Object

  • SelectedItem Object, SelectedItems Collection


VJProject Object, VJProjects Collection

The VJProjects collection contains all of the VJProjects in the solution.

You can access just the collection of Visual J++ projects with DTE.VJProjects.

Remarks

The Visual J++ package defines a VJProjects collection that is immediately accessible from the DTE Object, and this collection contains a project object for each Visual J++ project in the solution.

There is no projects collection containing all projects in the solution. The Solution object contains all the projects in the solution.


VJProjectItem Object, VJProjectItems Collection

The VJProjectItem object represents an item contained in a Visual J++ project.

The VJProjectItems collection contains all VJProjectItem objects in the current instance of the development environment.

See also:

  • Code Property


Code Property

Returns the root object of the model for Java code in a file.

Syntax

Property Get Code () As IJavaCompileUnit

This syntax has these parts:

Part | Description
object | This is the item just added.


VJProperty Object, VJProperties Collection

The VJProperty object represents a property of another object. It provides a way to associate a property with an object other than accessing it from the object as in object1.property1.

The VJProperties collection contains all currently available VJProperty objects.

Remarks

See also: Property Object, Properties Collection


VJProjectsEvents Property

Returns the VJProjectEvents object.

Syntax

Property Get VJProjectsEvents([Filter As Object]) As VJProjectsEvents

This syntax has these parts:

Part | Description
filter | If not NULL, this is a VJProject indicating that the resulting VJProjectsEvents object will only source events for the specified VJProject.


VJProjectItemsEvents Property

Returns the VJProjectItemsEvents object.

Syntax

Property Get VJProjectItemEvents([Filter As Object]) As VJProjectItemsEvents

This syntax has these parts:

Part | Description
filter | If not NULL, this is a VJProjectItem indicating that the resulting VJProjectItemsEvents object will only source events for the specified VJProject.


VJProjectsEvents Object

VJProjectsEvents Object, VJProjectItemsEvents Object

These objects source the following events:

  • ItemAdded Event

  • ItemRemoved Event

  • ItemRenamed Event


ItemAdded Event (Visual J++)

This event is signalled just after adding a VJProject.

Syntax

Event ItemAdded (object As VJProject)

Event ItemAdded (object As VJProjectItem)

This syntax has these parts:

Part | Description
object | This is the item just added.


ItemRemoved Event (Visual J++)

This event is signalled just after removing a VJProject or VJProjectItem.

Syntax

ProjectEvents object:

Event ItemRemoved (object As VJProject)

ProjectItemsEvents object:

Event ItemRemoved (object As VJProjectItem)

Syntax

This syntax has these parts:

Part | Description
object | This is the item just removed.


ItemRenamed Event (Visual J++)

This event is signalled just after renaming a VJProject or VJProjectItem.

Syntax

ProjectItemsEvents object:

Event ItemRenamed (object As VJProjectItem, oldname As String)

ProjectEvents object:

Event ItemRenamed (object As VJProject, oldname As String)

This syntax has these parts:

Part | Description
object | This is the item just renamed.
oldname | String. The previous name of the item.


SelectedItem Object, SelectedItems Collection

The SelectedItem object represents a selected project or project item.

The SelectedItems collection returns a collection of all SelectedItem objects.

Remarks

The SelectedItem object allows you to get the project with the focus in order to provide context for an add-in.

A project always has a SelectedItems collection, even when there are no project items selected. For example, if the Project Explorer has focus and a project node is selected, there is one SelectedItem object. That selected item’s Project property points to the selected project, and the ProjectItem property is Null.

When the alternate directory view is up, and a file is selected that is not a project item, the SelectedItem.Info field provides the full pathname to the selected file. The project and projectitem properties are set to Null.

  • .Name - Display name for the item (for example, what is displayed in the project browser)

  • .Info(i) - Indexed property of extra information about the selected item. This is used by VJ++ when the alternate directory view is shown in the project browser, and a file is selected that is not in the project. .Info(1) contains the full pathname to the file.

  • .InfoCount - tells you how many strings are in .Info. This is always 1 for VJ.


Conditional Compilation

Conditional compilation could be defined as “a process where selected parts of a program are included or excluded from the compilation of an application, based on a set of developer-defined conditions.” The two mechanisms Visual J++ provides for Conditional compilation are conditional compiler directives (conditional directives,) and conditional methods.

Conditional methods are useful for

Visual J++ allows you to select relies on the use of a preprocessor. A preprocessor is typically a component of a language compiler that reads in a source file and makes certain changes in order to prepare the source code for compilation. In a program written with Visual J++, the preprocessor examines the Java source code and looks for certain directives, all beginning with the pound sign symbol (#), evaluates the lines according to the information found, then performs such operations as extracting lines, replacing values, and emitting error and warning messages. After the preprocessor completes its work, the alter source code is then checked for syntactical errors and finally compiled into bytecode.

The conditional compilation mechanism in Visual J++ is an extension to the Java language, provided by Microsoft. Thus, source code containing these directives will not compile properly with other tools.

Conditional compilation is an extremely useful tool that aids software development. For example, you can use conditional compilation mechanisms to establish organization-wide coding standards, or you can use them to create helpful, ongoing debugging processes during the development process. In the later case, with just a few minor alterations, the code can be ready to shipped to customers without debugging information.

Other reasons to use conditional compilation include:

  • Output performance data from instrumented builds.

  • Output logic paths for debugging

  • View alternative implementations (experimental algorithms, new implementation paths.)

  • Add additional interfaces

  • Create slightly different code implementations.

Following is an example of compiler directives and conditional methods used in a Java application.

#define DEBUG // We’re debugging the application now

class printIt {

    //* @conditional(debug) */
    public void assert( ) {
        System.out.println(“Hello World – From the assert method”);
    }
}

public class myApp (

}

Before you start using these elements in your own code, it will be helpful to review some of the rules governing their use. After you’re familiar with the guidelines, take a look at the directives available and their specific uses.

Visual J++ recognizes the following conditional directives:


Conditional Directives: Guidelines for Their Use in Java

Like standard conditional constructs in Java, many of the conditional compiler directives also make use of conditional expressions that govern their use. For example, the #if compiler directive, like it’s Java language equivalent, the if statement, makes use of Java-like identifiers, operators, and expressions. With few differences, the same rules that govern the syntax of creating syntactically correct statements in Java also apply to the creation of conditional directives.

The primary difference hinted at above is in the use comments. For more information on using comments with conditional directives, see Proper Formatting of Conditional Compiler Directives.

Rules that apply to the use of identifiers in conditional compilation are summarized in section 3.8 of the Java language specification. The one exception to the rules documented in section 3.8 can be stated as follows:

Basically I need to say here: All rules applied to the use identifiers, operators, and expressions in the Java language, also apply to conditional directives, with one exception. Conditional directives may be up to 1024 characters in length.


Proper Formatting of Conditional Compiler Directives

Section should really be titled: Use of White Space and comments with Conditional Compiler Directives.

Like other language constructs, compiler directives have a set of formatting rules to abide by.

Conditional directives must be the first non-whitespace character on a line.

Spaces may appear between the pound sign (#) symbol and the directive to aid readability.

Use of Comments

When the compiler begins processing a source file containing compiler directives, it looks for lines containing compiler directives and either includes or excludes them, depending on the result of their expression when it’s evaluated. Because of this, it’s very important that comments related to the directive be properly formatted to take this into consideration. If these rules are not abided, errors may result once the compiler begins compiling the resulting source code.

Rules

Single line comments may appear on the line after well-formed conditional compiler directives. These are ignored by the compiler. The reason for this behavior is that the compiler will completely discard a line containing a conditional compiler directive.

Example:

#define DEBUG // This comment will be ignored

With this behavior, mult-line comments should not begin or end on a line with conditional compilation directives unless the comment encompasses the directive. Consider:

    #if DEBUG /* this…
               * is not a fine thing.
               */
  • In this case, the entire #if DEBUG line, including the /* token, will be discarded leaving an ill-formed syntax which will generate compiler errors.

  • Also:
    #define DEBUG /** @deprecated */

is useless at best, and misleading at worst. It will not have the effect of deprecating the subsequent member – the compiler will discard the entire line, including the comment.

Documentation comments with pragma tags can be included in conditional blocks, providing the comments are not included on the same line as the conditional directive, like so:

    #if DEBUG
    /** @deprecated */
    #endif

A last note on conditional directives and comments. Conditional compiler directives embedded in comments will be ignored – the compiler will not parse into comments looking for directives. Comments essentially take precedence over conditional compilation directives.

Example:

    /* this directive is completely ignored
     * #undef DEBUG
     */

Conditional directives must be the first non-whitespace token on a line. White space may appear between the # symbol and the directive. Whitespace before and after the # symbol allows for flexible indentation by the developer.

Single line comments may appear on the line after well-formed conditional compilation directives. These are ignored by the compiler. Multiline or block comments should not be used on the same line as conditional directives as the directive line is thrown away during compilation leaving a malformed block comment.

Doc comments with pragma tags can be included in conditional blocks, for example to conditionally deprecate members:

#if DEBUG

/** @deprecated */

#endif

Conditional compilation directives in comments are ignored – the compiler will not parse into


The #if, #elif, #else, and #endif Conditional Directives

Visual J++ uses the #if, #elif, #else, and #endif conditional compilation directives to include and exclude portions of your source file, prior to compilation.

The #if directive is used to include a statement or block of statements when it’s associated expression evaluates to true. An #if clause may also be used with an optional #elif clause and must have a closing #endif directive, or a compiler error occurs. If the expression defined by the #if statement is false, then the lines immediately following the directive (including the #if statement) are extracted from the source file, ending at the nearest #elif or #endif directive. If the expression following the #if directive evaluates to true, then the lines immediately following the directive are kept in the source file, and the lines following the optional #else clause are extracted from the source.

Any number of #elif directives can appear between the #if and #endif directives, but at most one #else directive is allowed. The #else directive, if present, must be the last directive before the #endif directive.

Example:

#if DEBUG
    if (myArray.length( )

If all occurrences of constant-expression are false, or if no #elif directives appear, the preprocessor selects the text block after the #else clause. If the #else clause is omitted and all instances of constant-expression in the #if block are false, no text block is selected.

Syntax

#if <expression>

group of lines to be compiled

#elif <expression>

group of lines to be compiled

#else

group of lines to be compiled

#endif

Each #if directive in a file must have a closing #endif directive. And number of #elif directives can be included between the #if and #endif directives, but at most, one #else is allowed. The #else directive, if present, must be the last directive before #endif.

The #if, #elif, #else, and #endif directives can nest in the text portions of other #if directives. Each nested #else, #elif, or #endif directive belongs to the nearest preceding #if directive.

If an expression evaluates to true, Visual J++ processes the subsequent program source code and passes it to the compiler. If the text contains additional preprocessor directives, the preprocessor carries out those directives. Only text blocks selected by the preprocessor are compiled.

The preprocessor selects a single text item by evaluating the constant expression following each #if or #elif directive until it fins a true expression. It selects all text, including other preprocessor directives, up to its associated #elif, #else, or #$endif.

If all occurrences of expressions are false, or if no #elif directives appears, the preprocessor selects the text block after the #else clause. If the #else clause is omitted and all instances of constant-expression in the #if block are false, no text block is selected.


The #define Conditional Directive

The #define compiler directive defines an identifier for a source file containing one or more class definitions. When the identifier is defined, it is implicitly set to the value true. The processing of identifier definitions is top-down; for example, if the line #if DEBUG appears before the #define DEBUG then it will be evaluated as false.

Any #define directives must appear at the beginning of a source file, before anything else except comments or other conditional compilation directives.

Syntax

#define <identifier>

Note that the Visual J++ Build Manager does not allow per-file build settings. This means that in order to turn on and off conditional identifiers within a single source file, the #define and #undef directives must be used.


The #undef Conditional Directive

The #undef directive removes the definition of identifier for a source file containing one or more class definitions. All subsequent tests of the identifier within that source file will evaluate to false. Like the #define directive, any #undef directives must appear at the beginning of a source file, before anything except comments or other conditional compilation directives.

Syntax

#undef <identifier>

Note that the Visual J++ Build Manager does not allow per-file build settings. This means that in order to turn on and off conditional identifiers within a single source file, the #define and #undef directives must be used.


The #error Conditional Directive

The #error compiler directive is used in conjunction with other conditional compilation directives to produce compile-time error messages. The compiler error messages include an argument message supplied by the developer. These directives are most useful for detecting programmer inconsistencies and violation of constraints during preprocessing. The following example demonstrates error processing during preprocessing:

#if WIDTH > MAX_WIDTH
    #error Maximum pixel resolution of 640 redefined.
#endif

Note that this error is treated as any other error; compilation of the source file will continue or terminate according to the same semantics.

Syntax

#error <message>


The #warning Conditional Directive

The #warning compiler directive is used in conjunction with other conditional compilation directives to produce compile-time warning messages. The compiler warning messages include an argument string supplied by the developer. These directives are most useful for detecting programmer inconsistencies and violation of constraints during preprocessing. The following example demonstrates warning processing during preprocessing:

#if !TRACING
    #warning This stuff won’t work yet – duck!
#endif

Note that this warning is treated as any other warning; compilation of the source file will continue or terminate according to the same semantics.

Syntax

#warning <message>


Java Language Specification

The Java Language Specification

Version 1.0

James Gosling
Bill Joy
Guy Steele

"When I use a word," Humpty Dumpty said,
in rather a scornful tone, "it means just what I
choose it to mean—neither more nor less."
"The question is," said Alice, "whether you
can make words mean so many different things."
"The question is," said Humpty Dumpty,
"which is to be master—that's all."
—Lewis Carroll, Through the Looking Glass


Copyright

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.

The release described in this manual may be protected by one or more U.S. patents, foreign patents, or pending applications.

Sun Microsystems, Inc. (SUN) hereby grants to you a fully-paid, nonexclusive, nontransferable, perpetual, worldwide limited license (without the right to sublicense) under SUN's intellectual property rights that are essential to practice this specification. This license allows and is limited to the creation and distribution of clean room implementations of this specification that (i) include a complete implementation of the current version of this specification without subsetting or supersetting, (ii) implement all the interfaces and functionality of the standard java.* packages as defined by SUN, without subsetting or supersetting, (iii) do not add any additional packages, classes or methods to the java.* packages (iv) pass all test suites relating to the most recent published version of this specification that are available from SUN six (6) months prior to any beta release of the clean room implementation or upgrade thereto, (v) do not derive from SUN source code or binary materials, and (vi) do not include any SUN binary materials without an appropriate and separate license from SUN.

Sun, Sun Microsystems, Sun Microsystems Computer Corporation, the Sun logo, the Sun Microsystems Computer Corporation logo, Java, JavaSoft, JavaScript and HotJava are trademarks or registered trademarks of Sun Microsystems, Inc. UNIX® is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. Apple and Dylan are trademarks of Apple Computer, Inc. All other product names mentioned herein are the trademarks of their respective owners.

THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

Credits and permissions for quoted material appear in a separate section on page 823.

ISBN 0-201-63451-1
1 2 3 4 5 6 7 8 9-MA-99989796
First printing, August 1996


Series Foreword

The Java Series books provide definitive reference documentation for Java programmers and end users. They are written by members of the Java team and published under the auspices of JavaSoft, a Sun Microsystems business. The World- Wide-Web allows Java documentation to be made available over the Internet, either by downloading or as hypertext. Nevertheless, the world-wide interest in Java technology led us to write and publish these books to supplement all of the documentation at our Web site

To learn the latest about the Java Platform and Environment or download the latest Java release, visit our World Wide Web site at http://java.sun.com/. For updated information about the Java Series, including sample code, errata, and previews of forthcoming books, visit http://java.sun.com/Series/.

We would like to thank the Corporate and Professional Publishing Group at Addison-Wesley for their partnership in putting together the Series. Our editor Mike Hendrickson and his team have done a superb job of navigating us through the world of publishing. Within Sun Microsystems, the support of James Gosling, Jon Kannegaard, and Bill Joy ensured that this series would have the resources it needed to be successful. In addition to the tremendous effort by individual authors, many members of the JavaSoft team have contributed behind the scenes to bring the highest level of quality and engineering to the books in the Series. A personal note of thanks to my children Christopher and James for putting a positive spin on the many trips to my office during the development of the Series.

Lisa Friendly
Series Editor


Preface

Java was originally called Oak, and designed for use in embedded consumer- electronic applications by James Gosling. After several years of experience with the language, and significant contributions by Ed Frank, Patrick Naughton, Jonathan Payne, and Chris Warth it was retargeted to the Internet, renamed Java, and substantially revised to be the language specified here. The final form of the language was defined by James Gosling, Bill Joy, Guy Steele, Richard Tuck, Frank Yellin, and Arthur van Hoff, with help from Graham Hamilton, Tim Lindholm and many other friends and colleagues.

Java is a general-purpose concurrent class-based object-oriented programming language, specifically designed to have as few implementation dependencies as possible. Java allows application developers to write a program once and then be able to run it everywhere on the Internet.

This book attempts a complete specification of the syntax and semantics of the Java language and the core packages java.lang, java.io, and java.util of its Application Programming Interface. We intend that the behavior of every language construct is specified here, so that all implementations of Java will accept the same programs. Except for timing dependencies or other non-determinisms and given sufficient time and sufficient memory space, a Java program should compute the same result on all machines and in all implementations.

We believe that Java is a mature language, ready for widespread use. Nevertheless, we expect some evolution of the language in the years to come. We intend to manage this evolution in a way that is completely compatible with existing applications. To do this, we intend to make relatively few new versions of the language, and to distinguish each new version with a different filename extension. Java compilers and systems will be able to support the several versions simultannously, with complete compatibility.

Much research and experimentation with Java is already underway. We encourage this work, and will continue to cooperate with external groups to explore improvements to Java. For example, we have already received several interesting proposals for parameterized types. In technically difficult areas, near the state of the art, this kind of research collaboration is essential.

We acknowledge and thank the many people who have contributed to this book through their excellent feedback, assistance and encouragement:

Particularly thorough, careful, and thoughtful reviews of drafts were provided by Tom Cargill, Peter Deutsch, Paul Hilfinger, Masayuki Ida, David Moon, Steven Muchnick, Charles L. Perkins, Chris Van Wyk, Steve Vinoski, Philip Wadler, Daniel Weinreb, and Kenneth Zadeck. We are very grateful for their extraordinary volunteer efforts.

We are also grateful for reviews, questions, comments, and suggestions from Stephen Adams, Bowen Alpern, Glenn Ammons, Leonid Arbuzov, Kim Bruce, Edwin Chan, David Chase, Pavel Curtis, Drew Dean, William Dietz, David Dill, Patrick Dussud, Ed Felten, John Giannandrea, John Gilmore, Charles Gust, Warren Harris, Lee Hasiuk, Mike Hendrickson, Mark Hill, Urs Hoelzle, Roger Hoover, Susan Flynn Hummel, Christopher Jang, Mick Jordan, Mukesh Kacker, Peter Kessler, James Larus, Derek Lieber, Bill McKeeman, Steve Naroff, Evi Nemeth, Robert O'Callahan, Dave Papay, Craig Partridge, Scott Pfeffer, Eric Raymond, Jim Roskind, Jim Russell, William Scherlis, Edith Schonberg, Anthony Scian, Matthew Self, Janice Shepherd, Kathy Stark, Barbara Steele, Rob Strom, William Waite, Greg Weeks, and Bob Wilson. (This list was generated semi-automatically from our e-mail records. We apologize if we have omitted anyone.)

The feedback from all these reviewers was invaluable to us in improving the definition of the Java language as well as the form of the presentation in this book. We thank them for their diligence. Any remaining errors in this book-we hope they are few-are our responsibility and not theirs.

We thank Francesca Freedman for assistance with matters of typography and layout. We thank Dan Mills of Adobe Systems Incorporated for assistance in exploring possible choices of typefaces.

Many of our colleagues at Sun Microsystems have helped us in one way or another. Lisa Friendly, our series editor, managed our relationship with Addison-Wesley. Susan Stambaugh managed the distribution of many hundreds of copies of drafts to reviewers. We received valuable assistance and technical advice from Ben Adida, Ole Agesen, Ken Arnold, Rick Cattell, Asmus Freytag, Norm Hardy, Steve Heller, David Hough, Doug Kramer, Nancy Lee, Marianne Mueller, Akira Tanaka, Greg Tarsy, David Ungar, Jim Waldo, Ann Wollrath, Geoff Wyant, and Derek White. We thank Alan Baratz, David Bowen, Mike Clary, John Doerr, Jon Kannegaard, Eric Schmidt, Bob Sproull, Bert Sutherland, and Scott McNealy for leadership and encouragement.

The on-line Bartleby Library of Columbia University, at URL:

http://www.cc.columbia.edu/acis/bartleby/

was invaluable to us during the process of researching and verifying many of the quotations that are scattered throughout this book. Here is one example:

They lard their lean books with the fat of others' works.
—Robert Burton (1576-1640)

We are grateful to those who have toiled on Project Bartleby, for saving us a great deal of effort and reawakening our appreciation for the works of Walt Whitman.

We are thankful for the tools and services we had at our disposal in writing this book: telephones, overnight delivery, desktop workstations, laser printers, photocopiers, text formatting and page layout software, fonts, electronic mail, the World Wide Web, and, of course, the Internet. We live in three different states, scattered across a continent, but collaboration with each other and with our reviewers has seemed almost effortless. Kudos to the thousands of people who have worked over the years to make these excellent tools and services work quickly and reliably.

Mike Hendrickson, Katie Duffy, Simone Payment, and Rosa Aimée González of Addison-Wesley were very helpful, encouraging, and patient during the long process of bringing this book to print. We also thank the copy editors.

Rosemary Simpson worked hard, on a very tight schedule, to create the index. We got into the act at the last minute, however; blame us and not her for any jokes you may find hidden therein.

Finally, we are grateful to our families and friends. Life has been a bit crazy for us these last few months and we thank these good people for their support.

In their book The C Programming Language, Brian Kernighan and Dennis Ritchie said that they felt that the C language "wears well as one's experience with it grows." If you like C, we think you will like Java. We hope that Java, too, wears well for you.

James Gosling
Cupertino, California

Bill Joy
Aspen, Colorado

Guy Steele
Chelmsford, Massachusetts

July, 1996


1. Introduction

CHAPTER 1

Introduction

If I have seen further it is by standing upon the shoulders of Giants.
—Sir Isaac Newton

Java is a general-purpose, concurrent, class-based, object-oriented language. It is designed to be simple enough that many programmers can achieve fluency in the language. Java is related to C and C++ but is organized rather differently, with a number of aspects of C and C++ omitted and a few ideas from other languages included. Java is intended to be a production language, not a research language, and so, as C. A. R. Hoare suggested in his classic paper on language design, the design of Java has avoided including new and untested features.

Java is strongly typed. This specification clearly distinguishes between the compile-time errors that can and must be detected, and those that occur at run time. Compile time normally consists of translating Java programs into a machine-independent byte-code representation. Run-time activities include loading and linking of the classes needed to execute a program, optional machine code generation and dynamic optimization of the program, and actual program execution.

Java is a relatively high-level language, in that details of the machine representation are not available through the language. It includes automatic storage management, typically using a garbage collector, to avoid the safety problems of explicit deallocation (as in C's free or C++'s delete). High-performance garbage-collected implementations of Java can have bounded pauses to support systems programming and real-time applications. Java does not include any unsafe constructs, such as array accesses without index checking, since such unsafe constructs would cause a program to behave in an unspecified way.

Java is normally compiled to a bytecoded instruction set and binary format defined in The Java Virtual Machine Specification (Addison-Wesley, 1996). Most implementations of Java for general-purpose programming will support the additional packages defined in the series of books under the general title The Java Application Programming Interface (Addison-Wesley).

This Java Language Specification is organized as follows:

Chapter 2 describes grammars and the notation used to present the lexical and syntactic grammars for Java.

Chapter 3 describes the lexical structure of Java, which is based on C and C++. Java is written in the Unicode character set. Java supports the writing of Unicode characters on systems that support only ASCII.

Chapter 4 describes Java's types, values, and variables. Java's types are the primitive types and reference types.

The primitive types are defined to be the same on all machines and in all implementations, and are various sizes of two's-complement integers, single- and double-precision IEEE 754 standard floating-point numbers, a boolean type, and a Unicode character char type. Values of the primitive types do not share state.

Java's reference types are the class types, the interface types, and the array types. The reference types are implemented by dynamically created objects that are either instances of classes or arrays. Many references to each object can exist. All objects (including arrays) support the methods of the standard class Object, which is the (single) root of the class hierarchy. A predefined String class supports Unicode character strings. Standard classes exist for wrapping primitive values inside of objects.

Variables are typed storage locations. A variable of a primitive type holds a value of that exact primitive type. A variable of a class type can hold a null reference or a reference to an object whose type is that class type or any subclass of that class type. A variable of an interface type can hold a null reference or a reference to an instance of any class that implements the interface. A variable of an array type can hold a null reference or a reference to an array. A variable of class type Object can hold a null reference or a reference to any object, whether class instance or array.

Chapter 5 describes Java's conversions and numeric promotions. Conversions change the compile-time type and, sometimes, the value of an expression. Numeric promotions are used to convert the operands of a numeric operator to a common type where an operation can be performed. There are no loopholes in the language; casts on reference types are checked at run time to ensure type safety.

Chapter 6 describes declarations and names, and how to determine what names mean (denote). Java does not require types or their members to be declared before they are used. Declaration order is significant only for local variables and the order of initializers of fields in a class or interface.

Java provides control over the scope of names and supports limitations on external access to members of packages, classes, and interfaces. This helps in writing large programs by distinguishing the implementation of a type from its users and those who extend it. Standard naming conventions that make for more readable programs are described here.

Chapter 7 describes the structure of a Java program, which is organized into packages similar to the modules of Modula. The members of a package are compilation units and subpackages. Compilation units contain type declarations and can import types from other packages to give them short names. Packages have names in a hierarchical namespace, and the Internet domain name system can be used to form unique package names.

Chapter 8 describes Java's classes. The members of classes are fields (variables) and methods. Class variables exist once per class. Class methods operate without reference to a specific object. Instance variables are dynamically created in objects that are instances of classes. Instance methods are invoked on instances of classes; such instances become the current object this during their execution, supporting the object-oriented programming style.

Classes support single implementation inheritance, in which the implementation of each class is derived from that of a single superclass, and ultimately from the class Object. Variables of a class type can reference an instance of that class or of any subclass of that class, allowing new types to be used with existing methods, polymorphically.

Classes support concurrent programming with synchronized methods. Methods declare the checked exceptions that can arise from their execution, which allows compile-time checking to ensure that exceptional conditions are handled. Objects can declare a finalize method that will be invoked before the objects are discarded by the garbage collector, allowing the objects to clean up their state.

For simplicity, Java has neither declaration "headers" separate from the implementation of a class nor separate type and class hierarchies.

Although Java does not include parameterized classes, the semantics of arrays are those of a parameterized class with some syntactic sugar. Like the programming language Beta, Java uses a run-time type check when storing references in arrays to ensure complete type safety.

Chapter 9 describes Java's interface types, which declare a set of abstract methods and constants. Classes that are otherwise unrelated can implement the same interface type. A variable of an interface type can contain a reference to any object that implements the interface. Multiple interface inheritance is supported.

Chapter 10 describes Java arrays. Array accesses include bounds checking. Arrays are dynamically created objects and may be assigned to variables of type Object. Java supports arrays of arrays, rather than multidimensional arrays.

Chapter 11 describes Java's exceptions, which are nonresuming and fully integrated with the language semantics and concurrency mechanisms. There are three kinds of exceptions: checked exceptions, run-time exceptions, and errors. The compiler ensures that checked exceptions are properly handled by requiring that a method or constructor can result in a checked exception only if it declares it. This provides compile-time checking that exception handlers exist, and aids programming in the large. Most user-defined exceptions should be checked exceptions. Invalid operations in the program detected by the Java Virtual Machine result in run-time exceptions, such as NullPointerException. Errors result from failures detected by the virtual machine, such as OutOfMemoryError. Most simple programs do not try to handle errors.

Chapter 12 describes activities that occur during execution of a Java program. A Java program is normally stored as binary files representing compiled classes and interfaces. These binary files can be loaded into a Java Virtual Machine, linked to other classes and interfaces, and initialized.

After initialization, class methods and class variables may be used. Some classes may be instantiated to create new objects of the class type. Objects that are class instances also contain an instance of each superclass of the class, and object creation involves recursive creation of these superclass instances.

When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded; if a class finalizer is declared, it is given a chance to clean up first. Objects and classes may be finalized on exit of the Java Virtual Machine.

Chapter 13 describes binary compatibility, specifying the impact of changes to types on other types that use the changed types but have not been recompiled. These considerations are of interest to developers of types that are to be widely distributed, in a continuing series of versions, often through the Internet. Good program development environments automatically recompile dependent code whenever a type is changed, so most programmers need not be concerned about these details.

Chapter 14 describes Java's blocks and statements, which are based on C and C++. Java has no goto, but includes labeled break and continue statements. Unlike C, Java requires boolean expressions in control-flow statements, and does not convert types to boolean implicitly, in the hope of catching more errors at compile time. A synchronized statement provides basic object-level monitor locking. A try statement can include catch and finally clauses to protect against non-local control transfers.

Chapter 15 describes Java's expressions. Java fully specifies the (apparent) order of evaluation of expressions, for increased determinism and portability. Overloaded methods and constructors are resolved at compile time by picking the most specific method or constructor from those which are applicable. Java chooses which method or constructor by using the same basic algorithm used in languages with richer dispatching, such as CLOS and Dylan, for the future.

Chapter 16 describes the precise way in which Java ensures that local variables are definitely set before use. While all other variables are automatically initialized to a default value, Java does not automatically initialize local variables in order to avoid masking programming errors.

Chapter 17 describes the semantics of Java threads and locks, which are based on the monitor-based concurrency originally introduced with the Mesa programming language. Java specifies a memory model for shared-memory multiprocessors that supports high-performance implementations.

Chapter 18 describes the facilities for automatically generating documentation from special comments in Java source code.

Chapter 19 presents a LALR(1) syntactic grammar for Java, and describes the differences between this grammar and the expository grammar used in the body of the language specification that precedes it.

Chapters 20 through 22 are the reference manual for the core of the standard Java Application Programming Interface. These packages must be included in all general purpose Java systems.

Chapter 20 describes the package java.lang. The types defined in java.lang are automatically imported to be available without qualification in all Java programs. They include the primordial class Object, which is a superclass of all other classes; classes such as Integer and Float, which wrap the primitive types inside objects; exceptions and errors defined by the language and the Java Virtual Machine; Thread support; metalinguistic classes such as Class and ClassLoader; and the class System, which abstracts the host system.

Chapter 21 describes the package java.util, which defines a few basic utility classes, such as a hashtable class and a pseudo-random number generator.

Chapter 22 describes the package java.io, which defines basic input/output facilities, including random access files and streams of values of primitive types.

The book concludes with two indexes: one for the types, methods, and fields defined and described in this specification, and the other a more traditional index.


1.1 Example Programs

Most of the example programs given in the text are ready to be executed by a Java system and are similar in form to:

class Test {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++)
            System.out.print(i == 0 ? args[i] : " " + args[i]);
        System.out.println();
    }
}

On a Sun workstation, this class, stored in the file Test.java, can be compiled and executed by giving the commands:

javac Test.java
java Test Hello, world.

producing the output:

Hello, world.


1.2 References

Apple Computer. Dylan Reference Manual. Apple Computer Inc., Cupertino, California. September 29, 1995. See also http://www.cambridge.apple.com/.

Bobrow, Daniel G., Linda G. DeMichiel, Richard P. Gabriel, Sonya E. Keene, Gregor Kiczales, and David A. Moon. Common Lisp Object System Specification, X3J13 Document 88-002R, June 1988; appears as Chapter 28 of Steele, Guy. Common Lisp: The Language, 2nd ed. Digital Press, 1990, ISBN 1-55558-041-6, 770-864.

Ellis, Margaret A., and Bjarne Stroustrup. The Annotated C++ Reference Manual. Addison-Wesley, Reading, Massachusetts, 1990, reprinted with corrections October 1992, ISBN 0-201-51459-1.

Harbison, Samuel. Modula-3. Prentice Hall, Englewood Cliffs, New Jersey, 1992, ISBN 0-13-596396.

Hoare, C. A. R. Hints on Programming Language Design. Stanford University Computer Science Department Technical Report No. CS-73-403, December 1973. Reprinted in SIGACT/SIGPLAN Symposium on Principles of Programming Languages. Association for Computing Machinery, New York, October 1973.

IEEE Standard for Binary Floating-Point Arithmetic. ANSI/IEEE Std. 754-1985. Available from Global Engineering Documents, 15 Inverness Way East, Englewood, Colorado 80112-5704 USA; 800-854-7179.

Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd ed. Prentice Hall, Englewood Cliffs, New Jersey, 1988, ISBN 0-13-110362-8.

Madsen, Ole Lehrmann, Birger Møller-Pedersen, and Kristen Nygaard. Object-Oriented Programming in the Beta Programming Language. Addison-Wesley, Reading, Massachusetts, 1993, ISBN 0-201-52430.

Mitchell, James G., William Maybury, and Richard Sweet. The Mesa Programming Language, Version 5.0. Xerox PARC, Palo Alto, California, CSL 79-3, April 1979.

Stroustrup, Bjarne. The C++ Progamming Language, 2nd ed. Addison-Wesley, Reading, Massachusetts, 1991, reprinted with corrections January 1994, ISBN 0-201-53992-6.

Unicode Consortium, The. The Unicode Standard: Worldwide Character Encoding, Version 1.0. Addison-Wesley, Reading, Massachusetts, Volume 1, 1991, ISBN 0-201-56788-1, and Volume 2, 1992, ISBN 0-201-60845-6. (Version 2, forthcoming, 1996.)


 2. Grammars

CHAPTER 2

Grammars

Grammar, which knows how to control even kings . . .
—Moliere, Les Femmes Savantes (1672), Act II, scene vi

This chapter describes the context-free grammars used in this specification to define the lexical and syntactic structure of a Java program.


2.1 Context-Free Grammars

A context-free grammar consists of a number of productions. Each production has an abstract symbol called a nonterminal as its left-hand side, and a sequence of one or more nonterminal and terminal symbols as its right-hand side. For each grammar, the terminal symbols are drawn from a specified alphabet.

Starting from a sentence consisting of a single distinguished nonterminal, called the goal symbol, a given context-free grammar specifies a language, namely, the infinite set of possible sequences of terminal symbols that can result from repeatedly replacing any nonterminal in the sequence with a right-hand side of a production for which the nonterminal is the left-hand side.


2.2 The Lexical Grammar

A lexical grammar for Java is given in §3. This grammar has as its terminal symbols the characters of the Unicode character set. It defines a set of productions, starting from the goal symbol Input (§3.5), that describe how sequences of Unicode characters (§3.1) are translated into a sequence of input elements (§3.5).

These input elements, with white space (§3.6) and comments (§3.7) discarded, form the terminal symbols for the syntactic grammar for Java and are called Java tokens (§3.5). These tokens are the identifiers (§3.8), keywords (§3.9), literals (§3.10), separators (§3.11), and operators (§3.12) of the Java language.


2.3 The Syntactic Grammar

The syntactic grammar for Java is given in Chapters 4, 6-10, 14, and 15. This grammar has Java tokens defined by the lexical grammar as its terminal symbols. It defines a set of productions, starting from the goal symbol CompilationUnit (§7.3), that describe how sequences of tokens can form syntactically correct Java programs.

A LALR(1) version of the syntactic grammar is presented in Chapter 19. The grammar in the body of this specification is very similar to the LALR(1) grammar but more readable.


2.4 Grammar Notation

Terminal symbols are shown in fixed width font in the productions of the lexical and syntactic grammars, and throughout this specification whenever the text is directly referring to such a terminal symbol. These are to appear in a program exactly as written.

Nonterminal symbols are shown in italic type. The definition of a nonterminal is introduced by the name of the nonterminal being defined followed by a colon. One or more alternative right-hand sides for the nonterminal then follow on succeeding lines. For example, the syntactic definition:

IfThenStatement:

    if ( Expression ) Statement

states that the nonterminal IfThenStatement represents the token if, followed by a left parenthesis token, followed by an Expression, followed by a right parenthesis token, followed by a Statement. As another example, the syntactic definition:

ArgumentList:

    Argument

    ArgumentList , Argument

states that an ArgumentList may represent either a single Argument or an ArgumentList, followed by a comma, followed by an Argument. This definition of ArgumentList is recursive, that is to say, it is defined in terms of itself. The result is that an ArgumentList may contain any positive number of arguments. Such recursive definitions of nonterminals are common.

The subscripted suffix "opt", which may appear after a terminal or nonterminal, indicates an optional symbol. The alternative containing the optional symbol actually specifies two right-hand sides, one that omits the optional element and one that includes it. This means that:

BreakStatement:

    break Identifieropt ;

is a convenient abbreviation for:

BreakStatement:

    break ;

    break Identifier ;

and that:

ForStatement:

    for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

is a convenient abbreviation for:

ForStatement:

    for ( ; Expressionopt ; ForUpdateopt ) Statement

    for ( ForInit ; Expressionopt ; ForUpdateopt ) Statement

which in turn is an abbreviation for:

ForStatement:

    for ( ; ; ForUpdateopt ) Statement

    for ( ; Expression ; ForUpdateopt ) Statement

    for ( ForInit ; ; ForUpdateopt ) Statement

    for ( ForInit ; Expression ; ForUpdateopt ) Statement

which in turn is an abbreviation for:

ForStatement:

    for ( ; ; ) Statement

    for ( ; ; ForUpdate ) Statement

    for ( ; Expression ; ) Statement

    for ( ; Expression ; ForUpdate ) Statement

    for ( ForInit ; ; ) Statement

    for ( ForInit ; ; ForUpdate ) Statement

    for ( ForInit ; Expression ; ) Statement

    for ( ForInit ; Expression ; ForUpdate ) Statement

so the nonterminal ForStatement actually has eight alternative right-hand sides.

A very long right-hand side may be continued on a second line by substantially indenting this second line, as in:

ConstructorDeclaration:

    ConstructorModifiersopt ConstructorDeclarator

        Throwsopt ConstructorBody

which defines one right-hand side for the nonterminal ConstructorDeclaration. (This right-hand side is an abbreviation for four alternative right-hand sides, because of the two occurrences of "opt".)

When the words "one of" follow the colon in a grammar definition, they signify that each of the terminal symbols on the following line or lines is an alternative definition. For example, the lexical grammar for Java contains the production:

ZeroToThree: one of

    0 1 2 3

which is merely a convenient abbreviation for:

ZeroToThree:

    0

    1

    2

    3

When an alternative in a lexical production appears to be a token, it represents the sequence of characters that would make up such a token. Thus, the definition:

BooleanLiteral: one of

    true false

in a lexical grammar production is shorthand for:

BooleanLiteral:

    t r u e

    f a l s e

The right-hand side of a lexical production may specify that certain expansions are not permitted by using the phrase "but not" and then indicating the expansions to be excluded, as in the productions for InputCharacter (§3.4) and Identifier (§3.8):

InputCharacter:

    UnicodeInputCharacter but not CR or LF

Identifier:

    IdentifierName but not a Keyword or BooleanLiteral or NullLiteral

Finally, a few nonterminal symbols are described by a descriptive phrase in roman type in cases where it would be impractical to list all the alternatives:

RawInputCharacter:

    any Unicode character


 3. Lexical Structure

CHAPTER 3

Lexical Structure

Lexicographer: A writer of dictionaries, a harmless drudge.
—Samuel Johnson, Dictionary (1755)

This chapter specifies the lexical structure of Java.

Java programs are written in Unicode (§3.1), but lexical translations are provided (§3.2) so that Unicode escapes (§3.3) can be used to include any Unicode character using only ASCII characters. Line terminators are defined (§3.4) to support the different conventions of existing host systems while maintaining consistent line numbers.

The Unicode characters resulting from the lexical translations are reduced to a sequence of input elements (§3.5), which are white space (§3.6), comments (§3.7), and tokens. The tokens are the identifiers (§3.8), keywords (§3.9), literals (§3.10), separators (§3.11), and operators (§3.12) of the Java syntactic grammar.


3.1 Unicode

Java programs are written using the Unicode character set, version 2.0. Information about this encoding may be found at:

http://www.unicode.org/ and ftp://unicode.org/

Versions of Java prior to 1.1 used Unicode version 1.1.5 (see The Unicode Standard: Worldwide Character Encoding (§1.2) and updates). See §20.5 for a discussion of the differences between Unicode version 1.1.5 and Unicode version 2.0.

Except for comments (§3.7), identifiers, and the contents of character and string literals (§3.10.4, §3.10.5), all input elements (§3.5) in a Java program are formed only from ASCII characters (or Unicode escapes (§3.3) which result in ASCII characters). ASCII (ANSI X3.4) is the American Standard Code for Information Interchange. The first 128 characters of the Unicode character encoding are the ASCII characters.


3.2 Lexical Translations

A raw Unicode character stream is translated into a sequence of Java tokens, using the following three lexical translation steps, which are applied in turn:

  • A translation of Unicode escapes (§3.3) in the raw stream of Unicode characters to the corresponding Unicode character. A Unicode escape of the form \u xxxx, where xxxx is a hexadecimal value, represents the Unicode character whose encoding is xxxx. This translation step allows any Java program to be expressed using only ASCII characters.
  • A translation of the Unicode stream resulting from step 1 into a stream of input characters and line terminators (§3.4).
  • A translation of the stream of input characters and line terminators resulting from step 2 into a sequence of Java input elements (§3.5) which, after white space (§3.6) and comments (§3.7) are discarded, comprise the tokens (§3.5) that are the terminal symbols of the syntactic grammar (§2.3) for Java.

Java always uses the longest possible translation at each step, even if the result does not ultimately make a correct Java program, while another lexical translation would. Thus the input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct Java program, even though the tokenization a, -, -, b could be part of a grammatically correct Java program.


3.3 Unicode Escapes

Java implementations first recognize Unicode escapes in their input, translating the ASCII characters \u followed by four hexadecimal digits to the Unicode character with the indicated hexadecimal value, and passing all other characters unchanged. This translation step results in a sequence of Unicode input characters:

UnicodeInputCharacter:

    UnicodeEscape

    RawInputCharacter

UnicodeEscape:

    \ UnicodeMarker HexDigit HexDigit HexDigit HexDigit

UnicodeMarker:

    u

    UnicodeMarker u

RawInputCharacter:

    any Unicode character

HexDigit: one of

    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

The \, u, and hexadecimal digits here are all ASCII characters.

In addition to the processing implied by the grammar, for each raw input character that is a backslash \, input processing must consider how many other \ characters contiguously precede it, separating it from a non-\ character or the start of the input stream. If this number is even, then the \ is eligible to begin a Unicode escape; if the number is odd, then the \ is not eligible to begin a Unicode escape. For example, the raw input "\\u2297=\u2297" results in the eleven characters " \ \ u 2 2 9 7 = [image] " (\u2297 is the Unicode encoding of the character " [image] ").

If an eligible \ is not followed by u, then it is treated as a RawInputCharacter and remains part of the escaped Unicode stream. If an eligible \ is followed by u, or more than one u, and the last u is not followed by four hexadecimal digits, then a compile-time error occurs.

The character produced by a Unicode escape does not participate in further Unicode escapes. For example, the raw input \u005cu005a results in the six characters \ u 0 0 5 a, because 005c is the Unicode value for \. It does not result in the character Z, which is Unicode character 005a, because the \ that resulted from the \u005c is not interpreted as the start of a further Unicode escape.

Java specifies a standard way of transforming a Unicode Java program into ASCII that changes a Java program into a form that can be processed by ASCII-based tools. The transformation involves converting any Unicode escapes in the source text of the program to ASCII by adding an extra u-for example, \u xxxx becomes \uu xxxx-while simultaneously converting non-ASCII characters in the source text to a \u xxxx escape containing a single u. This transformed version is equally acceptable to a Java compiler and represents the exact same program. The exact Unicode source can later be restored from this ASCII form by converting each escape sequence where multiple u's are present to a sequence of Unicode characters with one fewer u, while simultaneously converting each escape sequence with a single u to the corresponding single Unicode character.

Java systems should use the \u xxxx notation as an output format to display Unicode characters when a suitable font is not available.


3.4 Line Terminators

Java implementations next divide the sequence of Unicode input characters into lines by recognizing line terminators. This definition of lines determines the line numbers produced by a Java compiler or other Java system component. It also specifies the termination of the // form of a comment (§3.7).

LineTerminator:

    the ASCII LF character, also known as "newline"

    the ASCII CR character, also known as "return"

    the ASCII CR character followed by the ASCII LF character

InputCharacter:

    UnicodeInputCharacter but not CR or LF

Lines are terminated by the ASCII characters CR, or LF, or CR LF. The two characters CR immediately followed by LF are counted as one line terminator, not two. The result is a sequence of line terminators and input characters, which are the terminal symbols for the third step in the tokenization process.


3.5 Input Elements and Tokens

The input characters and line terminators that result from escape processing (§3.3) and then input line recognition (§3.4) are reduced to a sequence of input elements. Those input elements that are not white space (§3.6) or comments (§3.7) are tokens. The tokens are the terminal symbols of the Java syntactic grammar (§2.3).

This process is specified by the following productions:

Input:

    InputElementsopt Subopt

InputElements:

    InputElement

    InputElements InputElement

InputElement:

    WhiteSpace

    Comment

    Token

Token:

    Identifier

    Keyword

    Literal

    Separator

    Operator

Sub:

    the ASCII SUB character, also known as "control-Z"

White space (§3.6) and comments (§3.7) can serve to separate tokens that, if adjacent, might be tokenized in another manner. For example, the ASCII characters - and = in the input can form the operator token -= (§3.12) only if there is no intervening white space or comment.

As a special concession for compatibility with certain operating systems, the ASCII SUB character (\u001a, or control-Z) is ignored if it is the last character in the escaped input stream.

Consider two tokens x and y in the resulting input stream. If x precedes y, then we say that x is to the left of y and that y is to the right of x. For example, in this simple piece of Java code:

class Empty {
}

we say that the } token is to the right of the { token, even though it appears, in this two-dimensional representation on paper, downward and to the left of the { token. This convention about the use of the words left and right allows us to speak, for example, of the right-hand operand of a binary operator or of the left-hand side of an assignment.


3.6 White Space

White space is defined as the ASCII space, horizontal tab, and form feed characters, as well as line terminators (§3.4).

WhiteSpace:

    the ASCII SP character, also known as "space"

    the ASCII HT character, also known as "horizontal tab"

    the ASCII FF character, also known as "form feed"

    LineTerminator


3.7 Comments

Java defines three kinds of comments:

/* text */ A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++).

// text A single-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++).

/** documentation */ A documentation comment: the text enclosed by the ASCII characters /** and */ can be processed by a separate tool to prepare automatically generated documentation of the following class, interface, constructor, or member (method or field) declaration. See §18 for a full description of how the supplied documentation is processed.

These comments are formally specified by the following productions:

Comment:

    TraditionalComment

    EndOfLineComment

    DocumentationComment

TraditionalComment:

    / * NotStar CommentTail

EndOfLineComment:

    / / CharactersInLineopt LineTerminator

DocumentationComment:

    / * * CommentTailStar

CommentTail:

    * CommentTailStar

    NotStar CommentTail

CommentTailStar:

    /

    * CommentTailStar

    NotStarNotSlash CommentTail

NotStar:

    InputCharacter but not *

    LineTerminator

NotStarNotSlash:

    InputCharacter but not * or /

    LineTerminator

CharactersInLine:

    InputCharacter

    CharactersInLine InputCharacter

These productions imply all of the following properties:

  • Comments do not nest.
  • /* and */ have no special meaning in comments that begin with //.
  • // has no special meaning in comments that begin with /* or /**.

As a result, the text:

/* this comment /* // /** ends here: */

is a single complete comment.

The lexical grammar implies that comments do not occur within character literals (§3.10.4) or string literals (§3.10.5).

Note that /**/ is considered to be a documentation comment, while /* */ (with a space between the asterisks) is a traditional comment.


3.8 Identifiers

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), Boolean literal (§3.10.3), or the null literal (§3.10.7).

Identifier:

    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral

IdentifierChars:

    JavaLetter

    IdentifierChars JavaLetterOrDigit

JavaLetter:

    any Unicode character that is a Java letter (see below)

JavaLetterOrDigit:

    any Unicode character that is a Java letter-or-digit (see below)

Letters and digits may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese, Japanese, and Korean. This allows Java programmers to use identifiers in their programs that are written in their native languages.

A Java letter is a character for which the method Character.isJavaLetter (§20.5.17) returns true. A Java letter-or-digit is a character for which the method Character.isJavaLetterOrDigit (§20.5.18) returns true.

The Java letters include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated Java code or, rarely, to access preexisting names on legacy systems.

The Java digits include the ASCII digits 0-9 (\u0030-\u0039).

Two identifiers are the same only if they are identical, that is, have the same Unicode character for each letter or digit.

Identifiers that have the same external appearance may yet be different. For example, the identifiers consisting of the single letters LATIN CAPITAL LETTER A (A, \u0041), LATIN SMALL LETTER A (a, \u0061), GREEK CAPITAL LETTER ALPHA (A, \u0391), and CYRILLIC SMALL LETTER A (a, \u0430) are all different.

Unicode composite characters are different from the decomposed characters. For example, a LATIN CAPITAL LETTER A ACUTE (Á, \u00c1) could be considered to be the same as a LATIN CAPITAL LETTER A (A, \u0041) immediately followed by a NON-SPACING ACUTE (´, \u0301) when sorting, but these are different in Java identifiers. See The Unicode Standard, Volume 1, pages 412ff for details about decomposition, and see pages 626-627 of that work for details about sorting.

Examples of identifiers are:

    String			i3		          			MAX_VALUE				isLetterOrDigit


3.9 Keywords

The following character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers (§3.8):

Keyword: one of

    abstract	default	if	private	throw

    boolean	do	implements	protected	throws

    break	double	import	public	transient

    byte	else	instanceof	return	try

    case	extends	int	short	void

    catch	final	interface	static	volatile

    char	finally	long	super	while

    class	float	native	switch

    const	for	new	synchronized

    continue	goto	package	this

The keywords const and goto are reserved by Java, even though they are not currently used in Java. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in Java programs.

While true and false might appear to be keywords, they are technically Boolean literals (§3.10.3). Similarly, while null might appear to be a keyword, it is technically the null literal (§3.10.7).


3.10 Literals

A literal is the source code representation of a value of a primitive type (§4.2), the String type (§4.3.3, §20.12), or the null type (§4.1):

Literal:

    IntegerLiteral

    FloatingPointLiteral

    BooleanLiteral

    CharacterLiteral

    StringLiteral

    NullLiteral


3.10.1 Integer Literals

See §4.2.1 for a general discussion of the integer types and values.

An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8):

IntegerLiteral:

    DecimalIntegerLiteral

    HexIntegerLiteral

    OctalIntegerLiteral

DecimalIntegerLiteral:

    DecimalNumeral IntegerTypeSuffixopt

HexIntegerLiteral:

    HexNumeral IntegerTypeSuffixopt

OctalIntegerLiteral:

    OctalNumeral IntegerTypeSuffixopt

IntegerTypeSuffix: one of

    l L

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1). The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).

A decimal numeral is either the single ASCII character 0, representing the integer zero, or consists of an ASCII digit from 1 to 9, optionally followed by one or more ASCII digits from 0 to 9, representing a positive integer:

DecimalNumeral:

    0

    NonZeroDigit Digitsopt

Digits:

    Digit

    Digits Digit

Digit:

    0

    NonZeroDigit

NonZeroDigit: one of

    1 2 3 4 5 6 7 8 9

A hexadecimal numeral consists of the leading ASCII characters 0x or 0X followed by one or more ASCII hexadecimal digits and can represent a positive, zero, or negative integer. Hexadecimal digits with values 10 through 15 are represented by the ASCII letters a through f or A through F, respectively; each letter used as a hexadecimal digit may be uppercase or lowercase.

HexNumeral:

    0 x HexDigit

    0 X HexDigit

    HexNumeral HexDigit

The following production from §3.3 is repeated here for clarity:

HexDigit: one of

    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.

OctalNumeral:

    0 OctalDigit

    OctalNumeral OctalDigit

OctalDigit: one of

    0 1 2 3 4 5 6 7

Note that octal numerals are always consist of two or more digits; 0 is always considered to be a decimal numeral-not that it matters much in practice, for the numerals 0, 00, and 0x0 all represent exactly the same integer value.

The largest decimal literal of type int is 2147483648 ( [image]). All decimal literals from 0 to 2147483647 may appear anywhere an int literal may appear, but the literal 2147483648 may appear only as the operand of the unary negation operator -.

The largest positive hexadecimal and octal literals of type int are 0x7fffffff and 017777777777, respectively, which equal 2147483647 ( [image]). The most negative hexadecimal and octal literals of type int are 0x80000000 and 020000000000, respectively, each of which represents the decimal value -2147483648 ( [image]). The hexadecimal and octal literals 0xffffffff and 037777777777, respectively, represent the decimal value -1.

See also Integer.MIN_VALUE (§20.7.1) and Integer.MAX_VALUE (§20.7.2).

A compile-time error occurs if a decimal literal of type int is larger than 2147483648 ( [image]), or if the literal 2147483648 appears anywhere other than as the operand of the unary - operator, or if a hexadecimal or octal int literal does not fit in 32 bits.

Examples of int literals:

    0		2		0372			0xDadaCafe					1996		0x00FF00FF

The largest decimal literal of type long is 9223372036854775808L ( [image]). All decimal literals from 0L to 9223372036854775807L may appear anywhere a long literal may appear, but the literal 9223372036854775808L may appear only as the operand of the unary negation operator -.

The largest positive hexadecimal and octal literals of type long are 0x7fffffffffffffffL and 0777777777777777777777L, respectively, which equal 9223372036854775807L ( [image]). The literals 0x8000000000000000L and 01000000000000000000000L are the most negative long hexadecimal and octal literals, respectively. Each has the decimal value -9223372036854775808L ( [image]). The hexadecimal and octal literals 0xffffffffffffffffL and 01777777777777777777777L, respectively, represent the decimal value -1L.

See also Long.MIN_VALUE (§20.8.1) and Long.MAX_VALUE (§20.8.2).

A compile-time error occurs if a decimal literal of type long is larger than 9223372036854775808L ( [image]), or if the literal 9223372036854775808L appears anywhere other than as the operand of the unary - operator, or if a hexadecimal or octal long literal does not fit in 64 bits.

Examples of long literals:

    0l		0777L			0x100000000L					2147483648L				   0xC0B0L


3.10.2 Floating-Point Literals

See §4.2.3 for a general discussion of the floating-point types and values.

A floating-point literal has the following parts: a whole-number part, a decimal point (represented by an ASCII period character), a fractional part, an exponent, and a type suffix. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.

At least one digit, in either the whole number or the fraction part, and either a decimal point, an exponent, or a float type suffix are required. All other parts are optional.

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

FloatingPointLiteral:

    Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt

    . Digits ExponentPartopt FloatTypeSuffixopt

    Digits ExponentPart FloatTypeSuffixopt

    Digits ExponentPartopt FloatTypeSuffix

ExponentPart:

    ExponentIndicator SignedInteger

ExponentIndicator: one of

    e E

SignedInteger:

    Signopt Digits

Sign: one of

    + -

FloatTypeSuffix: one of

    f F d D

The Java types float and double are IEEE 754 32-bit single-precision and 64-bit double-precision binary floating-point values, respectively.

The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf of class Float (§20.9.17) and class Double (§20.10.16) of the package java.lang.

The largest positive finite float literal is 3.40282347e+38f. The smallest positive finite nonzero literal of type float is 1.40239846e-45f. The largest positive finite double literal is 1.79769313486231570e+308. The smallest positive finite nonzero literal of type double is 4.94065645841246544e-324.

See Float.MIN_VALUE (§20.9.1) and Float.MAX_VALUE (§20.9.2); see also Double.MIN_VALUE (§20.10.1) and Double.MAX_VALUE (§20.10.2).

A compile-time error occurs if a nonzero floating-point literal is too large, so that on rounded conversion to its internal representation it becomes an IEEE 754 infinity. A Java program can represent infinities without producing a compile-time error by using constant expressions such as 1f/0f or -1d/0d or by using the predefined constants POSITIVE_INFINITY and NEGATIVE_INFINITY of the classes Float (§20.9) and Double (§20.10).

A compile-time error occurs if a nonzero floating-point literal is too small, so that, on rounded conversion to its internal representation, it becomes a zero. A compile-time error does not occur if a nonzero floating-point literal has a small value that, on rounded conversion to its internal representation, becomes a nonzero denormalized number.

Predefined constants representing Not-a-Number values are defined in the classes Float and Double as Float.NaN (§20.9.5) and Double.NaN (§20.10.5).

Examples of float literals:

    1e1f			2.f			.3f		0f		3.14f			6.022137e+23f

Examples of double literals:

    1e1			2.			.3		0.0		3.14			1e-9d		1e137

There is no provision for expressing floating-point literals in other than decimal radix. However, method intBitsToFloat (§20.9.23) of class Float and method longBitsToDouble (§20.10.22) of class Double provide a way to express floating-point values in terms of hexadecimal or octal integer literals. For example, the value of:

Double.longBitsToDouble(0x400921FB54442D18L)

is equal to the value of Math.PI (§20.11.2).


3.10.3 Boolean Literals

The boolean type has two values, represented by the literals true and false, formed from ASCII letters.

A boolean literal is always of type boolean.

BooleanLiteral: one of

    true false


3.10.4 Character Literals

A character literal is expressed as a character or an escape sequence, enclosed in ASCII single quotes. (The single-quote, or apostrophe, character is \u0027.)

A character literal is always of type char.

CharacterLiteral:

    ' SingleCharacter '

    ' EscapeSequence '

SingleCharacter:

    InputCharacter but not ' or \

The escape sequences are described in §3.10.6.

As specified in §3.4, the characters CR and LF are never an InputCharacter; they are recognized as constituting a LineTerminator.

It is a compile-time error for the character following the SingleCharacter or EscapeSequence to be other than a '.

It is a compile-time error for a line terminator to appear after the opening ' and before the closing '.

The following are examples of char literals:

'a'
'%'
'\t'
'\\'
'\''
'\u03a9'
'\uFFFF'
'\177'
'  '
'  '

Because Unicode escapes are processed very early, it is not correct to write '\u000a' for a character literal whose value is linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), and so the character literal is not valid in step 3. Instead, one should use the escape sequence '\n' (§3.10.6). Similarly, it is not correct to write '\u000d' for a character literal whose value is carriage return (CR). Instead, use '\r'.

In C and C++, a character literal may contain representations of more than one character, but the value of such a character literal is implementation-defined. In Java, a character literal always represents exactly one character.


3.10.5 String Literals

A string literal consists of zero or more characters enclosed in double quotes. Each character may be represented by an escape sequence.

A string literal is always of type String (§4.3.3, §20.12). A string literal always refers to the same instance (§4.3.1) of class String.

StringLiteral:

    " StringCharactersopt "

StringCharacters:

    StringCharacter

    StringCharacters StringCharacter

StringCharacter:

    InputCharacter but not " or \

    EscapeSequence

The escape sequences are described in §3.10.6.

As specified in §3.4, neither of the characters CR and LF is ever considered to be an InputCharacter; each is recognized as constituting a LineTerminator.

It is a compile-time error for a line terminator to appear after the opening " and before the closing matching ". A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator + (§15.17.1).

The following are examples of string literals:

"" 							// the empty string
"\""							// a string containing " alone
"This is a string"							// a string containing 16 characters

"This is a " +							// actually a string-valued constant expression,
    "two-line string"						//		formed from two string literals

Because Unicode escapes are processed very early, it is not correct to write "\u000a" for a string literal containing a single linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), and so the string literal is not valid in step 3. Instead, one should write "\n" (§3.10.6). Similarly, it is not correct to write "\u000d" for a string literal containing a single carriage return (CR). Instead use "\r".

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3,§20.12). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.27)-are "interned" so as to share unique instances, using the method String.intern (§20.12.47).

Thus, the test program consisting of the compilation unit (§7.3):

package testPackage;

class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}

class Other { static String hello = "Hello"; }

and the compilation unit:

package other;

public class Other { static String hello = "Hello"; }

produces the output:

true true true true false true

This example illustrates six points:

  • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
  • Literal strings within different classes in the same package represent references to the same String object.
  • Literal strings within different classes in different packages likewise represent references to the same String object.
  • Strings computed by constant expressions (§15.27) are computed at compile time and then treated as if they were literals.
  • Strings computed at run time are newly created and therefore distinct.
  • The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.


3.10.6 Escape Sequences for Character and String Literals

The character and string escape sequences allow for the representation of some nongraphic characters as well as the single quote, double quote, and backslash characters in character literals (§3.10.4) and string literals (§3.10.5).

EscapeSequence:
\ b /* \u0008: backspace BS */
\ t /* \u0009: horizontal tab HT */
\ n /* \u000a: linefeed LF */
\ f /* \u000c: form feed FF */
\ r /* \u000d: carriage return CR */
\ " /* \u0022: double quote " */
\ ' /* \u0027: single quote ' */
\ \ /* \u005c: backslash \ */
OctalEscape /* \u0000 to \u00ff: from octal value */

OctalEscape:

    \ OctalDigit

    \ OctalDigit OctalDigit

    \ ZeroToThree OctalDigit OctalDigit

OctalDigit: one of

    0 1 2 3 4 5 6 7

ZeroToThree: one of

    0 1 2 3

It is a compile-time error if the character following a backslash in an escape is not an ASCII b, t, n, f, r, ", ', \, 0, 1, 2, 3, 4, 5, 6, or 7. The Unicode escape \u is processed earlier (§3.3). (Octal escapes are provided for compatibility with C, but can express only Unicode values \u0000 through \u00FF, so Unicode escapes are usually preferred.)


3.10.7 The Null Literal

The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.

NullLiteral:

    null


3.11 Separators

The following nine ASCII characters are the Java separators (punctuators):

Separator: one of
( ) { } [ ] ; , .


3.12 Operators

The following 37 tokens are the Java operators, formed from ASCII characters:

Operator: one of
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>>=

Give her no token but stones; for she's as hard as steel.
—William Shakespeare, Two Gentlemen of Verona, Act I, scene i

These lords are visited; you are not free;
For the Lord's tokens on you do I see.
—William Shakespeare, Love's Labour's Lost, Act V, scene ii

Thou, thou, Lysander, thou hast given her rhymes,
And interchanged love-tokens with my child.
—William Shakespeare, A Midsummer Night's Dream, Act I, scene i

Here is a letter from Queen Hecuba,
A token from her daughter . . .
—William Shakespeare, Troilus and Cressida, Act V, scene i

Are there no other tokens . . . ?
—William Shakespeare, Measure for Measure, Act IV, scene i


 4. Types, Values, and Variables

CHAPTER 4

Types, Values, and Variables

I send no agent or medium,
offer no representative of value,
but offer the value itself.
—Walt Whitman, Carol of Occupations (1855), in Leaves of Grass

Java is a strongly typed language, which means that every variable and every expression has a type that is known at compile time. Types limit the values that a variable (§4.5) can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong typing helps detect errors at compile time.

The types of the Java language are divided into two categories: primitive types and reference types. The primitive types (§4.2) are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types (§4.3) are class types, interface types, and array types. There is also a special null type. An object (§4.3.1) in Java is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object (§4.3.2). String literals are represented by String objects (§4.3.3).

Types are the same (§4.3.4) if they have the same fully qualified names and are loaded by the same class loader. Names of types are used (§4.4) in declarations, in casts, in class instance creation expressions, in array creation expressions, and in instanceof operator expressions.

A variable (§4.5) is a storage location. A variable of a primitive type always holds a value of that exact type. A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface. If T is a primitive type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of T"; if T is a reference type, then a variable of type "array of T" can hold a null reference or a reference to any array of type "array of S" such that type S is assignable (§5.2) to type T. A variable of type Object can hold a null reference or a reference to any object, whether class instance or array.


4.1 The Kinds of Types and Values

There are two kinds of types in Java: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).

Type:

    PrimitiveType

    ReferenceType

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the Java programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.


4.2 Primitive Types and Values

A primitive type is predefined by the Java language and named by its reserved keyword (§3.9):

PrimitiveType:

    NumericType

    boolean

NumericType:

    IntegralType

    FloatingPointType

IntegralType: one of

    byte short int long char

FloatingPointType: one of

    float double

Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.

The numeric types are the integral types and the floating-point types.

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing Unicode characters.

The floating-point types are float, whose values are 32-bit IEEE 754 floating-point numbers, and double, whose values are 64-bit IEEE 754 floating-point numbers.

The boolean type has exactly two values: true and false.


4.2.1 Integral Types and Values

The values of the integral types are integers in the following ranges:

  • For byte, from -128 to 127, inclusive
  • For short, from -32768 to 32767, inclusive
  • For int, from -2147483648 to 2147483647, inclusive
  • For long, from -9223372036854775808 to 9223372036854775807, inclusive
  • For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535


4.2.2 Integer Operations

Java provides a number of operators that act on integral values:

  • The comparison operators, which result in a value of type boolean:
    • The numerical comparison operators <, <=, >, and >= (§15.19.1)
    • The numerical equality operators == and != (§15.20.1)
  • The numerical operators, which result in a value of type int or long:
    • The unary plus and minus operators + and - (§15.14.3, §15.14.4)
    • The multiplicative operators *, /, and % (§15.16)
    • The additive operators + and - (§15.17.2)
    • The increment operator ++, both prefix (§15.14.1) and postfix (§15.13.2)
    • The decrement operator --, both prefix (§15.14.2) and postfix (§15.13.3)
    • The signed and unsigned shift operators <<, >>, and >>> (§15.18)
    • The bitwise complement operator ~ (§15.14.5)
    • The integer bitwise operators &, |, and ^ (§15.21.1)
  • The conditional operator ? : (§15.24)
  • The cast operator, which can convert from an integral value to a value of any specified numeric type (§5.4, §15.15)
  • The string concatenation operator + (§15.17.1), which, when given a String operand and an integral operand, will convert the integral operand to a String representing its value in decimal form, and then produce a newly created String that is the concatenation of the two strings

Other useful constructors, methods, and constants are predefined in the classes Integer (§20.7), Long (§20.8), and Character (§20.5).

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.2) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception (§11) are the integer divide operator / (§15.16.2) and the integer remainder operator % (§15.16.3), which throw an ArithmeticException if the right-hand operand is zero.

The example:

class Test {
    public static void main(String[] args) {
        int i = 1000000;
        System.out.println(i * i);
        long l = i;
        System.out.println(l * l);
        System.out.println(20296 / (l - i));
    }
}

produces the output:

-727379968
1000000000000

and then encounters an ArithmeticException in the division by l - i, because l - i is zero. The first multiplication is performed in 32-bit precision, whereas the second multiplication is a long multiplication. The value -727379968 is the decimal value of the low 32 bits of the mathematical result, 1000000000000, which is a value too large for type int.

Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type boolean.


4.2.3 Floating-Point Types and Values

The floating-point types are float and double, representing the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

The IEEE 754 standard includes not only positive and negative sign-magnitude numbers, but also positive and negative zeros, positive and negative infinities, and a special Not-a-Number (hereafter abbreviated NaN). The NaN value is used to represent the result of certain operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN (§20.9.5) and Double.NaN (§20.10.5).

The finite nonzero values of type float are of the form [image], where s is +1 or -1, m is a positive integer less than [image], and e is an integer between -149 and 104, inclusive. Values of that form such that m is positive but less than [image] and e is equal to -149 are said to be denormalized.

The finite nonzero values of type double are of the form [image], where s is +1 or -1, m is a positive integer less than [image], and e is an integer between -1075 and 970, inclusive. Values of that form such that m is positive but less than [image] and e is equal to -1075 are said to be denormalized.

Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative zero, positive zero, positive finite nonzero values, and positive infinity.

Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity. The operations Math.min and Math.max also distinguish positive zero and negative zero.

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.19.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.20.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.

Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type boolean.


4.2.4 Floating-Point Operations

Java provides a number of operators that act on floating-point values:

  • The comparison operators, which result in a value of type boolean:
    • The numerical comparison operators <, <=, >, and >= (§15.19.1)
    • The numerical equality operators == and != (§15.20.1)
  • The numerical operators, which result in a value of type float or double:
    • The unary plus and minus operators + and - (§15.14.3, §15.14.4)
    • The multiplicative operators *, /, and % (§15.16)
    • The additive operators + and - (§15.17.2)
    • The increment operator ++, both prefix (§15.14.1) and postfix (§15.13.2)
    • The decrement operator --, both prefix (§15.14.2) and postfix (§15.13.3)
  • The conditional operator ? : (§15.24)
  • The cast operator, which can convert from a floating-point value to a value of any specified numeric type (§5.4, §15.15)
  • The string concatenation operator + (§15.17.1), which, when given a String operand and a floating-point operand, will convert the floating-point operand to a String representing its value in decimal form (without information loss), and then produce a newly created String by concatenating the two strings

Other useful constructors, methods, and constants are predefined in the classes Float (§20.9), Double (§20.10), and Math (§20.11).

If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. (If the other operand is not a double, it is first widened to type double by numeric promotion (§5.6).) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. If the other operand is not a float, it is first widened to type float by numeric promotion.

Operators on floating-point numbers behave exactly as specified by IEEE 754. In particular, Java requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations in Java do not "flush to zero" if the calculated result is a denormalized number.

Java requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. Inexact results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as round to nearest.

Java uses round toward zero when converting a floating value to an integer (§5.1.3), which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.

Java floating-point operators produce no exceptions (§11). An operation that overflows produces a signed infinity, an operation that underflows produces a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.

The example program:

class Test {

    public static void main(String[] args) {

        // An example of overflow:
        double d = 1e308;
        System.out.print("overflow produces infinity: ");
        System.out.println(d + "*10==" + d*10);

        // An example of gradual underflow:
        d = 1e-305 * Math.PI;
        System.out.print("gradual underflow: " + d + "\n      ");
        for (int i = 0; i < 4; i++)
            System.out.print(" " + (d /= 100000));
        System.out.println();

        // An example of NaN:
        System.out.print("0.0/0.0 is Not-a-Number: ");
        d = 0.0/0.0;
        System.out.println(d);

        // An example of inexact results and rounding:
        System.out.print("inexact results with float:");
        for (int i = 0; i < 100; i++) {
            float z = 1.0f / i;
            if (z * i != 1.0f)
                System.out.print(" " + i);
        }
        System.out.println();

        // Another example of inexact results and rounding:
        System.out.print("inexact results with double:");
        for (int i = 0; i < 100; i++) {
            double z = 1.0 / i;
            if (z * i != 1.0)
                System.out.print(" " + i);
        }
        System.out.println();

        // An example of cast to integer rounding:
        System.out.print("cast to int rounds toward 0: ");
        d = 12345.6;
        System.out.println((int)d + " " + (int)(-d));
    }
}

produces the output:

overflow produces infinity: 1.0e+308*10==Infinity
gradual underflow: 3.141592653589793E-305
    3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
0.0/0.0 is Not-a-Number: NaN
inexact results with float: 0 41 47 55 61 82 83 94 97
inexact results with double: 0 49 98
cast to int rounds toward 0: 12345 -12345

This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision.

The inexact results when i is 0 involve division by zero, so that z becomes positive infinity, and z * 0 is NaN, which is not equal to 1.0.


4.2.5 The boolean Type and boolean Values

The boolean type represents a logical quantity with two possible values, indicated by the literals true and false (§3.10.3). The boolean operators are:

  • The relational operators == and != (§15.20.2)
  • The logical-complement operator ! (§15.14.6)
  • The logical operators &, ^, and | (§15.21.2)
  • The conditional-and and conditional-or operators && (§15.22) and || (§15.23)
  • The conditional operator ? : (§15.24)
  • The string concatenation operator + (§15.17.1), which, when given a String operand and a boolean operand, will convert the boolean operand to a String (either "true" or "false"), and then produce a newly created String that is the concatenation of the two strings

Boolean expressions determine the control flow in several kinds of statements:

  • The if statement (§14.8)
  • The while statement (§14.10)
  • The do statement (§14.11)
  • The for statement (§14.12)

A boolean expression also determines which subexpression is evaluated in the conditional ? : operator (§15.24).

Only boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :. An integer x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null.

A cast of a boolean value to type boolean is allowed (§5.1.1); no other casts on type boolean are allowed. A boolean can be converted to a string by string conversion (§5.4).


4.3 Reference Types and Values

There are three kinds of reference types: class types (§8), interface types (§9), and array types (§10).

ReferenceType:

    ClassOrInterfaceType

    ArrayType

ClassOrInterfaceType:

    ClassType

    InterfaceType

ClassType:

    TypeName

InterfaceType:

    TypeName

ArrayType:

    Type [ ]

Names are described in §6; type names in §6.5 and, specifically, §6.5.4.

The sample code:

class Point { int[] metrics; }

interface Move { void move(int deltax, int deltay); }

declares a class type Point, an interface type Move, and uses an array type int[] (an array of int) to declare the field metrics of the class Point.


4.3.1 Objects

An object is a class instance or an array.

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

A class instance is explicitly created by a class instance creation expression (§15.8), or by invoking the newInstance method of class Class (§20.3.8). An array is explicitly created by an array creation expression (§15.8).

A new class instance is implicitly created when the string concatenation operator + (§15.17.1) is used in an expression, resulting in a new object of type String (§4.3.3, §20.12). A new array object is implicitly created when an array initializer expression (§10.6) is evaluated; this can occur when a class or interface is initialized (§12.4), when a new instance of a class is created (§15.8), or when a local variable declaration statement is executed (§14.3).

Many of these cases are illustrated in the following example:

class Point {
    int x, y;
    Point() { System.out.println("default"); }
    Point(int x, int y) { this.x = x; this.y = y; }

    // A Point instance is explicitly created at class initialization time:
    static Point origin = new Point(0,0);

    // A String can be implicitly created by a + operator:
    public String toString() {

        return "(" + x + "," + y + ")";

    }
}

class Test {
    public static void main(String[] args) {
        // A Point is explicitly created using newInstance:
        Point p = null;
        try {
            p = (Point)Class.forName("Point").newInstance();
        } catch (Exception e) {
            System.out.println(e);
        }

        // An array is implicitly created by an array constructor:
        Point a[] = { new Point(0,0), new Point(1,1) };

        // Strings are implicitly created by + operators:
        System.out.println("p: " + p);
        System.out.println("a: { " + a[0] + ", "

                                           + a[1] + " }");

        // An array is explicitly created by an array creation expression:
        String sa[] = new String[2];
        sa[0] = "he"; sa[1] = "llo";
        System.out.println(sa[0] + sa[1]);
    }
}

which produces the output:

default
p: (0,0)
a: { (0,0), (1,1) }
hello

The operators on references to objects are:

  • Field access, using either a qualified name (§6.6) or a field access expression (§15.10)
  • Method invocation (§15.11)
  • The cast operator (§5.4, §15.15)
  • The string concatenation operator + (§15.17.1), which, when given a String operand and a reference, will convert the reference to a String by invoking the toString method (§20.1.2) of the referenced object (using "null" if either the reference or the result of toString is a null reference), and then will produce a newly created String that is the concatenation of the two strings
  • The instanceof operator (§15.19.2)
  • The reference equality operators == and != (§15.20.3)
  • The conditional operator ? : (§15.24).

There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

The example program:

class Value { int val; }

class Test {
    public static void main(String[] args) {
        int i1 = 3;
        int i2 = i1;
        i2 = 4;
        System.out.print("i1==" + i1);
        System.out.println(" but i2==" + i2);
        Value v1 = new Value();
        v1.val = 5;
        Value v2 = v1;
        v2.val = 6;
        System.out.print("v1.val==" + v1.val);
        System.out.println(" and v2.val==" + v2.val);
    }
}

produces the output:

i1==3 but i2==4
v1.val==6 and v2.val==6

because v1.val and v2.val reference the same instance variable (§4.5.3) in the one Value object created by the only new expression, while i1 and i2 are different variables.

See §10 and §15.9 for examples of the creation and use of arrays.

Each object has an associated lock (§17.13), which is used by synchronized methods (§8.4.3) and the synchronized statement (§14.17) to provide control over concurrent access to state by multiple threads (§17.12, §20.20).


4.3.2 The Class Object

The standard class Object is a superclass (§8.1) of all other classes. A variable of type Object can hold a reference to any object, whether it is an instance of a class or an array (§10). All class and array types inherit the methods of class Object, which are summarized here and completely specified in §20.1:

package java.lang;

public class Object {
    public final Class getClass() { . . . }
    public String toString() { . . . }
    public boolean equals(Object obj) { . . . }
    public int hashCode() { . . . }
    protected Object clone()
        throws CloneNotSupportedException { . . . }
    public final void wait()

        throws IllegalMonitorStateException,

            InterruptedException { . . . }
    public final void wait(long millis)
        throws IllegalMonitorStateException,
            InterruptedException { . . . }
    public final void wait(long millis, int nanos) { . . . }
        throws IllegalMonitorStateException,
            InterruptedException { . . . }
    public final void notify() { . . . }
        throws IllegalMonitorStateException
    public final void notifyAll() { . . . }
        throws IllegalMonitorStateException
    protected void finalize()
        throws Throwable { . . . }
}

The members of Object are as follows:

  • The method getClass returns the Class (§20.3) object that represents the class of the object. A Class object exists for each reference type. It can be used, for example, to discover the fully qualified name of a class, its members, its immediate superclass, and any interfaces that it implements. A class method that is declared synchronized (§8.4.3.5) synchronizes on the lock associated with the Class object of the class.
  • The method toString returns a String representation of the object.
  • The methods equals and hashCode are declared for the benefit of hashtables such as java.util.Hashtable (§21.7). The method equals defines a notion of object equality, which is based on value, not reference, comparison.
  • The method clone is used to make a duplicate of an object.
  • The methods wait, notify, and notifyAll are used in concurrent programming using threads, as described in §17.
  • The method finalize is run just before an object is destroyed and is described in §12.6.


4.3.3 The Class String

Instances of class String (§20.12) represent sequences of Unicode characters. A String object has a constant (unchanging) value. String literals (§3.10.5) are references to instances of class String.

The string concatenation operator + (§15.17.1) implicitly creates a new String object.


4.3.4 When Reference Types Are the Same

Two reference types the same type if:

  • They are both class or both interface types, are loaded by the same class loader, and have the same fully-qualified name (§6.6), in which case they are sometimes said to be the same class or the same interface.
  • They are both array types, and have the same component type (§10).


4.4 Where Types Are Used

Types are used when they appear in declarations or in certain expressions.

The following code fragment contains one or more instances of each kind of usage of a type:

import java.util.Random;

class MiscMath {

    int divisor;

    MiscMath(int divisor) {
        this.divisor = divisor;
    }

    float ratio(long l) {
        try {
            l /= divisor;
        } catch (Exception e) {
            if (e instanceof ArithmeticException)
                l = Long.MAX_VALUE;
            else
                l = 0;
        }
        return (float)l;
    }

    double gausser() {
        Random r = new Random();
        double[] val = new double[2];
        val[0] = r.nextGaussian();
        val[1] = r.nextGaussian();
        return (val[0] + val[1]) / 2;
    }

}

In this example, types are used in declarations of the following:

  • Imported types (§7.5); here the type Random, imported from the type java.util.Random of the package java.util, is declared
  • Fields, which are the class variables and instance variables of classes (§8.3), and constants of interfaces (§9.3); here the field divisor in the class MiscMath is declared to be of type int
  • Method parameters (§8.4.1); here the parameter l of the method ratio is declared to be of type long
  • Method results (§8.4); here the result of the method ratio is declared to be of type float, and the result of the method gausser is declared to be of type double
  • Constructor parameters (§8.6.1); here the parameter of the constructor for MiscMath is declared to be of type int
  • Local variables (§14.3, §14.12); the local variables r and val of the method gausser are declared to be of types Random and double[] (array of double)
  • Exception handler parameters (§14.18); here the exception handler parameter e of the catch clause is declared to be of type Exception

and in expressions of the following kinds:

  • Class instance creations (§15.8); here a local variable r of method gausser is initialized by a class instance creation expression that uses the type Random
  • Array creations (§15.9); here the local variable val of method gausser is initialized by an array creation expression that creates an array of double with size 2
  • Casts (§15.15); here the return statement of the method ratio uses the float type in a cast
  • The instanceof operator (§15.19.2); here the instanceof operator tests whether e is assignment compatible with the type ArithmeticException


4.5 Variables

A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3). A variable always contains a value that is assignment compatible (§5.2) with its type. A variable's value is changed by an assignment (§15.25) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.13.2, §15.13.3, §15.14.1, §15.14.2).

Compatibility of the value of a variable with its type is guaranteed by the design of the Java language. Default values are compatible (§4.5.4) and all assignments to a variable are checked for assignment compatibility (§5.2), usually at compile time, but, in a single case involving arrays, a run-time check is made (§10.10).


4.5.1 Variables of Primitive Type

A variable of a primitive type always holds a value of that exact primitive type.


4.5.2 Variables of Reference Type

A variable of reference type can hold either of the following:

  • A null reference
  • A reference to any object (§4.3) whose class (§4.5.5) is assignment compatible (§5.2) with the type of the variable


4.5.3 Kinds of Variables

There are seven kinds of variables:

  • A class variable is a field declared using the keyword static within a class declaration (§8.3.1.1), or with or without the keyword static within an interface declaration (§9.3). A class variable is created when its class or interface is loaded (§12.2) and is initialized to a default value (§4.5.4). The class variable effectively ceases to exist when its class or interface is unloaded (§12.8), after any necessary finalization of the class or interface (§12.6) has been completed.
  • An instance variable is a field declared within a class declaration without using the keyword static (§8.3.1.1). If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.5.4) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.3). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed.
  • Array components are unnamed variables that are created and initialized to default values (§4.5.4) whenever a new object that is an array is created (§15.9). The array components effectively cease to exist when the array is no longer referenced. See §10 for a description of arrays.
  • Method parameters (§8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.11). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.
  • Constructor parameters (§8.6.1) name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression (§15.8) or explicit constructor invocation (§8.6.5) invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete.
  • An exception-handler parameter is created each time an exception is caught by a catch clause of a try statement (§14.18). The new variable is initialized with the actual object associated with the exception (§11.3, §14.16). The exception-handler parameter effectively ceases to exist when execution of the block associated with the catch clause is complete.
  • Local variables are declared by local variable declaration statements (§14.3). Whenever the flow of control enters a block (§14.2) or for statement (§14.12), a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or for statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete.

Were it not for one exceptional situation, a local variable could always be regarded as being created when its local variable declaration statement is executed. The exceptional situation involves the switch statement (§14.9), where it is possible for control to enter a block but bypass execution of a local variable declaration statement. Because of the restrictions imposed by the rules of definite assignment (§16), however, the local variable declared by such a bypassed local variable declaration statement cannot be used before it has been definitely assigned a value by an assignment expression (§15.25).

The following example contains several different kinds of variables:

class Point {
    static int numPoints;								// numPoints is a class variable
    int x, y;								// x and y are instance variables
    int[] w = new int[10];								// w[0] is an array component
    int setX(int x) {								// x is a method parameter
        int oldx = this.x;							// oldx is a local variable
        this.x = x;
        return oldx;
    }
}


4.5.4 Initial Values of Variables

Every variable in a Java program must have a value before its value is used:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.8, §15.9, §20.3.6):
    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.
  • Each method parameter (§8.4.1) is initialized to the corresponding argument value provided by the invoker of the method (§15.11).
  • Each constructor parameter (§8.6.1) is initialized to the corresponding argument value provided by a class instance creation expression (§15.8) or explicit constructor invocation (§8.6.5).
  • An exception-handler parameter (§14.18) is initialized to the thrown object representing the exception (§11.3, §14.16).
  • A local variable (§14.3, §14.12) must be explicitly given a value before it is used, by either initialization (§14.3) or assignment (§15.25), in a way that can be verified by the compiler using the rules for definite assignment (§16).

The example program:

class Point {
    static int npoints;
    int x, y;
    Point root;
}

class Test {
    public static void main(String[] args) {
        System.out.println("npoints=" + Point.npoints);
        Point p = new Point();
        System.out.println("p.x=" + p.x + ", p.y=" + p.y);
        System.out.println("p.root=" + p.root);
    }
}

prints:

npoints=0
p.x=0, p.y=0
p.root=null

illustrating the default initialization of npoints, which occurs when the class Point is prepared (§12.3.2), and the default initialization of x, y, and root, which occurs when a new Point is instantiated. See §12 for a full description of all aspects of loading, linking, and initialization of classes and interfaces, plus a description of the instantiation of classes to make new class instances.


4.5.5 Variables Have Types, Objects Have Classes

Every object belongs to some particular class: the class that was mentioned in the creation expression that produced the object, the class whose class object was used to invoke the newInstance method (§20.3.6) to produce the object, or the String class for objects implicitly created by the string concatenation operator + (§15.17.1). This class is called the class of the object. (Arrays also have a class, as described at the end of this section.) An object is said to be an instance of its class and of all superclasses of its class.

(Sometimes a variable or expression is said to have a "run-time type" but that is an abuse of terminology; it refers to the class of the object referred to by the value of the variable or expression at run time, assuming that the value is not null. Properly speaking, type is a compile-time notion. A variable or expression has a type; an object or array has no type, but belongs to a class.)

The type of a variable is always declared, and the type of an expression can be deduced at compile time. The type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not null, it refers to an object or array that has a class (not a type), and that class will necessarily be compatible with the compile-time type.

Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.4) that interface.

Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object:

public interface Colorable {
    void setColor(byte r, byte g, byte b);
}

class Point { int x, y; }

class ColoredPoint extends Point implements Colorable {

    byte r, g, b;

    public void setColor(byte rv, byte gv, byte bv) {
        r = rv; g = gv; b = bv;
    }

}

class Test {
    public static void main(String[] args) {
        Point p = new Point();
        ColoredPoint cp = new ColoredPoint();
        p = cp;
        Colorable c = cp;
    }
}

In this example:

  • The local variable p of the method main of class Test has type Point and is initially assigned a reference to a new instance of class Point.
  • The local variable cp similarly has as its type ColoredPoint, and is initially assigned a reference to a new instance of class ColoredPoint.
  • The assignment of the value of cp to the variable p causes p to hold a reference to a ColoredPoint object. This is permitted because ColoredPoint is a subclass of Point, so the class ColoredPoint is assignment compatible (§5.2) with the type Point. A ColoredPoint object includes support for all the methods of a Point. In addition to its particular fields r, g, and b, it has the fields of class Point, namely x and y.
  • The local variable c has as its type the interface type Colorable, so it can hold a reference to any object whose class implements Colorable; specifically, it can hold a reference to a ColoredPoint.
  • Note that an expression such as "new Colorable()" is not valid because it is not possible to create an instance of an interface, only of a class.

Every array also has a class; the method getClass (§20.1.1), when invoked for an array object, will return a class object (of class Class) that represents the class of the array. The classes for arrays have strange names that are not valid Java identifiers; for example, the class for an array of int components has the name "[I" and so the value of the expression:

new int[10].getClass().getName()

is the string "[I"; see §20.1.1 for details.

Oft on the dappled turf at ease
I sit, and play with similes,
Loose types of things through all degrees.
—William Wordsworth, To the Same Flower


 5. Conversions and Promotions

CHAPTER 5

Conversions and Promotions

Thou art not for the fashion of these times,
Where none will sweat but for promotion.
—William Shakespeare, As You Like It, Act II, scene iii

Every Java expression has a type that can be deduced from the structure of the expression and the types of the literals, variables, and methods mentioned in the expression. It is possible, however, to write an expression in a context where the type of the expression is not appropriate. In some cases, this leads to an error at compile time; for example, if the expression in an if statement (§14.8) has any type other than boolean, a compile-time error occurs. In other cases, the context may be able to accept a type that is related to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly, the Java language performs an implicit conversion from the type of the expression to a type acceptable for its surrounding context.

A specific conversion from type S to type T allows an expression of type S to be treated at compile time as if it had type T instead. In some cases this will require a corresponding action at run time to check the validity of the conversion or to translate the run-time value of the expression into a form appropriate for the new type T. For example:

  • A conversion from type Object (§20.1) to type Thread (§20.20) requires a run-time check to make sure that the run-time value is actually an instance of class Thread or one of its subclasses; if it is not, an exception is thrown.
  • A conversion from type Thread to type Object requires no run-time action; Thread is a subclass of Object, so any reference produced by an expression of type Thread is a valid reference value of type Object.
  • A conversion from type int to type long requires run-time sign-extension of a 32-bit integer value to the 64-bit long representation. No information is lost.
  • A conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.

In every conversion context, only certain specific conversions are permitted. The specific conversions that are possible in Java are grouped for convenience of description into several broad categories:

  • Identity conversions
  • Widening primitive conversions
  • Narrowing primitive conversions
  • Widening reference conversions
  • Narrowing reference conversions
  • String conversions

There are five conversion contexts in which conversion of Java expressions may occur. Each context allows conversions in some of the categories named above but not others. The term "conversion" is also used to describe the process of choosing a specific conversion for such a context. For example, we say that an expression that is an actual argument in a method invocation is subject to "method invocation conversion," meaning that a specific conversion will be implicitly chosen for that expression according to the rules for the method invocation argument context.

One conversion context is the operand of a numeric operator such as + or *. The conversion process for such operands is called numeric promotion. Promotion is special in that, in the case of binary operators, the conversion chosen for one operand may depend in part on the type of the other operand expression.

This chapter first describes the six categories of conversions (§5.1), including the special conversions to String allowed for the string concatenation operator +. Then the five conversion contexts are described:

  • Assignment conversion (§5.2, §15.25) converts the type of an expression to the type of a specified variable. The conversions permitted for assignment are limited in such a way that assignment conversion never causes an exception.
  • Method invocation conversion (§5.3, §15.8, §15.11) is applied to each argument in a method or constructor invocation and, except in one case, performs the same conversions that assignment conversion does. Method invocation conversion never causes an exception.
  • Casting conversion (§5.4) converts the type of an expression to a type explicitly specified by a cast operator (§15.15). It is more inclusive than assignment or method invocation conversion, allowing any specific conversion other than a string conversion, but certain casts to a reference type may cause an exception at run time.
  • String conversion (§5.4, §15.17.1) allows any type to be converted to type String.
  • Numeric promotion (§5.6) brings the operands of a numeric operator to a common type so that an operation can be performed.

Here are some examples of the various contexts for conversion:

class Test {

    public static void main(String[] args) {

        // Casting conversion (§5.4) of a float literal to
        // type int. Without the cast operator, this would
        // be a compile-time error, because this is a
        // narrowing conversion (§5.1.3):
        int i = (int)12.5f;

        // String conversion (§5.4) of i's int value:
        System.out.println("(int)12.5f==" + i);

        // Assignment conversion (§5.2) of i's value to type
        // float. This is a widening conversion (§5.1.2):
        float f = i;

        // String conversion of f's float value:
        System.out.println("after float widening: " + f);

        // Numeric promotion (§5.6) of i's value to type
        // float. This is a binary numeric promotion.
        // After promotion, the operation is float*float:
        System.out.print(f);
        f = f * i;

        // Two string conversions of i and f:
        System.out.println("*" + i + "==" + f);

        // Method invocation conversion (§5.3) of f's value
        // to type double, needed because the method Math.sin
        // accepts only a double argument:
        double d = Math.sin(f);

        // Two string conversions of f and d:
        System.out.println("Math.sin(" + f + ")==" + d);

    }

}

which produces the output:

(int)12.5f==12
after float widening: 12.0
12.0*12==144.0
Math.sin(144.0)==-0.49102159389846934


5.1 Kinds of Conversion

Specific type conversions in Java are divided into six categories.


5.1.1 Identity Conversions

A conversion from a type to that same type is permitted for any type. This may seem trivial, but it has two practical consequences. First, it is always permitted for an expression to have the desired type to begin with, thus allowing the simply stated rule that every expression is subject to conversion, if only a trivial identity conversion. Second, it implies that it is permitted for a program to include redundant cast operators for the sake of clarity.

The only permitted conversion that involves the type boolean is the identity conversion from boolean to boolean.


5.1.2 Widening Primitive Conversions

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type and from float to double do not lose any information at all; the numeric value is preserved exactly. Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format. A widening conversion of a character to an integral type T zero-extends the representation of the character value to fill the wider format.

Despite the fact that loss of precision may occur, widening conversions among primitive types never result in a run-time exception (§11).

Here is an example of a widening conversion that loses precision:

class Test {
    public static void main(String[] args) {
        int big = 1234567890;
        float approx = big;
        System.out.println(big - (int)approx);
    }
}

which prints:

-46

thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.


5.1.3 Narrowing Primitive Conversions

The following 23 specific conversions on primitive types are called the narrowing primitive conversions:

  • byte to char
  • short to byte or char
  • char to byte or short
  • int to byte, short, or char
  • long to byte, short, char, or int
  • float to byte, short, char, int, or long
  • double to byte, short, char, int, long, or float

Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision.

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

A narrowing conversion of a character to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though characters represent 16-bit unsigned integer values.

A narrowing conversion of a floating-point number to an integral type T takes two steps:

  • In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:
    • If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.
    • Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:
      • If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.
      • Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.
    • Otherwise, one of the following two cases must be true:
      • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.
      • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.
  • In the second step:
    • If T is int or long, the result of the conversion is the result of the first step.
    • If T is byte, char, or short, the result of the conversion is the result of a narrowing conversion to type T (§5.1.3) of the result of the first step.

The example:

class Test {
    public static void main(String[] args) {
        float fmin = Float.NEGATIVE_INFINITY;
        float fmax = Float.POSITIVE_INFINITY;
        System.out.println("long: " + (long)fmin +
                                ".." + (long)fmax);
        System.out.println("int: " + (int)fmin +
                                ".." + (int)fmax);
        System.out.println("short: " + (short)fmin +
                                ".." + (short)fmax);
        System.out.println("char: " + (int)(char)fmin +
                                ".." + (int)(char)fmax);
        System.out.println("byte: " + (byte)fmin +
                                ".." + (byte)fmax);
    }
}

produces the output:

long: -9223372036854775808..9223372036854775807
int: -2147483648..2147483647
short: 0..-1
char: 0..65535
byte: 0..-1

The results for char, int, and long are unsurprising, producing the minimum and maximum representable values of the type.

The results for byte and short lose information about the sign and magnitude of the numeric values and also lose precision. The results can be understood by examining the low order bits of the minimum and maximum int. The minimum int is, in hexadecimal, 0x80000000, and the maximum int is 0x7fffffff. This explains the short results, which are the low 16 bits of these values, namely, 0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of these values, namely, '\u0000' and '\uffff'; and it explains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff.

A narrowing conversion from double to float behaves in accordance with IEEE 754. The result is correctly rounded using IEEE 754 round-to-nearest mode. A value too small to be represented as a float is converted to positive or negative zero; a value too large to be represented as a float is converted to a (positive or negative) infinity. A double NaN is always converted to a float NaN.

Despite the fact that overflow, underflow, or other loss of information may occur, narrowing conversions among primitive types never result in a run-time exception (§11).

Here is a small test program that demonstrates a number of narrowing conversions that lose information:

class Test {

    public static void main(String[] args) {

        // A narrowing of int to short loses high bits:
        System.out.println("(short)0x12345678==0x" +
                    Integer.toHexString((short)0x12345678));

        // A int value not fitting in byte changes sign and magnitude:
        System.out.println("(byte)255==" + (byte)255);

        // A float value too big to fit gives largest int value:
        System.out.println("(int)1e20f==" + (int)1e20f);

        // A NaN converted to int yields zero:
        System.out.println("(int)NaN==" + (int)Float.NaN);

        // A double value too large for float yields infinity:
        System.out.println("(float)-1e100==" + (float)-1e100);

        // A double value too small for float underflows to zero:
        System.out.println("(float)1e-50==" + (float)1e-50);

    }

}

This test program produces the following output:

(short)0x12345678==0x5678
(byte)255==-1
(int)1e20f==2147483647
(int)NaN==0
(float)-1e100==-Infinity
(float)1e-50==0.0


5.1.4 Widening Reference Conversions

The following conversions are called the widening reference conversions:

  • From any class type S to any class type T, provided that S is a subclass of T. (An important special case is that there is a widening conversion to the class type Object from any other class type.)
  • From any class type S to any interface type K, provided that S implements K.
  • From the null type to any class type, interface type, or array type.
  • From any interface type J to any interface type K, provided that J is a subinterface of K.
  • From any interface type to type Object.
  • From any array type to type Object.
  • From any array type to type Cloneable.
  • From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a widening conversion from SC to TC.

Such conversions never require a special action at run time and therefore never throw an exception at run time. They consist simply in regarding a reference as having some other type in a manner that can be proved correct at compile time.

See §8 for the detailed specifications for classes, §9 for interfaces, and §10 for arrays.


5.1.5 Narrowing Reference Conversions

The following conversions are called the narrowing reference conversions:

  • From any class type S to any class type T, provided that S is a superclass of T. (An important special case is that there is a narrowing conversion from the class type Object to any other class type.)
  • From any class type S to any interface type K, provided that S is not final and does not implement K. (An important special case is that there is a narrowing conversion from the class type Object to any interface type.)
  • From type Object to any array type.
  • From type Object to any interface type.
  • From any interface type J to any class type T that is not final.
  • From any interface type J to any class type T that is final, provided that T implements J.
  • From any interface type J to any interface type K, provided that J is not a subinterface of K and there is no method name m such that J and K both declare a method named m with the same signature but different return types.
  • From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a narrowing conversion from SC to TC.

Such conversions require a test at run time to find out whether the actual reference value is a legitimate value of the new type. If not, then a ClassCastException is thrown.


5.1.6 String Conversions

There is a string conversion to type String from every other type, including the null type.


5.1.7 Forbidden Conversions

  • There is no permitted conversion from any reference type to any primitive type.
  • Except for the string conversions, there is no permitted conversion from any primitive type to any reference type.
  • There is no permitted conversion from the null type to any primitive type.
  • There is no permitted conversion to the null type other than the identity conversion.
  • There is no permitted conversion to the type boolean other than the identity conversion.
  • There is no permitted conversion from the type boolean other than the identity conversion and string conversion.
  • There is no permitted conversion other than string conversion from class type S to a different class type T if S is not a subclass of T and T is not a subclass of S.
  • There is no permitted conversion from class type S to interface type K if S is final and does not implement K.
  • There is no permitted conversion from class type S to any array type if S is not Object.
  • There is no permitted conversion other than string conversion from interface type J to class type T if T is final and does not implement J.
  • There is no permitted conversion from interface type J to interface type K if J and K declare methods with the same signature but different return types.
  • There is no permitted conversion from any array type to any class type other than Object or String.
  • There is no permitted conversion from any array type to any interface type, except to the interface type Cloneable, which is implemented by all arrays.
  • There is no permitted conversion from array type SC[] to array type TC[] if there is no permitted conversion other than a string conversion from SC to TC.


5.2 Assignment Conversion

Assignment conversion occurs when the value of an expression is assigned (§15.25) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (§5.1.1), a widening primitive conversion (§5.1.2), or a widening reference conversion (§5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:

  • The expression is a constant expression of type int.
  • The type of the variable is byte, short, or char.
  • The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context, then a compile-time error occurs.

If the type of an expression can be converted to the type a variable by assignment conversion, we say the expression (or its value) is assignable to the variable or, equivalently, that the type of the expression is assignment compatible with the type of the variable.

An assignment conversion never causes an exception. (Note, however, that an assignment may result in an exception in a special case involving array elements -see §10.10 and §15.25.1.)

The compile-time narrowing of constants means that code such as:

byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer = (byte)42;									// cast is permitted but not required

A value of primitive type must not be assigned to a variable of reference type; an attempt to do so will result in a compile-time error. A value of type boolean can be assigned only to a variable of type boolean.

The following test program contains examples of assignment conversion of primitive values:

class Test {
    public static void main(String[] args) {
        short s = 12;							// narrow 12 to short
        float f = s;							// widen short to float
        System.out.println("f=" + f);

        char c = '\u0123';
        long l = c;							// widen char to long
        System.out.println("l=0x" + Long.toString(l,16));

        f = 1.23f;
        double d = f;							// widen float to double
        System.out.println("d=" + d);
    }
}

It produces the following output:

f=12.0
i=0x123
d=1.2300000190734863

The following test, however, produces compile-time errors:

class Test {
    public static void main(String[] args) {
        short s = 123;
        char c = s;							// error: would require cast
        s = c;							// error: would require cast
    }
}

because not all short values are char values, and neither are all char values short values.

A value of reference type must not be assigned to a variable of primitive type; an attempt to do so will result in a compile-time error.

A value of the null type (the null reference is the only such value) may be assigned to any reference type, resulting in a null reference of that type.

Here is a sample program illustrating assignments of references:

public class Point { int x, y; }

public class Point3D extends Point { int z; }

public interface Colorable {
    void setColor(int color);
}

public class ColoredPoint extends Point implements Colorable
{
    int color;
    public void setColor(int color) { this.color = color; }
}

class Test {

    public static void main(String[] args) {

        // Assignments to variables of class type:
        Point p = new Point();
        p = new Point3D();							// ok: because Point3d is a
                                    // subclass of Point

        Point3D p3d = p;							// error: will require a cast because a
                                    // Point might not be a Point3D
                                    // (even though it is, dynamically,
                                    // in this example.)

        // Assignments to variables of type Object:
        Object o = p;							// ok: any object to Object
        int[] a = new int[3];
        Object o2 = a;							// ok: an array to Object

        // Assignments to variables of interface type:
        ColoredPoint cp = new ColoredPoint();
        Colorable c = cp;							// ok: ColoredPoint implements
                                    // Colorable

        // Assignments to variables of array type:
        byte[] b = new byte[4];
        a = b;							// error: these are not arrays
                                    // of the same primitive type
        Point3D[] p3da = new Point3D[3];
        Point[] pa = p3da;							// ok: since we can assign a
                                    // Point3D to a Point
        p3da = pa;							// error: (cast needed) since a Point
                                    // can't be assigned to a Point3D

    }

}

Assignment of a value of compile-time reference type S (source) to a variable of compile-time reference type T (target) is checked as follows:

  • If S is a class type:
    • If T is a class type, then S must either be the same class as T, or S must be a subclass of T, or a compile-time error occurs.
    • If T is an interface type, then S must implement interface T, or a compile-time error occurs.
    • If T is an array type, then a compile-time error occurs.
  • If S is an interface type:
    • If T is a class type, then T must be Object, or a compile-time error occurs.
    • If T is an interface type, then T must be either the same interface as S or a superinterface of S, or a compile-time error occurs.
    • If T is an array type, then a compile-time error occurs.
  • If S is an array type SC[], that is, an array of components of type SC:
    • If T is a class type, then T must be Object, or a compile-time error occurs.
    • If T is an interface type, then a compile-time error occurs unless T is the interface type Cloneable, the only interface implemented by arrays.
    • If T is an array type TC[], that is, an array of components of type TC, then a compile-time error occurs unless one of the following is true:
      • TC and SC are the same primitive type.
      • TC and SC are both reference types and type SC is assignable to TC, as determined by a recursive application of these compile-time rules for assignability.

See §8 for the detailed specifications for classes, §9 for interfaces, and §10 for arrays.

The following test program illustrates assignment conversions on reference values, but fails to compile because it violates the preceding rules, as described in its comments. This example should be compared to the preceding one.

public class Point { int x, y; }

public interface Colorable { void setColor(int color); }

public class ColoredPoint extends Point implements Colorable
{
    int color;
    public void setColor(int color) { this.color = color; }
}

class Test {

    public static void main(String[] args) {

        Point p = new Point();

        ColoredPoint cp = new ColoredPoint();

        // Okay because ColoredPoint is a subclass of Point:
        p = cp;

        // Okay because ColoredPoint implements Colorable:
        Colorable c = cp;

        // The following cause compile-time errors because
        // we cannot be sure they will succeed, depending on
        // the run-time type of p; a run-time check will be
        // necessary for the needed narrowing conversion and
        // must be indicated by including a cast:
        cp = p;				// p might be neither a ColoredPoint
                        // nor a subclass of ColoredPoint
        c = p;				// p might not implement Colorable

    }

}

Here is another example involving assignment of array objects:

class Point { int x, y; }

class ColoredPoint extends Point { int color; }

class Test {
    public static void main(String[] args) {
        long[] veclong = new long[100];
        Object o = veclong;									// okay
        Long l = veclong;									// compile-time error
        short[] vecshort = veclong;									// compile-time error
        Point[] pvec = new Point[100];
        ColoredPoint[] cpvec = new ColoredPoint[100];
        pvec = cpvec;									// okay
        pvec[0] = new Point();									// okay at compile time,
                                            // but would throw an
                                            // exception at run time
        cpvec = pvec;									// compile-time error
    }
}

In this example:

  • The value of veclong cannot be assigned to a Long variable, because Long is a class type (§20.8) other than Object. An array can be assigned only to a variable of a compatible array type, or to a variable of type Object.
  • The value of veclong cannot be assigned to vecshort, because they are arrays of primitive type, and short and long are not the same primitive type.
  • The value of cpvec can be assigned to pvec, because any reference that could be the value of an expression of type ColoredPoint can be the value of a variable of type Point. The subsequent assignment of the new Point to a component of pvec then would throw an ArrayStoreException (if the program were otherwise corrected so that it could be compiled), because a ColoredPoint array can't have an instance of Point as the value of a component.
  • The value of pvec cannot be assigned to cpvec, because not every reference that could be the value of an expression of type ColoredPoint can correctly be the value of a variable of type Point. If the value of pvec at run time were a reference to an instance of Point[], and the assignment to cpvec were allowed, a simple reference to a component of cpvec, say, cpvec[0], could return a Point, and a Point is not a ColoredPoint. Thus to allow such an assignment would allow a violation of the type system. A cast may be used (§5.4, §15.15) to ensure that pvec references a ColoredPoint[]:

        cpvec = (ColoredPoint[])pvec;										// okay, but may throw an
                                                // exception at run time


5.3 Method Invocation Conversion

Method invocation conversion is applied to each argument value in a method or constructor invocation (§15.8, §15.11): the type of the argument expression must be converted to the type of the corresponding parameter. Method invocation contexts allow the use of an identity conversion (§5.1.1), a widening primitive conversion (§5.1.2), or a widening reference conversion (§5.1.4).

Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion (§5.2). The Java designers felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matching resolution process (§15.11.2). Thus, the example:

class Test {

    static int m(byte a, int b) { return a+b; }

    static int m(short a, short b) { return a-b; }

    public static void main(String[] args) {
        System.out.println(m(12, 2));										// compile-time error
    }

}

causes a compile-time error because the integer literals 12 and 2 have type int, so neither method m matches under the rules of (§15.11.2). A language that included implicit narrowing of integer constants would need additional rules to resolve cases like this example.


5.4 String Conversion

String conversion applies only to the operands of the binary + operator when one of the arguments is a String. In this single special case, the other argument to the + is converted to a String, and a new String which is the concatenation of the two strings is the result of the +. String conversion is specified in detail within the description of the string concatenation + operator (§15.17.1).


5.5 Casting Conversion

Sing away sorrow, cast away care.

-Miguel de Cervantes (1547-1616),
Don Quixote (Lockhart's translation), Chapter viii

Casting conversion is applied to the operand of a cast operator (§15.15): the type of the operand expression must be converted to the type explicitly named by the cast operator. Casting contexts allow the use of an identity conversion (§5.1.1), a widening primitive conversion (§5.1.2), a narrowing primitive conversion (§5.1.3), a widening reference conversion (§5.1.4), or a narrowing reference conversion (§5.1.5). Thus casting conversions are more inclusive than assignment or method invocation conversions: a cast can do any permitted conversion other than a string conversion.

Some casts can be proven incorrect at compile time; such casts result in a compile-time error.

A value of a primitive type can be cast to another primitive type by identity conversion, if the types are the same, or by a widening primitive conversion or a narrowing primitive conversion.

A value of a primitive type cannot be cast to a reference type by casting conversion, nor can a value of a reference type be cast to a primitive type.

The remaining cases involve conversion between reference types. The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:

  • If S is a class type:
    • If T is a class type, then S and T must be related classes-that is, S and T must be the same class, or S a subclass of T, or T a subclass of S; otherwise a compile-time error occurs.
    • If T is an interface type:
      • If S is not a final class (§8.1.2), then the cast is always correct at compile time (because even if S does not implement T, a subclass of S might).
      • If S is a final class (§8.1.2), then S must implement T, or a compile-time error occurs.
    • If T is an array type, then S must be the class Object, or a compile-time error occurs.
  • If S is an interface type:
    • If T is a class type that is not final (§8.1.2), then the cast is always correct at compile time (because even if T does not implement S, a subclass of T might).
    • If T is a class type that is final (§8.1.2), then T must implement S, or a compile-time error occurs.
    • If T is an interface type and if T and S contain methods with the same signature (§8.4.2) but different return types, then a compile-time error occurs.
  • If S is an array type SC[], that is, an array of components of type SC:
    • If T is a class type, then if T is not Object, then a compile-time error occurs (because Object is the only class type to which arrays can be assigned).
    • If T is an interface type, then a compile-time error occurs unless T is the interface type Cloneable, the only interface implemented by arrays.
    • If T is an array type TC[], that is, an array of components of type TC, then a compile-time error occurs unless one of the following is true:
      • TC and SC are the same primitive type.
      • TC and SC are reference types and type SC can be cast to TC by a recursive application of these compile-time rules for casting.

See §8 for the detailed specifications of classes, §9 for interfaces, and §10 for arrays.

If a cast to a reference type is not a compile-time error, there are two cases:

  • The cast can be determined to be correct at compile time. A cast from the compile-time type S to compile-time type T is correct at compile time if and only if S can be converted to T by assignment conversion (§5.2).
  • The cast requires a run-time validity check. If the value at run time is null, then the cast is allowed. Otherwise, let R be the class of the object referred to by the run-time reference value, and let T be the type named in the cast operator. A cast conversion must check, at run time, that the class R is assignment compatible with the type T, using the algorithm specified in §5.2 but using the class R instead of the compile-time type S as specified there. (Note that R cannot be an interface when these rules are first applied for any given cast, but R may be an interface if the rules are applied recursively because the run-time reference value refers to an array whose element type is an interface type.) This modified algorithm is shown here:
    • If R is an ordinary class (not an array class):
      • If T is a class type, then R must be either the same class (§4.3.4) as T or a subclass of T, or a run-time exception is thrown.
      • If T is an interface type, then R must implement (§8.1.4) interface T, or a run-time exception is thrown.
      • If T is an array type, then a run-time exception is thrown.
    • If R is an interface:
      • If T is a class type, then T must be Object (§4.3.2, §20.1), or a run-time exception is thrown.
      • If T is an interface type, then R must be either the same interface as T or a subinterface of T, or a run-time exception is thrown.
      • If T is an array type, then a run-time exception is thrown.
    • If R is a class representing an array type RC[]-that is, an array of components of type RC:
      • If T is a class type, then T must be Object (§4.3.2, §20.1), or a run-time exception is thrown.
      • If T is an interface type, then a run-time exception is thrown unless T is the interface type Cloneable, the only interface implemented by arrays (this case could slip past the compile-time checking if, for example, a reference to an array were stored in a variable of type Object).
      • If T is an array type TC[], that is, an array of components of type TC, then a run-time exception is thrown unless one of the following is true:
        • TC and RC are the same primitive type.
        • TC and RC are reference types and type RC can be cast to TC by a recursive application of these run-time rules for casting.

If a run-time exception is thrown, it is a ClassCastException (§11.5.1.1, §20.22).

Here are some examples of casting conversions of reference types, similar to the example in §5.2:

public class Point { int x, y; }

public interface Colorable { void setColor(int color); }

public class ColoredPoint extends Point implements Colorable
{
    int color;
    public void setColor(int color) { this.color = color; }
}

final class EndPoint extends Point { }

class Test {

    public static void main(String[] args) {
        Point p = new Point();
        ColoredPoint cp = new ColoredPoint();
        Colorable c;

        // The following may cause errors at run time because
        // we cannot be sure they will succeed; this possibility
        // is suggested by the casts:
        cp = (ColoredPoint)p;							// p might not reference an
                                    // object which is a ColoredPoint
                                    // or a subclass of ColoredPoint
        c = (Colorable)p;							// p might not be Colorable

        // The following are incorrect at compile time because
        // they can never succeed as explained in the text:
        Long l = (Long)p;							// compile-time error #1
        EndPoint e = new EndPoint();
        c = (Colorable)e;							// compile-time error #2

    }

}

Here the first compile-time error occurs because the class types Long and Point are unrelated (that is, they are not the same, and neither is a subclass of the other), so a cast between them will always fail.

The second compile-time error occurs because a variable of type EndPoint can never reference a value that implements the interface Colorable. This is because EndPoint is a final type, and a variable of a final type always holds a value of the same run-time type as its compile-time type. Therefore, the run-time type of variable e must be exactly the type EndPoint, and type EndPoint does not implement Colorable.

Here is an example involving arrays (§10):

class Point {

    int x, y;

    Point(int x, int y) { this.x = x; this.y = y; }

    public String toString() { return "("+x+","+y+")"; }

}

public interface Colorable { void setColor(int color); }

public class ColoredPoint extends Point implements Colorable
{

    int color;

    ColoredPoint(int x, int y, int color) {
        super(x, y); setColor(color);
    }

    public void setColor(int color) { this.color = color; }

    public String toString() {
        return super.toString() + "@" + color;
    }

}

class Test {

    public static void main(String[] args) {
        Point[] pa = new ColoredPoint[4];
        pa[0] = new ColoredPoint(2, 2, 12);
        pa[1] = new ColoredPoint(4, 5, 24);
        ColoredPoint[] cpa = (ColoredPoint[])pa;
        System.out.print("cpa: {");
        for (int i = 0; i < cpa.length; i++)
            System.out.print((i == 0 ? " " : ", ") + cpa[i]);
        System.out.println(" }");
    }

}

This example compiles without errors and produces the output:

cpa: { (2,2)@12, (4,5)@24, null, null }

The following example uses casts to compile, but it throws exceptions at run time, because the types are incompatible:

public class Point { int x, y; }

public interface Colorable { void setColor(int color); }

public class ColoredPoint extends Point implements Colorable
{

    int color;

    public void setColor(int color) { this.color = color; }

}

class Test {

    public static void main(String[] args) {

        Point[] pa = new Point[100];

        // The following line will throw a ClassCastException:
        ColoredPoint[] cpa = (ColoredPoint[])pa;

        System.out.println(cpa[0]);

        int[] shortvec = new int[2];

        Object o = shortvec;

        // The following line will throw a ClassCastException:
        Colorable c = (Colorable)o;

        c.setColor(0);

    }

}


5.6 Numeric Promotions

Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion (§5.1.1) or a widening primitive conversion (§5.1.2).

Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion (§5.6.1) and binary numeric promotion (§5.6.2). The analogous conversions in C are called "the usual unary conversions" and "the usual binary conversions."

Numeric promotion is not a general feature of Java, but rather a property of the specific definitions of the built-in operations.


5.6.1 Unary Numeric Promotion

Some operators apply unary numeric promotion to a single operand, which must produce a value of a numeric type:

  • If the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int by a widening conversion (§5.1.2).
  • Otherwise, a unary numeric operand remains as is and is not converted.

Unary numeric promotion is performed on expressions in the following situations:

  • The dimension expression in array creations (§15.9)
  • The index expression in array access expressions (§15.12)
  • Operands of the unary operators plus + (§15.14.3) and minus - (§15.14.4)
  • The operand of the bitwise complement operator ~ (§15.14.5)
  • Each operand, separately, of the shift operators >>, >>>, and << (§15.18), so that a long shift distance (right operand) does not promote the value being shifted (left operand) to long

Here is a test program that includes examples of unary numeric promotion:

class Test {
    public static void main(String[] args) {
        byte b = 2;
        int a[] = new int[b];							// dimension expression promotion
        char c = '\u0001';
        a[c] = 1;							// index expression promotion
        a[0] = -c;							// unary - promotion
        System.out.println("a: " + a[0] + "," + a[1]);

        b = -1;
        int i = ~b;							// bitwise complement promotion
        System.out.println("~0x" + Integer.toHexString(b)
                            + "==0x" + Integer.toHexString(i));

        i = b << 4L;							// shift promotion (left operand)
        System.out.println("0x" + Integer.toHexString(b)
                     + "<<4L==0x" + Integer.toHexString(i));
    }
}

This test program produces the output:

a: -1,1
~0xffffffff==0x0
0xffffffff<<4L==0xfffffff0


5.6.2 Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Binary numeric promotion is performed on the operands of certain operators:

  • The multiplicative operators *, / and % (§15.16)
  • The addition and subtraction operators for numeric types + and - (§15.17.2)
  • The numerical comparison operators <, <=, >, and >= (§15.19.1)
  • The numerical equality operators == and != (§15.20.1)
  • The integer bitwise operators &, ^, and | (§15.21.1)
  • In certain cases, the conditional operator ? : (§15.24)

An example of binary numeric promotion appears above in §5.1. Here is another:

class Test {
    public static void main(String[] args) {
        int i = 0;
        float f = 1.0f;
        double d = 2.0;

        // First i*f promoted to float*float, then
        // float==double is promoted to double==double:
        if (i * f == d)
            System.out.println("oops");

        // A char&byte is promoted to int&int:
        byte b = 0x1f;
        char c = 'G';
        int control = c & b;
        System.out.println(Integer.toHexString(control));

        // A int:float promoted to float:float:
        f = (b==0) ? f : 4.0f;
        System.out.println(1.0/f);

    }

}

which produces the output:

7
0.25

The example converts the ASCII character G to the ASCII control-G (BEL), by masking off all but the low 5 bits of the character. The 7 is the numeric value of this control character.

O suns! O grass of graves! O perpetual transfers and promotions!
—Walt Whitman, Walt Whitman (1855) in Leaves of Grass


 6. Names

CHAPTER 6

Names

The Tao that can be told is not the eternal Tao;
The name that can be named is not the eternal name.
The Nameless is the origin of Heaven and Earth;
The Named is the mother of all things.
—Lao-Tsu (c. 6th century BC)

Names are used to refer to entities declared in a Java program. A declared entity (§6.1) is a package, class type, interface type, member (field or method) of a reference type, parameter (to a method, constructor, or exception handler), or local variable.

Names in Java programs are either simple, consisting of a single identifier, or qualified, consisting of a sequence of identifiers separated by "." tokens (§6.2).

Every name introduced by a declaration has a scope (§6.3), which is the part of the Java program text within which the declared entity can be referred to by a simple name.

Packages and reference types (that is, class types, interface types, and array types) have members (§6.4). A member can be referred to using a qualified name N.x, where N is a simple or qualified name and x is an identifier. If N names a package, then x is a member of that package, which is either a class or interface type or a subpackage. If N names a reference type or a variable of a reference type, then x names a member of that type, which is either a field or a method.

In determining the meaning of a name (§6.5), Java uses the context of the occurrence to disambiguate among packages, types, variables, and methods with the same name.

Access control (§6.6) can be specified in a class, interface, method, or field declaration to control when access to a member is allowed. Access is a different concept from scope; access specifies the part of the Java program text within which the declared entity can be referred to by a qualified name, a field access expression (§15.10), or a method invocation expression (§15.11) in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.

Fully qualified names (§6.7) and naming conventions (§6.8) are also discussed in this chapter.

The name of a field, parameter, or local variable may be used as an expression (§15.13.1). The name of a method may appear in an expression only as part of a method invocation expression (§15.11). The name of a class or interface type may appear in an expression only as part of a class instance creation expression (§15.8), an array creation expression (§15.9), a cast expression (§15.15), or an instanceof expression (§15.19.2), or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.


6.1 Declarations

A declaration introduces an entity into a Java program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:

  • A package, declared in a package declaration (§7.4)
  • An imported type, declared in a single-type-import declaration (§7.5.1) or a type-import-on-demand declaration (§7.5.2)
  • A class, declared in a class type declaration (§8.1)
  • An interface, declared in an interface type declaration (§9.1)
  • A member of a reference type (§8.2, §9.2, §10.7), one of the following:
    • A field, one of the following:
      • A field declared in a class type (§8.3)
      • A constant field declared in an interface type (§9.3)
      • The field length, which is implicitly a member of every array type (§10.7)
    • A method, one of the following:
      • A method (abstract or otherwise) declared in a class type (§8.4)
      • A method (always abstract) declared in an interface type (§9.4)
  • A parameter, one of the following:
    • A parameter of a method or constructor of a class (§8.4.1, §8.6.1)
    • A parameter of an abstract method of an interface (§9.4)
    • A parameter of an exception handler declared in a catch clause of a try statement (§14.18)
  • A local variable, one of the following:
    • A local variable declared in a block (§14.3)
    • A local variable declared in a for statement (§14.12)

Constructors (§8.6) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.


6.2 Names

A name is used to refer to an entity declared in a Java program.

There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier.

In determining the meaning of a name (§6.5), the Java language takes into account the context in which the name appears. It distinguishes among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.4), a variable or value in an expression (§6.5.5), or a method (§6.5.6).

Not all identifiers in Java programs are a part of a name. Identifiers are also used in the following situations:

  • In declarations (§6.1), where an identifier may occur to specify the name by which the declared entity will be known
  • In field access expressions (§15.10), where an identifier occurs after a "." token to indicate a member of an object that is the value of an expression or the keyword super that appears before the "." token
  • In some method invocation expressions (§15.11), where an identifier may occur after a "." token and before a "(" token to indicate a method to be invoked for an object that is the value of an expression or the keyword super that appears before the "." token
  • As labels in labeled statements (§14.6) and in break (§14.13) and continue (§14.14) statements that refer to statement labels

In the example:

class Test {
    public static void main(String[] args) {
        Class c = System.out.getClass();
        System.out.println(c.toString().length() +
                                args[0].length() + args.length);
    }
}

the identifiers Test, main, and the first occurrences of args and c are not names; rather, they are used in declarations to specify the names of the declared entities. The names String, Class, System.out.getClass, System.out.println, c.toString, args, and args.length appear in the example. The first occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.11). The second occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.11).

The identifiers used in labeled statements and their associated break and continue statements are completely separate from those used in declarations. Thus, the following code is valid:

class TestString {

    char[] value;

    int offset, count;

    int indexOf(TestString str, int fromIndex) {
        char[] v1 = value, v2 = str.value;
        int max = offset + (count - str.count);
        int start = offset + ((fromIndex < 0) ? 0 : fromIndex);
    i:
        for (int i = start; i <= max; i++)

        {
            int n = str.count, j = i, k = str.offset;
            while (n-- != 0) {
                if (v1[j++] != v2[k++])
                    continue i;
            }
            return i - offset;
        }
        return -1;
    }
}

This code was taken from a version of the class String and its method indexOf (§20.12.26), where the label was originally called test. Changing the label to have the same name as the local variable i does not hide the label in the scope of the declaration of i. The identifier max could also have been used as the statement label; the label would not hide the local variable max within the labeled statement.


6.3 Scope of a Simple Name

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name:

  • The scope of a package, as introduced by a package declaration, is determined by the host system (§7.4.3). All Java code is within the scope of the standard package named java, so the package java can always be referred to by Java code.
  • The scope of a type imported by a single-type-import declaration (§7.5.1) or type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.
  • The scope of a type introduced by a class type declaration (§8.1.1) or interface type declaration (§9.1.1) is the declarations of all class and interface types in all the compilation units (§7.3) of the package in which it is declared.
  • The scope of a member declared in or inherited by a class type (§8.2) or interface type (§9.2) is the entire declaration of the class or interface type. The declaration of a member needs to appear before it is used only when the use is in a field initialization expression (§8.3.2, §12.4.2, §12.5). This means that a compile-time error results from the test program:

    class Test {
        int i = j;				// compile-time error: incorrect forward reference
        int j = 1;
    }

    whereas the following example compiles without error:

    class Test {
        Test() { k = 2; }
        int j = 1;
        int i = j;
        int k;
    }

even though the constructor (§8.6) for Test refers to the field k that is declared three lines later.

  • The scope of a parameter of a method (§8.4.1) is the entire body of the method.
  • The scope of a parameter of a constructor (§8.6.1) is the entire body of the constructor.
  • The scope of a local variable declaration in a block (§14.3.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.3) and including any further declarators to the right in the local variable declaration statement.
  • The scope of a local variable declared in the ForInit part of a for statement (§14.12) includes all of the following:
    • Its own initializer
    • Any further declarators to the right in the ForInit part of the for statement
    • The Expression and ForUpdate parts of the for statement
    • The contained Statement
  • The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.18) is the entire block associated with the catch.

These rules imply that declarations of class and interface types need not appear before uses of the types.

In the example:

package points;

class Point {
    int x, y;
    PointList list;
    Point next;
}

class PointList {
    Point first;
}

the use of PointList in class Point is correct, because the scope of the class type name PointList includes both class Point and class PointList, as well as any other type declarations in other compilation units of package points.


6.3.1 Hiding Names

Some declarations may be hidden (§6.3.1) in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

The example:

class Test {
    static int x = 1;
    public static void main(String[] args) {
        int x = 0;
        System.out.print("x=" + x);
        System.out.println(", Test.x=" + Test.x);
    }
}

produces the output:

x=0, Test.x=1

This example declares:

  • a class Test
  • a class (static) variable x that is a member of the class Test
  • a class method main that is a member of the class Test
  • a parameter args of the main method
  • a local variable x of the main method

Since the scope of a class variable includes the entire body of the class (§8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is hidden within the body of the method main by the declaration of the local variable x.

A local variable has as its scope the rest of the block in which it is declared (§14.3.2); in this case this is the rest of the body of the main method, namely its initializer "0" and the invocations of print and println.

This means that:

  • The expression "x" in the invocation of print refers to (denotes) the value of the local variable x.
  • The invocation of println uses a qualified name (§6.6) Test.x, which uses the class type name Test to access the class variable x, because the declaration of Test.x is hidden at this point and cannot be referred to by its simple name.

If the standard naming conventions (§6.8) are followed, then hiding that would make the identification of separate naming contexts matter should be rare. The following contrived example involves hiding because it does not follow the standard naming conventions:

class Point { int x, y; }

class Test {

    static Point Point(int x, int y) {
        Point p = new Point();
        p.x = x; p.y = y;
        return p;
    }

    public static void main(String[] args) {
        int Point;
        Point[] pa = new Point[2];
        for (Point = 0; Point < 2; Point++) {
            pa[Point] = new Point();
            pa[Point].x = Point;
            pa[Point].y = Point;
        }
        System.out.println(pa[0].x + "," + pa[0].y);
        System.out.println(pa[1].x + "," + pa[1].y);
        Point p = Point(3, 4);
        System.out.println(p.x + "," + p.y);
    }

}

This compiles without error and executes to produce the output:

0,0
1,1

3,4

Within the body of main, the lookups of Point find different declarations depending on the context of the use:

  • In the expression "new Point[2]", the two occurrences of the class instance creation expression "new Point()", and at the start of three different local variable declaration statements, the Point is a TypeName (§6.5.4) and denotes the class type Point in each case.
  • In the method invocation expression "Point(3, 4)" the occurrence of Point is a MethodName (§6.5.6) and denotes the class (static) method Point.
  • All other names are ExpressionNames (§6.5.5) and refer to the local variable Point.

The example:

import java.util.*;

class Vector {
    int val[] = { 1 , 2 };
}

class Test {
    public static void main(String[] args) {
        Vector v = new Vector();
        System.out.println(v.val[0]);
    }
}

compiles and prints:

1

using the class Vector declared here in preference to class java.util.Vector that might be imported on demand.


6.4 Members and Inheritance

Packages and reference types have members. The members of a package (§7) are subpackages (§7.1) and all the class (§8) and interface (§9) types declared in all the compilation units (§7.3) of the package. The members of a reference type (§4.3) are fields (§8.3, §9.3, §10.7) and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither hidden nor overridden (§8.4.6).

This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see §7.1, §8.2, §9.2, and §10.7.


6.4.1 The Members of a Package

A member of a package (§7) is a subpackage (§7.1), or a class (§8) or interface (§9) type declared in a compilation unit (§7.3) of the package.

In general, the subpackages of a package are determined by the host system (§7.2). However, the standard package java always includes the subpackages lang, util, io, and net and may include other subpackages. No two distinct members of the same package may have the same simple name (§7.1), but members of different packages may have the same simple name. For example, it is possible to declare a package:

package vector;
public class Vector { Object[] vec; }

that has as a member a public class named Vector, even though the standard package java.util also declares a class named Vector. These two class types are different, reflected by the fact that they have different fully qualified names (§6.7). The fully qualified name of this example Vector is vector.Vector, whereas java.util.Vector is the fully qualified name of the standard Vector class. Because the package vector contains a class named Vector, it cannot also have a subpackage named Vector.


6.4.2 The Members of a Class Type

The members of a class type (§8.2) are fields and methods. The members of a class type are all of the following:

  • Members inherited from its direct superclass (§8.1.3), if it has one (the class Object has no direct superclass)
  • Members inherited from any direct superinterfaces (§8.1.4)
  • Members declared in the body of the class (§8.1.5)

Constructors (§8.6) are not members.

There is no restriction against a field and a method of a class type having the same simple name.

A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (§6.5.6.2, §8.2).

In the example:

interface Colors {
    int WHITE = 0, BLACK = 1;
}

interface Separates {
    int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
}

class Test implements Colors, Separates {
    public static void main(String[] args) {
        System.out.println(BLACK); // compile-time error: ambiguous
    }
}

the name BLACK in the method main is ambiguous, because class Test has two members named BLACK, one inherited from Colors and one from Separates.

A class type may have two or more methods with the same simple name if the methods have different signatures (§8.4.2), that is, if they have different numbers of parameters or different parameter types in at least one parameter position. Such a method member name is said to be overloaded.

A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is abstract, then the new declaration is said to implement it; if the method not inherited is not abstract, then the new declaration is said to override it.

In the example:

class Point {
    float x, y;
    void move(int dx, int dy) { x += dx; y += dy; }
    void move(float dx, float dy) { x += dx; y += dy; }
    public String toString() { return "("+x+","+y+")"; }
}

the class Point has two members that are methods with the same name, move. The overloaded move method of class Point chosen for any particular method invocation is determined at compile time by the overloading resolution procedure given in §15.11.

In this example, the members of the class Point are the float instance variables x and y declared in Point, the two declared move methods, the declared toString method, and the members that Point inherits from its implicit direct superclass Object (§4.3.2), such as the method hashCode (§20.1.4). Note that Point does not inherit the toString method (§20.1.2) of class Object because that method is overridden by the declaration of the toString method in class Point.


6.4.3 The Members of an Interface Type

The members of an interface type (§9.2) are fields and methods. The members of an interface are all of the following:

  • Members inherited from any direct superinterfaces (§9.1.3)
  • Members declared in the body of the interface (§9.1.4)

An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (§6.5.5.1, §9.2).

In the example:

interface Colors {
    int WHITE = 0, BLACK = 1;
}

interface Separates {
    int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
}
interface ColorsAndSeparates extends Colors, Separates {

    int DEFAULT = BLACK;								 	// compile-time error: ambiguous

}

the members of the interface ColorsAndSeparates include those members inherited from Colors and those inherited from Separates, namely WHITE, BLACK (first of two), CYAN, MAGENTA, YELLOW, and BLACK (second of two). The member name BLACK is ambiguous in the interface ColorsAndSeparates.


6.4.4 The Members of an Array Type

The members of an array type (§10.7) are all of the following:

  • Members inherited from its implicit superclass Object (§4.3.2, §20.1)
  • The field length, which is a constant (final) field of every array; its type is int and it contains the number of components of the array

The example:

class Test {
    public static void main(String[] args) {
        int[] ia = new int[3];
        int[] ib = new int[6];
        System.out.println(ia.getClass() == ib.getClass());
        System.out.println("ia has length=" + ia.length);
    }
}

produces the output:

true
ia has length=3

This example uses the method getClass inherited from class Object and the field length. The result of the comparison of the Class objects in the second println demonstrates that all arrays whose components are of type int are instances of the same array type, which is int[].


6.5 Determining the Meaning of a Name

The meaning of a name in Java depends on the context in which it is used. The determination of the meaning of a name requires three steps. First, context causes a name syntactically to fall into one of five categories: PackageName, TypeName, ExpressionName, MethodName, or AmbiguousName. Second, a name that is initially classified by its context as an AmbiguousName is then reclassified by certain scoping rules to be a PackageName, TypeName, or ExpressionName. Third, the resulting category then dictates the final determination of the meaning of the name (or a compilation error if the name has no meaning).

PackageName:

    Identifier

    PackageName . Identifier

TypeName:

    Identifier

    PackageName . Identifier

ExpressionName:

    Identifier

    AmbiguousName . Identifier

MethodName:

    Identifier

    AmbiguousName . Identifier

AmbiguousName:

    Identifier

    AmbiguousName . Identifier

Java's use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in §6.8 are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. Java never has trouble distinguishing between a method and a field with the same name, since the context of a use always tells whether a method or a field is intended.


6.5.1 Syntactic Classification of a Name According to Context

A name is syntactically classified as a PackageName in these contexts:

  • In a package declaration (§7.4)
  • In a type-import-on-demand declaration (§7.5.2)
  • To the left of the "." in a qualified PackageName
  • To the left of the "." in a qualified TypeName

A name is syntactically classified as a TypeName in these contexts:

  • In a single-type-import declaration (§7.5.1)
  • In an extends clause in a class declaration (§8.1.3)
  • In an implements clause in a class declaration (§8.1.4)
  • In an extends clause in an interface declaration (§9.1.3)
  • As a Type (or the part of a Type that remains after all brackets are deleted) in any of the following contexts:
    • In a field declaration (§8.3, §9.3)
    • As the result type of a method (§8.4, §9.4)
    • As the type of a formal parameter of a method or constructor (§8.4.1, §8.6.1, §9.4)
    • As the type of an exception that can be thrown by a method or constructor (§8.4.4, §8.6.4, §9.4)
    • As the type of a local variable (§14.3)
    • As the type of an exception parameter in a catch clause of a try statement (§14.18)
    • As the class type of an instance that is to be created in a class instance creation expression (§15.8)
    • As the element type of an array to be created in an array creation expression (§15.9)
    • As the type mentioned in the cast operator of a cast expression (§15.15)
    • As the type that follows the instanceof relational operator (§15.19.2)

A name is syntactically classified as an ExpressionName in these contexts:

  • As the array reference expression in an array access expression (§15.12)
  • As a PostfixExpression (§15.13)
  • As the left-hand operand of an assignment operator (§15.25)

A name is syntactically classified as a MethodName in this context:

· Before the "(" in a method invocation expression (§15.11)

A name is syntactically classified as an AmbiguousName in these contexts:

  • To the left of the "." in a qualified ExpressionName
  • To the left of the "." in a qualified MethodName
  • To the left of the "." in a qualified AmbiguousName


6.5.2 Reclassification of Contextually Ambiguous Names

An AmbiguousName is then reclassified as follows:

  • If the AmbiguousName is a simple name, consisting of a single Identifier:
    • If the Identifier appears within the scope (§6.3) of a local variable declaration (§14.3) or parameter declaration (§8.4.1, §8.6.1, §14.18) with that name, then the AmbiguousName is reclassified as an ExpressionName.
    • Otherwise, consider the class or interface C within whose declaration the Identifier occurs. If C has one or more fields with that name, which may be either declared within it or inherited, then the AmbiguousName is reclassified as an ExpressionName.
    • Otherwise, if a type of that name is declared in the compilation unit (§7.3) containing the Identifier, either by a single-type-import declaration (§7.5.1) or by a class or interface type declaration (§7.6), then the AmbiguousName is reclassified as a TypeName.
    • Otherwise, if a type of that name is declared in another compilation unit (§7.3) of the package (§7.1) of the compilation unit containing the Identifier, then the AmbiguousName is reclassified as a TypeName.
    • Otherwise, if a type of that name is declared by exactly one type-import-on-demand declaration (§7.5.2) of the compilation unit containing the Identifier, then the AmbiguousName is reclassified as a TypeName.
    • Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit containing the Identifier, then a compile-time error results.
    • Otherwise, the AmbiguousName is reclassified as a PackageName. A later step determines whether or not a package of that name actually exists.
  • If the AmbiguousName is a qualified name, consisting of a name, a ".", and an Identifier, then the name to the left of the "." is first reclassified, for it is itself an AmbiguousName. There is then a choice:
    • If the name to the left of the "." is reclassified as a PackageName, then there is a further choice:
      • If there is a package whose name is the name to the left of the "." and that package contains a declaration of a type whose name is the same as the Identifier, then this AmbiguousName is reclassified as a TypeName.
      • Otherwise, this AmbiguousName is reclassified as a PackageName. A later step determines whether or not a package of that name actually exists.
    • If the name to the left of the "." is reclassified as a TypeName, then this AmbiguousName is reclassified as an ExpressionName. u If the name to the left of the "." is reclassified as an ExpressionName, then this AmbiguousName is reclassified as an ExpressionName.

As an example, consider the following contrived "library code":

package ORG.rpgpoet;

import java.util.Random;

interface Music { Random[] wizards = new Random[4]; }

and then consider this example code in another package:

package bazola;

class Gabriel {
    static int n = ORG.rpgpoet.Music.wizards.length;
}

First of all, the name ORG.rpgpoet.Music.wizards.length is classified as an ExpressionName because it functions as a PostfixExpression. Therefore, each of the names:

ORG.rpgpoet.Music.wizards
ORG.rpgpoet.Music
ORG.rpgpoet
ORG

is initially classified as an AmbiguousName. These are then reclassified:

  • Assuming that there is no class or interface named ORG in any other compilation unit of package bazola, then the simple name ORG is reclassified as a PackageName.
  • Next, assuming that there is no class or interface named rpgpoet in any compilation unit of package ORG (and we know that there is no such class or interface because package ORG has a subpackage named rpgpoet), the qualified name ORG.rpgpoet is reclassified as a PackageName.
  • Next, because package ORG.rpgpoet has an interface type named Music, the qualified name ORG.rpgpoet.Music is reclassified as a TypeName.
  • Finally, because the name ORG.rpgpoet.Music is a TypeName, the qualified name ORG.rpgpoet.Music.wizards is reclassified as an ExpressionName.


6.5.3 Meaning of Package Names

The meaning of a name classified as a PackageName is determined as follows.

6.5.3.1 Simple Package Names

If a package name consists of a single Identifier, then this identifier denotes a top- level package named by that identifier. If no package of that name is accessible, as determined by the host system (§7.4.3), then a compile-time error occurs.

6.5.3.2 Qualified Package Names

If a package name is of the form Q.Id, then Q must also be a package name. The package name Q.Id names a package that is the member named Id within the package named by Q. If Q does not name an accessible package or Id does not name an accessible subpackage of that package, then a compile-time error occurs.


6.5.4 Meaning of Type Names

The meaning of a name classified as a TypeName is determined as follows.

6.5.4.1 Simple Type Names

If a type name consists of a single Identifier, then the identifier must occur in the scope of a declaration of a type with this name, or a compile-time error occurs. It is possible that the identifier occurs within the scope of more than one type with that name, in which case the type denoted by the name is determined as follows:

  • If a type with that name is declared in the current compilation unit (§7.3), either by a single-type-import declaration (§7.5.1) or by a declaration of a class or interface type (§7.6), then the simple type name denotes that type.
  • Otherwise, if a type with that name is declared in another compilation unit (§7.3) of the package (§7.1) containing the identifier, then the identifier denotes that type. Note that, in systems that store compilation units in a file system, such a compilation unit must have a file name that is the name of the type (§7.6).
  • Otherwise, if a type of that name is declared by exactly one type-import-on-demand declaration (§7.5.2) of the compilation unit containing the identifier, then the simple type name denotes that type.
  • Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.
  • Otherwise, the name is undefined as a type name; a compile-time error occurs.

This order for considering type declarations is designed to choose the most explicit of two or more applicable type declarations.

6.5.4.2 Qualified Type Names

If a type name is of the form Q.Id, then Q must be a package name. The type name Q.Id names a type that is the member named Id within the package named by Q. If Q does not name an accessible package, or Id does not name a type within that package, or the type named Id within that package is not accessible (§6.6), then a compile-time error occurs.

The example:

package wnj.test;

class Test {
    public static void main(String[] args) {
        java.util.Date date =
            new java.util.Date(System.currentTimeMillis());
        System.out.println(date.toLocaleString());
    }
}

produced the following output the first time it was run:

Sun Jan 21 22:56:29 1996

In this example:

  • The name wnj.test must name a package on the host system. It is resolved by first looking for the package wnj, using the procedure described in §6.5.3.1, and then making sure that the subpackage test of this package is accessible.
  • The name java.util.Date (§21.3) must denote a type, so we first use the procedure recursively to determine if java.util is an accessible package, which it is, and then look to see if the type Date is accessible in this package.


6.5.5 Meaning of Expression Names

The meaning of a name classified as an ExpressionName is determined as follows.

6.5.5.1 Simple Expression Names

If an expression name consists of a single Identifier, then:

  • If the Identifier appears within the scope (§6.3) of a local variable declaration (§14.3) or parameter declaration (§8.4.1, §8.6.1, §14.18) with that name, then the expression name denotes a variable, that is, that local variable or parameter. Local variables and parameters are never hidden (§6.3, §6.3.1, §14.3), so there is necessarily at most one such local variable or parameter. The type of the expression name is the declared type of the local variable or parameter.
  • Otherwise, if the Identifier appears within a class declaration (§8):
    • If there is not exactly one member of that class (§8.2) that is a field with that name, then a compile-time error results.
    • Otherwise, if the single member field with that name is declared final (§8.3.1.2), then the expression name denotes the value of the field. The type of the expression name is the declared type of the field. If the Identifier appears in a context that requires a variable and not a value, then a compile-time error occurs.
    • Otherwise, the expression name denotes a variable, the single member field with that name. The type of the expression name is the field's declared type.

If the field is an instance variable (§8.3.1.1), the expression name must appear within the declaration of an instance method (§8.4), constructor (§8.6), or instance variable initializer (§8.3.2.2). If it appears within a static method (§8.4.3.2), static initializer (§8.5), or initializer for a static variable (§8.3.1.1, §12.4.2), then a compile-time error occurs.

  • Otherwise, the identifier appears within an interface declaration (§9):
    • If there is not exactly one member of that interface (§9.2) that is a field with that name, then a compile-time error results.
    • Otherwise, the expression name denotes the value of the single member field of that name. The type of the expression name is the declared type of the field. If the Identifier appears in a context that requires a variable and not a value, then a compile-time error occurs.

In the example:

class Test {

    static int v;

    static final int f = 3;

    public static void main(String[] args) {
        int i;
        i = 1;
        v = 2;
        f = 33;										// compile-time error
        System.out.println(i + " " + v + " " + f);
    }

}

the names used as the left-hand-sides in the assignments to i, v, and f denote the local variable i, the field v, and the value of f (not the variable f, because f is a final variable). The example therefore produces an error at compile time because the last assignment does not have a variable as its left-hand side. If the erroneous assignment is removed, the modified code can be compiled and it will produce the output:

1 2 3

6.5.5.2 Qualified Expression Names

If an expression name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name:

  • If Q is a package name, then a compile-time error occurs.
  • If Q is a type name that names a class type (§8), then:
    • If there is not exactly one accessible (§6.6) member of the class type that is a field named Id, then a compile-time error occurs.
    • Otherwise, if the single accessible member field is not a class variable (that is, it is not declared static), then a compile-time error occurs.
    • Otherwise, if the class variable is declared final, then Q.Id denotes the value of the class variable. The type of the expression Q.Id is the declared type of the class variable. If Q.Id appears in a context that requires a variable and not a value, then a compile-time error occurs.
    • Otherwise, Q.Id denotes the class variable. The type of the expression Q.Id is the declared type of the class variable.
  • If Q is a type name that names an interface type (§9), then:
    • If there is not exactly one accessible (§6.6) member of the interface type that is a field named Id, then a compile-time error occurs.
    • Otherwise, Q.Id denotes the value of the field. The type of the expression Q.Id is the declared type of the field. If Q.Id appears in a context that requires a variable and not a value, then a compile-time error occurs.
  • If Q is an expression name, let T be the type of the expression Q:
    • If T is not a reference type, a compile-time error occurs.
    • If there is not exactly one accessible (§6.6) member of the type T that is a field named Id, then a compile-time error occurs.
    • Otherwise, if this field is any of the following:
      • A field of an interface type
      • A final field of a class type (which may be either a class variable or an instance variable)
      • The final field length of an array type then Q.Id denotes the value of the field. The type of the expression Q.Id is the declared type of the field. If Q.Id appears in a context that requires a variable and not a value, then a compile-time error occurs.

    • Otherwise, Q.Id denotes a variable, the field Id of class T, which may be either a class variable or an instance variable. The type of the expression Q.Id is the declared type of the field

The example:

class Point {
    int x, y;
    static int nPoints;
}

class Test {
    public static void main(String[] args) {
        int i = 0;
        i.x++;								// compile-time error
        Point p = new Point();
        p.nPoints();								// compile-time error
    }
}

encounters two compile-time errors, because the int variable i has no members, and because nPoints is not a method of class Point.


6.5.6 Meaning of Method Names

A MethodName can appear only in a method invocation expression (§15.11). The meaning of a name classified as a MethodName is determined as follows.

6.5.6.1 Simple Method Names

If a method name consists of a single Identifier, then Identifier is the method name to be used for method invocation. The Identifier must name at least one method of the class or interface within whose declaration the Identifier appears. See §15.11 for further discussion of the interpretation of simple method names in method invocation expressions.

6.5.6.2 Qualified Method Names

If a method name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name. If Q is a package name, then a compile-time error occurs. Otherwise, Id is the method name to be used for method invocation. If Q is a type name, then Id must name at least one static method of the type Q. If Q is an expression name, then let T be the type of the expression Q; Id must name at least one method of the type T. See §15.11 for further discussion of the interpretation of qualified method names in method invocation expressions.


6.6 Qualified Names and Access Control

Qualified names are a means of access to members of packages and reference types; related means of access include field access expressions (§15.10) and method invocation expressions (§15.11). All three are syntactically similar in that a "." token appears, preceded by some indication of a package, type, or expression having a type and followed by an Identifier that names a member of the package or type. These are collectively known as constructs for qualified access.

Java provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. Access control applies to qualified access and to the invocation of constructors by class instance creation expressions (§15.8), explicit constructor invocations (§8.6.5), and the method newInstance of class Class (§20.3.6).

If access is permitted, then the accessed entity is said to be accessible.


6.6.1 Determining Accessibility

  • Whether a package is accessible is determined by the host system (§7.2).
  • If a class or interface type is declared public, then it may be accessed by any Java code that can access the package in which it is declared. If a class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
  • A member (field or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    • If the member or constructor is declared public, then access is permitted. All members of interfaces are implicitly public.
    • Otherwise, if the member or constructor is declared protected, then access is permitted only when one of the following is true:
        • Access to the member or constructor occurs from within the package containing the class in which the protected member is declared.
        • Access occurs within a subclass of the class in which the protected member is declared, and the access is correct as described in §6.6.2.

    • Otherwise, if the member or constructor is declared private, then access is permitted only when it occurs from within the class in which it is declared.
    • Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.


6.6.2 Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object. Let C be the class in which a protected member or constructor is declared and let S be the subclass of C in whose declaration the use of the protected member or constructor occurs. Then:

  • If an access is of a protected member (field or method), let Id be its name. Consider then the means of qualified access:
    • If the access is by a field access expression of the form super.Id, then the access is permitted.
    • If the access is by a qualified name Q.Id, where Q is a TypeName, then the access is permitted if and only if Q is S or a subclass of S.
    • If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.
    • If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.
  • Otherwise, if an access is of a protected constructor:
    • If the access is by a superclass constructor invocation super(. . .), then the access is permitted.
    • If the access is by a class instance creation expression new T(. . .), then the access is not permitted. (A protected constructor can be accessed by a class instance creation expression only from within the package in which it is defined.)
    • If the access is by an invocation of the method newInstance of class Class (§20.3.6), then the access is not permitted.


6.6.3 An Example of Access Control

For examples of access control, consider the two compilation units:

package points;

class PointVec { Point[] vec; }

and:

package points;

public class Point {
    protected int x, y;
    public void move(int dx, int dy) { x += dx; y += dy; }
    public int getX() { return x; }
    public int getY() { return y; }
}

which declare two class types in the package points:

  • The class type PointVec is not public and not part of the public interface of the package points, but rather can be used only by other classes in the package.
  • The class type Point is declared public and is available to other packages. It is part of the public interface of the package points.
  • The methods move, getX, and getY of the class Point are declared public and so are available to any Java code that uses an object of type Point.
  • The fields x and y are declared protected and are accessible outside the package points only in subclasses of class Point, and only when they are fields of objects that are being implemented by the code that is accessing them.

See §6.6.7 for an example of how the protected access modifier limits access.


6.6.4 Example: Access to public and Non-public Classes

If a class lacks the public modifier, access to the class declaration is limited to the package in which it is declared (§6.6). In the example:

package points;

public class Point {
    public int x, y;
    public void move(int dx, int dy) { x += dx; y += dy; }
}

class PointList {
    Point next, prev;
}

two classes are declared in the compilation unit. The class Point is available outside the package points, while the class PointList is available for access only within the package. Thus a compilation unit in another package can access points.Point, either by using its fully qualified name:

package pointsUser;

class Test {
    public static void main(String[] args) {
        points.Point p = new points.Point();
        System.out.println(p.x + " " + p.y);
    }
}

or by using a single-type-import declaration (§7.5.1) that mentions the fully qualfied name, so that the simple name may be used thereafter:

package pointsUser;

import points.Point;

class Test {
    public static void main(String[] args) {
        Point p = new Point();
        System.out.println(p.x + " " + p.y);
    }
}

However, this compilation unit cannot use or import points.PointList, which is not declared public and is therefore inaccessible outside package points.


6.6.5 Example: Default-Access Fields, Methods, and Constructors

If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package. If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package.

For example, if we have:

package points;

public class Point {
    public int x, y;
    void move(int dx, int dy) { x += dx; y += dy; }
    public void moveAlso(int dx, int dy) { move(dx, dy); }
}

then a subclass in another package may declare an unrelated move method, with the same signature (§8.4.2) and return type, but because the original move method is not accessible from package morepoints super may not be used:

package morepoints;

public class PlusPoint extends points.Point {
    public void move(int dx, int dy) {
        super.move(dx, dy);								// compile-time error
        moveAlso(dx, dy);
    }
}

Because move of Point is not overridden by move in PlusPoint, the method moveAlso in Point never calls the method move in PlusPoint.

Thus if you delete the super.move call from PlusPoint and execute the test program:

import points.Point;

import morepoints.PlusPoint;

class Test {

    public static void main(String[] args) {
        PlusPoint pp = new PlusPoint();
        pp.move(1, 1);
    }

}

it terminates normally. If move of Point were overridden by move in PlusPoint, then this program would recurse infinitely, until a StackoverflowError occurred.


6.6.6 Example: public Fields, Methods, and Constructors

A public class member or constructor is accessible throughout the package where it is declared and from any other package that has access to the package in which it is declared (§7.4.4). For example, in the compilation unit:

package points;

public class Point {

    int x, y;

    public void move(int dx, int dy) {
        x += dx; y += dy;
        moves++;
    }

    public static int moves = 0;

}

the public class Point has as public members the move method and the moves field. These public members are accessible to any other package that has access to package points. The fields x and y are not public and therefore are accessible only from within the package points.


6.6.7 Example: protected Fields, Methods, and Constructors

Consider this example, where the point package declares:

package points;

public class Point {

    protected int x, y;

    void warp(threePoint.Point3d a) {
        if (a.z > 0)						// compile-time error: cannot access a.z
            a.delta(this);
    }

}

and the threePoint package declares:

package threePoint;

import points.Point;

public class Point3d extends Point {

    protected int z;

    public void delta(Point p) {
        p.x += this.x;						// compile-time error: cannot access p.x
        p.y += this.y;						// compile-time error: cannot access p.y
    }

    public void delta3d(Point3d q) {
        q.x += this.x;
        q.y += this.y;
        q.z += this.z;
    }

}

which defines a class Point3d. A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

The method delta could try to cast (§5.4, §15.15) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d.

A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point (the type of the parameter a), it is not a subclass of Point (the class in which z is declared).


6.6.8 Example: private Fields, Methods, and Constructors

A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited by subclasses. In the example:

class Point {

    Point() { setMasterID(); }

    int x, y;
    private int ID;
    private static int masterID = 0;

    private void setMasterID() { ID = masterID++; }

}

the private members ID, masterID, and setMasterID may be used only within the body of class Point. They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.

See §8.6.8 for an example that uses a private constructor.


6.7 Fully Qualified Names

Every package, class, interface, array type, and primitive type has a fully qualified name. It follows that every type except the null type has a fully qualified name.

  • The fully qualified name of a primitive type is the keyword for that primitive type, namely boolean, char, byte, short, int, long, float, or double.
  • The fully qualified name of a named package that is not a subpackage of a named package is its simple name.
  • The fully qualified name of a named package that is a subpackage of another named package consists of the fully qualified name of the containing package, followed by ".", followed by the simple (member) name of the subpackage.
  • The fully qualified name of a class or interface that is declared in an unnamed package is the simple name of the class or interface.
  • The fully qualified name of a class or interface that is declared in a named package consists of the fully qualified name of the package, followed by ".", followed by the simple name of the class or interface.
  • The fully qualified name of an array type consists of the fully qualified name of the component type of the array type followed by "[]".

Examples:

  • The fully qualified name of the type long is "long".
  • The fully qualified name of the standard package java.lang is "java.lang" because it is subpackage lang of package java.
  • The fully qualified name of the class Object, which is defined in the package java.lang, is "java.lang.Object".
  • The fully qualified name of the interface Enumeration, which is defined in the package java.util, is "java.util.Enumeration".
  • The fully qualified name of the type "array of double" is "double[]".
  • The fully qualified name of the type "array of array of array of array of String" is "java.lang.String[][][][]".

In the example:

package points;

class Point { int x, y; }

class PointVec {
    Point[] vec;
}

the fully qualified name of the type Point is "points.Point"; the fully qualified name of the type PointVec is "points.PointVec"; and the fully qualified name of the type of the field vec of class PointVec is "points.Point[]".


6.8 Naming Conventions

The Java system and standard classes attempt to use, whenever possible, names chosen according to the conventions presented here. These conventions help to make code more readable and avoid certain kinds of name conflicts.

We recommend these conventions for use in all Java programs. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout Java convention because they are short and are not verbs.


6.8.1 Package Names

Names of packages that are to be made widely available should be formed as described in §7.7. Such names are always qualified names whose first identifier consists of two or three uppercase letters that name an Internet domain, such as COM, EDU, GOV, MIL, NET, ORG, or a two-letter ISO country code such as UK or JP. Here are examples of hypothetical unique names that might be formed under this convention:

COM.JavaSoft.jag.Oak
ORG.NPR.pledge.driver
UK.ac.city.rugby.game

Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved to JavaSoft for naming standard Java packages.

When package names occur in expressions:

  • If a package name is hidden by a field declaration, then import declarations (§7.5) can usually be used to make available the type names declared in that package.
  • If a package name is hidden by a declaration of a parameter or local variable, then the name of the parameter or local variable can be changed without affecting other Java code.
  • The first component of a package name is normally not easily mistaken for a type name, as a type name normally begins with a single uppercase letter. (The Java language does not actually rely on case distinctions to determine whether a name is a package name or a type name. It is not possible for a type name to hide a package name.)


6.8.2 Class and Interface Type Names

Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized. For example:

ClassLoader
SecurityManager
Thread
Dictionary
BufferedInputStream

Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces java.lang.Runnable and java.lang.Cloneable.

Hiding involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not hide type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter.


6.8.3 Method Names

Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized. Here are some additional specific conventions for method names:

  • Methods to get and set an attribute that might be thought of as a variable V should be named get V and set V. An example is the methods getPriority (§20.20.22) and setPriority (§20.20.23) of class java.lang.Thread.
  • A method that returns the length of something should be named length, as in class java.lang.String (§20.12.11).
  • A method that tests a boolean condition V about an object should be named is V. An example is the method isInterrupted of class java.lang.Thread (§20.20.32).
  • A method that converts its object to a particular format F should be named to F. Examples are the method toString of class java.lang.Object (§20.1.2) and the methods toLocaleString (§21.3.27) and toGMTString (§21.3.28) of class java.util.Date.

Whenever possible and appropriate, basing the names of methods in a new class on names in an existing class that is similar, especially a class from the standard Java Application Programming Interface classes, will make it easier to use.

Method names cannot hide or be hidden by other names (§6.5.6).


6.8.4 Field Names

Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. Note that well-designed Java classes have very few public or protected fields, except for fields that are constants (final static fields) (§6.8.5).

Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream (§22.6) and the field bytesTransferred of the class java.io.InterruptedIOException (§22.30.1).

Hiding involving field names is rare.

  • If a field name hides a package name, then an import declaration (§7.5) can usually be used to make available the type names declared in that package.
  • If a field name hides a type name, then a fully qualified name for the type can be used.
  • Field names cannot hide method names.
  • If a field name is hidden by a declaration of a parameter or local variable, then the name of the parameter or local variable can be changed without affecting other Java code.


6.8.5 Constant Names

The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class java.lang.Character.

A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

interface ProcessStates {
    int PS_RUNNING = 0;
    int PS_SUSPENDED = 1;
}

Hiding involving constant names is rare:

  • Constant names should be longer than three letters, so that they do not hide the initial component of a unique package name.
  • Constant names normally have no lowercase letters, so they will not normally hide names of packages, types, or fields, whose names normally contain at least one lowercase letter.
  • Constant names cannot hide method names, because they are distinguished syntactically.


6.8.6 Local Variable and Parameter Names

Local variable and parameter names should be short, yet meaningful. They are often short sequences of lowercase letters that are not words. For example:

  • Acronyms, that is the first letter of a series of words, as in cp for a variable holding a reference to a ColoredPoint
  • Abbreviations, as in buf holding a pointer to a buffer of some kind
  • Mnemonic terms, organized in some way to aid memory and understanding, typically by using a set of local variables with conventional names patterned after the names of parameters to widely used classes. For example:
    • in and out, whenever some kind of input and output are involved, patterned after the fields of java.lang.System
    • off and len, whenever an offset and length are involved, patterned after the parameters to the read and write methods of the interfaces DataInput and DataOutput of java.io

One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:

  • b for a byte
  • c for a char
  • d for a double
  • e for an Exception
  • f for a float
  • i, j, and k for integers
  • l for a long
  • o for an Object
  • s for a String
  • v for an arbitrary value of some type

Local variable or parameter names that consist of only two or three uppercase letters should be avoided to avoid potential conflicts with the initial country codes and domain names that are the first component of unique package names (§7.7).

What's in a name? That which we call a rose
By any other name would smell as sweet.
—William Shakespeare, Romeo and Juliet (c. 1594), Act II, scene ii

Rose is a rose is a rose is a rose.
—Gertrude Stein, "Sacred Emily" (1913), in Geographies and Plays

. . . stat rosa pristina nomine, nomina nuda tenemus.
—Bernard of Morlay, De contemptu mundi (12th century),
quoted in Umberto Eco, The Name of the Rose (1980)


 7. Packages

CHAPTER 7

Packages

Good things come in small packages.
—Traditional proverb

Java programs are organized as sets of packages. Each package has its own set of names for types, which helps to prevent name conflicts. A type is accessible (§6.6) outside the package that declares it only if the type is declared public.

The naming structure for packages is hierarchical (§7.1). The members of a package are class and interface types (§7.6), which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.

A package can be stored in a file system (§7.2.1) or in a database (§7.2.2). Packages that are stored in a file system have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily. In either case, the set of packages available to a Java program is determined by the host system, but must always include at least the three standard packages java.lang, java.util, and java.io as specified in Chapters 20, 21, and 22. In most host environments, the standard packages java.applet, java.awt, and java.net, which are not described in this specification, are also available to Java programs.

A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports each of the types declared in the predefined package java.lang.

A compilation unit has three parts, each of which is optional:

  • A package declaration (§7.4), giving the fully qualified name (§6.7) of the package to which the compilation unit belongs
  • import declarations (§7.5) that allow types from other packages to be referred to using their simple names
  • Type declarations (§7.6) of class and interface types

For small programs and casual development, a package can be unnamed (§7.4.2) or have a simple name, but if Java code is to be widely distributed, unique package names should be chosen (§7.7). This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program.


7.1 Package Members

A package can have members of either or both of the following kinds:

  • Subpackages of the package
  • Types declared in the compilation units (§7.3) of the package

For example, in the standard Java Application Programming Interface:

  • The package java has subpackages awt, applet, io, lang, net, and util, but no compilation units.
  • The package java.awt has a subpackage named image, as well as a number of compilation units containing declarations of class and interface types.

If the fully qualified name (§6.7) of a package is P, and Q is a subpackage of P, then P.Q is the fully qualified name of the subpackage.

The subpackages of package java named lang, util, and io (whose fully qualified package names are therefore java.lang, java.util, and java.io) are a standard part of every Java implementation and are specified in Chapters 20, 21, and 22. Many Java implementations will include the entire set of java packages defined in the series of books The Java Application Programming Interface.

A package may not contain a type declaration and a subpackage of the same name, or a compile-time error results. Here are some examples:

  • Because the package java.awt has a subpackage image, it cannot (and does not) contain a declaration of a class or interface type named image.
  • If there is a package named mouse and a type Button in that package (which then might be referred to as mouse.Button), then there cannot be any package with the fully qualified name mouse.Button or mouse.Button.Click.
  • If COM.Sun.java.jag is the fully qualified name of a type, then there cannot be any package whose fully qualified name is either COM.Sun.java.jag or COM.Sun.java.jag.scrabble.

The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in the Java language itself other than the prohibition against a package having a subpackage with the same simple name as a type declared in that package. There is no special access relationship in the Java language between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.Waugh. For example, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.


7.2 Host Support for Packages

Each Java host determines how packages, compilation units, and subpackages are created and stored; which top-level package names are in scope in a particular compilation; and which packages are accessible.

The packages may be stored in a local file system in simple implementations of Java. Other implementations may use a distributed file system or some form of database to store Java source and/or binary code.


7.2.1 Storing Packages in a File System

As an extremely simple example, all the Java packages and source and binary code on a system might be stored in a single directory and its subdirectories. Each immediate subdirectory of this directory would represent a top-level package, that is, one whose fully qualified name consists of a single simple name. The directory might contain the following immediate subdirectories:

COM
gls
jag
java
wnj

where directory java would contain the standard Java Application Programming Interface packages that are part of every standard Java system; the directories jag, gls, and wnj might contain packages that the three authors of this specification created for their personal use and to share with each other within this small group; and the directory COM would contain packages procured from companies that used the conventions described in §7.7 to generate unique names for their packages.

Continuing the example, the directory java would probably contain at least the following subdirectories:

applet
awt
io
lang
net
util

corresponding to the standard packages java.applet, java.awt, java.io, java.lang, java.net, and java.util that are defined as part of the standard Java Application Programming Interface.

Still continuing the example, if we were to look inside the directory util, we might see the following files:

BitSet.java										Observable.java
BitSet.class										Observable.class
Date.java										Observer.java
Date.class										Observer.class
Dictionary.java										Properties.java
Dictionary.class										Properties.class
EmptyStackException.java										Random.java
EmptyStackException.class										Random.class
Enumeration.java										Stack.java
Enumeration.class										Stack.class
Hashtable.java										StringTokenizer.java
Hashtable.class										StringTokenizer.class
NoSuchElementException.java										Vector.java
NoSuchElementException.class										Vector.class

where each of the .java files contains the source for a compilation unit (§7.3) that contains the definition of a class or interface whose binary compiled form is contained in the corresponding .class file.

Under this simple organization of packages, an implementation of Java would transform a package name into a pathname by concatenating the components of the package name, placing a file name separator (directory indicator) between adjacent components. For example, if this simple organization were used on a UNIX system, where the file name separator is /, the package name:

jag.scrabble.board

would be transformed into the directory name:

jag/scrabble/board

and:

COM.Sun.sunsoft.DOE

would be transformed to the directory name:

COM/Sun/sunsoft/DOE

In fact, the standard JavaSoft Java Developer's Kit on UNIX differs from the very simple discipline described here only in that it provides a CLASSPATH environment variable that specifies a set of directories, each of which is treated like the single directory described here. These directories are searched in order for definitions of named packages and types.

A package name component or class name might contain a character that cannot correctly appear in a host file system's ordinary directory name, such as a Unicode character on a system that allows only ASCII characters in file names. As a convention, the character can be escaped by using, say, the @ character followed by four hexadecimal digits giving the numeric value of the character, as in the \u xxxx escape (§3.3), so that the package name:

children.activities.crafts.papierM\u00e2ch\u00e9

which can also be written using full Unicode as:

children.activities.crafts.papierMache;

might be mapped to the directory name:

children/activities/crafts/papierM@00e2ch@00e9

If the @ character is not a valid character in a file name for some given host file system, then some other character that is not valid in a Java identifier could be used instead.


7.2.2 Storing Packages in a Database

A host system may store packages and their compilation units and subpackages in a database.

Java allows such a database to relax the restrictions (§7.6) on compilation units in file-based implementations. For example, a system that uses a database to store packages need not enforce a maximum of one public class or interface per compilation unit. Systems that use a database must, however, provide an option to convert a Java program to a form that obeys the restrictions, for purposes of export to file-based implementations.


7.3 Compilation Units

CompilationUnit is the goal symbol (§2.1) for the syntactic grammar (§2.3) of Java programs. It is defined by the following productions:

CompilationUnit:

    PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt

ImportDeclarations:

    ImportDeclaration

    ImportDeclarations ImportDeclaration

TypeDeclarations:

    TypeDeclaration

    TypeDeclarations TypeDeclaration

Types declared in different compilation units can depend on each other, circularly. A Java compiler must arrange to compile all such types at the same time.

A compilation unit consists of three parts, each of which is optional:

  • A package declaration (§7.4), giving the fully qualified name (§6.7) of the package to which the compilation unit belongs
  • import declarations (§7.5) that allow types from other packages to be referred to using their simple names
  • Type declarations (§7.6) of class and interface types

Every compilation unit automatically and implicitly imports every public type name declared in the predefined package java.lang, so that the names of all those types are available as simple names, as described in §7.5.3.


7.4 Package Declarations

A package declaration appears within a compilation unit to indicate the package to which the compilation unit belongs. A compilation unit that has no package declaration is part of an unnamed package.


7.4.1 Named Packages

A package declaration in a compilation unit specifies the name (§6.2) of the package to which the compilation unit belongs.

PackageDeclaration:

    package PackageName ;

The package name mentioned in a package declaration must be the fully qualified name (§6.7) of the package.

If a type named T is declared in a compilation unit of a package whose fully qualified name is P, then the fully qualified name of the type is P.T; thus in the example:

package wnj.points;
class Point { int x, y; }

the fully qualified name of class Point is wnj.points.Point.


7.4.2 Unnamed Packages

A compilation unit that has no package declaration is part of an unnamed package. As an example, the compilation unit:

class FirstCall {
    public static void main(String[] args) {
        System.out.println("Mr. Watson, come here. "
                                    + "I want you.");
    }
}

defines a very simple compilation unit as part of an unnamed package.

A Java system must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.

In Java systems that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is available at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.

Unnamed packages are provided by Java principally for convenience when developing small or temporary applications or when just beginning development.

Caution must be taken when using unnamed packages. It is possible for a compilation unit in a named package to import a type from an unnamed package, but the compiled version of this compilation unit will likely then work only when that particular unnamed package is "current." For this reason, it is strongly recommended that compilation units of named packages never import types from unnamed packages. It is also recommended that any type declared in an unnamed package not be declared public, to keep them from accidentally being imported by a named package.

It is recommended that a Java system provide safeguards against unintended consequences in situations where compilation units of named packages import types from unnamed packages. One strategy is to provide a way to associate with each named package at most one unnamed package, and then to detect and warn about situations in which a named package is used by more than one unnamed package. It is specifically not required-indeed, it is strongly discouraged-for an implementation to support use of a named package by more than one unnamed package by maintaining multiple compiled versions of the named package.


7.4.3 Scope and Hiding of a Package Name

Which top-level package names are in scope (§6.3, §6.5) is determined by conventions of the host system.

Package names never hide other names.


7.4.4 Access to Members of a Package

Whether access to members of a package is allowed is determined by the host system. The package java should always be accessible, and its standard subpackages lang, io, and util should always be accessible.

It is strongly recommended that the protections of a file system or database used to store Java programs be set to make all compilation units of a package available whenever any of the compilation units is available.


7.5 Import Declarations

An import declaration allows a type declared in another package to be referred to by a simple name (§6.2) that consists of a single identifier. Without the use of an appropriate import declaration, the only way to refer to a type declared in another package is to use its fully qualified name (§6.7).

ImportDeclaration:

    SingleTypeImportDeclaration

    TypeImportOnDemandDeclaration

A single-type-import declaration (§7.5.1) imports a single type, by mentioning its fully qualified name. A type-import-on-demand declaration (§7.5.2) imports all the public types of a named package as needed.

An import declaration makes types available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the name(s) it introduces specifically does not include the package statement, other import statements in the current compilation unit, or other compilation units in the same package. Please see §7.5.4 for an illustrative example.


7.5.1 Single-Type-Import Declaration

A single-type-import declaration imports a single type by giving its fully qualified name, making it available under a simple name in the class and interface declarations of its compilation unit.

SingleTypeImportDeclaration:

    import TypeName ;

The TypeName must be the fully qualified name of a class or interface type; a compile-time error occurs if the named type does not exist. If the named type is not in the current package, then it must be accessible (§6.6)-in an accessible package and declared public (§8.1.2, §9.1.2)-or a compile-time error occurs.

The example:

import java.util.Vector;

causes the simple name Vector to be available within the class and interface declarations in a compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places where it is not hidden (§6.3) by a declaration of a field, parameter, or local variable with the same name.

If two single-type-import declarations in the same compilation unit attempt to import types with the same simple name, then a compile-time error occurs, unless the two types are the same type, in which case the duplicate declaration is ignored. If another type with the same name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration (§7.5.2), then a compile-time error occurs.

So the sample program:

import java.util.Vector;

class Vector { Object[] vec; }

causes a compile-time error because of the duplicate declaration of Vector, as does:

import java.util.Vector;

import myVector.Vector;

where myVector is a package containing the compilation unit:

package myVector;

public class Vector { Object[] vec; }

The compiler keeps track of types by their fully qualified names (§6.7). Simple names and fully qualified names may be used interchangeably whenever they are both available.

Note that an import statement cannot import a subpackage, only a type. For example, it does not work to try to import java.util and then use the name util.Random to refer to the type java.util.Random:

import java.util;										// incorrect: compile-time error

class Test { util.Random generator; }


7.5.2 Type-Import-on-Demand Declaration

A type-import-on-demand declaration allows all public types declared in the package named by a fully qualified name to be imported as needed.

TypeImportOnDemandDeclaration:

    import PackageName . * ;

It is a compile-time error for a type-import-on-demand declaration to name a package that is not accessible (§6.6), as determined by the host system (§7.2). Two or more type-import-on-demand declarations in the same compilation unit may name the same package; the effect is as if there were exactly one such declaration. It is not a compile-time error to name the current package or java.lang in a type-import-on-demand declaration, even though they are already imported; the duplicate type-import-on-demand declaration is ignored.

The example:

import java.util.*;

causes the simple names of all public types declared in the package java.util to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector refers to the type Vector in the package java.util in all places where it is not hidden (§6.3) by a single-type-import declaration of a type whose simple name is Vector; by a type named Vector and declared in the package to which the compilation unit belongs; or by a declaration of a field, parameter, or local variable named Vector. (It would be unusual for any of these conditions to occur.)


7.5.3 Automatic Imports

Each compilation unit automatically imports each of the public type names declared in the predefined package java.lang, as if the declaration:

import java.lang.*;

appeared at the beginning of each compilation unit, immediately following any package statement.

The full specification of java.lang is given in Chapter 20. The following public types are defined in java.lang:

AbstractMethodError										LinkageError
ArithmeticException										Long
ArrayStoreException										Math
Boolean										NegativeArraySizeException
Character										NoClassDefFoundError
Class										NoSuchFieldError
ClassCastException										NoSuchMethodError
ClassCircularityError										NullPointerException
ClassFormatError										Number
ClassLoader										NumberFormatException
ClassNotFoundException										Object
CloneNotSupportedException										OutOfMemoryError
Cloneable										Process
Compiler										Runnable
Double										Runtime
Error										RuntimeException
Exception										SecurityException
ExceptionInInitializerError										SecurityManager
Float										StackOverflowError
IllegalAccessError										String
IllegalAccessException										StringBuffer
IllegalArgumentException										System
IllegalMonitorStateException										Thread
IllegalThreadStateException										ThreadDeath
IncompatibleClassChangeError										ThreadGroup
IndexOutOfBoundsException										Throwable
InstantiationError										UnknownError
InstantiationException										UnsatisfiedLinkError
Integer										VerifyError
InternalError										VirtualMachineError
InterruptedException


7.5.4 A Strange Example

Package names and type names are usually different under the naming conventions described in §6.8. Nevertheless, in a contrived example where there is an unconventionally-named package Vector, which declares a public class named Mosquito:

package Vector;

public class Mosquito { int capacity; }

and then the compilation unit:

package strange.example;

import java.util.Vector;

import Vector.Mosquito;

class Test {
    public static void main(String[] args) {
        System.out.println(new Vector().getClass());
        System.out.println(new Mosquito().getClass());
    }
}

the single-type-import declaration (§7.5.1) importing class Vector from package java.util does not prevent the package name Vector from appearing and being correctly recognized in subsequent import declarations. The example compiles and produces the output:

class java.util.Vector
class Vector.Mosquito


7.6 Type Declarations

A type declaration declares a class type (§8) or an interface type (§9):

TypeDeclaration:

    ClassDeclaration

    InterfaceDeclaration

    ;

A Java compiler must ignore extra ";" tokens appearing at the level of type declarations. Stray semicolons are permitted in Java solely as a concession to C++ programmers who are used to writing:

class date { int month, day, year; };

(In C++, but not in Java, one can provide a comma-separated list of identifiers in order to declare variables between the "}" and the ";".) Extra semicolons should not be used in new Java code. Software that reformats Java code can delete them.

By default, the types declared in a package are accessible only within the compilation units of that package, but a type may be declared to be public to grant access to the type from code in other packages (§6.6, §8.1.2, §9.1.2).

A Java implementation must keep track of types within packages by their fully qualified names (§6.7). Multiple ways of naming a type must be expanded to fully qualified names to make sure that such names are understood as referring to the same type. For example, if a compilation unit contains the single-type-import declaration (§7.5.1):

import java.util.Vector;

then within that compilation unit the simple name Vector and the fully qualified name java.util.Vector refer to the same type.

When Java packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.
  • The type is declared public (and therefore is potentially accessible from code in other packages).

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler and Java Virtual Machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

When Java packages are stored in a database (§7.2.2), the host system need not enforce such restrictions.

In practice, many Java programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.


7.7 Unique Package Names

Did I ever tell you that Mrs. McCave
Had twenty-three sons and she named them all "Dave"?
Well, she did. And that wasn't a smart thing to do. . . .

-Dr. Seuss (Theodore Geisel), Too Many Daves (1961)

Developers should take steps to avoid the possibility of two published packages having the same name by choosing unique package names for packages that are widely distributed. This allows packages to be easily and automatically installed and catalogued. This section specifies a standard convention, not enforced by a Java compiler, for generating such unique package names. Java systems are encouraged to provide automatic support for converting a set of packages from local and casual package names to the unique name format described here.

If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader (§20.14) of the standard Java Virtual Machine environment can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naive Java program.

You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as Sun.COM. You then reverse this name, component by component, to obtain, in this example, COM.Sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.

Such a convention might specify that certain directory name components be division, department, project, machine, or login names. Some possible examples:

COM.Sun.sunsoft.DOE
COM.Sun.java.jag.scrabble
COM.Apple.quicktime.v2
EDU.cmu.cs.bovik.cheese
GOV.whitehouse.socks.mousefinder

The first component of a unique package name is always written in all-uppercase ASCII letters and should be one of the top-level domain names, currently COM, EDU, GOV, MIL, NET, ORG, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. For more information, refer to the documents stored at ftp://rs.internic.net/rfc, for example, rfc920.txt and rfc1032.txt.

The name of a package is not meant to imply anything about where the package is stored within the Internet; for example, a package named EDU.cmu.cs.bovik.cheese is not necessarily obtainable from Internet address cmu.EDU or from cs.cmu.EDU or from bovik.cs.cmu.EDU. The Java convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for Java package names.

If you need to get a new Internet domain name, you can get an application form from ftp://ftp.internic.net and submit the complete forms by E-mail to domreg@internic.net. To find out what the currently registered domain names are, you can telnet to rs.internic.net and use the whois facility.


 8. Classes

CHAPTER 8

Classes

class 1. The noun class derives from Medieval French and French classe from Latin classis, probably originally a summons, hence a summoned collection of persons, a group liable to be summoned: perhaps for callassis from calare, to call, hence to summon.
—Eric Partridge, Origins: A Short Etymological Dictionary of Modern English

Class declarations define new reference types and describe how they are implemented (§8.1).

The name of a class has as its scope all type declarations in the package in which the class is declared (§8.1.1). A class may be declared abstract (§8.1.2.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final (§8.1.2.2), in which case it cannot have subclasses. If a class is declared public, then it can be referred to from other packages.

Each class except Object is an extension of (that is, a subclass of) a single existing class (§8.1.3) and may implement interfaces (§8.1.4).

The body of a class declares members (fields and methods), static initializers, and constructors (§8.1.5). The scope of the name of a member is the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may include the access modifiers (§6.6) public, protected, or private. The members of a class include both declared and inherited members (§8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.

Field declarations (§8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final (§8.3.1.2), in which case it cannot be assigned to except as part of its declaration. Any field declaration may include an initializer; the declaration of a final field must include an initializer.

Method declarations (§8.4) describe code that may be invoked by method invocation expressions (§15.11). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of the class type. A method whose declaration does not indicate how it is implemented must be declared abstract. A method may be declared final (§8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native code (§8.4.3.4). A synchronized method (§8.4.3.5) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized statement (§14.17), thus allowing its activities to be synchronized with those of other threads (§17).

Method names may be overloaded (§8.4.7).

Static initializers (§8.5) are blocks of executable code that may be used to help initialize a class when it is first loaded (§12.4).

Constructors (§8.6) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (§8.6.6).


8.1 Class Declaration

A class declaration specifies a new reference type:

ClassDeclaration:

    ClassModifiersopt class Identifier Superopt Interfacesopt ClassBody

If a class is declared in a named package (§7.4.1) with fully qualified name P (§6.7), then the class has the fully qualified name P.Identifier. If the class is in an unnamed package (§7.4.2), then the class has the fully qualified name Identifier. In the example:

class Point { int x, y; }

the class Point is declared in a compilation unit with no package statement, and thus Point is its fully qualified name, whereas in the example:

package vista;
class Point { int x, y; }

the fully qualified name of the class Point is vista.Point. (The package name vista is suitable for local or personal use; if the package were intended to be widely distributed, it would be better to give it a unique package name (§7.7).)

A compile-time error occurs if the Identifier naming a class appears as the name of any other class type or interface type declared in the same package (§7.6).

A compile-time error occurs if the Identifier naming a class is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the class declaration.

In the example:

package test;

import java.util.Vector;

class Point {
    int x, y;
}

interface Point {											// compile-time error #1
    int getR();
    int getTheta();
}

class Vector { Point[] pts; }											// compile-time error #2

the first compile-time error is caused by the duplicate declaration of the name Point as both a class and an interface in the same package. A second error detected at compile time is the attempt to declare the name Vector both by a class type declaration and by a single-type-import declaration.

Note, however, that it is not an error for the Identifier that names a class also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example:

package test;

import java.util.*;

class Vector { Point[] pts; }											// not a compile-time error

the declaration of the class Vector is permitted even though there is also a class java.util.Vector. Within this compilation unit, the simple name Vector refers to the class test.Vector, not to java.util.Vector (which can still be referred to by code within the compilation unit, but only by its fully qualified name).


8.1.1 Scope of a Class Type Name

The Identifier in a class declaration specifies the name of the class. This class name has as its scope (§6.3) the entire package in which the class is declared. As an example, the compilation unit:

package points;

class Point {
    int x, y;									// coordinates
    PointColor color;									// color of this point
    Point next;									// next point with this color

    static int nPoints;
}

class PointColor {
    Point first;									// first point with this color
    PointColor(int color) {
        this.color = color;
    }
    private int color;									// color components
}

defines two classes that use each other in the declarations of their class members. Because the class type names Point and PointColor have the entire package points, including the entire current compilation unit, as their scope, this example compiles correctly-that is, forward reference is not a problem.


8.1.2 Class Modifiers

A class declaration may include class modifiers.

ClassModifiers:

    ClassModifier

    ClassModifiers ClassModifier

ClassModifier: one of

    public abstract final

The access modifier public is discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a class declaration. If two or more class modifiers appear in a class declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for ClassModifier.

8.1.2.1 abstract Classes

An abstract class is a class that is incomplete, or to be considered incomplete. Only abstract classes may have abstract methods (§8.4.3.1, §9.4), that is, methods that are declared but not yet implemented. If a class that is not abstract contains an abstract method, then a compile-time error occurs. A class has abstract methods if any of the following is true:

  • It explicitly contains a declaration of an abstract method (§8.4.3).
  • It inherits an abstract method from its direct superclass (§8.1.3).
  • A direct superinterface (§8.1.4) of the class declares or inherits a method (which is therefore necessarily abstract) and the class neither declares nor inherits a method that implements it.

In the example:

abstract class Point {
    int x = 1, y = 1;
    void move(int dx, int dy) {
        x += dx;
        y += dy;
        alert();
    }
    abstract void alert();
}

abstract class ColoredPoint extends Point {
    int color;
}

class SimplePoint extends Point {
    void alert() { }
}

a class Point is declared that must be declared abstract, because it contains a declaration of an abstract method named alert. The subclass of Point named ColoredPoint inherits the abstract method alert, so it must also be declared abstract. On the other hand, the subclass of Point named SimplePoint provides an implementation of alert, so it need not be abstract.

A compile-time error occurs if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.8). An attempt to instantiate an abstract class using the newInstance method of class Class (§20.3.6) will cause an InstantiationException (§11.5.1) to be thrown. Thus, continuing the example just shown, the statement:

    Point p = new Point();

would result in a compile-time error; the class Point cannot be instantiated because it is abstract. However, a Point variable could correctly be initialized with a reference to any subclass of Point, and the class SimplePoint is not abstract, so the statement:

    Point p = new SimplePoint();

would be correct.

A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a SimplePoint causes the default constructor and field initializers for x and y of Point to be executed.

It is a compile-time error to declare an abstract class type such that it is not possible to create a subclass that implements all of its abstract methods. This situation can occur if the class would have as members two abstract methods that have the same method signature (§8.4.2) but different return types. As an example, the declarations:

interface Colorable { void setColor(int color); }

abstract class Colored implements Colorable {
    abstract int setColor(int color);
}

result in a compile-time error: it would be impossible for any subclass of class Colored to provide an implementation of a method named setColor, taking one argument of type int, that can satisfy both abstract method specifications, because the one in interface Colorable requires the same method to return no value, while the one in class Colored requires the same method to return a value of type int (§8.4).

A class type should be declared abstract only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor (§8.6.8) of no arguments, make it private, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class java.lang.Math is an example of a class that cannot be instantiated; its declaration looks like this:

public final class Math {

    private Math() { }							// never instantiate this class

    declarations of class variables and methods

}

8.1.2.2 final Classes

A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time error occurs if the name of a final class appears in the extends clause (§8.1.3) of another class declaration; this implies that a final class cannot have any subclasses. A compile-time error occurs if a class is declared both final and abstract, because the implementation of such a class could never be completed (§8.1.2.1).

Because a final class never has any subclasses, the methods of a final class are never overridden (§8.4.6.1).


8.1.3 Superclasses and Subclasses

The optional extends clause in a class declaration specifies the direct superclass of the current class. A class is said to be a direct subclass of the class it extends. The direct superclass is the class from whose implementation the implementation of the current class is derived. The extends clause must not appear in the definition of the class java.lang.Object (§20.1), because it is the primordial class and has no direct superclass. If the class declaration for any other class has no extends clause, then the class has the class java.lang.Object as its implicit direct superclass.

Super:

    extends ClassType

The following is repeated from §4.3 to make the presentation here clearer:

ClassType:

    TypeName

The ClassType must name an accessible (§6.6) class type, or a compile-time error occurs. All classes in the current package are accessible. Classes in other packages are accessible if the host system permits access to the package (§7.2) and the class is declared public. If the specified ClassType names a class that is final (§8.1.2.2), then a compile-time error occurs; final classes are not allowed to have subclasses.

In the example:

class Point { int x, y; }

final class ColoredPoint extends Point { int color; }

class Colored3DPoint extends ColoredPoint { int z; } // error

the relationships are as follows:

  • The class Point is a direct subclass of java.lang.Object.
  • The class java.lang.Object is the direct superclass of the class Point.
  • The class ColoredPoint is a direct subclass of class Point.
  • The class Point is the direct superclass of class ColoredPoint.

The declaration of class Colored3dPoint causes a compile-time error because it attempts to extend the final class ColoredPoint.

The subclass relationship is the transitive closure of the direct subclass relationship. A class A is a subclass of class C if either of the following is true:

  • A is the direct subclass of C.
  • There exists a class B such that A is a subclass of B, and B is a subclass of C, applying this definition recursively.

Class C is said to be a superclass of class A whenever A is a subclass of C.

In the example:

class Point { int x, y; }

class ColoredPoint extends Point { int color; }

final class Colored3dPoint extends ColoredPoint { int z; }

the relationships are as follows:

  • The class Point is a superclass of class ColoredPoint.
  • The class Point is a superclass of class Colored3dPoint.
  • The class ColoredPoint is a subclass of class Point.
  • The class ColoredPoint is a superclass of class Colored3dPoint.
  • The class Colored3dPoint is a subclass of class ColoredPoint.
  • The class Colored3dPoint is a subclass of class Point.

A compile-time error occurs if a class is declared to be a subclass of itself. For example:

class Point extends ColoredPoint { int x, y; }

class ColoredPoint extends Point { int color; }

causes a compile-time error. If circularly declared classes are detected at run time, as classes are loaded (§12.2), then a ClassCircularityError is thrown.


8.1.4 Superinterfaces

The optional implements clause in a class declaration lists the names of interfaces that are direct superinterfaces of the class being declared:

Interfaces:

    implements InterfaceTypeList

InterfaceTypeList:

    InterfaceType

    InterfaceTypeList , InterfaceType

The following is repeated from §4.3 to make the presentation here clearer:

InterfaceType:

    TypeName

Each InterfaceType must name an accessible (§6.6) interface type, or a compile- time error occurs. All interfaces in the current package are accessible. Interfaces in other packages are accessible if the host system permits access to the package (§7.4.4) and the interface is declared public.

A compile-time error occurs if the same interface is mentioned two or more times in a single implements clause, even if the interface is named in different ways; for example, the code:

class Redundant implements java.lang.Cloneable, Cloneable {
    int x;
}

results in a compile-time error because the names java.lang.Cloneable and Cloneable refer to the same interface.

An interface type I is a superinterface of class type C if any of the following is true:

  • I is a direct superinterface of C.
  • C has some direct superinterface J for which I is a superinterface, using the definition of "superinterface of an interface" given in §9.1.3.
  • I is a superinterface of the direct superclass of C, using this definition recursively.

A class is said to implement all its superinterfaces.

In the example:

public interface Colorable {
    void setColor(int color);
    int getColor();
}

public interface Paintable extends Colorable {
    int MATTE = 0, GLOSSY = 1;
    void setFinish(int finish);
    int getFinish();
}

class Point { int x, y; }

class ColoredPoint extends Point implements Colorable {
    int color;
    public void setColor(int color) { this.color = color; }
    public int getColor() { return color; }
}

class PaintedPoint extends ColoredPoint implements Paintable

{
    int finish;
    public void setFinish(int finish) {
        this.finish = finish;
    }
    public int getFinish() { return finish; }
}

the relationships are as follows:

  • The interface Paintable is a superinterface of class PaintedPoint.
  • The interface Colorable is a superinterface of class ColoredPoint and of class PaintedPoint.
  • The interface Paintable is a subinterface of the interface Colorable, and Colorable is a superinterface of Paintable, as defined in §9.1.3.

A class can have a superinterface in more than one way. In this example, the class PaintedPoint has Colorable as a superinterface both because it is a superinterface of ColoredPoint and because it is a superinterface of Paintable.

Unless the class being declared is abstract, the declarations of the methods defined in each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract is not permitted to have abstract methods (§8.1.2.1).

Thus, the example:

interface Colorable {
    void setColor(int color);
    int getColor();
}

class Point { int x, y; };

class ColoredPoint extends Point implements Colorable {
    int color;
}

causes a compile-time error, because ColoredPoint is not an abstract class but it fails to provide an implementation of methods setColor and getColor of the interface Colorable.

It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:

interface Fish { int getNumberOfScales(); }

interface Piano { int getNumberOfScales(); }

class Tuna implements Fish, Piano {
    // You can tune a piano, but can you tuna fish?
    int getNumberOfScales() { return 91; }
}

the method getNumberOfScales in class Tuna has a name, signature, and return type that matches the method declared in interface Fish and also matches the method declared in interface Piano; it is considered to implement both.

On the other hand, in a situation such as this:

interface Fish { int getNumberOfScales(); }

interface StringBass { double getNumberOfScales(); }

class Bass implements Fish, StringBass {
    // This declaration cannot be correct, no matter what type is used.
    public ??? getNumberOfScales() { return 91; }
}

it is impossible to declare a method named getNumberOfScales with the same signature and return type as those of both the methods declared in interface Fish and in interface StringBass, because a class can have only one method with a given signature (§8.4). Therefore, it is impossible for a single class to implement both interface Fish and interface StringBass (§8.4.6).


8.1.5 Class Body and Member Declarations

A class body may contain declarations of members of the class, that is, fields (§8.3) and methods (§8.4). A class body may also contain static initializers (§8.5) and declarations of constructors (§8.6) for the class.

ClassBody:

    { ClassBodyDeclarationsopt }

ClassBodyDeclarations:

    ClassBodyDeclaration

    ClassBodyDeclarations ClassBodyDeclaration

ClassBodyDeclaration:

    ClassMemberDeclaration

    StaticInitializer

    ConstructorDeclaration

ClassMemberDeclaration:

    FieldDeclaration

    MethodDeclaration

The scope of the name of a member declared in or inherited by a class type is the entire body of the class type declaration.


8.2 Class Members

The members of a class type are all of the following:

  • Members inherited from its direct superclass (§8.1.3), except in class Object, which has no direct superclass
  • Members inherited from any direct superinterfaces (§8.1.4)
  • Members declared in the body of the class (§8.1.5)

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

Constructors and static initializers are not members and therefore are not inherited.

The example:

class Point {
    int x, y;
    private Point() { reset(); }
    Point(int x, int y) { this.x = x; this.y = y; }
    private void reset() { this.x = 0; this.y = 0; }
}

class ColoredPoint extends Point {
    int color;
    void clear() { reset(); }														// error
}

class Test {
    public static void main(String[] args) {
        ColoredPoint c = new ColoredPoint(0, 0);													// error
        c.reset();													// error
    }
}

causes four compile-time errors:

  • An error occurs because ColoredPoint has no constructor declared with two integer parameters, as requested by the use in main. This illustrates the fact that ColoredPoint does not inherit the constructors of its superclass Point.
  • Another error occurs because ColoredPoint declares no constructors, and therefore a default constructor for it is automatically created (§8.6.7), and this default constructor is equivalent to: ColoredPoint() { super(); }

which invokes the constructor, with no arguments, for the direct superclass of the class ColoredPoint. The error is that the constructor for Point that takes no arguments is private, and therefore is not accessible outside the class Point, even through a superclass constructor invocation (§8.6.5).

  • Two more errors occur because the method reset of class Point is private, and therefore is not inherited by class ColoredPoint. The method invocations in method clear of class ColoredPoint and in method main of class Test are therefore not correct.


8.2.1 Examples of Inheritance

This section illustrates inheritance of class members through several examples.

8.2.1.1 Example: Inheritance with Default Access

Consider the example where the points package declares two compilation units:

package points;

public class Point {
    int x, y;

    public void move(int dx, int dy) { x += dx; y += dy; }
}

and:

package points;

public class Point3d extends Point {
    int z;
    public void move(int dx, int dy, int dz) {
        x += dx; y += dy; z += dz;
    }
}

and a third compilation unit, in another package, is:

import points.Point3d;

class Point4d extends Point3d {
    int w;
    public void move(int dx, int dy, int dz, int dw) {
        x += dx; y += dy; z += dz; w += dw; // compile-time errors
    }
}

Here both classes in the points package compile. The class Point3d inherits the fields x and y of class Point, because it is in the same package as Point. The class Point4d, which is in a different package, does not inherit the fields x and y of class Point or the field z of class Point3d, and so fails to compile.

A better way to write the third compilation unit would be:

import points.Point3d;

class Point4d extends Point3d {
    int w;
    public void move(int dx, int dy, int dz, int dw) {
        super.move(dx, dy, dz); w += dw;
    }
}

using the move method of the superclass Point3d to process dx, dy, and dz. If Point4d is written in this way it will compile without errors.

8.2.1.2 Inheritance with public and protected

Given the class Point:

package points;

public class Point {

    public int x, y;

    protected int useCount = 0;

    static protected int totalUseCount = 0;

    public void move(int dx, int dy) {
        x += dx; y += dy; useCount++; totalUseCount++;
    }

}

the public and protected fields x, y, useCount and totalUseCount are inherited in all subclasses of Point. Therefore, this test program, in another package, can be compiled successfully:

class Test extends points.Point {
    public void moveBack(int dx, int dy) {
        x -= dx; y -= dy; useCount++; totalUseCount++;
    }
}

8.2.1.3 Inheritance with private

In the example:

class Point {

    int x, y;

    void move(int dx, int dy) {
        x += dx; y += dy; totalMoves++;
    }

    private static int totalMoves;

    void printMoves() { System.out.println(totalMoves); }

}

class Point3d extends Point {

    int z;

    void move(int dx, int dy, int dz) {
        super.move(dx, dy); z += dz; totalMoves++;
    }

}

the class variable totalMoves can be used only within the class Point; it is not inherited by the subclass Point3d. A compile-time error occurs at the point where method move of class Point3d tries to increment totalMoves.

8.2.1.4 Accessing Members of Inaccessible Classes

Even though a class might not be declared public, instances of the class might be available at run time to code outside the package in which it is declared if it has a public superclass or superinterface. An instance of the class can be assigned to a variable of such a public type. An invocation of a public method of the object referred to by such a variable may invoke a method of the class if it implements or overrides a method of the public superclass or superinterface. (In this situation, the method is necessarily declared public, even though it is declared in a class that is not public.)

Consider the compilation unit:

package points;

public class Point {
    public int x, y;
    public void move(int dx, int dy) {
        x += dx; y += dy;
    }
}

and another compilation unit of another package:

package morePoints;

class Point3d extends points.Point {
    public int z;
    public void move(int dx, int dy, int dz) {
        super.move(dx, dy); z += dz;
    }
}

public class OnePoint {
    static points.Point getOne() { return new Point3d(); }
}

An invocation morePoints.OnePoint.getOne() in yet a third package would return a Point3d that can be used as a Point, even though the type Point3d is not available outside the package morePoints. The method move could then be invoked for that object, which is permissible because method move of Point3d is public (as it must be, for any method that overrides a public method must itself be public, precisely so that situations such as this will work out correctly). The fields x and y of that object could also be accessed from such a third package.

While the field z of class Point3d is public, it is not possible to access this field from code outside the package morePoints, given only a reference to an instance of class Point3d in a variable p of type Point. This is because the expression p.z is not correct, as p has type Point and class Point has no field named z; also, the expression ((Point3d)p).z is not correct, because the class type Point3d cannot be referred to outside package morePoints. The declaration of the field z as public is not useless, however. If there were to be, in package morePoints, a public subclass Point4d of the class Point3d:

package morePoints;

public class Point4d extends Point3d {
    public int w;
    public void move(int dx, int dy, int dz, int dw) {
        super.move(dx, dy, dz); w += dw;
    }
}

then class Point4d would inherit the field z, which, being public, could then be accessed by code in packages other than morePoints, through variables and expressions of the public type Point4d.


8.3 Field Declarations

Poetic fields encompass me around,
And still I seem to tread on classic ground.
—Joseph Addison (1672-1719), A Letter from Italy

The variables of a class type are introduced by field declarations:

FieldDeclaration:

    FieldModifiersopt Type VariableDeclarators ;

VariableDeclarators:

    VariableDeclarator

    VariableDeclarators , VariableDeclarator

VariableDeclarator:

    VariableDeclaratorId

    VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:

    Identifier

    VariableDeclaratorId [ ]

VariableInitializer:

    Expression

    ArrayInitializer

The FieldModifiers are described in §8.3.1. The Identifier in a FieldDeclarator may be used in a name to refer to the field. The name of a field has as its scope (§6.3) the entire body of the class declaration in which it is declared. More than one field may be declared in a single field declaration by using more than one declarator; the FieldModifiers and Type apply to all the declarators in the declaration. Variable declarations involving array types are discussed in §10.2.

It is a compile-time error for the body of a class declaration to contain declarations of two fields with the same name. Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).

If the class declares a field with a certain name, then the declaration of that field is said to hide (§6.3.1) any and all accessible declarations of fields with the same name in the superclasses and superinterfaces of the class.

If a field declaration hides the declaration of another field, the two fields need not have the same type.

A class inherits from its direct superclass and direct superinterfaces all the fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

It is possible for a class to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.

A hidden field can be accessed by using a qualified name (if it is static) or by using a field access expression (§15.10) that contains the keyword super or a cast to a superclass type. See §15.10.2 for discussion and an example.


8.3.1 Field Modifiers

FieldModifiers:

    FieldModifier

    FieldModifiers FieldModifier

FieldModifier: one of

    public protected private

    final static transient volatile

The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a field declaration, or if a field declaration has more than one of the access modifiers public, protected, and private. If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.

8.3.1.1 static Fields

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.

The example program:

class Point {
    int x, y, useCount;
    Point(int x, int y) { this.x = x; this.y = y; }
    final static Point origin = new Point(0, 0);
}

class Test {
    public static void main(String[] args) {
        Point p = new Point(1,1);
        Point q = new Point(2,2);
        p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++;
        System.out.println("(" + q.x + "," + q.y + ")");
        System.out.println(q.useCount);
        System.out.println(q.origin == Point.origin);
        System.out.println(q.origin.useCount);
    }
}

prints:

(2,2)
0
true
1

showing that changing the fields x, y, and useCount of p does not affect the fields of q, because these fields are instance variables in distinct objects. In this example, the class variable origin of the class Point is referenced both using the class name as a qualifier, in Point.origin, and using variables of the class type in field access expressions (§15.10), as in p.origin and q.origin. These two ways of accessing the origin class variable access the same object, evidenced by the fact that the value of the reference equality expression (§15.20.3):

q.origin==Point.origin

is true. Further evidence is that the incrementation:

p.origin.useCount++;

causes the value of q.origin.useCount to be 1; this is so because p.origin and q.origin refer to the same variable.

8.3.1.2 final Fields

A field can be declared final, in which case its declarator must include a variable initializer or a compile-time error occurs. Both class and instance variables (static and non-static fields) may be declared final.

Any attempt to assign to a final field results in a compile-time error. Therefore, once a final field has been initialized, it always contains the same value. If a final field holds a reference to an object, then the state of the object may be changed by operations on the object, but the field will always refer to the same object. This applies also to arrays, because arrays are objects; if a final field holds a reference to an array, then the components of the array may be changed by operations on the array, but the field will always refer to the same array.

Declaring a field final can serve as useful documentation that its value will not change, can help to avoid programming errors, and can make it easier for a compiler to generate efficient code.

In the example:

class Point {
    int x, y;
    int useCount;
    Point(int x, int y) { this.x = x; this.y = y; }
    final static Point origin = new Point(0, 0);
}

the class Point declares a final class variable origin. The origin variable holds a reference to an object that is an instance of class Point whose coordinates are (0, 0). The value of the variable Point.origin can never change, so it always refers to the same Point object, the one created by its initializer. However, an operation on this Point object might change its state-for example, modifying its useCount or even, misleadingly, its x or y coordinate.

8.3.1.3 transient Fields

Variables may be marked transient to indicate that they are not part of the persistent state of an object. If an instance of the class Point:

class Point {
    int x, y;
    transient float rho, theta;
}

were saved to persistent storage by a system service, then only the fields x and y would be saved. This specification does not yet specify details of such services; we intend to provide them in a future version of this specification.

8.3.1.4 volatile Fields

As described in §17, the Java language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. These working copies need be reconciled with the master copies in the shared main memory only at prescribed synchronization points, namely when objects are locked or unlocked. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

Java provides a second mechanism that is more convenient for some purposes: a field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.

If, in the following example, one thread repeatedly calls the method one (but no more than Integer.MAX_VALUE (§20.7.2) times in all), and another thread repeatedly calls the method two:

class Test {

    static int i = 0, j = 0;

    static void one() { i++; j++; }

    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }

}

then method two could occasionally print a value for j that is greater than the value of i, because the example includes no synchronization and, under the rules explained in §17, the shared values of i and j might be updated out of order.

One way to prevent this out-or-order behavior would be to declare methods one and two to be synchronized (§8.4.3.5):

class Test {

    static int i = 0, j = 0;

    static synchronized void one() { i++; j++; }

    static synchronized void two() {
        System.out.println("i=" + i + " j=" + j);
    }

}

This prevents method one and method two from being executed concurrently, and furthermore guarantees that the shared values of i and j are both updated before method one returns. Therefore method two never observes a value for j greater than that for i; indeed, it always observes the same value for i and j.

Another approach would be to declare i and j to be volatile:

class Test {

    static volatile int i = 0, j = 0;

    static void one() { i++; j++; }

    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }

}

This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread. Therefore, method two never observes a value for j greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs. It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.

See §17 for more discussion and examples.

A compile-time error occurs if a final variable is also declared volatile.


8.3.2 Initialization of Fields

If a field declarator contains a variable initializer, then it has the semantics of an assignment (§15.25) to the declared variable, and:

  • If the declarator is for a class variable (that is, a static field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized (§12.4).
  • If the declarator is for an instance variable (that is, a field that is not static), then the variable initializer is evaluated and the assignment performed each time an instance of the class is created (§12.5).

The example:

class Point {
    int x = 1, y = 5;
}

class Test {
    public static void main(String[] args) {
        Point p = new Point();
        System.out.println(p.x + ", " + p.y);
    }
}

produces the output:

1, 5

because the assignments to x and y occur whenever a new Point is created.

Variable initializers are also used in local variable declaration statements (§14.3), where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.

It is a compile-time error if the evaluation of a variable initializer for a field of a class (or interface) can complete abruptly with a checked exception (§11.2).

8.3.2.1 Initializers for Class Variables

A compile-time error occurs if an initialization expression for a class variable contains a use by a simple name of that class variable or of another class variable whose declaration occurs to its right (that is, textually later) in the same class. Thus:

class Test {
    static float f = j;							// compile-time error: forward reference
    static int j = 1;
    static int k = k+1;							// compile-time error: forward reference
}

causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.

If the keyword this (§15.7.2) or the keyword super (§15.10.2, §15.11) occurs in an initialization expression for a class variable, then a compile-time error occurs.

(One subtlety here is that, at run time, static variables that are final and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces (§9.3.1). These variables are "constants" that will never be observed to have their default initial values (§4.5.4), even by devious programs. See §12.4.2 and §13.4.8 for more discussion.)

8.3.2.2 Initializers for Instance Variables

A compile-time error occurs if an initialization expression for an instance variable contains a use by a simple name of that instance variable or of another instance variable whose declaration occurs to its right (that is, textually later) in the same class. Thus:

class Test {
    float f = j;
    int j = 1;
    int k = k+1;
}

causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later. Thus the example:

class Test {
    float f = j;
    static int j = 1;
}

compiles without error; it initializes j to 1 when class Test is initialized, and initializes f to the current value of j every time an instance of class Test is created.

Initialization expressions for instance variables are permitted to refer to the current object this (§15.7.2) and to use the keyword super (§15.10.2, §15.11).


8.3.3 Examples of Field Declarations

The following examples illustrate some (possibly subtle) points about field declarations.

8.3.3.1 Example: Hiding of Class Variables

The example:

class Point {
    static int x = 2;
}

class Test extends Point {
    static double x = 4.7;
    public static void main(String[] args) {

        new Test().printX();
    }
    void printX() {
        System.out.println(x + " " + super.x);
    }
}

produces the output:

4.7 2

because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. Within the declaration of class Test, the simple name x refers to the field declared within class Test. Code in class Test may refer to the field x of class Point as super.x (or, because x is static, as Point.x). If the declaration of Test.x is deleted:

class Point {
    static int x = 2;
}

class Test extends Point {
    public static void main(String[] args) {
        new Test().printX();
    }
    void printX() {
        System.out.println(x + " " + super.x);
    }
}

then the field x of class Point is no longer hidden within class Test; instead, the simple name x now refers to the field Point.x. Code in class Test may still refer to that same field as super.x. Therefore, the output from this variant program is:

2 2

8.3.3.2 Example: Hiding of Instance Variables

This example is similar to that in the previous section, but uses instance variables rather than static variables. The code:

class Point {
    int x = 2;
}

class Test extends Point {
    double x = 4.7;
    void printBoth() {
        System.out.println(x + " " + super.x);
    }
    public static void main(String[] args) {
        Test sample = new Test();
        sample.printBoth();
        System.out.println(sample.x + " " +

                                                ((Point)sample).x);
    }
}

produces the output:

4.7 2
4.7 2

because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. It must be noted, however, that while the field x of class Point is not inherited by class Test, it is nevertheless implemented by instances of class Test. In other words, every instance of class Test contains two fields, one of type int and one of type float. Both fields bear the name x, but within the declaration of class Test, the simple name x always refers to the field declared within class Test. Code in instance methods of class Test may refer to the instance variable x of class Point as super.x.

Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a float value, the instance variable declared in class Test, because the type of the variable sample is Test, but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point, because of the cast to type Point.

If the declaration of x is deleted from class Test, as in the program:

class Point {
    static int x = 2;
}

class Test extends Point {
    void printBoth() {
        System.out.println(x + " " + super.x);
    }
    public static void main(String[] args) {
        Test sample = new Test();
        sample.printBoth();
        System.out.println(sample.x + " " +

                                                ((Point)sample).x);
    }
}

then the field x of class Point is no longer hidden within class Test. Within instance methods in the declaration of class Test, the simple name x now refers to the field declared within class Point. Code in class Test may still refer to that same field as super.x. The expression sample.x still refers to the field x within type Test, but that field is now an inherited field, and so refers to the field x declared in class Point. The output from this variant program is:

2 2
2 2

8.3.3.3 Example: Multiply Inherited Fields

A class may inherit two or more fields with the same name, either from two interfaces or from its superclass and an interface. A compile-time error occurs on any attempt to refer to any ambiguously inherited field by its simple name. A qualified name or a field access expression that contains the keyword super (§15.10.2) may be used to access such fields unambiguously. In the example:

interface Frob { float v = 2.0f; }

class SuperTest { int v = 3; }

class Test extends SuperTest implements Frob {
    public static void main(String[] args) {
        new Test().printV();
    }
    void printV() { System.out.println(v); }
}

the class Test inherits two fields named v, one from its superclass SuperTest and one from its superinterface Frob. This in itself is permitted, but a compile-time error occurs because of the use of the simple name v in method printV: it cannot be determined which v is intended.

The following variation uses the field access expression super.v to refer to the field named v declared in class SuperTest and uses the qualified name Frob.v to refer to the field named v declared in interface Frob:

interface Frob { float v = 2.0f; }

class SuperTest { int v = 3; }

class Test extends SuperTest implements Frob {
    public static void main(String[] args) {
        new Test().printV();
    }
    void printV() {
        System.out.println((super.v + Frob.v)/2);
    }
}

It compiles and prints:

2.5

Even if two distinct inherited fields have the same type, the same value, and are both final, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:

interface Color { int RED=0, GREEN=1, BLUE=2; }

interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }

class Test implements Color, TrafficLight {
    public static void main(String[] args) {
        System.out.println(GREEN);										// compile-time error
        System.out.println(RED);										// compile-time error
    }
}

it is not astonishing that the reference to GREEN should be considered ambiguous, because class Test inherits two different declarations for GREEN with different values. The point of this example is that the reference to RED is also considered ambiguous, because two distinct declarations are inherited. The fact that the two fields named RED happen to have the same type and the same unchanging value does not affect this judgment.

8.3.3.4 Example: Re-inheritance of Fields

If the same field declaration is inherited from an interface by multiple paths, the field is considered to be inherited only once. It may be referred to by its simple name without ambiguity. For example, in the code:

public interface Colorable {
    int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
}

public interface Paintable extends Colorable {
    int MATTE = 0, GLOSSY = 1;
}

class Point { int x, y; }

class ColoredPoint extends Point implements Colorable {
    . . .
}

class PaintedPoint extends ColoredPoint implements Paintable
{
    . . .       RED       . . .
}

the fields RED, GREEN, and BLUE are inherited by the class PaintedPoint both through its direct superclass ColoredPoint and through its direct superinterface Paintable. The simple names RED, GREEN, and BLUE may nevertheless be used without ambiguity within the class PaintedPoint to refer to the fields declared in interface Colorable.


8.4 Method Declarations

The diversity of physical arguments and opinions embraces all sorts of methods.
—Michael de Montaigne (1533-1592), Of Experience

A method declares executable code that can be invoked, passing a fixed number of values as arguments.

MethodDeclaration:

    MethodHeader MethodBody

MethodHeader:

    MethodModifiersopt ResultType MethodDeclarator Throwsopt

ResultType:

    Type

    void

MethodDeclarator:

    Identifer ( FormalParameterListopt )

The MethodModifiers are described in §8.4.3, the Throws clause in §8.4.4, and the MethodBody in §8.4.5. A method declaration either specifies the type of value that the method returns or uses the keyword void to indicate that the method does not return a value.

The Identifier in a MethodDeclarator may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field of the class.

For compatibility with older versions of Java, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:

MethodDeclarator:

    MethodDeclarator [ ]

but should not be used in new Java code.

It is a compile-time error for the body of a class to have as members two methods with the same signature (§8.4.2) (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures (§6.5).


8.4.1 Formal Parameters

The formal parameters of a method, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type and an identifier (optionally followed by brackets) that specifies the name of the parameter:

FormalParameterList:

    FormalParameter

    FormalParameterList , FormalParameter

FormalParameter:

    Type VariableDeclaratorId

The following is repeated from §8.3 to make the presentation here clearer:

VariableDeclaratorId:

    Identifier

    VariableDeclaratorId [ ]

If a method has no parameters, only an empty pair of parentheses appears in the method's declaration.

If two formal parameters are declared to have the same name (that is, their declarations mention the same Identifier), then a compile-time error occurs.

When the method is invoked (§15.11), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method to refer to the formal parameter.

The scope of formal parameter names is the entire body of the method. These parameter names may not be redeclared as local variables or exception parameters within the method; that is, hiding the name of a parameter is not permitted.

Formal parameters are referred to only using simple names, never by using qualified names (§6.6).


8.4.2 Method Signature

The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile-time error occurs. The example:

class Point implements Move {
    int x, y;
    abstract void move(int dx, int dy);
    void move(int dx, int dy) { x += dx; y += dy; }
}

causes a compile-time error because it declares two move methods with the same signature. This is an error even though one of the declarations is abstract.


8.4.3 Method Modifiers

MethodModifiers:

    MethodModifier

    MethodModifiers MethodModifier

MethodModifier: one of

    public protected private

    abstract static final synchronized native

The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a method declaration, or if a method declaration has more than one of the access modifiers public, protected, and private. A compile-time error occurs if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, or synchronized.

If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for MethodModifier.

8.4.3.1 abstract Methods

An abstract method declaration introduces the method as a member, providing its signature (name and number and type of parameters), return type, and throws clause (if any), but does not provide an implementation. The declaration of an abstract method m must appear within an abstract class (call it A); otherwise a compile-time error results. Every subclass of A that is not abstract must provide an implementation for m, or a compile-time error occurs. More precisely, for every subclass C of the abstract class A, if C is not abstract, then there must be some class B such that all of the following are true:

  • B is a superclass of C or is C itself.
  • B is a subclass of A.
  • B provides a declaration of the method m that is not abstract, and this declaration is inherited by C, thereby providing an implementation of method m that is visible to C.

If there is no such class B, then a compile-time error occurs.

It is a compile-time error for a private method to be declared abstract. It would be impossible for a subclass to implement a private abstract method, because private methods are not visible to subclasses; therefore such a method could never be used.

It is a compile-time error for a static method to be declared abstract.

It is a compile-time error for a final method to be declared abstract.

An abstract class can override an abstract method by providing another abstract method declaration. This can provide a place to put a documentation comment (§18), or to declare that the set of checked exceptions (§11.2) that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code:

class BufferEmpty extends Exception {
    BufferEmpty() { super(); }
    BufferEmpty(String s) { super(s); }
}

class BufferError extends Exception {
    BufferError() { super(); }
    BufferError(String s) { super(s); }
}

public interface Buffer {
    char get() throws BufferEmpty, BufferError;
}

public abstract class InfiniteBuffer implements Buffer {
    abstract char get() throws BufferError;
}

The overriding declaration of method get in class InfiniteBuffer states that method get in any subclass of InfiniteBuffer never throws a BufferEmpty exception, putatively because it generates the data in the buffer, and thus can never run out of data.

An instance method that is not abstract can be overridden by an abstract method. For example, we can declare an abstract class Point that requires its subclasses to implement toString if they are to be complete, instantiable classes:

abstract class Point {
    int x, y;
    public abstract String toString();
}

This abstract declaration of toString overrides the non-abstract toString method of class Object (§20.1.2). (Class Object is the implicit direct superclass of class Point.) Adding the code:

class ColoredPoint extends Point {
    int color;
    public String toString() {
        return super.toString() + ": color " + color; // error
    }
}

results in a compile-time error because the invocation super.toString() refers to method toString in class Point, which is abstract and therefore cannot be invoked. Method toString of class Object can be made available to class ColoredPoint only if class Point explicitly makes it available through some other method, as in:

abstract class Point {
    int x, y;
    public abstract String toString();
    protected String objString() { return super.toString(); }
}

class ColoredPoint extends Point {
    int color;
    public String toString() {
        return objString() + ": color " + color;														// correct
    }
}

8.4.3.2 static Methods

A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super in the body of a class method results in a compile time error. It is a compile-time error for a static method to be declared abstract.

A method that is not declared static is called an instance method, and sometimes called a non-static method). An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

8.4.3.3 final Methods

A method can be declared final to prevent subclasses from overriding or hiding it. It is a compile-time error to attempt to override or hide a final method.

A private method and all methods declared in a final class (§8.1.2.2) are implicitly final, because it is impossible to override them. It is permitted but not required for the declarations of such methods to redundantly include the final keyword.

It is a compile-time error for a final method to be declared abstract.

At run-time, a machine-code generator or optimizer can easily and safely "inline" the body of a final method, replacing an invocation of the method with the code in its body, as in the example:

final class Point {
    int x, y;
    void move(int dx, int dy) { x += dx; y += dy; }
}

class Test {
    public static void main(String[] args) {
        Point[] p = new Point[100];
        for (int i = 0; i < p.length; i++) {
            p[i] = new Point();
            p[i].move(i, p.length-1-i);
        }
    }
}

Here, inlining the method move of class Point in method main would transform the for loop to the form:

        for (int i = 0; i < p.length; i++) {
            p[i] = new Point();
            Point pi = p[i];
            pi.x += i;
            pi.y += p.length-1-i;
        }

The loop might then be subject to further optimizations.

Such inlining cannot be done at compile time unless it can be guaranteed that Test and Point will always be recompiled together, so that whenever Point-and specifically its move method-changes, the code for Test.main will also be updated.

8.4.3.4 native Methods

A method that is native is implemented in platform-dependent code, typically written in another programming language such as C, C++, FORTRAN, or assembly language. The body of a native method is given as a semicolon only, indicating that the implementation is omitted, instead of a block.

A compile-time error occurs if a native method is declared abstract.

For example, the class RandomAccessFile of the standard package java.io might declare the following native methods:

package java.io;

public class RandomAccessFile

    implements DataOutput, DataInput
{	. . .
    public native void open(String name, boolean writeable)
        throws IOException;
    public native int readBytes(byte[] b, int off, int len)
        throws IOException;
    public native void writeBytes(byte[] b, int off, int len)
        throws IOException;
    public native long getFilePointer() throws IOException;
    public native void seek(long pos) throws IOException;
    public native long length() throws IOException;
    public native void close() throws IOException;
}

8.4.3.5 synchronized Methods

A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method, the lock associated with the Class object (§20.3) for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used. These are the same locks that can be used by the synchronized statement (§14.17); thus, the code:

class Test {
    int count;
    synchronized void bump() { count++; }
    static int classCount;
    static synchronized void classBump() {
        classCount++;
    }
}

has exactly the same effect as:

class BumpTest {
    int count;
    void bump() {
        synchronized (this) {
            count++;
        }
    }
    static int classCount;
    static void classBump() {
        try {
            synchronized (Class.forName("BumpTest")) {
                classCount++;
            }
        } catch (ClassNotFoundException e) {
                ...
        }
    }
}

The more elaborate example:

public class Box {

    public synchronized Object get() {
        return contents;
    }

    public synchronized boolean put(Object contents) {
            return false;
        return true;
    }

}

defines a class which is designed for concurrent use. Each instance of the class Box has an instance variable contents that can hold a reference to any object. You can put an object in a Box by invoking put, which returns false if the box is already full. You can get something out of a Box by invoking get, which returns a null reference if the box is empty.

If put and get were not synchronized, and two threads were executing methods for the same instance of Box at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to put occurred at the same time.

See §17 for more discussion of threads and locks.


8.4.4 Throws

A throws clause is used to declare any checked exceptions (§11.2) that can result from the execution of a method or constructor:

Throws:

    throws ClassTypeList

ClassTypeList:

    ClassType

    ClassTypeList , ClassType

A compile-time error occurs if any ClassType mentioned in a throws clause is not the class Throwable (§20.22) or a subclass of Throwable. It is permitted but not required to mention other (unchecked) exceptions in a throws clause.

For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws clause in the declaration of the method or constructor.

The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a throws clause. Java thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.

The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:

  • Exceptions that are represented by the subclasses of class Error, for example OutOfMemoryError, are thrown due to a failure in or of the virtual machine. Many of these are the result of linkage failures and can occur at unpredictable points in the execution of a Java program. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions.
  • The exceptions that are represented by the subclasses of the class RuntimeException, for example NullPointerException, result from runtime integrity checks and are thrown either directly from the Java program or in library routines. It is beyond the scope of the Java language, and perhaps beyond the state of the art, to include sufficient information in the program to reduce to a manageable number the places where these can be proven not to occur.

A method that overrides or hides another method (§8.4.6), including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.

More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws clause that mentions any checked exception types, then m must have a throws clause, and for every checked exception type listed in the throws clause of n, that same exception class or one of its superclasses must occur in the throws clause of m; otherwise, a compile-time error occurs.

See §11 for more information about exceptions and a large example.


8.4.5 Method Body

A method body is either a block of code that implements the method or simply a semicolon, indicating the lack of an implementation. The body of a method must be a semicolon if and only if the method is either abstract (§8.4.3.1) or native (§8.4.3.4).

MethodBody:

    Block

    ;

A compile-time error occurs if a method declaration is either abstract or native and has a block for its body. A compile-time error occurs if a method declaration is neither abstract nor native and has a semicolon for its body.

If an implementation is to be provided for a method but the implementation requires no executable code, the method body should be written as a block that contains no statements: "{ }".

If a method is declared void, then its body must not contain any return statement (§14.15) that has an Expression.

If a method is declared to have a return type, then every return statement (§14.15) in its body must have an Expression. A compile-time error occurs if the body of the method can complete normally (§14.1). In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."

Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:

class DizzyDean {

    int pitch() { throw new RuntimeException("90 mph?!"); }

}


8.4.6 Inheritance, Overriding, and Hiding

A class inherits from its direct superclass and direct superinterfaces all the methods (whether abstract or not) of the superclass and superinterfaces that are accessible to code in the class and are neither overridden (§8.4.6.1) nor hidden (§8.4.6.2) by a declaration in the class.

8.4.6.1 Overriding (By Instance Methods)

If a class declares an instance method, then the declaration of that method is said to override any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. Moreover, if the method declared in the class is not abstract, then the declaration of that method is said to implement any and all declarations of abstract methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class.

A compile-time error occurs if an instance method overrides a static method. In this respect, overriding of methods differs from hiding of fields (§8.3), for it is permissible for an instance variable to hide a static variable.

An overridden method can be accessed by using a method invocation expression (§15.11) that contains the keyword super. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See §15.11.4.10 for discussion and examples of this point.

8.4.6.2 Hiding (By Class Methods)

If a class declares a static method, then the declaration of that method is said to hide any and all methods with the same signature in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. A compile-time error occurs if a static method hides an instance method. In this respect, hiding of methods differs from hiding of fields (§8.3), for it is permissible for a static variable to hide an instance variable.

A hidden method can be accessed by using a qualified name or by using a method invocation expression (§15.11) that contains the keyword super or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.

8.4.6.3 Requirements in Overriding and Hiding

If a method declaration overrides or hides the declaration of another method, then a compile-time error occurs if they have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (§8.4.4) with that of any method that it overrides or hides; otherwise, a compile-time error occurs. In these respects, overriding of methods differs from hiding of fields (§8.3), for it is permissible for a field to hide a field of another type.

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:

  • If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
  • If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

Note that a private method is never accessible to subclasses and so cannot be hidden or overridden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private method in the superclass.

8.4.6.4 Inheriting Methods with the Same Signature

It is possible for a class to inherit more than one method with the same signature (§8.4.6.4). Such a situation does not in itself cause a compile-time error. There are then two possible cases:

  • If one of the inherited methods is not abstract, then there are two subcases:
    • If the method that is not abstract is static, a compile-time error occurs.
    • Otherwise, the method that is not abstract is considered to override, and therefore to implement, all the other methods on behalf of the class that inherits it. A compile-time error occurs if, comparing the method that is not abstract with each of the other of the inherited methods, for any such pair, either they have different return types or one has a return type and the other is void. Moreover, a compile-time error occurs if the inherited method that is not abstract has a throws clause that conflicts (§8.4.4) with that of any other of the inherited methods.
  • If none of the inherited methods is not abstract, then the class is necessarily an abstract class and is considered to inherit all the abstract methods. A compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is void. (The throws clauses do not cause errors in this case.)

It is not possible for two or more inherited methods with the same signature not to be abstract, because methods that are not abstract are inherited only from the direct superclass, not from superinterfaces.

There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.


8.4.7 Overloading

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.

Methods are overridden on a signature-by-signature basis. If, for example, a class declares two public methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method. In this respect, Java differs from C++.

When a method is invoked (§15.11), the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.11.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.11.4).


8.4.8 Examples of Method Declarations

The following examples illustrate some (possibly subtle) points about method declarations.

8.4.8.1 Example: Overriding

In the example:

class Point {

    int x = 0, y = 0;

    void move(int dx, int dy) { x += dx; y += dy; }

}

class SlowPoint extends Point {

    int xLimit, yLimit;

    void move(int dx, int dy) {
        super.move(limit(dx, xLimit), limit(dy, yLimit));
    }

    static int limit(int d, int limit) {
        return d > limit ? limit : d < -limit ? -limit : d;
    }

}

the class SlowPoint overrides the declarations of method move of class Point with its own move method, which limits the distance that the point can move on each invocation of the method. When the move method is invoked for an instance of class SlowPoint, the overriding definition in class SlowPoint will always be called, even if the reference to the SlowPoint object is taken from a variable whose type is Point.

8.4.8.2 Example: Overloading, Overriding, and Hiding

In the example:

class Point {

    int x = 0, y = 0;

    void move(int dx, int dy) { x += dx; y += dy; }

    int color;

}

class RealPoint extends Point {

    float x = 0.0f, y = 0.0f;

    void move(int dx, int dy) { move((float)dx, (float)dy); }

    void move(float dx, float dy) { x += dx; y += dy; }

}

the class RealPoint hides the declarations of the int instance variables x and y of class Point with its own float instance variables x and y, and overrides the method move of class Point with its own move method. It also overloads the name move with another method with a different signature (§8.4.2).

In this example, the members of the class RealPoint include the instance variable color inherited from the class Point, the float instance variables x and y declared in RealPoint, and the two move methods declared in RealPoint.

Which of these overloaded move methods of class RealPoint will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in §15.11.

8.4.8.3 Example: Incorrect Overriding

This example is an extended variation of that in the preceding section:

class Point {

    int x = 0, y = 0, color;

    void move(int dx, int dy) { x += dx; y += dy; }

    int getX() { return x; }

    int getY() { return y; }

}

class RealPoint extends Point {

    float x = 0.0f, y = 0.0f;

    void move(int dx, int dy) { move((float)dx, (float)dy); }

    void move(float dx, float dy) { x += dx; y += dy; }

    float getX() { return x; }

    float getY() { return y; }

}

Here the class Point provides methods getX and getY that return the values of its fields x and y; the class RealPoint then overrides these methods by declaring methods with the same signature. The result is two errors at compile time, one for each method, because the return types do not match; the methods in class Point return values of type int, but the wanna-be overriding methods in class RealPoint return values of type float.

8.4.8.4 Example: Overriding versus Hiding

This example corrects the errors of the example in the preceding section:

class Point {

    int x = 0, y = 0;

    void move(int dx, int dy) { x += dx; y += dy; }

    int getX() { return x; }

    int getY() { return y; }

    int color;

}

class RealPoint extends Point {

    float x = 0.0f, y = 0.0f;

    void move(int dx, int dy) { move((float)dx, (float)dy); }

    void move(float dx, float dy) { x += dx; y += dy; }

    int getX() { return (int)Math.floor(x); }

    int getY() { return (int)Math.floor(y); }

}

Here the overriding methods getX and getY in class RealPoint have the same return types as the methods of class Point that they override, so this code can be successfully compiled.

Consider, then, this test program:

class Test {

    public static void main(String[] args) {
        RealPoint rp = new RealPoint();
        Point p = rp;
        rp.move(1.71828f, 4.14159f);
        p.move(1, -1);
        show(p.x, p.y);
        show(rp.x, rp.y);
        show(p.getX(), p.getY());
        show(rp.getX(), rp.getY());
    }

    static void show(int x, int y) {
        System.out.println("(" + x + ", " + y + ")");
    }

    static void show(float x, float y) {
        System.out.println("(" + x + ", " + y + ")");
    }

}

The output from this program is:

(0, 0)
(2.7182798, 3.14159)
(2, 3)
(2, 3)

The first line of output illustrates the fact that an instance of RealPoint actually contains the two integer fields declared in class Point; it is just that their names are hidden from code that occurs within the declaration of class RealPoint (and those of any subclasses it might have). When a reference to an instance of class RealPoint in a variable of type Point is used to access the field x, the integer field x declared in class Point is accessed. The fact that its value is zero indicates that the method invocation p.move(1, -1) did not invoke the method move of class Point; instead, it invoked the overriding method move of class RealPoint.

The second line of output shows that the field access rp.x refers to the field x declared in class RealPoint. This field is of type float, and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name show is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked.

The last two lines of output show that the method invocations p.getX() and rp.getX() each invoke the getX method declared in class RealPoint. Indeed, there is no way to invoke the getX method of class Point for an instance of class RealPoint from outside the body of RealPoint, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding.

8.4.8.5 Example: Invocation of Hidden Class Methods

A hidden class (static) method can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:

class Super {
    static String greeting() { return "Goodnight"; }
    String name() { return "Richard"; }
}

class Sub extends Super {
    static String greeting() { return "Hello"; }
    String name() { return "Dick"; }
}

class Test {
    public static void main(String[] args) {
        Super s = new Sub();
        System.out.println(s.greeting() + ", " + s.name());
    }
}

produces the output:

Goodnight, Dick

because the invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke, whereas the invocation of name uses the class of s, namely Sub, to figure out, at run time, which instance method to invoke.

8.4.8.6 Large Example of Overriding

Overriding makes it easy for subclasses to extend the behavior of an existing class, as shown in this example:

import java.io.OutputStream;

import java.io.IOException;

class BufferOutput {

    private OutputStream o;

    BufferOutput(OutputStream o) { this.o = o; }

    protected byte[] buf = new byte[512];

    protected int pos = 0;

    public void putchar(char c) throws IOException {
        if (pos == buf.length)
            flush();
        buf[pos++] = (byte)c;
    }

    public void putstr(String s) throws IOException {
        for (int i = 0; i < s.length(); i++)
            putchar(s.charAt(i));
    }

    public void flush() throws IOException {
        o.write(buf, 0, pos);
        pos = 0;
    }

}

class LineBufferOutput extends BufferOutput {

    LineBufferOutput(OutputStream o) { super(o); }

    public void putchar(char c) throws IOException {
        super.putchar(c);
        if (c == '\n')
            flush();
    }

}

class Test {
    public static void main(String[] args)

        throws IOException

    {
        LineBufferOutput lbo =

            new LineBufferOutput(System.out);
        lbo.putstr("lbo\nlbo");
        System.out.print("print\n");
        lbo.putstr("\n");
    }
}

This example produces the output:

lbo
print
lbo

The class BufferOutput implements a very simple buffered version of an OutputStream, flushing the output when the buffer is full or flush is invoked. The subclass LineBufferOutput declares only a constructor and a single method putchar, which overrides the method putchar of BufferOutput. It inherits the methods putstr and flush from class Buffer.

In the putchar method of a LineBufferOutput object, if the character argument is a newline, then it invokes the flush method. The critical point about overriding in this example is that the method putstr, which is declared in class BufferOutput, invokes the putchar method defined by the current object this, which is not necessarily the putchar method declared in class BufferOutput.

Thus, when putstr is invoked in main using the LineBufferOutput object lbo, the invocation of putchar in the body of the putstr method is an invocation of the putchar of the object lbo, the overriding declaration of putchar that checks for a newline. This allows a subclass of BufferOutput to change the behavior of the putstr method without redefining it.

Documentation for a class such as BufferOutput, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the putchar method in this way. The implementor of the BufferOutput class would not, therefore, want to change the implementation of putstr in a future implementation of BufferOutput not to use the method putchar, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in §13, especially §13.2.

8.4.8.7 Example: Incorrect Overriding because of Throws

This example uses the usual and conventional form for declaring a new exception type, in its declaration of the class BadPointException:

class BadPointException extends Exception {
    BadPointException() { super(); }
    BadPointException(String s) { super(s); }
}

class Point {
    int x, y;
    void move(int dx, int dy) { x += dx; y += dy; }
}

class CheckedPoint extends Point {
    void move(int dx, int dy) throws BadPointException {
        if ((x + dx) < 0 || (y + dy) < 0)
            throw new BadPointException();
        x += dx; y += dy;
    }
}

This example results in a compile-time error, because the override of method move in class CheckedPoint declares that it will throw a checked exception that the move in class Point has not declared. If this were not considered an error, an invoker of the method move on a reference of type Point could find the contract between it and Point broken if this exception were thrown.

Removing the throws clause does not help:

class CheckedPoint extends Point {
    void move(int dx, int dy) {
        if ((x + dx) < 0 || (y + dy) < 0)
            throw new BadPointException();
        x += dx; y += dy;
    }
}

A different compile-time error now occurs, because the body of the method move cannot throw a checked exception, namely BadPointException, that does not appear in the throws clause for move.


8.5 Static Initializers

Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

StaticInitializer:

    static Block

It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.5) with a checked exception (§11.2).

The static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. This restriction is designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:

class Z {
    static int i = j + 2;
    static int j = 4;
}

and:

class Z {
    static { i = j + 2; }
    static int i, j;
    static { j = 4; }
}

result in compile-time errors.

Accesses to class variables by methods are not checked in this way, so:

class Z {
    static int peek() { return j; }

    static int i = peek();
    static int j = 1;
}

class Test {
    public static void main(String[] args) {
        System.out.println(Z.i);
    }

}

produces the output:

0

because the variable initializer for i uses the class method peek to access the value of the variable j before j has been initialized by its variable initializer, at which point it still has its default value (§4.5.4).

If a return statement (§14.15) appears anywhere within a static initializer, then a compile-time error occurs.

If the keyword this (§15.7.2) or the keyword super (§15.10, §15.11) appears anywhere within a static initializer, then a compile-time error occurs.


8.6 Constructor Declarations

The constructor of wharves, bridges, piers, bulk-heads,
floats, stays against the sea . . .
—Walt Whitman, Song of the Broad-Axe (1856)

A constructor is used in the creation of an object that is an instance of a class:

ConstructorDeclaration:

    ConstructorModifiersopt ConstructorDeclarator

        Throwsopt ConstructorBody

ConstructorDeclarator:

    SimpleTypeName ( FormalParameterListopt )

The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs. In all other respects, the constructor declaration looks just like a method declaration that has no result type.

Here is a simple example:

class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}

Constructors are invoked by class instance creation expressions (§15.8), by the newInstance method of class Class (§20.3), by the conversions and concatenations caused by the string concatenation operator + (§15.17.1), and by explicit constructor invocations from other constructors (§8.6.5). Constructors are never invoked by method invocation expressions (§15.11).

Access to constructors is governed by access modifiers (§6.6). This is useful, for example, in preventing instantiation by declaring an inaccessible constructor (§8.6.8).

Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.


8.6.1 Formal Parameters

The formal parameters of a constructor are identical in structure and behavior to the formal parameters of a method (§8.4.1).


8.6.2 Constructor Signature

The signature of a constructor is identical in structure and behavior to the signature of a method (§8.4.2).


8.6.3 Constructor Modifiers

ConstructorModifiers:

    ConstructorModifier

    ConstructorModifiers ConstructorModifier

ConstructorModifier: one of

    public protected private

The access modifiers public, protected, and private are discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in a constructor declaration, or if a constructor declaration has more than one of the access modifiers public, protected, and private.

Unlike methods, a constructor cannot be abstract, static, final, native, or synchronized. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static. There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of native constructors is an arbitrary language design choice that makes it easy for an implementation of the Java Virtual Machine to verify that superclass constructors are always properly invoked during object creation.


8.6.4 Throws

The throws clause for a constructor is identical in structure and behavior to the throws clause for a method (§8.4.4).


8.6.5 Constructor Body

The first statement of a constructor body may be an explicit invocation of another constructor of the same class, written as this followed by a parenthesized argument list, or an explicit invocation of a constructor of the direct superclass, written as super followed by a parenthesized argument list.

ConstructorBody:

    { ExplicitConstructorInvocationopt BlockStatementsopt }

ExplicitConstructorInvocation:

    this ( ArgumentListopt ) ;

    super ( ArgumentListopt ) ;

It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.

If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.

Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (§8.4.5). A return statement (§14.15) may be used in the body of a constructor if it does not include an expression.

In the example:

class Point {

    int x, y;

    Point(int x, int y) { this.x = x; this.y = y; }

}

class ColoredPoint extends Point {

    static final int WHITE = 0, BLACK = 1;

    int color;

    ColoredPoint(int x, int y) {
        this(x, y, WHITE);
    }

    ColoredPoint(int x, int y, int color) {
        super(x, y);

        this.color = color;

    }

}

the first constructor of ColoredPoint invokes the second, providing an additional argument; the second constructor of ColoredPoint invokes the constructor of its superclass Point, passing along the coordinates.

An explicit constructor invocation statement may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs. For example, if the first constructor of ColoredPoint in the example above were changed to:

    ColoredPoint(int x, int y) {
        this(x, y, color);
    }

then a compile-time error would occur, because an instance variable cannot be used within a superclass constructor invocation.

An invocation of the constructor of the direct superclass, whether it actually appears as an explicit constructor invocation statement or is provided automatically (§8.6.7), performs an additional implicit action after a normal return of control from the constructor: all instance variables that have initializers are initialized at that time, in the textual order in which they appear in the class declaration. An invocation of another constructor in the same class using the keyword this does not perform this additional implicit action.

§12.5 describes the creation and initialization of new class instances.


8.6.6 Constructor Overloading

Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (§15.8).


8.6.7 Default Constructor

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

  • If the class being declared is the primordial class Object, then the default constructor has an empty body.
  • Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.

A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have a constructor that takes no arguments.

If the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); otherwise, the default constructor has the default access implied by no access modifier. Thus, the example:

public class Point {
    int x, y;
}

is equivalent to the declaration:

public class Point {
    int x, y;
    public Point() { super(); }
}

where the default constructor is public because the class Point is public.


8.6.8 Preventing Instantiation of a Class

A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of an implicit constructor, and declaring all constructors to be private. A public class can likewise prevent the creation of instances outside its package by declaring at least one constructor, to prevent creation of a default constructor with public access, and declaring no constructor that is public.

Thus, in the example:

class ClassOnly {
    private ClassOnly() { }
    static String just = "only the lonely";
}

the class ClassOnly cannot be instantiated, while in the example:

package just;

public class PackageOnly {
    PackageOnly() { }
    String[] justDesserts = { "cheesecake", "ice cream" };
}

the class PackageOnly can be instantiated only within the package just, in which it is declared.

Bow, bow, ye lower middle classes!
Bow, bow, ye tradesmen, bow, ye masses!
Blow the trumpets, bang the brasses!
Tantantara! Tzing! Boom!
—W.S. Gilbert, Iolanthe


 9. Interfaces

CHAPTER 9

Interfaces

My apple trees will never get across
And eat the cones under his pines, I tell him.
He only says "Good Fences Make Good Neighbors."
—Robert Frost, Mending Wall (1914)

An interface declaration introduces a new reference type whose members are constants and abstract methods. This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.

Java programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to Object.

An interface may be declared to be an direct extension of one or more other interfaces, meaning that it implicitly specifies all the abstract methods and constants of the interfaces it extends, except for any constants that it may hide.

A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.

A variable whose declared type is an interface type may have as its value a reference to any object that is an instance of a class declared to implement the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.


9.1 Interface Declarations

An interface declaration specifies a new reference type:

InterfaceDeclaration:

    InterfaceModifiersopt interface Identifier

        ExtendsInterfacesopt InterfaceBody

A compile-time error occurs if the Identifier naming an interface appears as the name of any other class or interface in the same package. A compile-time error also occurs if the Identifier naming an interface appears as the name by which a class or interface is to be known via a single-type-import declaration (§7.5.1) in the compilation unit containing the interface declaration. In the example:

class Point { int x, y; }

interface Point { void move(int dx, int dy); }

a compile-time error occurs because a class and an interface in the same package cannot have the same name.


9.1.1 Scope of an Interface Type Name

The Identifier specifies the name of the interface and has as its scope the entire package in which it is declared. This is the same scoping rule as for class type names; see §8.1.1 for an example involving classes.


9.1.2 Interface Modifiers

An interface declaration may be preceded by interface modifiers:

InterfaceModifiers:

    InterfaceModifier

    InterfaceModifiers InterfaceModifier

InterfaceModifier: one of

    public abstract

The access modifier public is discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in an interface declaration.

9.1.2.1 abstract Interfaces

Every interface is implicitly abstract. This modifier is obsolete and should not be used in new Java programs.


9.1.3 Superinterfaces

If an extends clause is provided, then the interface being declared extends each of the other named interfaces and therefore inherits the methods and constants of each of the other named interfaces. These other named interfaces are the direct superinterfaces of the interface being declared. Any class that implements the declared interface is also considered to implement all the interfaces that this interface extends and that are accessible to the class.

ExtendsInterfaces:

    extends InterfaceType

    ExtendsInterfaces , InterfaceType

The following is repeated from §4.3 to make the presentation here clearer:

InterfaceType:

    TypeName

Each InterfaceType in the extends clause of an interface declaration must name an accessible interface type; otherwise a compile-time error occurs.

A compile-time error occurs if there is a circularity such that an interface directly or indirectly extends itself.

There is no analogue of the class Object for interfaces; that is, while every class is an extension of class Object, there is no single interface of which all interfaces are extensions.

The superinterface relationship is the transitive closure of the direct superinterface relationship. An interface K is a superinterface of interface I if either of the following is true:

  • K is a direct superinterface of I.
  • There exists an interface J such that K is a superinterface of J, and J is a superinterface of I, applying this definition recursively.

Interface I is said to be a subinterface of interface K whenever K is a superinterface of I.


9.1.4 Interface Body and Member Declarations

The body of an interface may declare members of the interface:

InterfaceBody:

    { InterfaceMemberDeclarationsopt }

InterfaceMemberDeclarations:

    InterfaceMemberDeclaration

    InterfaceMemberDeclarations InterfaceMemberDeclaration

InterfaceMemberDeclaration:

    ConstantDeclaration

    AbstractMethodDeclaration

The scope of the name of a member declared in an interface type is the entire body of the interface type declaration.


9.1.5 Access to Interface Member Names

All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public and the package containing the interface is accessible as described in §7.1.


9.2 Interface Members

The members of an interface are those members inherited from direct superinterfaces and those members declared in the interface.

The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields that it hides and methods that it overrides.


9.3 Field (Constant) Declarations

The materials of action are variable,
but the use we make of them should be constant.
—Epictetus (circa 60 A.D.), translated by Thomas Wentworth Higginson

ConstantDeclaration:

    ConstantModifiers Type VariableDeclarator

ConstantModifiers: one of

    public static final

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted, but strongly discouraged as a matter of style, to redundantly specify any or all of these modifiers for such fields.

A constant declaration in an interface must not include any of the modifiers synchronized, transient, or volatile, or a compile-time error occurs.

It is possible for an interface to inherit more than one field with the same name (§8.3.3.3). Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to either field by its simple name will result in a compile-time error, because such a reference is ambiguous.

There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.


9.3.1 Initialization of Fields in Interfaces

Every field in the body of an interface must have an initialization expression, which need not be a constant expression. The variable initializer is evaluated and the assignment performed exactly once, when the interface is initialized (§12.4).

A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface. Thus:

interface Test {
    float f = j;
    int j = 1;
    int k = k+1;
}

causes two compile-time errors, because j is referred to in the initialization of f before j is declared and because the initialization of k refers to k itself.

(One subtlety here is that, at run time, fields that are initialized with compile-time constant values are initialized first. This applies also to static final fields in classes (§8.3.2.1). This means, in particular, that these fields will never be observed to have their default initial values (§4.5.4), even by devious programs. See §12.4.2 and §13.4.8 for more discussion.)

If the keyword this (§15.7.2) or the keyword super (15.10.2, 15.11) occurs in an initialization expression for a field of an interface, then a compile-time error occurs.


9.3.2 Examples of Field Declarations

The following example illustrates some (possibly subtle) points about field declarations.

9.3.2.1 Ambiguous Inherited Fields

If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error. Thus in the example:

interface BaseColors {
    int RED = 1, GREEN = 2, BLUE = 4;
}

interface RainbowColors extends BaseColors {
    int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
}

interface PrintColors extends BaseColors {
    int YELLOW = 8, CYAN = 16, MAGENTA = 32;
}

interface LotsOfColors extends RainbowColors, PrintColors {
    int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
}

the interface LotsOfColors inherits two fields named YELLOW. This is all right as long as the interface does not contain any reference by simple name to the field YELLOW. (Such a reference could occur within a variable initializer for a field.)

Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous.

9.3.2.2 Multiply Inherited Fields

If a single field is inherited multiple times from the same interface because, for example, both this interface and one of this interface's direct superinterfaces extend the interface that declares the field, then only a single member results. This situation does not in itself cause a compile-time error.

In the example in the previous section, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved.


9.4 Abstract Method Declarations

AbstractMethodDeclaration:

    AbstractMethodModifiersopt ResultType MethodDeclarator Throwsopt ;

AbstractMethodModifiers:

    AbstractMethodModifier

    AbstractMethodModifiers AbstractMethodModifier

AbstractMethodModifier: one of

    public abstract

The access modifier public is discussed in §6.6. A compile-time error occurs if the same modifier appears more than once in an abstract method declaration.

Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block. For compatibility with older versions of Java, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

Every method declaration in the body of an interface is implicitly public. It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because in Java static methods cannot be abstract.

Note that a method declared in an interface must not be declared native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared native or synchronized in a class that implements the interface.

Note that a method declared in an interface must not be declared final or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared final in a class that implements the interface.


9.4.1 Inheritance and Overriding

If the interface declares a method, then the declaration of that method is said to override any and all methods with the same signature in the superinterfaces of the interface that would otherwise be accessible to code in this interface.

If a method declaration in an interface overrides the declaration of a method in another interface, a compile-time error occurs if the methods have different return types or if one has a return type and the other is void. Moreover, a method declaration must not have a throws clause that conflicts (§8.4.4) with that of any method that it overrides; otherwise, a compile-time error occurs.

Methods are overridden on a signature-by-signature basis. If, for example, an interface declares two public methods with the same name, and a subinterface overrides one of them, the subinterface still inherits the other method.

An interface inherits from its direct superinterfaces all methods of the superinterfaces that are not overridden by a declaration in the interface.

It is possible for an interface to inherit more than one method with the same signature (§8.4.2). Such a situation does not in itself cause a compile-time error. The interface is considered to inherit all the methods. However, a compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is void. (The throws clauses do not cause errors in this case.)

There might be several paths by which the same method declaration is inherited from an interface. This fact causes no difficulty and never of itself results in a compile-time error.


9.4.2 Overloading

If two methods of an interface (whether both declared in the same interface, or both inherited by a interface, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.


9.4.3 Examples of Abstract Method Declarations

The following examples illustrate some (possibly subtle) points about abstract method declarations.

9.4.3.1 Example: Overriding

Methods declared in interfaces are abstract and thus contain no implementation. About all that can be accomplished by an overriding method declaration, other than to affirm a method signature, is to restrict the exceptions that might be thrown by an implementation of the method. Here is a variation of the example shown in §8.4.3.1:

class BufferEmpty extends Exception {
    BufferEmpty() { super(); }
    BufferEmpty(String s) { super(s); }
}

class BufferError extends Exception {
    BufferError() { super(); }
    BufferError(String s) { super(s); }
}

public interface Buffer {
    char get() throws BufferEmpty, BufferError;
}

public interface InfiniteBuffer extends Buffer {
     char get() throws BufferError;												// override
}

9.4.3.2 Example: Overloading

In the example code:

interface PointInterface {
    void move(int dx, int dy);
}

interface RealPointInterface extends PointInterface {
    void move(float dx, float dy);
    void move(double dx, double dy);
}

the method name move is overloaded in interface RealPointInterface with three different signatures, two of them declared and one inherited. Any class that implements interface RealPointInterface must provide implementations of all three method signatures.

Death, life, and sleep, reality and thought,
Assist me, God, their boundaries to know . . .
—William Wordsworth, Maternal Grief


 10. Arrays

CHAPTER 10

Arrays

Even Solomon in all his glory was not arrayed like one of these.
—Matthew 6:29

Java arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to [image], inclusive.

All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.

There is one situation in which an element of an array can be an array: if the element type is Object, then some or all of the elements may be arrays, because any array object can be assigned to any variable of type Object.


10.1 Array Types

An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. An array's length is not part of its type.

The element type of an array may be any type, whether primitive or reference. In particular:

  • Arrays with an interface type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any class type that implements the interface.
  • Arrays with an abstract class type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any subclass of the abstract class that is not itself abstract.

Array types are used in declarations and in cast expressions (§15.15).


10.2 Array Variables

A variable of array type holds a reference to an object. Declaring a variable of array type does not create an array object or allocate any space for array components. It creates only the variable itself, which can contain a reference to an array. However, the initializer part of a declarator (§8.3) may create an array, a reference to which then becomes the initial value of the variable.

Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.

Here are examples of declarations of array variables that do not create arrays:

int[] ai;							// array of int
short[][] as;							// array of array of short
Object[]			ao,				// array of Object
            otherAo;				// array of Object
short		s,					// scalar short
        aas[][];					// array of array of short

Here are some examples of declarations of array variables that create array objects:

Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
                 'S', 't', 'r', 'i', 'n', 'g' };
String[] aas = { "array", "of", "String", };

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see §10.10 for a discussion.


10.3 Array Creation

An array is created by an array creation expression (§15.9) or an array initializer (§10.6).

An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable length.

An array initializer creates an array and provides initial values for all its components. (Contrast this with C and C++, where it is possible for an array initializer to specify initial values for some but not all of the components of an array.)


10.4 Array Access

A component of an array is accessed by an array access expression (§15.12) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i]. All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error.

All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an IndexOutOfBoundsException to be thrown.


10.5 A Simple Example

The example:

class Gauss {
    public static void main(String[] args) {
        int[] ia = new int[101];
        for (int i = 0; i < ia.length; i++)
            ia[i] = i;
        int sum = 0;
        for (int i = 0; i < ia.length; i++)
            sum += ia[i];
        System.out.println(sum);
    }
}

that produces output:

5050

declares a variable ia that has type array of int, that is, int[]. The variable ia is initialized to reference a newly created array object, created by an array creation expression (§15.9). The array creation expression specifies that the array should have 101 components. The length of the array is available using the field length, as shown.

The example program fills the array with the integers from 0 to 100, sums these integers, and prints the result.


10.6 Arrays Initializers

An array initializer may be specified in a declaration, creating an array and providing some initial values:

ArrayInitializer:

    { VariableInitializersopt ,opt }

VariableInitializers:

    VariableInitializer

    VariableInitializers , VariableInitializer

The following is repeated from §8.3 to make the presentation here clearer:

VariableInitializer:

    Expression

    ArrayInitializer

An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".

The length of the constructed array will equal the number of expressions.

Each expression specifies a value for one array component. Each expression must be assignment-compatible (§5.2) with the array's component type, or a compile-time error results.

If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.

A trailing comma may appear after the last expression in an array initializer and is ignored.

As an example:

class Test {
    public static void main(String[] args) {
        int ia[][] = { {1, 2}, null };
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                System.out.println(ia[i][j]);
    }
}

prints:

1
2

before causing a NullPointerException in trying to index the second component of the array ia, which is a null reference.


10.7 Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array (length may be positive or zero)
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method

An array thus has the same methods as the following class:

class A implements Cloneable {
    public final int length = X;
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e.getMessage());
        }
    }

}

Every array implements interface Cloneable. That arrays are cloneable is shown by the test program:

class Test {
    public static void main(String[] args) {
        int ia1[] = { 1, 2 };
        int ia2[] = (int[])ia1.clone();
        System.out.print((ia1 == ia2) + " ");
        ia1[1]++;
        System.out.println(ia2[1]);
    }
}

which prints:

false 2

showing that the components of the arrays referenced by ia1 and ia2 are different variables. (In some early implementations of Java this example failed to compile because the compiler incorrectly believed that the clone method for an array could throw a CloneNotSupportedException.)

A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, as shown by the example program:

class Test {
    public static void main(String[] args) throws Throwable {
        int ia[][] = { { 1 , 2}, null };
        int ja[][] = (int[][])ia.clone();
        System.out.print((ia == ja) + " ");
        System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
    }
}

which prints:

false true

showing that the int[] array that is ia[0] and the int[] array that is ja[0] are the same array.


10.8 Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the same component type. The superclass of an array type is considered to be Object, as shown by the following example code:

class Test {
    public static void main(String[] args) {
        int[] ia = new int[3];
        System.out.println(ia.getClass());
        System.out.println(ia.getClass().getSuperclass());
    }
}

which prints:

class [I
class java.lang.Object

where the string "[I" is the run-time type signature for the class object "array with component type int" (§20.1.1).


10.9 An Array of Characters is Not a String

In Java, unlike C, an array of char is not a String (§20.12), and neither a String nor an array of char is terminated by '\u0000' (the NUL character).

A Java String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters (§20.13).


10.10 Array Store Exception

If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A.

Thus, the example:

class Point { int x, y; }

class ColoredPoint extends Point { int color; }

class Test {
    public static void main(String[] args) {
        ColoredPoint[] cpa = new ColoredPoint[10];
        Point[] pa = cpa;
        System.out.println(pa[1] == null);
        try {
            pa[0] = new Point();
        } catch (ArrayStoreException e) {
            System.out.println(e);
        }
    }
}

produces the output:

true
java.lang.ArrayStoreException

Here the variable pa has type Point[] and the variable cpa has as its value a reference to an object of type ColoredPoint[]. A ColoredPoint can be assigned to a Point; therefore, the value of cpa can be assigned to pa.

A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.

On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint.

Java checks for such a situation at run-time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown. More formally: an assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.

At length burst in the argent revelry,
With plume, tiara, and all rich array . . .
—John Keats, The Eve of St. Agnes (1819)


 11. Exceptions

CHAPTER 11

Exceptions

If anything can go wrong, it will.
—Finagle's Law (often incorrectly attributed to Murphy, whose law is
rather different—which only goes to show that Finagle was right)

When a Java program violates the semantic constraints of the Java language, a Java Virtual Machine signals this error to the program as an exception. An example of such a violation is an attempt to index outside the bounds of an array. Some programming languages and their implementations react to such errors by peremptorily terminating the program; other programming languages allow an implementation to react in an arbitrary or unpredictable way. Neither of these approaches is compatible with the design goals of Java: to provide portability and robustness. Instead, Java specifies that an exception will be thrown when semantic constraints are violated and will cause a non-local transfer of control from the point where the exception occurred to a point that can be specified by the programmer. An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Java programs can also throw exceptions explicitly, using throw statements (§14.16). This provides an alternative to the old-fashioned style of handling error conditions by returning funny values, such as the integer value -1 where a negative value would not normally be expected. Experience shows that too often such funny values are ignored or not checked for by callers, leading to programs that are not robust, exhibit undesirable behavior, or both.

Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. Handlers are established by catch clauses of try statements (§14.18). During the process of throwing an exception, a Java Virtual Machine abruptly completes, one by one, any expressions, statements, method and constructor invocations, static initializers, and field initialization expressions that have begun but not completed execution in the current thread. This process continues until a handler is found that indicates that it handles that particular exception by naming the class of the exception or a superclass of the class of the exception. If no such handler is found, then the method uncaughtException (§20.21.31) is invoked for the ThreadGroup that is the parent of the current thread-thus every effort is made to avoid letting an exception go unhandled.

The Java exception mechanism is integrated with the Java synchronization model (§17), so that locks are released as synchronized statements (§14.17) and invocations of synchronized methods (§8.4.3.5, §15.11) complete abruptly.

This chapter describes the different causes of exceptions (§11.1). It details how exceptions are checked at compile time (§11.2) and processed at run time (§11.3). A detailed example (§11.4) is then followed by an explanation of the exception hierarchy and the standard exception classes (§11.5).


11.1 The Causes of Exceptions

If we do not succeed, then we run the risk of failure.
—J. Danforth Quayle (1990)

An exception is thrown for one of three reasons:

  • An abnormal execution condition was synchronously detected by a Java Virtual Machine. Such conditions arise because:
    • evaluation of an expression violates the normal semantics of the Java language, such as an integer divide by zero, as summarized in §15.5
    • an error occurs in loading or linking part of the Java program (§12.2, §12.3)
    • some limitation a resource is exceeded, such as using too much memory

These exceptions are not thrown at an arbitrary point in the program, but rather at a point where they are specified as a possible result of an expression evaluation or statement execution.

  • A throw statement (§14.16) was executed in Java code.
  • An asynchronous exception occurred either because:
    • the method stop of class Thread (§20.20.16) was invoked
    • an internal error has occurred in the virtual machine (§11.5.2.2)

Exceptions are represented by instances of the class Throwable and instances of its subclasses. These classes are, collectively, the exception classes.


11.2 Compile-Time Checking of Exceptions

The Java language checks, at compile time, that a Java program contains handlers for checked exceptions, by analyzing which checked exceptions can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.4) or constructor (§8.6.4) must mention the class of that exception or one of the superclasses of the class of that exception. This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled.

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The standard Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by Java programmers. See §11.5 for a description of the Java exception class hierarchy and the exception classes defined by the standard Java API and Java Virtual Machine.

The checked exception classes named in the throws clause are part of the contract between the implementor and user of the method or constructor. The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw. When interfaces are involved, more than one method declaration may be overridden by a single overriding declaration. In this case, the overriding declaration must have a throws clause that is compatible with all the overridden declarations (§9.4).

Variable initializers for fields (§8.3.2) and static initializers (§8.5) must not result in a checked exception; if one does, a compile-time error occurs.


11.2.1 Why Errors are Not Checked

Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A Java program declaring such exceptions would be cluttered, pointlessly.


11.2.2 Why Runtime Exceptions are Not Checked

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of Java, having to declare such exceptions would not aid significantly in establishing the correctness of Java programs. Many of the operations and constructs of the Java language can result in runtime exceptions. The information available to a Java compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such runtime exceptions cannot occur, even though this may be obvious to the Java programmer. Requiring such exception classes to be declared would simply be an irritation to Java programmers.

For example, certain code might implement a circular data structure that, by construction, can never involve null references; the programmer can then be certain that a NullPointerException cannot occur, but it would be difficult for a compiler to prove it. The theorem-proving technology that is needed to establish such global properties of data structures is beyond the scope of this Java Language Specification.


11.3 Handling of an Exception

When an exception is thrown, control is transferred from the code that caused the exception to the nearest dynamically-enclosing catch clause of a try statement (§14.18) that handles the exception.

A statement or expression is dynamically enclosed by a catch clause if it appears within the try block of the try statement of which the catch clause is a part, or if the caller of the statement or expression is dynamically enclosed by the catch clause.

The caller of a statement or expression depends on where it occurs:

  • If within a method, then the caller is the method invocation expression (§15.11) that was executed to cause the method to be invoked.
  • If within a constructor or the initializer for an instance variable, then the caller is the class instance creation expression (§15.8) or the method invocation of newInstance that was executed to cause an object to be created.
  • If within a static initializer or an initializer for a static variable, then the caller is the expression that used the class or interface so as to cause it to be initialized.

Whether a particular catch clause handles an exception is determined by comparing the class of the object that was thrown to the declared type of the parameter of the catch clause. The catch clause handles the exception if the type of its parameter is the class of the exception or a superclass of the class of the exception. Equivalently, a catch clause will catch any exception object that is an instanceof (§15.19.2) the declared parameter type.

The control transfer that occurs when an exception is thrown causes abrupt completion of expressions (§15.5) and statements (§14.1) until a catch clause is encountered that can handle the exception; execution then continues by executing the block of that catch clause. The code that caused the exception is never resumed.

If no catch clause handling an exception can be found, then the current thread (the thread that encountered the exception) is terminated, but only after all finally clauses have been executed and the method uncaughtException (§20.21.31) has been invoked for the ThreadGroup that is the parent of the current thread.

In situations where it is desirable to ensure that one block of code is always executed after another, even if that other block of code completes abruptly, a try statement with a finally clause (§14.18.2) may be used. If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found. If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.

The exact rules for abrupt completion and for the catching of exceptions are specified in detail with the specification of each statement in §14 and for expressions in §15 (especially §15.5).


11.3.1 Exceptions are Precise

Exceptions in Java are precise: when the transfer of control takes place, all effects of the statements executed and expressions evaluated before the point from which the exception is thrown must appear to have taken place. No expressions, statements, or parts thereof that occur after the point from which the exception is thrown may appear to have been evaluated. If optimized code has speculatively executed some of the expressions or statements which follow the point at which the exception occurs, such code must be prepared to hide this speculative execution from the user-visible state of the Java program.


11.3.2 Handling Asynchronous Exceptions

Most exceptions in Java occur synchronously as a result of an action by the thread in which they occur, and at a point in the Java program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a Java program.

Asynchronous exceptions are rare in Java. They occur only as a result of:

  • An invocation of the stop methods of class Thread (§20.20.15, §20.20.16) or ThreadGroup (§20.21.8, §20.21.9)
  • An InternalError (§11.5.2.2) in the Java Virtual Machine

The stop methods may be invoked by one thread to affect another thread or all the threads in a specified thread group. They are asynchronous because they may occur at any point in the execution of the other thread or threads. An InternalError is considered asynchronous so that it may be handled using the same mechanism that handles the stop method, as will now be described.

Java permits a small but bounded amount of execution to occur before an asynchronous exception is thrown. This delay is permitted to allow optimized code to detect and throw these exceptions at points where it is practical to handle them while obeying the semantics of the Java language.

A simple implementation might poll for asynchronous exceptions at the point of each control transfer instruction. Since a Java program has a finite size, this provides a bound on the total delay in detecting an asynchronous exception. Since no asynchronous exception will occur between control transfers, the code generator has some flexibility to reorder computation between control transfers for greater performance.

The paper Polling Efficiently on Stock Hardware by Mark Feeley, Proc. 1993 Conference on Functional Programming and Computer Architecture, Copenhagen, Denmark, pp. 179-187, is recommended as further reading.

Like all exceptions, asynchronous exceptions are precise (§11.3.1).


11.4 An Example of Exceptions

Consider the following example:

class TestException extends Exception {

    TestException() { super(); }

    TestException(String s) { super(s); }

}

class Test {

    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {

            try {
                thrower(args[i]);
                System.out.println("Test \"" + args[i] +
                    "\" didn't throw an exception");
            } catch (Exception e) {
                System.out.println("Test \"" + args[i] +
                    "\" threw a " + e.getClass() +
                    "\n        with message: " + e.getMessage());
            }
        }
    }

    static int thrower(String s) throws TestException {
        try {
            if (s.equals("divide")) {
                int i = 0;
                return i/i;
            }
            if (s.equals("null")) {
                s = null;
                return s.length();
            }
            if (s.equals("test"))
                throw new TestException("Test message");
            return 0;
        } finally {
            System.out.println("[thrower(\"" + s +
                    "\") done]");
        }
    }
}

If we execute the test program, passing it the arguments:

divide null not test

it produces the output:

[thrower("divide") done]
Test "divide" threw a class java.lang.ArithmeticException
        with message: / by zero
[thrower("null") done]
Test "null" threw a class java.lang.NullPointerException
        with message: null
[thrower("not") done]
Test "not" didn't throw an exception
[thrower("test") done]
Test "test" threw a class TestException
        with message: Test message

This example declares an exception class TestException. The main method of class Test invokes the thrower method four times, causing exceptions to be thrown three of the four times. The try statement in method main catches each exception that the thrower throws. Whether the invocation of thrower completes normally or abruptly, a message is printed describing what happened.

The declaration of the method thrower must have a throws clause because it can throw instances of TestException, which is a checked exception class (§11.2). A compile-time error would occur if the throws clause were omitted.

Notice that the finally clause is executed on every invocation of thrower, whether or not an exception occurs, as shown by the "[thrower(...) done]" output that occurs for each invocation.


11.5 The Exception Hierarchy

The possible exceptions in a Java program are organized in a hierarchy of classes, rooted at class Throwable (§20.22), a direct subclass of Object. The classes Exception and Error are direct subclasses of Throwable. The class RuntimeException is a direct subclass of Exception.

The exception classes declared by the standard packages java.lang, java.util, java.io and java.net are called the standard exception classes.

Java programs can use the pre-existing exception classes in throw statements, or define additional exception classes, as subclasses of Throwable or of any of its subclasses, as appropriate. To take advantage of Java's compile-time checking for exception handlers, it is typical to define most new exception classes as checked exception classes, specifically as subclasses of Exception that are not subclasses of RuntimeException.


11.5.1 The Classes Exception and RuntimeException

The class Exception is the superclass of all the exceptions that ordinary programs may wish to recover from.

11.5.1.1 Standard Runtime Exceptions

The class RuntimeException is a subclass of class Exception. The subclasses of RuntimeException are unchecked exception classes.

Package java.lang defines the following standard unchecked runtime exceptions, which, like all other classes in package java.lang, are implicitly imported and therefore may be referred to by their simple names:

  • ArithmeticException: An exceptional arithmetic situation has arisen, such as an integer division (§15.16.2) operation with a zero divisor.
  • ArrayStoreException: An attempt has been made to store into an array component a value whose class is not assignment compatible with the component type of the array (§10.10, §15.25.1).
  • ClassCastException: An attempt has been made to cast (§5.4, §15.15) a reference to an object to an inappropriate type.
  • IllegalArgumentException: A method was passed an invalid or inappropriate argument or invoked on an inappropriate object. Subclasses of this class include:
    • IllegalThreadStateException: A thread was not in an appropriate state for a requested operation.
    • NumberFormatException: An attempt was made to convert a String to a value of a numeric type, but the String did not have an appropriate format.
  • IllegalMonitorStateException: A thread has attempted to wait on (§20.1.6, §20.1.7, §20.1.8) or notify (§20.1.9, §20.1.10) other threads waiting on an object that it has not locked.
  • IndexOutOfBoundsException: Either an index of some sort (such as to an array, a string, or a vector) or a subrange, specified either by two index values or by an index and a length, was out of range.
  • NegativeArraySizeException: An attempt was made to create an array with a negative length (§15.9).
  • NullPointerException: An attempt was made to use a null reference in a case where an object reference was required.
  • SecurityException: A security violation was detected (§20.17).

Package java.util defines the following additional standard unchecked runtime exceptions:

  • java.util.EmptyStackException: An attempt was made to access an element of an empty stack.
  • java.util.NoSuchElementException: An attempt was made to access an element of an empty vector.

11.5.1.2 Standard Checked Exceptions

The standard subclasses of Exception other than RuntimeException are all checked exception classes.

Package java.lang defines the following standard exceptions, which, like all other classes in package java.lang, are implicitly imported and therefore may be referred to by their simple names:

  • ClassNotFoundException: A class or interface with a specified name could not be found (§20.3.8).
  • CloneNotSupportedException: The clone method (§20.1.5) of class Object has been invoked to clone an object, but the class of that object does not implement the Cloneable interface.
  • IllegalAccessException: An attempt has been made to load a class using a string giving its fully qualified name, but the currently executing method does not have access to the definition of the specified class because the class is not public and is in another package.
  • InstantiationException: An attempt was made to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface, is abstract, or is an array.
  • InterruptedException: The current thread was waiting, and another thread has interrupted the current thread, using the interrupt method of class Thread (§20.20.31).

Package java.io defines the following additional standard exceptions:

  • java.io.IOException: A requested I/O operation could not be completed normally. Subclasses of this class include:
    • java.io.EOFException: End of file has been encountered before normal completion of an input operation.
    • java.io.FileNotFoundException: A file with the name specified by a file name string or path was not found within the file system.
    • java.io.InterruptedIOException: The current thread was waiting for completion of an I/O operation, and another thread has interrupted the current thread, using the interrupt method of class Thread (§20.20.31).
    • java.io.UTFDataFormatException: A requested conversion of a string to or from Java modified UTF-8 format could not be completed (§22.1.15, §22.2.14) because the string was too long or because the purported UTF-8 data was not the result of encoding a Unicode string into UTF-8.

The standard package java.net defines the following additional subclasses of java.io.IOException:

u java.net.MalformedURLException: A string that was provided as a URL, or as part of a URL, had an inappropriate format or specified an unknown protocol.

    • java.net.ProtocolException: Some aspect of a network protocol was not correctly carried out.
    • java.net.SocketException: An operation involving a socket could not be completed normally.
    • java.net.UnknownHostException: The name of a network host could not be resolved to a network address.
    • java.net.UnknownServiceException: The network connection cannot support the requested service.


11.5.2 The Class Error

The class Error and its standard subclasses are exceptions from which ordinary programs are not ordinarily expected to recover. The class Error is a separate subclass of Throwable, distinct from Exception in the class hierarchy, to allow programs to use the idiom:

} catch (Exception e) {

to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible.

Package java.lang defines all the error classes described here. These classes, like all other classes in package java.lang, are implicitly imported and therefore may be referred to by their simple names.

11.5.2.1 Loading and Linkage Errors

A Java Virtual Machine throws an object that is an instance of a subclass of LinkageError when a loading, linkage, preparation, verification or initialization error occurs:

  • The loading process is described in §12.2. The errors ClassFormatError, ClassCircularityError, and NoClassDefFoundError are described there.
  • The linking process is described in §12.3. The linking errors are described there. These errors include IllegalAccessError, InstantiationError, NoSuchFieldError, and NoSuchMethodError, all of which are subclasses of IncompatibleClassChangeError, and, also, UnsatisfiedLinkError.
  • The class verification process is described in §12.3.1. The verification failure error VerifyError is described there.
  • The class preparation process is described in §12.3.2. The preparation error described there is AbstractMethodError.
  • The class initialization process is described in §12.4. A virtual machine will throw the error ExceptionInInitializerError if execution of a static initializer or of an initializer for a static field results in an exception that is not an Error or a subclass of Error.

11.5.2.2 Virtual Machine Errors

A Java Virtual Machine throws an object that is an instance of a subclass of the class VirtualMachineError when an internal error or resource limitation prevents it from implementing the semantics of the Java Language. This language specification and the Java Virtual Machine Specification define the following virtual machine errors:

  • InternalError: An internal error has occurred in a Java Virtual Machine, because of a fault in the software implementing the virtual machine, a fault in the underlying host system software, or a fault in the hardware. This error is delivered asynchronously when it is detected, and may occur at any point in a Java program.
  • OutOfMemoryError: A Java Virtual Machine has run out of either virtual or physical memory, and the automatic storage manager wasn't able to reclaim enough memory to satisfy an object creation request.
  • StackOverflowError: A Java Virtual Machine has run out of stack space for a thread, typically because the thread is doing an unbounded number of recursive invocations due to a fault in the executing program.
  • UnknownError: An exception or error has occurred but, for some reason, a Java Virtual Machine is unable to report the actual exception or error.

A sophisticated Java program may be designed to handle OutOfMemoryError and attempt to recover from it, perhaps by carefully dropping references to objects.

We are exploring enhancements to Java to simplify handling of out-of-memory conditions. One possibility would be to support automatic suspension of a thread which encounters an OutOfMemoryError and allow another thread to handle the error situation. Such a technique might also permit a Java program to recover from a StackOverflowError if this overflow does not result from a nonterminating recursion. Suggestions for other approaches are welcomed.

No rule is so general, which admits not some exception.
—Robert Burton (1576-1640)


 12. Execution

CHAPTER 12

Execution

We must all hang together, or assuredly we shall all hang separately.
—Benjamin Franklin (July 4, 1776)

This chapter specifies activities that occur during execution of a Java program. It is organized around the life cycle of a Java Virtual Machine and of the classes, interfaces, and objects that form a Java program.

A Java Virtual Machine starts up by loading a specified class and then invoking the method main in this specified class. Section §12.1 outlines the loading, linking, and initialization steps involved in executing main, as an introduction to the concepts in this chapter. Further sections specify the details of loading (§12.2), linking (§12.3), and initialization (§12.4).

The chapter continues with a specification of the procedures for creation of new class instances (§12.5); finalization of class instances (§12.6); and finalization of classes (§12.7). It concludes by describing the unloading of classes (§12.8) and the procedure followed when a virtual machine exits (§12.9).


12.1 Virtual Machine Start-Up

A Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings. In the examples in this specification, this first class is typically called Test.

The manner in which the initial class is specified to the Java Virtual Machine is beyond the scope of this specification, but it is typical, in host environments that use command lines, for the fully-qualified name of the class to be specified as a command-line argument and for following command-line arguments to be used as strings to be provided as the argument to the method main. For example, in a UNIX implementation, the command line:

java Test reboot Bob Dot Enzo

will typically start a Java Virtual Machine by invoking method main of class Test (a class in an unnamed package), passing it an array containing the four strings "reboot", "Bob", "Dot", and "Enzo".

We now outline the steps the virtual machine may take to execute Test, as an example of the loading, linking, and initialization processes that are described further in later sections.


12.1.1 Load the Class Test

The initial attempt to execute the method main of class Test discovers that the class Test is not loaded-that is, that the virtual machine does not currently contain a binary representation for this class. The virtual machine then uses a class loader (§20.14) to attempt to find such a binary representation. If this process fails, then an error is thrown. This loading process is described further in §12.2.


12.1.2 Link Test: Verify, Prepare, (Optionally) Resolve

After Test is loaded, it must be initialized before main can be invoked. And Test, like all (class or interface) types, must be linked before it is initialized. Linking involves verification, preparation and (optionally) resolution. Linking is described further in §12.3.

Verification checks that the loaded representation of Test is well-formed, with a proper symbol table. Verification also checks that the code that implements Test obeys the semantic requirements of Java and the Java Virtual Machine. If a problem is detected during verification, then an error is thrown. Verification is described further in §12.3.1.

Preparation involves allocation of static storage and any data structures that are used internally by the virtual machine, such as method tables. If a problem is detected during preparation, then an error is thrown. Preparation is described further in §12.3.2.

Resolution is the process of checking symbolic references from Test to other classes and interfaces, by loading the other classes and interfaces that are mentioned and checking that the references are correct.

The resolution step is optional at the time of initial linkage. An implementation may resolve symbolic references from a class or interface that is being linked very early, even to the point of resolving all symbolic references from the classes and interfaces that are further referenced, recursively. (This resolution may result in errors from these further loading and linking steps.) This implementation choice represents one extreme and is similar to the kind of "static" linkage that has been done for many years in simple implementations of the C language. (In these implementations, a compiled program is typically represented as an "a.out" file that contains a fully-linked version of the program, including completely resolved links to library routines used by the program. Copies of these library routines are included in the "a.out" file.)

An implementation may instead choose to resolve a symbolic reference only when it is actively used; consistent use of this strategy for all symbolic references would represent the "laziest" form of resolution. In this case, if Test had several symbolic references to another class, then the references might be resolved one at a time, as they are used, or perhaps not at all, if these references were never used during execution of the program.

The only requirement on when resolution is performed is that any errors detected during resolution must be thrown at a point in the program where some action is taken by the program that might, directly or indirectly, require linkage to the class or interface involved in the error. Using the "static" example implementation choice described above, loading and linkage errors could occur before the program is executed if they involved a class or interface mentioned in the class Test or any of the further, recursively referenced, classes and interfaces. In a system that implemented the "laziest" resolution, these errors would be thrown only when an incorrect symbolic reference is actively used.

The resolution process is described further in §12.3.3.


12.1.3 Initialize Test: Execute Initializers

In our continuing example, the virtual machine is still trying to execute the method main of class Test. This is an attempted active use (§12.4.1) of the class, which is permitted only if the class has been initialized.

Initialization consists of execution of any class variable initializers and static initializers of the class Test, in textual order. But before Test can be initialized, its direct superclass must be initialized, as well as the direct superclass of its direct superclass, and so on, recursively. In the simplest case, Test has Object as its implicit direct superclass; if class Object has not yet been initialized, then it must be initialized before Test is initialized. Class Object has no superclass, so the recursion terminates here.

If class Test has another class Super as its superclass, then Super must be initialized before Test. This requires loading, verifying, and preparing Super if this has not already been done and, depending on the implementation, may also involve resolving the symbolic references from Super and so on, recursively.

Initialization may thus cause loading, linking, and initialization errors, including such errors involving other types.

The initialization process is described further in §12.4.


12.1.4 Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must accept a single argument that is an array of strings.


12.2 Loading of Classes and Interfaces

Loading refers to the process of finding the binary form of a class or interface type with a particular name, perhaps by computing it on the fly, but more typically by retrieving a binary representation previously computed from source code by a compiler, and constructing, from that binary form, a Class object to represent the class or interface.

The binary format of a class or interface is normally the class file format described in The Java Virtual Machine, but other formats are possible, provided they meet the requirements specified in §13.1. The method defineClass (§20.14.3) of class ClassLoader may be used to construct Class objects from binary representations in the class file format.

A Java Virtual Machine system should maintain an internal table of classes and interfaces that have been loaded for the sake of resolving symbolic references. Each entry in the table should consist of a fully qualified class name (as a string), a class loader, and a Class object. Whenever a symbolic reference to a class or interface is to be resolved, a class loader is identified that is responsible for loading the class or interface, if necessary. The table should be consulted first, however; if it already contains an entry for that class name and class loader, then the class object in that entry should be used and no method of the class loader should be invoked. If the table contains no such entry, then the method loadClass (§20.14.2) of the class loader should be invoked, giving it the name of the class or interface. If and when it returns, the class object that it returns should be used to make a new entry in the table for that class name and class loader.

The purpose of this internal table is to allow the verification process (§12.3.1) to assume, for its purposes, that two classes or interfaces are the same if they have the same name and the same class loader. This property allows a class to be verified without loading all the classes and interfaces that it uses, whether actively or passively. Well-behaved class loaders do maintain this property: given the same name twice, a good class loader should return the same class object each time. But without the internal table, a malicious class loader could violate this property and undermine the security of the Java type system. A basic principle of the design of the Java language is that the type system cannot be subverted by code written in Java, not even by implementations of such otherwise sensitive system classes as ClassLoader (§20.14) and SecurityManager (§20.17).

An entry may be deleted from the internal table only after unloading (§12.8) the class or interface represented by the class object in the entry.


12.2.1 The Loading Process

The loading process is implemented by the class ClassLoader (§20.14) and its subclasses. Different subclasses of ClassLoader may implement different loading policies. In particular, a class loader may cache binary representations of classes and interfaces, prefetch them based on expected usage, or load a group of related classes together. These activities may not be completely transparent to a running Java application if, for example, a newly compiled version of a class is not found because an older version is cached by a class loader. It is the responsibility of a class loader, however, to reflect loading errors only at points in the program they could have arisen without prefetching or group loading.

If an error occurs during class loading, then an instance of one of the following subclasses of class LinkageError will be thrown at any point in the Java program that (directly or indirectly) uses the type:

  • ClassCircularityError: A class or interface could not be loaded because it would be its own superclass or superinterface (§13.4.4).
  • ClassFormatError: The binary data that purports to specify a requested compiled class or interface is malformed.
  • NoClassDefFoundError: No definition for a requested class or interface could be found by the relevant class loader.

Because loading involves the allocation of new data structures, it may fail with an OutOfMemoryError.


12.2.2 Implications for Code Generation

A cooperating class loader can enable a code generator to generate code for a group of class and interface types-perhaps an entire package-by loading the binary code for these types as a group. A format can be designed that allows all the internal symbolic references in such a group to be resolved, before the group is loaded. Such a strategy may also allow the generated code to be optimized before loading based on the known concrete types in the group. This approach may be useful in specific cases, but is discouraged as a general technique, since such a class file format is unlikely to be widely understood.


12.3 Linking of Classes and Interfaces

Linking is the process of taking a binary form of a class or interface type and combining it into the runtime state of the Java Virtual Machine, so that it can be executed. A class or interface type is always loaded before it is linked. Three different activities are involved in linking: verification, preparation, and resolution of symbolic references.

Java allows an implementation flexibility as to when linking activities (and, because of recursion, loading) take place, provided that the semantics of the language are respected, that a class or interface is completely verified and prepared before it is initialized, and that errors detected during linkage are thrown at a point in the program where some action is taken by the program that might require linkage to the class or interface involved in the error.

For example, an implementation may choose to resolve each symbolic reference in a class or interface individually, only when it is used (lazy or late resolution), or to resolve them all at once while the class is being verified (static resolution). This means that the resolution process may continue, in some implementations, after a class or interface has been initialized.

Because linking involves the allocation of new data structures, it may fail with an OutOfMemoryError.


12.3.1 Verification of the Binary Representation

Verification ensures that the binary representation of a class or interface is structurally correct. For example, it checks that every instruction has a valid operation code; that every branch instruction branches to the start of some other instruction, rather than into the middle of an instruction; that every method is provided with a structurally correct signature; and that every instruction obeys the type discipline of the Java language.

For a more detailed description of the verification process, see the separate volume of this series, The Java Virtual Machine Specification.

If an error occurs during verification, then an instance of the following subclass of class LinkageError will be thrown at the point in the Java program that caused the class to be verified:

  • VerifyError: The binary definition for a class or interface failed to pass a set of required checks to verify that it obeys the semantics of the Java language and that it cannot violate the integrity of the Java Virtual Machine. (See §13.4.2, §13.4.4, §13.4.8, and §13.4.16 for some examples.)


12.3.2 Preparation of a Class or Interface Type

Preparation involves creating the static fields (class variables and constants) for a class or interface and initializing such fields to the standard default values (§4.5.4). This does not require the execution of any Java code; explicit initializers for static fields are executed as part of initialization (§12.4), not preparation.

Java implementations must detect the following error during preparation:

  • AbstractMethodError: A class that is not declared to be abstract has an abstract method. This can occur, for example, if a method that is originally not abstract is changed to be abstract after another class that inherits the now abstract method declaration has been compiled (§13.4.15).

If such an error is detected, then an instance of AbstractMethodError should be thrown at the point in the Java program that caused the class to be prepared.

Implementations of the Java Virtual Machine may precompute additional data structures at preparation time in order to make later operations on a class or interface more efficient. One particularly useful data structure is a "method table" or other data structure that allows any method to be invoked on instances of a class without requiring a search of superclasses at invocation time.


12.3.3 Resolution of Symbolic References

A Java binary file references other classes and interfaces and their fields, methods, and constructors symbolically, using the fully-qualified names of the other classes and interfaces (§13.1). For fields and methods, these symbolic references include the name of the class or interface type that declares the field or method as well as the name of the field or method itself, together with appropriate type information.

Before a symbolic reference can be used it must be undergo resolution, wherein a symbolic reference is checked to be correct and, typically, replaced with a direct reference that can be more efficiently processed if the reference is used repeatedly.

If an error occurs during resolution, then an error will be thrown. Most typically, this will be an instance of one of the following subclasses of the class IncompatibleClassChangeError, but it may also be an instance of some other subclass of IncompatibleClassChangeError or even an instance of the class IncompatibleClassChangeError itself. This error may be thrown at any point in the program that uses a symbolic reference to the type, directly or indirectly:

  • IllegalAccessError: A symbolic reference has been encountered that specifies a use or assignment of a field, or invocation of a method, or creation of an instance of a class, to which the code containing the reference does not have access because the field or method was declared private, protected, or default access (not public), or because the class was not declared public. This can occur, for example, if a field that is originally declared public is changed to be private after another class that refers to the field has been compiled (§13.4.6).
  • InstantiationError: A symbolic reference has been encountered that is used in a class instance creation expression, but an instance cannot be created because the reference turns out to refer to an interface or to an abstract class. This can occur, for example, if a class that is originally not abstract is changed to be abstract after another class that refers to the class in question has been compiled (§13.4.1).
  • NoSuchFieldError: A symbolic reference has been encountered that refers to a specific field of a specific class or interface, but the class or interface does not declare a field of that name (it is specifically not sufficient for it simply to be an inherited field of that class or interface). This can occur, for example, if a field declaration was deleted from a class after another class that refers to the field was compiled (§13.4.7).
  • NoSuchMethodError: A symbolic reference has been encountered that refers to a specific method of a specific class or interface, but the class or interface does not declare a method of that signature (it is specifically not sufficient for it simply to be an inherited method of that class or interface). This can occur, for example, if a method declaration was deleted from a class after another class that refers to the method was compiled (§13.4.12).

Additionally, an UnsatisfiedLinkError (a subclass of LinkageError) may be thrown if a class declares a native method for which no implementation can be found. The error will occur if the method is used, or earlier depending on what kind of resolution strategy is being used by the virtual machine (§12.3).


12.3.4 Implications for Code Generation

The symbolic references within a group of types may be resolved even before the group is loaded (§12.2.2), in an implementation that uses a special (non-standard) binary format (§13.1). This corresponds to the traditional practice of "linkage editing." Even if this is not done, a Java implementation has a lot of flexibility. It may resolve all symbolic references from a type at the point of the first linkage activity on the type, or defer the resolution of each symbolic reference to the first use of that reference.

We note that the flexibility accorded the Java implementation in the linkage process does not affect correctly formed Java programs, which should never encounter linkage errors.


12.4 Initialization of Classes and Interfaces

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class. Initialization of an interface consists of executing the initializers for fields (constants) declared there.

Before a class is initialized, its superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.


12.4.1 When Initialization Occurs

A class or interface type T will be initialized at its first active use, which occurs if:

  • T is a class and a method actually declared in T (rather than inherited from a superclass) is invoked.
  • T is a class and a constructor for class T is invoked, or U is an array with element type T, and an array of type U is created.
  • A non-constant field declared in T (rather than inherited from a superclass or superinterface) is used or assigned. A constant field is one that is (explicitly or implicitly) both final and static, and that is initialized with the value of a compile-time constant expression (§15.27). Java specifies that a reference to a constant field must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field are never active uses. See §13.4.8 for a further discussion.

All other uses of a type are passive uses.

The intent here is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.5). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.

As shown in an example in §8.5, the fact that initialization code is unrestricted allows examples to be constructed where the value of a class variable can be observed when it still has its initial default value, before its initializing expression is evaluated, but such examples are rare in practice. (Such examples can be also constructed for instance variable initialization; see the example at the end of §12.5). Java provides the full power of the language in these initializers; programmers must exercise some care. This power places an extra burden on code generators, but this burden would arise in any case because Java is concurrent (§12.4.3).

Before a class is initialized, its superclasses are initialized, if they have not previously been initialized.

Thus, the test program:

class Super {
    static { System.out.print("Super "); }
}

class One {
    static { System.out.print("One "); }
}

class Two extends Super {
    static { System.out.print("Two "); }
}

class Test {
    public static void main(String[] args) {
        One o = null;
        Two t = new Two();
        System.out.println((Object)o == (Object)t);
    }
}

prints:

Super Two false

The class One is never initialized, because it not used actively and therefore is never linked to. The class Two is initialized only after its superclass Super has been initialized.

A reference to a field is an active use of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface. The test program:

class Super { static int taxi = 1729; }

class Sub extends Super {
    static { System.out.print("Sub "); }
}

class Test {
    public static void main(String[] args) {
        System.out.println(Sub.taxi);
    }
}

prints only:

1729

because the class Sub is never initialized; the reference to Sub.taxi is a reference to a field actually declared in class Super and is not an active use of the class Sub.

Initialization of an interface does not, of itself, require initialization of any of its superinterfaces. Thus, the test program:

interface I {
    int i = 1, ii = Test.out("ii", 2);
}

interface J extends I {
    int j = Test.out("j", 3), jj = Test.out("jj", 4);
}

interface K extends J {
    int k = Test.out("k", 5);
}

class Test {

    public static void main(String[] args) {
        System.out.println(J.i);
        System.out.println(K.j);
    }

    static int out(String s, int i) {
        System.out.println(s + "=" + i);
        return i;
    }
}

produces the output:

1
j=3
jj=4
3

The reference to J.i is to a field that is a compile-time constant; therefore, it does not cause I to be initialized. The reference to K.j is a reference to a field actually declared in interface J that is not a compile-time constant; this causes initialization of the fields of interface J, but not those of its superinterface I, nor those of interface K. Despite the fact that the name K is used to refer to field j of interface J, interface K is not actively used.


12.4.2 Detailed Initialization Procedure

Because Java is multithreaded, initialization of a class or interface requires careful synchronization, since some other thread may be trying to initialize the same class or interface at the same time. There is also the possibility that initialization of a class or interface may be requested recursively as part of the initialization of that class or interface; for example, a variable initializer in class A might invoke a method of an unrelated class B, which might in turn invoke a method of class A. The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization by using the following procedure. It assumes that the Class object has already been verified and prepared, and that the Class object contains state that indicates one of four situations:

  • This Class object is verified and prepared but not initialized.
  • This Class object is being initialized by some particular thread T.
  • This Class object is fully initialized and ready for use.
  • This Class object is in an erroneous state, perhaps because the verification or preparation step failed, or because initialization was attempted and failed.

The procedure for initializing a class or interface is then as follows:

  1. Synchronize (§14.17) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.13).
  2. If initialization is in progress for the class or interface by some other thread, then wait (§20.1.6) on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.
  3. If initialization is in progress for the class or interface by the current thread, then this must be a recursive request for initialization. Release the lock on the Class object and complete normally.
  4. If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally.
  5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.
  6. Otherwise, record the fact that initialization of the Class object is now in progress by the current thread and release the lock on the Class object.
  7. Next, if the Class object represents a class rather than an interface, and the superclass of this class has not yet been initialized, then recursively perform this entire procedure for the superclass. If necessary, verify and prepare the superclass first. If the initialization of the superclass completes abruptly because of a thrown exception, then lock this Class object, label it erroneous, notify all waiting threads (§20.1.10), release the lock, and complete abruptly, throwing the same exception that resulted from initializing the superclass.
  8. Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block, except that final class variables and fields of interfaces whose values are compile-time constants are initialized first (§8.3.2.1, §9.3.1, §13.4.8).
  9. If the execution of the initializers completes normally, then lock this Class object, label it fully initialized, notify all waiting threads (§20.1.10), release the lock, and complete this procedure normally.
  10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.
  11. Lock the Class object, label it erroneous, notify all waiting threads (§20.1.10), release the lock, and complete this procedure abruptly with reason E or its replacement as determined in the previous step.
(Due to a flaw in some early implementations of Java, a exception during class initialization was ignored, rather than causing an ExceptionInInitializerError as described here.)


12.4.3 Implications for Code Generation

Code generators need to preserve the points of possible initialization of a class or interface, inserting an invocation of the initialization procedure just described. If this initialization procedure completes normally and the Class object is fully initialized and ready for use, then the invocation of the initialization procedure is no longer necessary and it may be eliminated from the code-for example, by patching it out or otherwise regenerating the code.

Compile-time analysis may, in some cases, be able to eliminate many of the checks that a type has been initialized from the generated code, if an initialization order for a group of related types can be determined. Such analysis must, however, fully account for the fact that Java is concurrent and that initialization code is unrestricted.


12.5 Creation of New Class Instances

A new class instance is explicitly created when one of the following situations occurs:

  • Evaluation of a class instance creation expression (§15.8) creates a new instance of the class whose name appears in the expression.
  • Invocation of the newInstance method (§20.3.6) of class Class creates a new instance of the class represented by the Class object for which the method was invoked.

A new class instance may be implicitly created in the following situations:

  • Loading of a class or interface that contains a String literal (§3.10.5) may create a new String object (§20.12) to represent that literal. (This might not occur if the same String has previously been interned (§3.10.5).)
  • Execution of a string concatenation operator (§15.17.1) that is not part of a constant expression sometimes creates a new String object to represent the result. String concatenation operators may also create temporary wrapper objects for a value of a primitive type.

Each of these situations identifies a particular constructor to be called with specified arguments (possibly none) as part of the class instance creation process.

Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (§4.5.4). Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
  2. If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with a explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.
  4. Execute the instance variable initializers for this class, assigning their values to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early Java implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type.)
  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.
In the example:

class Point {
    int x, y;
    Point() { x = 1; y = 1; }
}

class ColoredPoint extends Point {
    int color = 0xFF00FF;
}

class Test {
    public static void main(String[] args) {
        ColoredPoint cp = new ColoredPoint();
        System.out.println(cp.color);
    }
}

a new instance of ColoredPoint is created. First, space is allocated for the new ColoredPoint, to hold the fields x, y, and color. All these fields are then initialized to their default values (in this case, 0 for each field). Next, the ColoredPoint constructor with no arguments is first invoked. Since ColoredPoint declares no constructors, a default constructor of the form:

ColoredPoint() { super(); }

is provided for it automatically by the Java compiler.

This constructor then invokes the Point constructor with no arguments. The Point constructor does not begin with an invocation of a constructor, so the compiler provides an implicit invocation of its superclass constructor of no arguments, as though it had been written:

Point() { super(); x = 1; y = 1; }

Therefore, the constructor for Object which takes no arguments is invoked.

The class Object has no superclass, so the recursion terminates here. Next, any instance variable initializers and static initializers of Object are invoked. Next, the body of the constructor of Object that takes no arguments is executed. No such constructor is declared in Object, so the compiler supplies a default one, which in this special case is:

Object() { }

This constructor executes without effect and returns.

Next, all initializers for the instance variables of class Point are executed. As it happens, the declarations of x and y do not provide any initialization expressions, so no action is required for this step of the example. Then the body of the Point constructor is executed, setting x to 1 and y to 1.

Next, the initializers for the instance variables of class ColoredPoint are executed. This step assigns the value 0xFF00FF to color. Finally, the rest of the body of the ColoredPoint constructor is executed (the part after the invocation of super); there happen to be no statements in the rest of the body, so no further action is required and initialization is complete.

Unlike C++, the Java language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely initialized. Thus, compiling and running the example:

class Super {
    Super() { printThree(); }
    void printThree() { System.out.println("three"); }
}

class Test extends Super {
    int indiana = (int)Math.PI;													// That is, 3

    public static void main(String[] args) {
        Test t = new Test();
        t.printThree();
    }
    void printThree() { System.out.println(indiana); }
}

produces the output:

0
3

This shows that the invocation of printThree in the constructor for class Super does not invoke the definition of printThree in class Super, but rather invokes the overriding definition of printThree in class Test. This method therefore runs before the field initializers of Test have been executed, which is why the first value output is 0, the default value to which the field three of Test is initialized. The later invocation of printThree in method main invokes the same definition of printThree, but by that point the initializer for instance variable three has been executed, and so the value 3 is printed.

See §8.6 for more details on constructor declarations.


12.6 Finalization of Class Instances

The class Object has a protected method called finalize (§20.1.11); this method can be overridden by other classes. The particular definition of finalize that can be invoked for an object is called the finalizer of that object. Before the storage for an object is reclaimed by the garbage collector, the Java Virtual Machine will invoke the finalizer of that object.

Finalizers provide a chance to free up resources (such as file descriptors or operating system graphics contexts) that cannot be freed automatically by an automatic storage manager. In such situations, simply reclaiming the memory used by an object would not guarantee that the resources it held would be reclaimed.

The Java language does not specify how soon a finalizer will be invoked, except to say that it will happen before the storage for the object is reused. Also, the Java language does not specify which thread will invoke the finalizer for any given object. If an uncaught exception is thrown during the finalization, the exception is ignored and finalization of that object terminates.

The finalize method declared in class Object takes no action. However, the fact that class Object declares a finalize method means that the finalize method for any class can always invoke the finalize method for its superclass, which is usually good practice. (Unlike constructors, finalizers do not automatically invoke the finalizer for the superclass; such an invocation must be coded explicitly.)

For efficiency, an implementation may keep track of classes that do not override the finalize method of class Object, or override it in a trivial way, such as:

protected void finalize() throws Throwable {

    super.finalize();

}

We encourage implementations to treat such objects as having a finalizer that is not overridden, and to finalize them more efficiently, as described in §12.6.1.

A finalizer may be invoked explicitly, just like any other method.


12.6.1 Implementing Finalization

Every object can be characterized by two attributes: it may be reachable, finalizer- reachable, or unreachable, and it may also be unfinalized, finalizable, or finalized.

A reachable object is any object that can be accessed in any potential continuing computation from any live thread. Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a compiler or code generator may choose, explicitly or implicitly, to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner. A finalizer-reachable object can be reached from some finalizable object through some chain of references, but not from any live thread. An unreachable object cannot be reached by either means.

An unfinalized object has never had its finalizer automatically invoked; a finalized object has had its finalizer automatically invoked. A finalizable object has never had its finalizer automatically invoked, but the Java Virtual Machine may eventually automatically invoke its finalizer.

The life cycle of an object obeys the following transition diagram, where we abbreviate "finalizer-reachable" as "f-reachable":

When an object is first created (A), it is reachable and unfinalized.

As references to an object are discarded during program execution, an object that was reachable may become finalizer-reachable (B, C, D) or unreachable (E, F). (Note that a finalizer-reachable object never becomes unreachable directly; it becomes reachable when the finalizer from which it can be reached is invoked, as explained below.)

If the Java Virtual Machine detects that an unfinalized object has become finalizer-reachable or unreachable, it may label the object finalizable (G, H); moreover, if the object was unreachable, it becomes finalizer-reachable (H).

If the Java Virtual Machine detects that a finalized object has become unreachable, it may reclaim the storage occupied by the object because the object will never again become reachable (I).

At any time, a Java Virtual Machine may take any finalizable object, label it finalized, and then invoke its finalize method in some thread. This causes the object to become finalized and reachable (J, K), and it also may cause other objects that were finalizer-reachable to become reachable again (L, M, N).

A finalizable object cannot also be unreachable; it can be reached because its finalizer may eventually be invoked, whereupon the thread running the finalizer will have access to the object, as this (§15.7.2). Thus, there are actually only eight possible states for an object.

After an object has been finalized, no further action is taken until the automatic storage management determines that it is unreachable. Because of the way that an object progresses from the unfinalized state through the finalizable state to the finalized state, the finalize method is never automatically invoked more than once by a Java Virtual Machine for each object, even if the object is again made reachable after it has been finalized.

Explicit invocation of a finalizer ignores the current state of the object and does not change the state of the object from unfinalized or finalizable to finalized.

If a class does not override method finalize of class Object (or overrides it in only a trivial way, as described above), then if instances of such as class become unreachable, they may be discarded immediately rather than made to await a second determination that they have become unreachable. This strategy is indicated by the dashed arrow (O) in the transition diagram.

Java programmers should also be aware that a finalizer can be automatically invoked, even though it is reachable, during finalization-on-exit (§12.9); moreover, a finalizer can also be invoked explicitly as an ordinary method. Therefore, we recommend that the design of finalize methods be kept simple and that they be programmed defensively, so that they will work in all cases.


12.6.2 Finalizer Invocations are Not Ordered

Java imposes no ordering on finalize method calls. Finalizers may be called in any order, or even concurrently.

As an example, if a circularly linked group of unfinalized objects becomes unreachable (or finalizer-reachable), then all the objects may become finalizable together. Eventually, the finalizers for these objects may be invoked, in any order, or even concurrently using multiple threads. If the automatic storage manager later finds that the objects are unreachable, then their storage can be reclaimed.

It is straightforward to implement a Java class that will cause a set of finalizer-like methods to be invoked in a specified order for a set of objects when all the objects become unreachable. Defining such a class is left as an exercise for the reader.


12.7 Finalization of Classes

If a class declares a class method classFinalize that takes no arguments and returns no result:

static void classFinalize() throws Throwable { . . . }

then this method will be invoked before the class is unloaded (§12.8). Like the finalize method for objects, this method will be automatically invoked only once. This method may optionally be declared private, protected, or public.


12.8 Unloading of Classes and Interfaces

A Java Virtual Machine may provide mechanisms whereby classes are unloaded. The details of such mechanisms are not specified in this version of the Java Language Specification. In general, groups of related class and interface types will be unloaded together. This can be used, for example, to unload a group of related types that have been loaded using a particular class loader. Such a group might consist of all the classes implementing a single applet in a Java-based browser such as HotJava, for example.

A class may not be unloaded while any instance of it is still reachable (§12.6). A class or interface may not be unloaded while the Class object that represents it is still reachable.

Classes that declare class finalizers (§12.7) will have these finalizers run before they are unloaded.


12.9 Virtual Machine Exit

A Java Virtual Machine terminates all its activity and exits when one of two things happens:

  • All the threads that are not daemon threads (§20.20.24) terminate.
  • Some thread invokes the exit method (§20.16.2) of class Runtime or class System and the exit operation is not forbidden by the security manager (§20.17.13).

A Java program can specify that the finalizers of all objects that have finalizers, and all classes that have class finalizers, that have not yet been automatically invoked are to be run before the virtual machine exits. This is done by invoking the method runFinalizersOnExit of class System with the argument true. The default is to not run finalizers on exit, and this behavior may be restored by invoking runFinalizersOnExit with the argument false. An invocation of the runFinalizersOnExit method is permitted only if the caller is allowed to exit, and is otherwise rejected by the SecurityManager (§20.17).

. . . Farewell!
The day frowns more and more. Thou'rt like to have
A lullaby too rough: I never saw
The heavens so dim by day: A savage clamour!
Well may I get aboard! This is the chase.
I am gone for ever! [Exit, pursued by a bear]
—William Shakespeare, The Winter's Tale, Act III, scene iii


 13. Binary Compatibility

CHAPTER 13

Binary Compatibility

Java development tools should support automatic recompilation as necessary whenever source code is available. Particular implementations of Java may also store the source and binary of types in a versioning database and implement a ClassLoader (§20.14) that uses integrity mechanisms of the database to prevent linkage errors by providing binary-compatible versions of types to clients.

Developers of packages and classes that are to be widely distributed face a different set of problems. In the Internet, which is our favorite example of a widely distributed system, it is often impractical or impossible to automatically recompile the pre-existing binaries that directly or indirectly depend on a type that is to be changed. Instead, Java defines a set of changes that developers are permitted to make to a package or to a class or interface type while preserving (not breaking) compatibility with existing binaries.

The paper quoted above appears in Proceedings of OOPSLA '95, published as ACM SIGPLAN Notices, Volume 30, Number 10, October 1995, pages 426-438. Within the framework of that paper, Java binaries are binary (release-to-release) compatible under all relevant transformations that the authors identify. Using their scheme, here is a list of some important binary compatible changes that Java supports:

  • Reimplementing existing methods, constructors, and initializers to improve performance.
  • Changing methods or constructors to return values on inputs for which they previously either threw exceptions that normally should not occur or failed by going into an infinite loop or causing a deadlock.
  • Adding new fields, methods, or constructors to an existing class or interface.
  • Deleting private fields, methods, or constructors of a class or interface.
  • When an entire package is updated, deleting default (package-only) access fields, methods, or constructors of classes and interfaces in the package.
  • Reordering the fields, methods, or constructors in an existing type declaration.
  • Moving a method upward in the class hierarchy, provided a forwarding method is left in its place.
  • Reordering the list of direct superinterfaces of a class or interface.
  • Inserting new class or interface types in the type hierarchy.

This chapter specifies minimum standards for binary compatibility guaranteed by all Java implementations. Java guarantees compatibility when binaries of classes and interfaces are mixed that are not known to be from compatible sources, but whose sources have been modified in the compatible ways described here.

We encourage Java development systems to provide facilities that alert developers to the impact of changes on pre-existing binaries that cannot be recompiled.

This chapter first specifies some properties that any Java binary format must have (§13.1). It next defines binary compatibility, explaining what it is and what it is not (§13.2). It finally enumerates a large set of possible changes to packages (§13.3), classes (§13.4) and interfaces (§13.5), specifying which changes are guaranteed to preserve binary compatibility and which are not.


13.1 The Form of a Java Binary

While many Java binary files are likely to be in exactly the class file format specified by the The Java Virtual Machine Specification, this specification does not mandate the use of any specific binary file format. Rather, it specifies properties that any binary format for compiled types must obey. A number of these properties are specifically chosen to support source code transformations that preserve binary compatibility.

The requirements are:

  • Binary formats for Java programs must be defined and processed to respect the specifications of loading (§12.2), linking (§12.3) and initialization (§12.4) of class and interface types.
  • A reference to another class or interface type must be symbolic, using the fully qualified name of the type as determined at compile time.
  • A reference to a field of another class or interface must be resolved at compile time to a symbolic reference to the class or interface in which the field is declared, plus the simple name of the field. (Including the exact class or interface in which the field is declared makes the binaries more robust, since adding another field with the same name, even in a subclass, cannot cause confusion at link time. This rule does mean, however, that moving a field to a superclass is not a binary compatible change; see §13.4.5 for a discussion.) The reference must also include a symbolic reference to the declared type of the field so that the verifier can check that the type is as expected. References to fields that are static, final, and initialized with compile-time constant expressions are resolved at compile time to the constant value that is denoted. No reference to such a constant field should be present in the code in a binary file (except in the class or interface containing the constant field, which will have code to initialize it), and such constant fields must always appear to have been initialized; the default initial value for the type of such a field must never be observed. See §13.4.8 for a discussion.
  • A reference to a method or constructor must be resolved at compile time to a symbolic reference to the class or interface in which the denoted method or constructor is declared, plus the signature of the method or constructor. (As for fields, this makes the binaries more robust, with the caveat that such a method cannot be moved to a superclass without leaving a forwarding method behind; see §13.4.5 for a discussion.) A reference to a method must also include either a symbolic reference to the return type of the denoted method or an indication that the denoted method is declared void and does not return a value. The signature of a method must include all of the following:
    • The simple name of the method
    • The number of parameters to the method
    • A symbolic reference to the type of each parameter

    The signature of a constructor must include both:
    • The number of parameters to the constructor
    • A symbolic reference to the type of each parameter

A Java binary representation for a class or interface must also contain all of the following:

  • If it is a class and is not class java.lang.Object, then a symbolic reference to the direct superclass of this class
  • A symbolic reference to each direct superinterface, if any
  • A specification of each field that is not private declared in the class or interface, given as the simple name of the field and a symbolic reference to the type of the field
  • If it is a class, then the signature of each constructor, as described above
  • For each method that is not private declared in the class or interface, its signature and return type, as described above
  • The code needed to implement the class or interface:
    • For an interface, code for the field initializers
    • For a class, code for the field initializers, the static initializers, and the implementation of each method or constructor that is not declared private

If a Java system defines a binary format that represents a group of classes and interfaces comprised by an entire package, then this binary format need not expose information about fields, methods, or constructors that are declared with default (package) access.

The following sections specify the changes that may be made to class and interface type declarations without breaking compatibility with pre-existing binaries. The Java Virtual Machine and its standard class file format support these changes; other Java binary formats are required to support these changes as well.


13.2 What Binary Compatibility Is and Is Not

A change to a type is binary compatible with (equivalently, does not break binary compatibility with) preexisting binaries if preexisting binaries that previously linked without error will continue to link without error.

As described in §13.1, symbolic references to methods and fields name the exact class or interface in which the method or field is declared. This means that binaries are compiled to rely on the accessible members and constructors of other classes and interfaces. To preserve binary compatibility, a class or interface should treat these accessible members and constructors, their existence and behavior, as a contract with users of the class or interface.

Java is designed to prevent additions to contracts and accidental name collisions from breaking binary compatibility; specifically:

  • Introducing a new field with the same name as an existing field, in a subclass of the class containing the existing field declaration, does not break compatibility with preexisting binaries. See the example at the beginning of §13.4.5.
  • Addition of more methods overloading a particular method name does not break compatibility with preexisting binaries. The method signature that the preexisting binary will use for method lookup is chosen by Java's method overload resolution algorithm at compile time (§15.11.2). (If Java had been designed so that the particular method to be executed was chosen at run time, then such an ambiguity might be detected at run time. Such a rule would imply that adding an additional overloaded method so as to make ambiguity possible at a call site became possible could break compatibility with an unknown number of preexisting binaries. See §13.4.22 for more discussion.)

Binary compatibility is not the same as source compatibility. In particular, the example in §13.4.5 shows that a set of compatible binaries can be produced from sources that will not compile all together. This example is typical: a new declaration is added, changing the meaning of a name in an unchanged part of the source code, while the preexisting binary for that unchanged part of the source code retains the fully-qualified, previous meaning of the name. Producing a consistent set of source code requires providing a qualified name or field access expression corresponding to the previous meaning.

We hope to make some improvements to future versions of Java to better support both source and binary compatible evolution of types. In particular, we are considering a mechanism to allow a class to implement two interfaces that have methods with the same signature but are to be considered different or have different return types. We welcome suggestions and proposals that would help us to make additional improvements, either in managing name and signature conflicts or other sources of incompatibility.


13.3 Evolution of Packages

A new class or interface type may be added to a package without breaking compatibility with pre-existing binaries, provided the new type does not reuse a name previously given to an unrelated type. If a new type reuses a name previously given to an unrelated type, then a conflict may result, since binaries for both types could not be loaded by the same class loader.

Changes in class and interface types that are not public and that are not a superclass or superinterface, respectively, of a public type, affect only types within the package in which they are declared. Such types may be deleted or otherwise changed, even if incompatibilities are otherwise described here, provided that the affected binaries of that package are updated together.


13.4 Evolution of Classes

This section describes the effects of changes to the declaration of a class and its members and constructors on pre-existing binaries.


13.4.1 abstract Classes

If a class that was not abstract is changed to be declared abstract, then pre- existing binaries that attempt to create new instances of that class will throw either an InstantiationError at link time, or an InstantiationException at run time (if the method newInstance (§20.3.6) of class Class is used); such a change is therefore not recommended for widely distributed classes.

Changing a class that was declared abstract to no longer be declared abstract does not break compatibility with pre-existing binaries.


13.4.2 final Classes

If a class that was not declared final is changed to be declared final, then a VerifyError is thrown if a binary of a pre-existing subclass of this class is loaded, because final classes can have no subclasses; such a change is not recommended for widely distributed classes.

Changing a class that was declared final to no longer be declared final does not break compatibility with pre-existing binaries.


13.4.3 public Classes

Changing a class that was not declared public to be declared public does not break compatibility with pre-existing binaries.

If a class that was declared public is changed to not be declared public, then an IllegalAccessError is thrown if a pre-existing binary is linked that needs but no longer has access to the class type; such a change is not recommended for widely distributed classes.


13.4.4 Superclasses and Superinterfaces

A ClassCircularityError is thrown at load time if a class would be a superclass of itself. Changes to the class hierarchy that could result in such a circularity when newly compiled binaries are loaded with pre-existing binaries are not recommended for widely distributed classes.

Changing the direct superclass or the set of direct superinterfaces of a class type will not break compatibility with pre-existing binaries, provided that the total set of superclasses or superinterfaces, respectively, of the class type loses no members.

Changes to the set of superclasses of a class will not break compatibility with pre-existing binaries simply because of uses of class variables and class methods. This is because uses of class variables and class methods are resolved at compile time to symbolic references to the name of the class that declares them. Such uses therefore depend only on the continuing existence of the class declaring the variable or method, not on the shape of the class hierarchy.

If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, then link-time errors may result if pre-existing binaries are loaded with the binary of the modified class. Such changes are not recommended for widely distributed classes. The resulting errors are detected by the verifier of the Java Virtual Machine when an operation that previously compiled would violate the type system. For example, suppose that the following test program:

class Hyper { char h = 'h'; }
class Super extends Hyper { char s = 's'; }
class Test extends Super {
    public static void main(String[] args) {
        Hyper h = new Super();
        System.out.println(h.h);
    }
}

is compiled and executed, producing the output:

h

Suppose that a new version of class Super is then compiled:

class Super { char s = 's'; }

This version of class Super is not a subclass of Hyper. If we then run the existing binaries of Hyper and Test with the new version of Super, then a VerifyError is thrown at link time. The verifier objects because the result of new Super() cannot be assigned to a variable of type Hyper, because Super is not a subclass of Hyper.

It is instructive to consider what might happen without the verification step: the program might run and print:

s

This demonstrates that without the verifier the type system could be defeated by linking inconsistent binary files, even though each was produced by a correct Java compiler.

As a further example, here is an implementation of a cast from a reference type to int, which could be made to run in certain implementations of Java if they failed to perform the verification process. Assume an implementation that uses method dispatch tables and whose linker assigns offsets into those tables in a sequential and straightforward manner. Then suppose that the following Java code is compiled:

class Hyper { int zero(Object o) { return 0; } }
class Super extends Hyper { int peek(int i) { return i; }  }

class Test extends Super {
    public static void main(String[] args) throws Throwable {
        Super as = new Super();
        System.out.println(as);
        System.out.println(Integer.toHexString(as.zero(as)));
    }
}

The assumed implementation determines that the class Super has two methods: the first is method zero inherited from class Hyper, and the second is the method peek. Any subclass of Super would also have these same two methods in the first two entries of its method table. (Actually, all these methods would be preceded in the method tables by all the methods inherited from class Object but, to simplify the discussion, we ignore that here.) For the method invocation as.zero(as), the compiler specifies that the first method of the method table should be invoked; this is always correct if type safety is preserved.

If the compiled code is then executed, it prints something like:

Super@ee300858
0

which is the correct output. But if a new version of Super is compiled, which is the same except for the extends clause:

class Super { int peek(int i) { return i; }  }

then the first method in the method table for Super will now be peek, not zero. Using the new binary code for Super with the old binary code for Hyper and Test will cause the method invocation as.zero(as) to dispatch to the method peek in Super, rather than the method zero in Hyper. This is a type violation, of course; the argument is of type Super but the parameter is of type int. With a few plausible assumptions about internal data representations and the consequences of the type violation, execution of this incorrect program might produce the output:

Super@ee300848
ee300848

A poke method, capable of altering any location in memory, could be concocted in a similar manner. This is left as an exercise for the reader.

The lesson is that a implementation of Java that lacks a verifier or fails to use it will not maintain type safety and is, therefore, not a valid Java implementation.


13.4.5 Class Body and Member Declarations

No incompatibility with pre-existing binaries is caused by adding a class member that has the same name (for fields) or same name, signature, and return type (for methods) as a member of a superclass or subclass. References to the original field or method were resolved at compile time to a symbolic reference containing the name of the class in which they were declared. This makes compiled Java code more robust against changes than it might otherwise be. No error occurs even if the set of classes being linked would encounter a compile-time error. As an example, if the program:

class Hyper { String h = "Hyper"; }
class Super extends Hyper { }
class Test extends Super {
    public static void main(String[] args) {
        String s = new Test().h;
        System.out.println(s);
    }
}

is compiled and executed, it produces the output:

Hyper

Suppose that a new version of class Super is then compiled:

class Super extends Hyper { char h = 'h'; }

If the resulting binary is used with the existing binaries for Hyper and Test, then the output is still:

Hyper

even though compiling the source for these binaries:

class Hyper { String h = "Hyper"; }
class Super extends Hyper { char h = 'h'; }
class Test extends Super {
    public static void main(String[] args) {
        String s = new Test().h;
        System.out.println(s);
    }
}

would result in a compile-time error, because the h in the source code for main would now be construed as referring to the char field declared in Super, and a char value can't be assigned to a String.

Deleting a class member or constructor that is not declared private may cause a linkage error if the member or constructor is used by a pre-existing binary, even if the member was an instance method that was overriding a superclass method. This is because, during resolution, the linker looks only in the class that was identified at compile time. Thus, if the program:

class Hyper {
    void hello() { System.out.println("hello from Hyper"); }
}

class Super extends Hyper {
    void hello() { System.out.println("hello from Super"); }
}

class Test {
    public static void main(String[] args) {
        new Super().hello();
    }
}

is compiled and executed, it produces the output:

hello from Super

Suppose that a new version of class Super is produced:

class Super extends Hyper { }

If Super and Hyper are recompiled but not Test, then a NoSuchMethodError will result at link time, because the method hello is no longer declared in class Super.

To preserve binary compatibility, methods should not be deleted; instead, "forwarding methods" should be used. In our example, replacing the declaration of Super with:

class Super extends Hyper {
    void hello() { super.hello(); }
}

then recompiling Super and Hyper and executing these new binaries with the original binary for Test, produces the output:

hello from Hyper

as might have naively been expected from the previous example.

The super keyword can be used to access a method declared in a superclass, bypassing any methods declared in the current class. The expression:

super.Identifier

is resolved, at compile time, to a method M declared in a particular superclass S. The method M must still be declared in that class at run time or a linkage error will result. If the method M is an instance method, then the method MR invoked at run time is the method with the same signature as M that is a member of the direct superclass of the class containing the expression involving super. Thus, if the program:

class Hyper {
    void hello() { System.out.println("hello from Hyper"); }
}
class Super extends Hyper { }
class Test extends Super {

    public static void main(String[] args) {
        new Test().hello();
    }

    void hello() {
        super.hello();
    }
}

is compiled and executed, it produces the output:

hello from Hyper

Suppose that a new version of class Super is produced:

class Super extends Hyper {
    void hello() { System.out.println("hello from Super"); }
}

If Super and Hyper are recompiled but not Test, then running the new binaries with the existing binary of Test produces the output:

hello from Super

as you might expect. (A flaw in some early versions of Java caused them to print:

hello from Hyper

incorrectly.)


13.4.6 Access to Members and Constructors

Changing the declared access of a member or constructor to permit less access may break compatibility with pre-existing binaries, causing a linkage error to be thrown when these binaries are resolved. Less access is permitted if the access modifier is changed from default access to private access; from protected access to default or private access; or from public access to protected, default, or private access. Changing a member or constructor to permit less access is therefore not recommended for widely distributed classes.

Perhaps surprisingly, Java is defined so that changing a member or constructor to be more accessible does not cause a linkage error when a subclass (already) defines a method to have less access. So, for example, if the package points defines the class Point:

package points;

public class Point {
    public int x, y;
    protected void print() {
        System.out.println("(" + x + "," + y + ")");
    }
}

used by the Test program:

class Test extends points.Point {
    protected void print() { System.out.println("Test"); }
    public static void main(String[] args) {
        Test t = new Test();
        t.print();
    }
}

then these classes compile and Test executes to produce the output:

Test

If the method print in class Point is changed to be public, and then only the Point class is recompiled, and then executed with the previously existing binary for Test then no linkage error occurs, even though it is improper, at compile time, for a public method to be overridden by a protected method (as shown by the fact that the class Test could not be recompiled using this new Point class unless print were changed to be public.)

Allowing superclasses to change protected methods to be public without breaking binaries of preexisting subclasses helps make Java binaries less fragile. The alternative, where such a change would cause a linkage error, would create additional binary incompatibilities with no apparent benefit.


13.4.7 Field Declarations

Adding a field to a class will not break compatibility with any pre-existing binaries that are not recompiled, even in the case where a class could no longer be recompiled because a field access previously referenced a field of a superclass with an incompatible type. The previously compiled class with such a reference will continue to reference the field declared in a superclass. Thus compiling and executing the code:

class Hyper { String h = "hyper"; }
class Super extends Hyper { String s = "super"; }
class Test {
    public static void main(String[] args) {
        System.out.println(new Super().h);
    }
}

produces the output:

hyper

Changing Super to be defined as:

class Super extends Hyper {
    String s = "super";
    int h = 0;
}

recompiling Hyper and Super, and executing the resulting new binaries with the old binary of Test produces the output:

hyper

The field h of Hyper is output by the original binary of main no matter what type field h is declared in Super. While this may seem surprising at first, it serves to reduce the number of incompatibilities that occur at run time. (In an ideal world, all source files that needed recompilation would be recompiled whenever any one of them changed, eliminating such surprises. But such a mass recompilation is often impractical or impossible, especially in the Internet. And, as was previously noted, such recompilation would sometimes require further changes to the source code.)

Deleting a field from a class will break compatibility with any pre-existing binaries that reference this field, and a NoSuchFieldError will be thrown when such a reference from a pre-existing binary is linked. Only private fields may be safely deleted from a widely distributed class.


13.4.8 final Fields and Constants

If a field that was not final is changed to be final, then it can break compatibility with pre-existing binaries that attempt to assign new values to the field. For example, if the program:

class Super { static char s; }

class Test extends Super {
    public static void main(String[] args) {
        s = 'a';
        System.out.println(s);
    }
}

is compiled and executed, it produces the output:

a

Suppose that a new version of class Super is produced:

class Super { static char s; }

If Super is recompiled but not Test, then running the new binary with the existing binary of Test results in a IncompatibleClassChangeError. (In certain early implementations of Java this example would run without error, because of a flaw in the implementation.)

We call a field that is static, final, and initialized with a compile-time constant expression a primitive constant. Note that all fields in interfaces are implicitly static and final, and they are often, but not always, constants.

If a field is not a primitive constant, then deleting the keyword final or changing the value to which the field is initialized does not break compatibility with existing binaries.

If a field is a primitive constant, then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for the constant unless they are recompiled. If the example:

class Flags { final static boolean debug = true; }

class Test {
    public static void main(String[] args) {
        if (Flags.debug)
            System.out.println("debug is true");
    }
}

is compiled and executed, it produces the output:

debug is true

Suppose that a new version of class Flags is produced:

class Flags { final static boolean debug = false; }

If Flags is recompiled but not Test, then running the new binary with the existing binary of Test produces the output:

debug is true

because the value of debug was a compile-time primitive constant, and could have been used in compiling Test without making a reference to the class Flags.

This behavior would not change if Flags were changed to be an interface, as in the modified example:

interface Flags { boolean debug = true; }
class Test {
    public static void main(String[] args) {
        if (Flags.debug)
            System.out.println("debug is true");
    }
}

(One reason for requiring inlining of primitive constants is that Java switch statements require constants on each case, and no two such constant values may be the same. Java checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.)

The best way to avoid problems with "inconstant constants" in widely-distributed code is to declare as primitive constants only values which truly are unlikely ever to change. Many primitive constants in interfaces are small integer values replacing enumerated types, which Java does not support; these small values can be chosen arbitrarily, and should not need to be changed. Other than for true mathematical constants, we recommend that Java code make very sparing use of class variables that are declared static and final. If the read-only nature of final is required, a better choice is to declare a private static variable and a suitable accessor method to get its value. Thus we recommend:

private static int N;
public static int getN() { return N; }

rather than:

public static final int N = ...;

There is no problem with:

public static int N = ...;

if N need not be read-only. We also recommend, as a general rule, that only truly constant values be declared in interfaces. We note, but do not recommend, that if a field of primitive type of an interface may change, its value may be expressed idiomatically as in:

interface Flags {
    boolean debug = new Boolean(true).booleanValue();
}

insuring that this value is not a constant. Similar idioms exist for the other primitive types.

One other thing to note is that static final fields that have constant values (whether of primitive or String type) must never appear to have the default initial value for their type (§4.5.4). This means that all such fields appear to be initialized first during class initialization (§8.3.2.1, §9.3.1, §12.4.2).


13.4.9 static Fields

If a field that is not declared private was not declared static and is changed to be declared static, or vice versa, then a linkage time error, specifically an IncompatibleClassChangeError, will result if the field is used by a preexisting binary which expected a field of the other kind. Such changes are not recommended in code that has been widely distributed.


13.4.10 transient Fields

Adding or deleting a transient modifier of a field does not break compatibility with pre-existing binaries.


13.4.11 volatile Fields

If a field that is not declared private was not declared volatile and is changed to be declared volatile, or vice versa, then a linkage time error, specifically an IncompatibleClassChangeError, may result if the field is used by a preexisting binary that expected a field of the opposite volatility. Such changes are not recommended in code that has been widely distributed.


13.4.12 Method and Constructor Declarations

Adding a method or constructor declaration to a class will not break compatibility with any pre-existing binaries, even in the case where a type could no longer be recompiled because a method invocation previously referenced a method of a superclass with an incompatible type. The previously compiled class with such a reference will continue to reference the method declared in a superclass.

Deleting a method or constructor from a class will break compatibility with any pre-existing binary that referenced this method or constructor; a NoSuchMethodError will be thrown when such a reference from a pre-existing binary is linked. Only private methods or constructors may be safely deleted from a widely distributed class.

If the source code for a class contains no declared constructors, the Java compiler automatically supplies a constructor with no parameters. Adding one or more constructor declarations to the source code of such a class will prevent this default constructor from being supplied automatically, effectively deleting a constructor, unless one of the new constructors also has no parameters, thus replacing the default constructor. The automatically supplied constructor with no parameters is given the same access modifier as the class of its declaration, so any replacement should have as much or more access if compatibility with pre-existing binaries is to be preserved.


13.4.13 Method and Constructor Parameters

Changing the name of a formal parameter of a method or constructor does not impact pre-existing binaries. Changing the name of a method, the type of a formal parameter to a method or constructor, or adding a parameter to or deleting a parameter from a method or constructor declaration creates a method or constructor with a new signature, and has the combined effect of deleting the method or constructor with the old signature and adding a method or constructor with the new signature (see §13.4.12).


13.4.14 Method Result Type

Changing the result type of a method, replacing a result type with void, or replacing void with a result type has the combined effect of deleting the old method or constructor and adding a new method or constructor with the new result type or newly void result (see §13.4.12).


13.4.15 abstract Methods

Changing a method that is declared abstract to no longer be declared abstract does not break compatibility with pre-existing binaries.

Changing a method that is not declared abstract to be declared abstract will break compatibility with pre-existing binaries that previously invoked the method, causing an AbstractMethodError. If the example program:

class Super { void out() { System.out.println("Out"); } }

class Test extends Super {
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("Way ");
        t.out();
    }
}

is compiled and executed, it produces the output:

Way
Out

Suppose that a new version of class Super is produced:

abstract class Super {
    abstract void out();
}

If Super is recompiled but not Test, then running the new binary with the existing binary of Test results in a AbstractMethodError, because class Test has no implementation of the method out, and is therefore is (or should be) abstract. (An early version of Java incorrectly produced the output:

Way

before encountering an AbstractMethodError while invoking the method out, incorrectly allowing the class Test to be prepared even though it has an abstract method and is not declared abstract.)


13.4.16 final Methods

Changing an instance method that is not final to be final may break compatibility with existing binaries that depend on the ability to override the method. If the test program:

class Super { void out() { System.out.println("out"); } }
class Test extends Super {

    public static void main(String[] args) {
        Test t = new Test();
        t.out();
    }
    void out() { super.out(); }
}

is compiled and executed, it produces the output:

out

Suppose that a new version of class Super is produced:

class Super { final void out() { System.out.println("!"); } }

If Super is recompiled but not Test, then running the new binary with the existing binary of Test results in a VerifyError because the class Test improperly tries to override the instance method out.

Changing a class (static) method that is not final to be final does not break compatibility with existing binaries, because the class of the actual method to be invoked is resolved at compile time.

Removing the final modifier from a method does not break compatibility with pre-existing binaries.


13.4.17 native Methods

Adding or deleting a native modifier of a method does not break compatibility with pre-existing binaries.

The impact of changes to Java types on preexisting native methods that are not recompiled is beyond the scope of this specification and should be provided with the description of an implementation of Java. Implementations are encouraged, but not required, to implement native methods in a way that limits such impact.


13.4.18 static Methods

If a method that is not declared private was declared static (that is, a class method) and is changed to not be declared static (that is, to an instance method), or vice versa, then compatibility with pre-existing binaries may be broken, resulting in a linkage time error, namely an IncompatibleClassChangeError, if these methods are used by the pre-existing binaries. Such changes are not recommended in code that has been widely distributed.


13.4.19 synchronized Methods

Adding or deleting a synchronized modifier of a method does not break compatibility with existing binaries.


13.4.20 Method and Constructor Throws

Changes to the throws clause of methods or constructors do not break compatibility with existing binaries; these clauses are checked only at compile time.

We are considering whether a future version of the Java language should require more rigorous checking of throws clauses when classes are verified.


13.4.21 Method and Constructor Body

Changes to the body of a method or constructor do not break compatibility with pre-existing binaries.

We note that a compiler cannot inline expand a method at compile time unless, for example, either:

  • the method is private to its class
  • an entire package is guaranteed to be kept together and the method is accessible only within that package
  • a set of Java code is being compiled to a special binary format where the specified method is available only within a binary or set of binaries which are being kept together.

The keyword final on a method does not mean that the method can be safely inlined; it only means that the method cannot be overridden. Unless the compiler has extraordinary knowledge, it is still possible that a new version of that method will be provided at link time.

In general we suggest that Java implementations use late-bound (run-time) code generation and optimization.


13.4.22 Method and Constructor Overloading

Adding new methods that overload existing method names does not break compatibility with pre-existing binaries. The method signature to be used for each method invocation was determined when these existing binaries were compiled; therefore newly added methods will not be used, even if their signatures are both applicable and more specific than the method signature originally chosen.

While adding a new overloaded method or constructor may cause a compile-time error the next time a class or interface is compiled because there is no method or constructor that is most specific (§15.11.2.2), no such error occurs when a Java program is executed, because no overload resolution is done at execution time.

If the example program:

class Super {
    static void out(float f) { System.out.println("float"); }
}

class Test {
    public static void main(String[] args) {
        Super.out(2);
    }
}

is compiled and executed, it produces the output:

float

Suppose that a new version of class Super is produced:

class Super {
    static void out(float f) { System.out.println("float"); }
    static void out(int i) { System.out.println("int"); }
}

If Super is recompiled but not Test, then running the new binary with the existing binary of Test still produces the output:

float

However, if Test is then recompiled, using this new Super, the output is then:

int

as might have been naively expected in the previous case.


13.4.23 Method Overriding

If an instance method is added to a subclass and it overrides a method in a superclass, then the subclass method will be found by method invocations in pre-existing binaries, and these binaries are not impacted. If a class method is added to a class, then this method will not be found, because the invocation of a class method is resolved at compile time to use the fully qualified name of the class where the method is declared. Thus if the example:

class Hyper {
    void hello() { System.out.print("Hello, "); }
    static void world() { System.out.println("world!"); }
}
class Super extends Hyper { }

class Test {
    public static void main(String[] args) {
        Super s = new Super();
        s.hello();
        s.world();
    }
}

is compiled and executed, it produces the output:

Hello, world!

Suppose that a new version of class Super is produced:

class Super extends Hyper {
    void hello() { System.out.print("Goodbye, cruel "); }
    static void world() { System.out.println("earth!"); }
}

If Super is recompiled but not Hyper or Test, then running the new binary with the existing binaries for Hyper and Test will produce the output:

Goodbye, cruel world!

This example demonstrates that the invocation in:

s.world();

in the method main is resolved, at compile time, to a symbolic reference to the class containing the class method world, as though it had been written:

Hyper.world();

This is why the world method of Hyper rather than Super is invoked in this example. Of course, recompiling all the classes to produce new binaries will allow the output:

Goodbye, cruel earth!

to be produced.


13.4.24 Static Initializers

Adding, deleting, or changing a static initializer (§8.5) of a class does not impact pre-existing binaries.


13.5 Evolution of Interfaces

This section describes the impact of changes to the declaration of an interface and its members on pre-existing binaries.


13.5.1 public Interfaces

Changing an interface that is not declared public to be declared public does not break compatibility with pre-existing binaries.

If an interface that is declared public is changed to not be declared public, then an IllegalAccessError is thrown if a pre-existing binary is linked that needs but no longer has access to the interface type, so such a change is not recommended for widely distributed interfaces.


13.5.2 Superinterfaces

Changes to the interface hierarchy cause errors in the same way that changes to the class hierarchy do, as described in §13.4.4. In particular, changes that result in any previous superinterface of a class no longer being a superinterface can break compatibility with pre-existing binaries, resulting in a VerifyError.


13.5.3 The Interface Members

Adding a member to an interface does not break compatibility with pre-existing binaries.

Deleting a member from an interface may cause linkage errors in pre-existing binaries. If the example program:

interface I { void hello(); }
class Test implements I {

    public static void main(String[] args) {
        I anI = new Test();
        anI.hello();
    }
    public void hello() { System.out.println("hello"); }
}

is compiled and executed, it produces the output:

hello

Suppose that a new version of interface I is compiled:

interface I { }

If I is recompiled but not Test, then running the new binary with the existing binary for Test will result in a NoSuchMethodError. (In some early implementations of Java this program still executed; the fact that the method hello no longer exists in interface I was not correctly detected.)


13.5.4 Field Declarations

The considerations for changing field declarations in interfaces are the same as those for static final fields in classes, as described in §13.4.7 and §13.4.8.


13.5.5 Abstract Method Declarations

The considerations for changing abstract method declarations in interfaces are the same as those for abstract methods in classes, as described in §13.4.13, §13.4.14, §13.4.20, and §13.4.22.

Lo! keen-eyed, towering Science! . . .
Yet again, lo! the Soul—above all science . . .
For it, the partial to the permanent flowing,
For it, the Real to the Ideal tends.
For it, the mystic evolution . . .
—Walt Whitman, Song of the Universal (1874)


 14. Blocks and Statements

CHAPTER 14

Blocks and Statements

He was not merely a chip of the old block, but the old block itself.
—Edmund Burke, On Pitt's First Speech

The sequence of execution of a Java program is controlled by statements, which are executed for their effect and do not have values.

Some statements contain other statements as part of their structure; such other statements are substatements of the statement. We say that statement S immediately contains statement U if there is no statement T different from S and U such that S contains T and T contains U. In the same manner, some statements contain expressions (§15) as part of their structure.

The first section of this chapter discusses the distinction between normal and abrupt completion of statements (§14.1). Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.

Blocks are explained first (§14.2), because they can appear in certain places where other kinds of statements are not allowed, and because one other kind of statement, a local variable declaration statement (§14.3), must be immediately contained within a block.

Next a grammatical maneuver is explained that sidesteps the familiar "dangling else" problem (§14.4).

Statements that will be familiar to C and C++ programmers are the empty (§14.5), labeled (§14.6), expression (§14.7), if (§14.8), switch (§14.9), while (§14.10), do (§14.11), for (§14.12), break (§14.13), continue (§14.14), and return (§14.15) statements.

Unlike C and C++, Java has no goto statement. However, the break and continue statements are extended in Java to allow them to mention statement labels.

The Java statements that are not in the C language are the throw (§14.16), synchronized (§14.17), and try (§14.18) statements.

The last section (§14.19) of this chapter addresses the requirement that every statement be reachable in a certain technical sense.


14.1 Normal and Abrupt Completion of Statements

Poirot's abrupt departure had intrigued us all greatly.
—Agatha Christie, The Mysterious Affair at Styles (1920), Chapter 12

Every statement has a normal mode of execution in which certain computational steps are carried out. The following sections describe the normal mode of execution for each kind of statement. If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:

  • The break (§14.13), continue (§14.14), and return (§14.15) statements cause a transfer of control that may prevent normal completion of statements that contain them.
  • Evaluation of certain Java expressions may throw exceptions from the Java Virtual Machine; these expressions are summarized in §15.5. An explicit throw (§14.16) statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.

If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to complete abruptly. An abrupt completion always has an associated reason, which is one of the following:

  • A break with no label
  • A break with a given label
  • A continue with no label
  • A continue with a given label
  • A return with no value
  • A return with a given value
  • A throw with a given value, including exceptions thrown by the Java Virtual Machine

The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions (§15.5). The only reason an expression can complete abruptly is that an exception is thrown, because of either a throw with a given value (§14.16) or a run-time exception or error (§11, §15.5).

If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.

Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.

Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.


14.2 Blocks

A block is a sequence of statements and local variable declaration statements within braces.

Block:

    { BlockStatementsopt }

BlockStatements:

    BlockStatement

    BlockStatements BlockStatement

BlockStatement:

    LocalVariableDeclarationStatement

    Statement

A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.


14.3 Local Variable Declaration Statements

A local variable declaration statement declares one or more local variable names.

LocalVariableDeclarationStatement:

    LocalVariableDeclaration ;

LocalVariableDeclaration:

    Type VariableDeclarators

The following are repeated from §8.3 to make the presentation here clearer:

VariableDeclarators:

    VariableDeclarator

    VariableDeclarators , VariableDeclarator

VariableDeclarator:

    VariableDeclaratorId

    VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:

    Identifier

    VariableDeclaratorId [ ]

VariableInitializer:

    Expression

    ArrayInitializer

Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

A local variable declaration can also appear in the header of a for statement (§14.12). In this case it is executed in the same manner as if it were part of a local variable declaration statement.


14.3.1 Local Variable Declarators and Types

Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.

The type of the variable is denoted by the Type that appears at the start of the local variable declaration, followed by any bracket pairs that follow the Identifier in the declarator. Thus, the local variable declaration:

int a, b[], c[][];

is equivalent to the series of declarations:

int a;
int[] b;
int[][] c;

Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rule, however, also means that the local variable declaration:

float[][] f[][], g[][][], h[];	// Yechh!

is equivalent to the series of declarations:

float[][][][] f;
float[][][][][] g;
float[][][] h;

We do not recommend such "mixed notation" for array declarations.


14.3.2 Scope of Local Variable Declarations

The scope of a local variable declared in a block is the rest of the block, including its own initializer. The name of the local variable parameter may not be redeclared as a local variable or exception parameter within its scope, or a compile-time error occurs; that is, hiding the name of a local variable is not permitted.

A local variable cannot be referred to using a qualified name (§6.6), only a simple name.

The example:

class Test {
    static int x;
    public static void main(String[] args) {
        int x = x;
    }
}

causes a compile-time error because the initialization of x is within the scope of the declaration of x as a local variable, and the local x does not yet have a value and cannot be used.

The following program does compile:

class Test {
    static int x;
    public static void main(String[] args) {
        int x = (x=2)*2;
        System.out.println(x);
    }
}

because the local variable x is definitely assigned (§16) before it is used. It prints:

4

Here is another example:

class Test {
    public static void main(String[] args) {
        System.out.print("2+1=");
        int two = 2, three = two + 1;
        System.out.println(three);
    }
}

which compiles correctly and produces the output:

2+1=3

The initializer for three can correctly refer to the variable two declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable three declared earlier in the block.

The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

If a declaration of an identifier as a local variable appears within the scope of a parameter or local variable of the same name, a compile-time error occurs. Thus the following example does not compile:

class Test {
    public static void main(String[] args) {
        int i;
        for (int i = 0; i < 10; i++)
            System.out.println(i);
    }
}

This restriction helps to detect some otherwise very obscure bugs. (A similar restriction on hiding of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables.)

On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:

class Test {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++)
            System.out.print(i + " ");
        for (int i = 10; i > 0; i--)
            System.out.print(i + " ");
        System.out.println();
    }
}

compiles without error and, when executed, produces the output:

0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1


14.3.3 Hiding of Names by Local Variables

If a name declared as a local variable is already declared as a field or type name, then that outer declaration is hidden throughout the scope of the local variable. The field or type name can almost always (§6.8) still be accessed using an appropriately qualified name. For example, the keyword this can be used to access a hidden field x, using the form this.x. Indeed, this idiom typically appears in constructors (§8.6):

class Pair {
    Object first, second;
    public Pair(Object first, Object second) {
        this.first = first;
        this.second = second;
    }
}

In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.


14.3.4 Execution of Local Variable Declarations

A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in §16, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.

Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.


14.4 Statements

There are many kinds of statements in the Java language. Most correspond to statements in the C and C++ languages, but some are unique to Java.

As in C and C++, the Java if statement suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

if (door.isOpen())
    if (resident.isVisible())
        resident.greet("Hello!");
else door.bell.ring();								// A "dangling else"

The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement. The Java language, like C and C++ and many languages before them, arbitrarily decree that an else clause belongs to the innermost if to which it might possibly belong. This rule is captured by the following grammar:

Statement:

    StatementWithoutTrailingSubstatement

    LabeledStatement

    IfThenStatement

    IfThenElseStatement

    WhileStatement

    ForStatement

StatementNoShortIf:

    StatementWithoutTrailingSubstatement

    LabeledStatementNoShortIf

    IfThenElseStatementNoShortIf

    WhileStatementNoShortIf

    ForStatementNoShortIf

StatementWithoutTrailingSubstatement:

    Block

    EmptyStatement

    ExpressionStatement

    SwitchStatement

    DoStatement

    BreakStatement

    ContinueStatement

    ReturnStatement

    SynchronizedStatement

    ThrowStatement

    TryStatement

The following are repeated from §14.8 to make the presentation here clearer:

IfThenStatement:

    if ( Expression ) Statement

IfThenElseStatement:

    if ( Expression ) StatementNoShortIf else Statement

IfThenElseStatementNoShortIf:

    if ( Expression ) StatementNoShortIf else StatementNoShortIf

Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not. Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause. This simple rule prevents the "dangling else" problem. The execution behavior of a statement with the "no short if" restriction is identical to the execution behavior of the same kind of statement without the "no short if" restriction; the distinction is drawn purely to resolve the syntactic difficulty.


14.5 The Empty Statement

An empty statement does nothing.

EmptyStatement:

    ;

Execution of an empty statement always completes normally.


14.6 Labeled Statements

Statements may have label prefixes.

LabeledStatement:

    Identifier : Statement

LabeledStatementNoShortIf:

    Identifier : StatementNoShortIf

The Identifier is declared to be the label of the immediately contained Statement.

Unlike C and C++, the Java language has no goto statement; identifier statement labels are used with break (§14.13) or continue (§14.14) statements appearing anywhere within the labeled statement.

A statement labeled by an identifier must not appear anywhere within another statement labeled by the same identifier, or a compile-time error will occur. Two statements can be labeled by the same identifier only if neither statement contains the other.

There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not hide a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier as a local variable or as the parameter of an exception handler (§14.18) does not hide a statement label with the same name.

A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason.


14.7 Expression Statements

Certain kinds of expressions may be used as statements by following them with semicolons:

ExpressionStatement:

    StatementExpression ;

StatementExpression:

    Assignment

    PreIncrementExpression

    PreDecrementExpression

    PostIncrementExpression

    PostDecrementExpression

    MethodInvocation

    ClassInstanceCreationExpression

An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

Unlike C and C++, the Java language allows only certain forms of expressions to be used as expression statements. Note that Java does not allow a "cast to void"-void is not a type in Java-so the traditional C trick of writing an expression statement such as:

(void) ... ;		// This idiom belongs to C, not to Java!

does not work in Java. On the other hand, Java allows all the most useful kinds of expressions in expressions statements, and Java does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.25) or a local variable declaration statement (§14.3) can be used instead.


14.8 The if Statement

The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.

IfThenStatement:

    if ( Expression ) Statement

IfThenElseStatement:

    if ( Expression ) StatementNoShortIf else Statement

IfThenElseStatementNoShortIf:

    if ( Expression ) StatementNoShortIf else StatementNoShortIf

The Expression must have type boolean, or a compile-time error occurs.


14.8.1 The if-then Statement

I took an early opportunity of testing that statement . . .
--Agatha Christie, The Mysterious Affair at Styles (1920), Chapter 12

An if-then statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the if-then statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

  • If the value is true, then the contained Statement is executed; the if-then statement completes normally only if execution of the Statement completes normally.
  • If the value is false, no further action is taken and the if-then statement completes normally.


14.8.2 The if-then-else Statement

An if-then-else statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, then the if- then-else statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

  • If the value is true, then the first contained Statement (the one before the else keyword) is executed; the if-then-else statement completes normally only if execution of that statement completes normally.
  • If the value is false, then the second contained Statement (the one after the else keyword) is executed; the if-then-else statement completes normally only if execution of that statement completes normally.


14.9 The switch Statement

The switch statement transfers control to one of several statements depending on the value of an expression.

SwitchStatement:

    switch ( Expression ) SwitchBlock

SwitchBlock:

    { SwitchBlockStatementGroupsopt SwitchLabelsopt }

SwitchBlockStatementGroups:

    SwitchBlockStatementGroup

    SwitchBlockStatementGroups SwitchBlockStatementGroup

SwitchBlockStatementGroup:

    SwitchLabels BlockStatements

SwitchLabels:

    SwitchLabel

    SwitchLabels SwitchLabel

SwitchLabel:

    case ConstantExpression :

    default :

The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

The body of a switch statement must be a block. Any statement immediately contained by the block may be labeled with one or more case or default labels. These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.27) in the case labels.

All of the following must be true, or a compile-time error will result:

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
  • No two of the case constant expressions associated with a switch statement may have the same value.
  • At most one default label may be associated with the same switch statement.

In C and C++ the body of a switch statement can be a statement and statements with case labels do not have to be immediately contained by that statement. Consider the simple loop:

for (i = 0; i < n; ++i) foo();

where n is known to be positive. A trick known as Duff's device can be used in C or C++ to unroll the loop, but this is not valid Java code:

int q = (n+7)/8;
switch (n%8) {
case 0:			do {		foo(); // Great C hack, Tom,
case 7:					foo(); // but it's not valid in Java.
case 6:					foo();
case 5:					foo();
case 4:					foo();
case 3:					foo();
case 2:					foo();
case 1:					foo();
            } while (--q >= 0);
}

Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.

When the switch statement is executed, first the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the switch statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the Expression with each case constant. Then there is a choice:

  • If one of the case constants is equal to the value of the expression, then we say that the case matches, and all statements after the matching case label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the matching case label, then the entire switch statement completes normally.
  • If no case matches but there is a default label, then all statements after the matching default label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the default label, then the entire switch statement completes normally.
  • If no case matches and there is no default label, then no further action is taken and the switch statement completes normally.

If any statement immediately contained by the Block body of the switch statement completes abruptly, it is handled as follows:

  • If execution of the Statement completes abruptly because of a break with no label, no further action is taken and the switch statement completes normally.
  • If execution of the Statement completes abruptly for any other reason, the switch statement completes abruptly for the same reason. The case of abrupt completion because of a break with a label is handled by the general rule for labeled statements (§14.6).

As in C and C++, execution of statements in a switch block "falls through labels" in Java. For example, the program:

class Toomany {

    static void howMany(int k) {
        switch (k) {
        case 1:			System.out.print("one ");
        case 2:			System.out.print("too ");
        case 3:			System.out.println("many");
        }
    }

    public static void main(String[] args) {
        howMany(3);
        howMany(2);
        howMany(1);
    }

}

contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:

many
too many
one too many

If code is not to fall through case to case in this manner, then break statements should be used, as in this example:

class Twomany {

    static void howMany(int k) {
        switch (k) {
        case 1:			System.out.println("one");
                    break; // exit the switch
        case 2:			System.out.println("two");
                    break; // exit the switch
        case 3:			System.out.println("many");
                    break; // not needed, but good style
        }
    }

    public static void main(String[] args) {
        howMany(1);
        howMany(2);
        howMany(3);
    }

}

This program prints:

one
two
many


14.10 The while Statement

The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.

WhileStatement:

    while ( Expression ) Statement

WhileStatementNoShortIf:

    while ( Expression ) StatementNoShortIf

The Expression must have type boolean, or a compile-time error occurs.

A while statement is executed by first evaluating the Expression. If evaluation of the Expression completes abruptly for some reason, the while statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:

  • If the value is true, then the contained Statement is executed. Then there is a choice:
    • If execution of the Statement completes normally, then the entire while statement is executed again, beginning by re-evaluating the Expression.
    • If execution of the Statement completes abruptly, see §14.10.1 below.
  • If the value of the Expression is false, no further action is taken and the while statement completes normally.

If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.


14.10.1 Abrupt Completion

Abrupt completion of the contained Statement is handled in the following manner:

  • If execution of the Statement completes abruptly because of a break with no label, no further action is taken and the while statement completes normally.
    • If execution of the Statement completes abruptly because of a continue with no label, then the entire while statement is executed again.
    • If execution of the Statement completes abruptly because of a continue with label L, then there is a choice:
      • If the while statement has label L, then the entire while statement is executed again.
      • If the while statement does not have label L, the while statement completes abruptly because of a continue with label L.
    • If execution of the Statement completes abruptly for any other reason, the while statement completes abruptly for the same reason. Note that the case of abrupt completion because of a break with a label is handled by the general rule for labeled statements (§14.6).


14.11 The do Statement

The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false.

DoStatement:

    do Statement while ( Expression ) ;

The Expression must have type boolean, or a compile-time error occurs.

A do statement is executed by first executing the Statement. Then there is a choice:

  • If execution of the Statement completes normally, then the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the do statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value:
    • If the value is true, then the entire do statement is executed again.
    • If the value is false, no further action is taken and the do statement completes normally.
  • If execution of the Statement completes abruptly, see §14.11.1 below.

Executing a do statement always executes the contained Statement at least once.


14.11.1 Abrupt Completion

Abrupt completion of the contained Statement is handled in the following manner:

  • If execution of the Statement completes abruptly because of a break with no label, then no further action is taken and the do statement completes normally.
  • If execution of the Statement completes abruptly because of a continue with no label, then the Expression is evaluated. Then there is a choice based on the resulting value:
    • If the value is true, then the entire do statement is executed again.
    • If the value is false, no further action is taken and the do statement completes normally.
  • If execution of the Statement completes abruptly because of a continue with label L, then there is a choice:
    • If the do statement has label L, then the Expression is evaluated. Then there is a choice:
      • If the value of the Expression is true, then the entire do statement is executed again.
      • If the value of the Expression is false, no further action is taken and the do statement completes normally.
    • If the do statement does not have label L, the do statement completes abruptly because of a continue with label L.
  • If execution of the Statement completes abruptly for any other reason, the do statement completes abruptly for the same reason. The case of abrupt completion because of a break with a label is handled by the general rule (§14.6).


14.11.2 Example

The following code is one possible implementation of the toHexString method (§20.7.14) of class Integer:

public static String toHexString(int i) {
    StringBuffer buf = new StringBuffer(8);
    do {
        buf.append(Character.forDigit(i & 0xF, 16));
        i >>>= 4;
    } while (i != 0);
    return buf.reverse().toString();
}

Because at least one digit must be generated, the do statement is an appropriate control structure.


14.12 The for Statement

The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

ForStatement:

    for ( ForInitopt ; Expressionopt ; ForUpdateopt )

        Statement

ForStatementNoShortIf:

    for ( ForInitopt ; Expressionopt ; ForUpdateopt )

        StatementNoShortIf

ForInit:

    StatementExpressionList

    LocalVariableDeclaration

ForUpdate:

    StatementExpressionList

StatementExpressionList:

    StatementExpression

    StatementExpressionList , StatementExpression

The Expression must have type boolean, or a compile-time error occurs.


14.12.1 Initialization

A for statement is executed by first executing the ForInit code:

  • If the ForInit code is a list of statement expressions (§14.7), the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForInit statement expressions to the right of the one that completed abruptly are not evaluated.
  • If the ForInit code is a local variable declaration, it is executed as if it were a local variable declaration statement (§14.3) appearing in a block. In this case, the scope of a declared local variable is its own initializer and any further declarators in the ForInit part, plus the Expression, ForUpdate, and contained Statement of the for statement. If execution of the local variable declaration completes abruptly for any reason, the for statement completes abruptly for the same reason.
  • If the ForInit part is not present, no action is taken.


14.12.2 Iteration

Next, a for iteration step is performed, as follows:

  • If the Expression is present, it is evaluated, and if evaluation of the Expression completes abruptly, the for statement completes abruptly for the same reason. Otherwise, there is then a choice based on the presence or absence of the Expression and the resulting value if the Expression is present:
    • If the Expression is not present, or it is present and the value resulting from its evaluation is true, then the contained Statement is executed. Then there is a choice:
      • If execution of the Statement completes normally, then the following two steps are performed in sequence:
        • First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the for statement completes abruptly for the same reason; any ForUpdate statement expressions to the right of the one that completed abruptly are not evaluated. If the ForUpdate part is not present, no action is taken.
        • Second, another for iteration step is performed.
      • If execution of the Statement completes abruptly, see §14.12.3 below.
    • If the Expression is present and the value resulting from its evaluation is false, no further action is taken and the for statement completes normally.

If the value of the Expression is false the first time it is evaluated, then the Statement is not executed.

If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement.


14.12.3 Abrupt Completion

Abrupt completion of the contained Statement is handled in the following manner:

  • If execution of the Statement completes abruptly because of a break with no label, no further action is taken and the for statement completes normally.
  • If execution of the Statement completes abruptly because of a continue with no label, then the following two steps are performed in sequence:
    • First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForUpdate part is not present, no action is taken.
    • Second, another for iteration step is performed.
  • If execution of the Statement completes abruptly because of a continue with label L, then there is a choice:
    • If the for statement has label L, then the following two steps are performed in sequence:
      • First, if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the ForUpdate is not present, no action is taken.
      • Second, another for iteration step is performed.
    • If the for statement does not have label L, the for statement completes abruptly because of a continue with label L.
  • If execution of the Statement completes abruptly for any other reason, the for statement completes abruptly for the same reason. Note that the case of abrupt completion because of a break with a label is handled by the general rule for labeled statements (§14.6).


14.13 The break Statement

A break statement transfers control out of an enclosing statement.

BreakStatement:

    break Identifieropt ;

A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement; this statement, which is called the break target, then immediately completes normally. To be precise, a break statement with no label always completes abruptly, the reason being a break with no label. If no switch, while, do, or for statement encloses the break statement, a compile-time error occurs.

A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.6) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a while, do, for, or switch statement. To be precise, a break statement with label Identifier always completes abruptly, the reason being a break with label Identifier. If no labeled statement with Identifier as its label encloses the break statement, a compile-time error occurs.

It can be seen, then, that a break statement always completes abruptly.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the break target whose try blocks contain the break statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a break statement.

In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes P and Q, where Q may be the same as P, there is at most one edge from P to Q. Nodes are represented by integers, and there is an edge from node i to node edges[i][j] for every i and j for which the array reference edges[i][j] does not throw an IndexOutOfBoundsException.

The task of the method loseEdges, given integers i and j, is to construct a new graph by copying a given graph but omitting the edge from node i to node j, if any, and the edge from node j to node i, if any:

class Graph {
    int edges[][];
    public Graph(int[][] edges) { this.edges = edges; }

    public Graph loseEdges(int i, int j) {
        int n = edges.length;
        int[][] newedges = new int[n][];
        for (int k = 0; k < n; ++k) {

            edgelist: {
                int z;

                search: {
                    if (k == i) {
                        for (z = 0; z < edges[k].length; ++z)
                            if (edges[k][z] == j)
                                break search;
                    } else if (k == j) {
                        for (z = 0; z < edges[k].length; ++z)
                            if (edges[k][z] == i)
                                break search;
                    }
                    // No edge to be deleted; share this list.
                    newedges[k] = edges[k];
                    break edgelist;
                }//search
                // Copy the list, omitting the edge at position z.
                int m = edges[k].length - 1;
                int ne[] = new int[m];
                System.arraycopy(edges[k], 0, ne, 0, z);
                System.arraycopy(edges[k], z+1, ne, z, m-z);
                newedges[k] = ne;
            }//edgelist
        }
        return new Graph(newedges);
    }
}

Note the use of two statement labels, edgelist and search, and the use of break statements. This allows the code that copies a list, omitting one edge, to be shared between two separate tests, the test for an edge from node i to node j, and the test for an edge from node j to node i.


14.14 The continue Statement

A continue statement may occur only in a while, do, or for statement; statements of these three kinds are called iteration statements. Control passes to the loop-continuation point of an iteration statement.

ContinueStatement:

    continue Identifieropt ;

A continue statement with no label attempts to transfer control to the innermost enclosing while, do, or for statement; this statement, which is called the continue target, then immediately ends the current iteration and begins a new one. To be precise, such a continue statement always completes abruptly, the reason being a continue with no label. If no while, do, or for statement encloses the continue statement, a compile-time error occurs.

A continue statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.6) that has the same Identifier as its label; that statement, which is called the continue target, then immediately ends the current iteration and begins a new one. The continue target must be a while, do, or for statement or a compile-time error occurs. More precisely, a continue statement with label Identifier always completes abruptly, the reason being a continue with label Identifier. If no labeled statement with Identifier as its label contains the continue statement, a compile-time error occurs.

It can be seen, then, that a continue statement always completes abruptly.

See the descriptions of the while statement (§14.10), do statement (§14.11), and for statement (§14.12) for a discussion of the handling of abrupt termination because of continue.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the continue target whose try blocks contain the continue statement, then any finally clauses of those try statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a continue statement.

In the Graph example in the preceding section, one of the break statements is used to finish execution of the entire body of the outermost for loop. This break can be replaced by a continue if the for loop itself is labeled:

class Graph {
    . . .
    public Graph loseEdges(int i, int j) {
        int n = edges.length;
        int[][] newedges = new int[n][];

        edgelists: for (int k = 0; k < n; ++k) {
            int z;

            search: {
                if (k == i) {
                    . . .
                } else if (k == j) {
                    . . .
                }
                newedges[k] = edges[k];
                continue edgelists;
            }//search
            . . .
        }//edgelists
        return new Graph(newedges);
    }
}

Which to use, if either, is largely a matter of programming style.


14.15 The return Statement

A return statement returns control to the invoker of a method (§8.4, §15.11) or constructor (§8.6, §15.8).

ReturnStatement:

    return Expressionopt ;

A return statement with no Expression must be contained in the body of a method that is declared, using the keyword void, not to return any value (§8.4), or in the body of a constructor (§8.6). A compile-time error occurs if a return statement appears within a static initializer (§8.5). A return statement with no Expression attempts to transfer control to the invoker of the method or constructor that contains it. To be precise, a return statement with no Expression always completes abruptly, the reason being a return with no value.

A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.

It can be seen, then, that a return statement always completes abruptly.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.18) within the method or constructor whose try blocks contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.


14.16 The throw Statement

A throw statement causes an exception (§11) to be thrown. The result is an immediate transfer of control (§11.3) that may exit multiple statements and multiple constructor, static and field initializer evaluations, and method invocations until a try statement (§14.18) is found that catches the thrown value. If no such try statement is found, then execution of the thread (§17, §20.20) that executed the throw is terminated (§11.3) after invocation of the UncaughtException method (§20.21.31) for the thread group to which the thread belongs.

ThrowStatement:

    throw Expression ;

The Expression in a throw statement must denote a variable or value of a reference type which is assignable (§5.2) to the type Throwable, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:

  • The exception is not a checked exception (§11.2)-specifically, one of the following situations is true:
    • The type of the Expression is the class RuntimeException or a subclass of RuntimeException.
    • The type of the Expression is the class Error or a subclass of Error.
  • The throw statement is contained in the try block of a try statement (§14.18) and the type of the Expression is assignable (§5.2) to the type of the parameter of at least one catch clause of the try statement. (In this case we say the thrown value is caught by the try statement.)
  • The throw statement is contained in a method or constructor declaration and the type of the Expression is assignable (§5.2) to at least one type listed in the throws clause (§8.4.4, §8.6.4) of the declaration.

A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the throw statement completes abruptly, the reason being a throw with value V.

It can be seen, then, that a throw statement always completes abruptly.

If there are any enclosing try statements (§14.18) whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.

If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw.

If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the class instance creation expression (or the method invocation of method newInstance of class Class) that invoked the constructor will complete abruptly because of the throw.

If a throw statement is contained in a static initializer (§8.5), then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is rethrown if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInInitializerError object, which is then thrown (§12.4.2).

By convention, user-declared throwable types should usually be declared to be subclasses of class Exception, which is a subclass of class Throwable (§11.5, §20.22).


14.17 The synchronized Statement

A synchronized statement acquires a mutual-exclusion lock (§17.13) on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.

SynchronizedStatement:

    synchronized ( Expression ) Block

The type of Expression must be a reference type, or a compile-time error occurs.

A synchronized statement is executed by first evaluating the Expression.

If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

The locks acquired by synchronized statements are the same as the locks that are acquired implicitly by synchronized methods; see §8.4.3.5. A single thread may hold a lock more than once. The example:

class Test {
    public static void main(String[] args) {
        Test t = new Test();
        synchronized(t) {
            synchronized(t) {
                System.out.println("made it!");
            }
        }
    }
}

prints:

made it!

This example would deadlock if a single thread were not permitted to lock a lock more than once.


14.18 The try statement

These are the times that try men's souls.
—Thomas Paine, The American Crisis (1780)

. . . and they all fell to playing the game of catch as catch can,
till the gunpowder ran out at the heels of their boots.
—Samuel Foote

A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

TryStatement:

    try Block Catches

    try Block Catchesopt Finally

Catches:

    CatchClause

    Catches CatchClause

CatchClause:

    catch ( FormalParameter ) Block

Finally:

    finally Block

The following is repeated from §8.4.1 to make the presentation here clearer:

FormalParameter:

    Type VariableDeclaratorId

The following is repeated from §8.3 to make the presentation here clearer:

VariableDeclaratorId:

    Identifier

    VariableDeclaratorId [ ]

The Block immediately after the keyword try is called the try block of the try statement. The Block immediately after the keyword finally is called the finally block of the try statement.

A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compile-time error occurs. The scope of the parameter variable is the Block of the catch clause. An exception parameter must not have the same name as a local variable or parameter in whose scope it is declared, or a compile-time error occurs.

The scope of the name of an exception parameter is the Block of the catch clause. The name of the parameter may not be redeclared as a local variable or exception parameter within the Block of the catch clause; that is, hiding the name of an exception parameter is not permitted.

Exception parameters cannot be referred to using qualified names (§6.6), only by simple names.

Exception handlers are considered in left-to-right order: the earliest possible catch clause accepts the exception, receiving as its actual argument the thrown exception object.

A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

Handling of the finally block is rather complex, so the two cases of a try statement with and without a finally block are described separately.


14.18.1 Execution of try-catch

Our supreme task is the resumption of our onward, normal way.
—Warren G. Harding, Inaugural Address (1921)

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then no further action is taken and the try statement completes normally.
  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable (§5.2) to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.
  • If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason.

In the example:

class BlewIt extends Exception {
    BlewIt() { }
    BlewIt(String s) { super(s); }
}
class Test {
    static void blowUp() throws BlewIt { throw new BlewIt(); }
    public static void main(String[] args) {

        try {
            blowUp();
        } catch (RuntimeException r) {
            System.out.println("RuntimeException:" + r);
        } catch (BlewIt b) {
            System.out.println("BlewIt");
        }
    }

}

the exception BlewIt is thrown by the method blowUp. The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is:

BlewIt


14.18.2 Execution of try-catch-finally

After the great captains and engineers have accomplish'd their work,
After the noble inventors—after the scientists, the chemist,
the geologist, ethnologist,
Finally shall come the Poet . . .
—Walt Whitman, Passage to India (1870)

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then the finally block is executed, and then there is a choice:
    • If the finally block completes normally, then the try statement completes normally.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.
  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    • If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
      • If the catch block completes normally, then the finally block is executed. Then there is a choice:
        • If the finally block completes normally, then the try statement completes normally.
        • If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
      • If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
        • If the finally block completes normally, then the try statement completes abruptly for reason R.
        • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
    • If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
  • If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
    • If the finally block completes normally, then the try statement completes abruptly for reason R.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

The example:

class BlewIt extends Exception {
    BlewIt() { }
    BlewIt(String s) { super(s); }
}

class Test {

    static void blowUp() throws BlewIt {

        throw new NullPointerException();

    }

    public static void main(String[] args) {
        try {
            blowUp();
        } catch (BlewIt b) {
            System.out.println("BlewIt");
        } finally {
            System.out.println("Uncaught Exception");
        }
    }

}

produces the output:

Uncaught Exception
java.lang.NullPointerException
    at Test.blowUp(Test.java:7)
    at Test.main(Test.java:11)

The NullPointerException (which is a kind of RuntimeException) that is thrown by method blowUp is not caught by the try statement in main, because a NullPointerException is not assignable to a variable of type BlewIt. This causes the finally clause to execute, after which the thread executing main, which is the only thread of the test program, terminates because of an uncaught exception (§20.21.31), which results in printing the exception name and a simple backtrace.


14.19 Unreachable Statements

That looks like a path.
Is that the way to reach the top from here?
—Robert Frost, The Mountain (1915)

It is a compile-time error if a statement cannot be executed because it is unreachable. Every Java compiler must carry out the conservative flow analysis specified here to make sure all statements are reachable.

This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis. For example, a Java compiler will accept the code:

{
    int n = 5;
    while (n > 7) n = 2;
}

even though the value of n is known at compile time and in principle it can be known at compile time that the assignment to k can never be executed. A Java compiler must operate according to the rules laid out in this section.

The rules in this section define two technical terms:

  • whether a statement is reachable
  • whether a statement can complete normally

The definitions here allow a statement to complete normally only if it is reachable.

To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."

The rules are as follows:

  • The block that is the body of a constructor, method, or static initializer is reachable.
  • An empty block that is not a switch block can complete normally iff it is reachable. A nonempty block that is not a switch block can complete normally iff the last statement in it can complete normally. The first statement in a nonempty block that is not a switch block is reachable iff the block is reachable. Every other statement S in a nonempty block that is not a switch block is reachable iff the statement preceding S can complete normally.
  • A local variable declaration statement can complete normally iff it is reachable.
  • An empty statement can complete normally iff it is reachable.
  • A labeled statement can complete normally if at least one of the following is true:
    • The contained statement can complete normally.
    • There is a reachable break statement that exits the labeled statement.

The contained statement is reachable iff the labeled statement is reachable.

  • An expression statement can complete normally iff it is reachable.
  • The if statement, whether or not it has an else part, is handled in an unusual manner. For this reason, it is discussed separately at the end of this section.
  • A switch statement can complete normally iff at least one of the following is true:
    • The last statement in the switch block can complete normally.
    • The switch block is empty or contains only switch labels.
    • There is at least one switch label after the last switch block statement group.
    • There is a reachable break statement that exits the switch statement.
  • A switch block is reachable iff its switch statement is reachable.
  • A statement in a switch block is reachable iff its switch statement is reachable and at least one of the following is true:
    • It bears a case or default label.
    • There is a statement preceding it in the switch block and that preceding statement can complete normally.
  • A while statement can complete normally iff at least one of the following is true:
    • The while statement is reachable and the condition expression is not a constant expression with value true.
    • There is a reachable break statement that exits the while statement.

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

  • A do statement can complete normally iff at least one of the following is true:
    • The contained statement can complete normally and the condition expression is not a constant expression with value true.
    • There is a reachable break statement that exits the do statement.

The contained statement is reachable iff the do statement is reachable.

  • A for statement can complete normally iff at least one of the following is true:
    • The for statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value true.
    • There is a reachable break statement that exits the for statement.

The contained statement is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.

  • A break, continue, return, or throw statement cannot complete normally.
  • A synchronized statement can complete normally iff the contained statement can complete normally. The contained statement is reachable iff the synchronized statement is reachable.
  • A try statement can complete normally iff both of the following are true:
    • The try block can complete normally or any catch block can complete normally.
    • If the try statement has a finally block, then the finally block can complete normally.
  • The try block is reachable iff the try statement is reachable.
  • A catch block C is reachable iff both of the following are true:
    • Some expression or throw statement in the try block is reachable and can throw an exception whose type is assignable to the parameter of the catch clause C. (An expression is considered reachable iff the innermost statement containing it is reachable.)
    • There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
  • If a finally block is present, it is reachable iff the try statement is reachable.

One might expect the if statement to be handled in the following manner, but these are not the rules that Java actually uses:

  • HYPOTHETICAL: An if-then statement can complete normally iff at least one of the following is true:
    • The if-then statement is reachable and the condition expression is not a constant expression whose value is true.
    • The then-statement can complete normally.

The then-statement is reachable iff the if-then statement is reachable and the condition expression is not a constant expression whose value is false.

  • HYPOTHETICAL: An if-then-else statement can complete normally iff the then-statement can complete normally or the else-statement can complete normally. The then-statement is reachable iff the if-then-else statement is reachable and the condition expression is not a constant expression whose value is false. The else statement is reachable iff the if-then-else statement is reachable and the condition expression is not a constant expression whose value is true.

This approach would be consistent with the treatment of other control structures in Java. However, in order to allow the if statement to be used conveniently for "conditional compilation" purposes, the actual rules are as follows:

  • ACTUAL: An if-then statement can complete normally iff it is reachable. The then-statement is reachable iff the if-then statement is reachable.
  • ACTUAL: An if-then-else statement can complete normally iff the then-statement can complete normally or the else-statement can complete normally. The then-statement is reachable iff the if-then-else statement is reachable. The else-statement is reachable iff the if-then-else statement is reachable.

As an example, the following statement results in a compile-time error:

while (false) { x=3; }

because the statement x=3; is not reachable; but the superficially similar case:

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility (§13). If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries (§13.4.8). (There are other reasons for such incompatibility as well, such as the use of constants in case labels in switch statements; see §13.4.8.)

One ought not to be thrown into confusion
By a plain statement of relationship . . .
—Robert Frost, The Generations of Men (1914)


 15. Expressions

CHAPTER 15

Expressions

When you can measure what you are speaking about,
and express it in numbers, you know something about it;
but when you cannot measure it, when you cannot express it in numbers,
your knowledge of it is of a meager and unsatisfactory kind:
it may be the beginning of knowledge, but you have scarcely,
in your thoughts, advanced to the stage of science.
—William Thompson, Lord Kelvin

Much of the work in a Java program is done by evaluating expressions, either for their side effects, such as assignments to variables, or for their values, which can be used as arguments or operands in larger expressions, or to affect the execution sequence in statements, or both.

This chapter specifies the meanings of Java expressions and the rules for their evaluation.


15.1 Evaluation, Denotation, and Result

When an expression in a Java program is evaluated (executed), the result denotes one of three things:

  • A variable (§4.5) (in C, this would be called an lvalue)
  • A value (§4.2, §4.3)
  • Nothing (the expression is said to be void)

Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.

An expression denotes nothing if and only if it is a method invocation (§15.11) that invokes a method that does not return a value, that is, a method declared void (§8.4). Such an expression can be used only as an expression statement (§14.7), because every other context in which an expression can appear requires the expression to denote something. An expression statement that is a method invocation may also invoke a method that produces a result; in this case the value returned by the method is quietly discarded.

Each expression occurs in the declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in a constructor declaration, or in the code for a method.


15.2 Variables as Values

If an expression denotes a variable, and a value is required for use in further evaluation, then the value of that variable is used. In this context, if the expression denotes a variable or a value, we may speak simply of the value of the expression.


15.3 Type of an Expression

If an expression denotes a variable or a value, then the expression has a type known at compile time. The rules for determining the type of an expression are explained separately below for each kind of expression.

The value of an expression is always assignment compatible (§5.2) with the type of the expression, just as the value stored in a variable is always compatible with the type of the variable. In other words, the value of an expression whose type is T is always suitable for assignment to a variable of type T.

Note that an expression whose type is a class type F that is declared final is guaranteed to have a value that is either a null reference or an object whose class is F itself, because final types have no subclasses.


15.4 Expressions and Run-Time Checks

If the type of an expression is a primitive type, then the value of the expression is of that same primitive type. But if the type of an expression is a reference type, then the class of the referenced object, or even whether the value is a reference to an object rather than null, is not necessarily known at compile time. There are a few places in the Java language where the actual class of a referenced object affects program execution in a manner that cannot be deduced from the type of the expression. They are as follows:

  • Method invocation (§15.11). The particular method used for an invocation o.m(...) is chosen based on the methods that are part of the class or interface that is the type of o. For instance methods, the class of the object referenced by the run-time value of o participates because a subclass may override a specific method already declared in a parent class so that this overriding method is invoked. (The overriding method may or may not choose to further invoke the original overridden m method.)
  • The instanceof operator (§15.19.2). An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression is assignment compatible (§5.2) with some other reference type.
  • Casting (§5.4, §15.15). The class of the object referenced by the run-time value of the operand expression might not be compatible with the type specified by the cast. For reference types, this may require a run-time check that throws an error if the class of the referenced object, as determined at run time, is not assignment compatible (§5.2) with the target type.
  • Assignment to an array component of reference type (§10.10, §15.12, §15.25.1). The type-checking rules allow the array type S[] to be treated as a subtype of T[] if S is a subtype of T, but this requires a run-time check for assignment to an army component, similar to the check performed for a cast.
  • Exception handling (§14.18). An exception is caught by a catch clause only if the class of the thrown exception object is an instanceof the type of the formal parameter of the catch clause.

The first two of the cases just listed ought never to result in detecting a type error. Thus, a Java run-time type error can occur only in these situations:

  • In a cast, when the actual class of the object referenced by the value of the operand expression is not compatible with the target type specified by the cast operator (§5.4, §15.15); in this case a ClassCastException is thrown.
  • In an assignment to an array component of reference type, when the actual class of the object referenced by the value to be assigned is not compatible with the actual run-time component type of the array (§10.10, §15.12, §15.25.1); in this case an ArrayStoreException is thrown.
  • When an exception is not caught by any catch handler (§11.3); in this case the thread of control that encountered the exception first invokes the method uncaughtException (§20.21.31) for its thread group and then terminates.


15.5 Normal and Abrupt Completion of Evaluation

No more: the end is sudden and abrupt.
--William Wordsworth, Apology for the Foregoing Poems (1831)

Every expression has a normal mode of evaluation in which certain computational steps are carried out. The following sections describe the normal mode of evaluation for each kind of expression. If all the steps are carried out without an exception being thrown, the expression is said to complete normally.

If, however, evaluation of an expression throws an exception, then the expression is said to complete abruptly. An abrupt completion always has an associated reason, which is always a throw with a given value.

Run-time exceptions are thrown by the predefined operators as follows:

  • A class instance creation expression (§15.8), array creation expression (§15.9), or string concatenation operatior expression (§15.17.1) throws an OutOfMemoryError if there is insufficient memory available.
  • An array creation expression throws an ArrayNegativeSizeException if the value of any dimension expression is less than zero (§15.9).
  • A field access (§15.10) throws a NullPointerException if the value of the object reference expression is null.
  • A method invocation expression (§15.11) that invokes an instance method throws a NullPointerException if the target reference is null.
  • An array access (§15.12) throws a NullPointerException if the value of the array reference expression is null.
  • An array access (§15.12) throws an IndexOutOfBoundsException if the value of the array index expression is negative or greater than or equal to the length of the array.
  • A cast (§15.15) throws a ClassCastException if a cast is found to be impermissible at run time.
  • An integer division (§15.16.2) or integer remainder (§15.16.3) operator throws an ArithmeticException if the value of the right-hand operand expression is zero.
  • An assignment to an array component of reference type (§15.25.1) throws an ArrayStoreException when the value to be assigned is not compatible with the component type of the array.

A method invocation expression can also result in an exception being thrown if an exception occurs that causes execution of the method body to complete abruptly. A class instance creation expression can also result in an exception being thrown if an exception occurs that causes execution of the constructor to complete abruptly. Various linkage and virtual machine errors may also occur during the evaluation of an expression. By their nature, such errors are difficult to predict and difficult to handle.

If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly. The terms "complete normally" and "complete abruptly" are also applied to the execution of statements (§14.1). A statement may complete abruptly for a variety of reasons, not just because an exception is thrown.

If evaluation of an expression requires evaluation of a subexpression, abrupt completion of the subexpression always causes the immediate abrupt completion of the expression itself, with the same reason, and all succeeding steps in the normal mode of evaluation are not performed.


15.6 Evaluation Order

Let all things be done decently and in order.
--I Corinthians 14:40

Java guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

It is recommended that Java code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.


15.6.1 Left-Hand Operand First

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first.

Thus:

class Test {
    public static void main(String[] args) {
        int i = 2;
        int j = (i=3) * i;
        System.out.println(j);
    }
}

prints:

9

It is not permitted for it to print 6 instead of 9.

If the operator is a compound-assignment operator (§15.25.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:

class Test {
    public static void main(String[] args) {
        int a = 9;
        a += (a = 3);									// first example
        System.out.println(a);
        int b = 9;
        b = b + (b = 3);									// second example
        System.out.println(b);
    }
}

prints:

12
12

because the two assignment statements both fetch and remember the value of the left-hand operand, which is 9, before the right-hand operand of the addition is evaluated, thereby setting the variable to 3. It is not permitted for either example to produce the result 6. Note that both of these examples have unspecified behavior in C, according to the ANSI/ISO standard.

If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.

Thus, the test program:

class Test {

    public static void main(String[] args) {

        int j = 1;

        try {
            int i = forgetIt() / (j = 2);
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("Now j = " + j);
        }
    }

    static int forgetIt() throws Exception {
        throw new Exception("I'm outta here!");
    }
}

prints:

java.lang.Exception: I'm outta here!
Now j = 1

because the left-hand operand forgetIt() of the operator / throws an exception before the right-hand operand and its embedded assignment of 2 to j occurs.


15.6.2 Operands before Operation

Java also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

If the binary operator is an integer division / (§15.16.2) or integer remainder % (§15.16.3), then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.

So, for example, the program:

class Test {

    public static void main(String[] args) {
        int divisor = 0;
        try {
            int i = 1 / (divisor * loseBig());
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    static int loseBig() throws Exception {
        throw new Exception("Shuffle off to Buffalo!");
    }

}

always prints:

java.lang.Exception: Shuffle off to Buffalo!

and not:

java.lang.ArithmeticException: / by zero

since no part of the division operation, including signaling of a divide-by-zero exception, may appear to occur before the invocation of loseBig completes, even though the implementation may be able to detect or infer that the division operation would certainly result in a divide-by-zero exception.


15.6.3 Parentheses and Precedence Respected

That is too weighty a subject to be discussed parenthetically . . .
--John Stuart Mill, On Liberty (1869), Chapter IV

Java implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence. An implementation may not take advantage of algebraic identities such as the associative law to rewrite expressions into a more convenient computational order unless it can be proven that the replacement expression is equivalent in value and in its observable side effects, even in the presence of multiple threads of execution (using the thread execution model in §17), for all possible computational values that might be involved.

In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, !(x<y) may not be rewritten as x>=y, because these expressions have different values if either x or y is NaN.

Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered. For example, it is not correct for a Java compiler to rewrite 4.0*x*0.5 as 2.0*x; while roundoff happens not to be an issue here, there are large values of x for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.

So, for example, the test program:

class Test {

    public static void main(String[] args) {
        double d = 8e+307;
        System.out.println(4.0 * d * 0.5);
        System.out.println(2.0 * d);
    }
}

prints:

Infinity
1.6e+308

because the first expression overflows and the second does not.

In contrast, integer addition and multiplication are provably associative in Java; for example a+b+c, where a, b, and c are local variables (this simplifying assumption avoids issues involving multiple threads and volatile variables), will always produce the same answer whether evaluated as (a+b)+c or a+(b+c); if the expression b+c occurs nearby in the code, a smart compiler may be able to use this common subexpression.


15.6.4 Argument Lists Evaluated Left-to-Right

In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

Thus:

class Test {

    public static void main(String[] args) {
        String s = "going, ";
        print3(s, s, s = "gone");
    }

    static void print3(String a, String b, String c) {
        System.out.println(a + b + c);
    }
}

always prints:

going, going, gone

because the assignment of the string "gone" to s occurs after the first two arguments to print3 have been evaluated.

If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.

Thus, the example:

class Test {
    static int id;
    public static void main(String[] args) {
        try {
            test(id = 1, oops(), id = 3);
        } catch (Exception e) {
            System.out.println(e + ", id=" + id);
        }
    }

    static int oops() throws Exception {
        throw new Exception("oops");
    }

    static int test(int a, int b, int c) {
        return a + b + c;
    }

}

prints:

java.lang.Exception: oops, id=1

because the assignment of 3 to id is not executed.


15.6.5 Ordering of Other Expressions

The order of evaluation for some expressions is not completely covered by these general rules, because these expressions may raise exceptional conditions at times that must be specified. See, specifically, the detailed explanations of evaluation order for the following kinds of expressions:

  • class instance creation expressions (§15.8.1)
  • array creation expressions (§15.9.1)
  • method invocation expressions (§15.11.4)
  • array access expressions (§15.12.1)
  • assignments involving array components (§15.25)


15.7 Primary Expressions

Primary expressions include most of the simplest kinds of expressions, from which all others are constructed: literals, field accesses, method invocations, and array accesses. A parenthesized expression is also treated syntactically as a primary expression.

Primary:

    PrimaryNoNewArray

    ArrayCreationExpression

PrimaryNoNewArray:

    Literal

    this

    ( Expression )

    ClassInstanceCreationExpression

    FieldAccess

    MethodInvocation

    ArrayAccess

As programming language grammars go, this part of the Java grammar is unusual, in two ways. First, one might expect simple names, such as names of local variables and method parameters, to be primary expressions. For technical reasons, names are lumped together with primary expressions a little later when postfix expressions are introduced (§15.13).

The technical reasons have to do with allowing left-to-right parsing of Java programs with only one-token lookahead. Consider the expressions (z[3]) and (z[]). The first is a parenthesized array access (§15.12) and the second is the start of a cast (§15.15). At the point that the look-ahead symbol is [, a left-to-right parse will have reduced the z to the nonterminal Name. In the context of a cast we prefer not to have to reduce the name to a Primary, but if Name were one of the alternatives for Primary, then we could not tell whether to do the reduction (that is, we could not determine whether the current situation would turn out to be a parenthesized array access or a cast) without looking ahead two tokens, to the token following the [. The Java grammar presented here avoids the problem by keeping Name and Primary separate and allowing either in certain other syntax rules (those for MethodInvocation, ArrayAccess, PostfixExpression, but not for FieldAccess, because this is covered by Name). This strategy effectively defers the question of whether a Name should be treated as a Primary until more context can be examined. (Other problems remain with cast expressions; see §19.1.5.)

The second unusual feature avoids a potential grammatical ambiguity in the expression:

new int[3][3]

which in Java always means a single creation of a multidimensional array, but which, without appropriate grammatical finesse, might also be interpreted as meaning the same as:

(new int[3])[3]

This ambiguity is eliminated by splitting the expected definition of Primary into Primary and PrimaryNoNewArray. (This may be compared to the splitting of Statement into Statement and StatementNoShortIf (§14.4) to avoid the "dangling else" problem.)


15.7.1 Literals

A literal (§3.10) denotes a fixed, unchanging value.

The following production from §3.10 is repeated here for convenience:

Literal:

    IntegerLiteral

    FloatingPointLiteral

    BooleanLiteral

    CharacterLiteral

    StringLiteral

    NullLiteral

The type of a literal is determined as follows:

  • The type of an integer literal that ends with L or l is long; the type of any other integer literal is int.
  • The type of a floating-point literal that ends with F or f is float; the type of any other floating-point literal is double.
  • The type of a boolean literal is boolean.
  • The type of a character literal is char.
  • The type of a string literal is String.
  • The type of the null literal null is the null type; its value is the null reference.

Evaluation of a literal always completes normally.


15.7.2 this

The keyword this may be used only in the body of an instance method or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

When used as a primary expression, the keyword this denotes a value, that is a reference to the object for which the instance method was invoked (§15.11), or to the object being constructed. The type of this is the class C within which the keyword this occurs. At run time, the class of the actual object referred to may be the class C or any subclass of C.

In the example:

class IntVector {
    int[] v;
    boolean equals(IntVector other) {
        if (this == other)
            return true;
        if (v.length != other.v.length)
            return false;
        for (int i = 0; i < v.length; i++)
            if (v[i] != other.v[i])
                return false;
        return true;
    }

}

the class IntVector implements a method equals, which compares two vectors. If the other vector is the same vector object as the one for which the equals method was invoked, then the check can skip the length and value comparisons. The equals method implements this check by comparing the reference to the other object to this.

The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.6.5).


15.7.3 Parenthesized Expressions

A parenthesized expression is a primary expression whose type is the type of the contained expression and whose value at run time is the value of the contained expression.


15.8 Class Instance Creation Expressions

A class instance creation expression is used to create new objects that are instances of classes.

ClassInstanceCreationExpression:

    new ClassType ( ArgumentListopt )

ArgumentList:

    Expression

    ArgumentList , Expression

In a class instance creation expression, the ClassType must name a class that is not abstract. This class type is the type of the creation expression.

The arguments in the argument list, if any, are used to select a constructor declared in the body of the named class type, using the same matching rules as for method invocations (§15.11). As in method invocations, a compile-time method matching error results if there is no unique constructor that is both applicable to the provided arguments and the most specific of all the applicable constructors.


15.8.1 Run-time Evaluation of Class Instance Creation Expressions

At run time, evaluation of a class instance creation expression is as follows.

First, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError (§15.8.2).

The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its standard default value (§4.5.4).

Next, the argument list is evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.

Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.6) and is described in detail in §12.5.

The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.


15.8.2 Example: Evaluation Order and Out-of-Memory Detection

If evaluation of a class instance creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs before any argument expressions are evaluated.

So, for example, the test program:

class List {
    int value;
    List next;
    static List head = new List(0);
    List(int n) { value = n; next = head; head = this; }
}

class Test {
    public static void main(String[] args) {
        int id = 0, oldid = 0;
        try {
            for (;;) {
                ++id;
                new List(oldid = id);
            }
        } catch (Error e) {
            System.out.println(e + ", " + (oldid==id));
        }
    }
}

prints:

java.lang.OutOfMemoryError: List, false

because the out-or-memory condition is detected before the argument expression oldid = id is evaluated.

Compare this to the treatment of array creation expressions (§15.9), for which the out-of-memory condition is detected after evaluation of the dimension expressions (§15.9.3).


15.9 Array Creation Expressions

An array instance creation expression is used to create new arrays (§10).

ArrayCreationExpression:

    new PrimitiveType DimExprs Dimsopt

    new TypeName DimExprs Dimsopt

DimExprs:

    DimExpr

    DimExprs DimExpr

DimExpr:

    [ Expression ]

Dims:

    [ ]

    Dims [ ]

An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or TypeName. The TypeName may name any reference type, even an abstract class type (§8.1.2.1) or an interface type (§9).

The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the new keyword and every DimExpr expression have been deleted; for example, the type of the creation expression:

new double[3][3][]

is:

double[][][]

The type of each dimension expression DimExpr must be an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be long.


15.9.1 Run-time Evaluation of Array Creation Expressions

At run time, evaluation of an array creation expression behaves as follows.

First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.

Next, the values of the dimension expressions are checked. If the value of any DimExpr expression is less than zero, then an NegativeArraySizeException is thrown.

Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an OutOfMemoryError.

Then, if a single DimExpr appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its standard default value (§4.5.4).

If an array creation expression contains N DimExpr expressions, then it effectively executes a set of nested loops of depth [image] to create the implied arrays of arrays. For example, the declaration:

float[][] matrix = new float[3][3];

is equivalent in behavior to:

float[][] matrix = new float[3][];
for (int d = 0; d < matrix.length; d++)
    matrix[d] = new float[3];

and:

Age[][][][][] Aquarius = new Age[6][10][8][12][];

is equivalent to:

Age[][][][][] Aquarius = new Age[6][][][][];
for (int d1 = 0; d1 < Aquarius.length; d1++) {
    Aquarius[d1] = new Age[8][][][];
    for (int d2 = 0; d2 < Aquarius[d1].length; d2++) {
        Aquarius[d1][d2] = new Age[10][][];
        for (int d3 = 0; d3 < Aquarius[d1][d2].length; d3++) {
            Aquarius[d1][d2][d3] = new Age[12][];
        }
    }
}

with d, d1, d2 and d3 replaced by names that are not already locally declared. Thus, a single new expression actually creates one array of length 6, 6 arrays of length 10, [image] arrays of length 8, and [image] arrays of length 12. This example leaves the fifth dimension, which would be arrays containing the actual array elements (references to Age objects), initialized only to null references. These arrays can be filled in later by other code, such as:

Age[] Hair = { new Age("quartz"), new Age("topaz") };
Aquarius[1][9][6][9] = Hair;

A multidimensional array need not have arrays of the same length at each level; thus, a triangular matrix may be created by:

float triang[][] = new float[100][];
for (int i = 0; i < triang.length; i++)
    triang[i] = new float[i+1];

There is, however, no way to get this effect with a single creation expression.


15.9.2 Example: Evaluation Order

In an array creation expression (§15.9), there may be one or more dimension expressions, each within brackets. Each dimension expression is fully evaluated before any part of any dimension expression to its right.

Thus:

class Test {
    public static void main(String[] args) {
        int i = 4;
        int ia[][] = new int[i][i=3];
        System.out.println(
            "[" + ia.length + "," + ia[0].length + "]");
    }
}

prints:

[4,3]

because the first dimension is calculated as 4 before the second dimension expression sets i to 3.

If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated. Thus, the example:

class Test {

    public static void main(String[] args) {
        int[][] a = { { 00, 01 }, { 10, 11 } };
        int i = 99;
        try {
            a[val()][i = 1]++;
        } catch (Exception e) {
            System.out.println(e + ", i=" + i);
        }
    }

    static int val() throws Exception {
        throw new Exception("unimplemented");
    }

}

prints:

java.lang.Exception: unimplemented, i=99

because the embedded assignment that sets i to 1 is never executed.


15.9.3 Example: Evaluation Order and Out-of-Memory Detection

If evaluation of an array creation expression finds there is insufficient memory to perform the creation operation, then an OutOfMemoryError is thrown. This check occurs only after evaluation of all dimension expressions has completed normally.

So, for example, the test program:

class Test {
    public static void main(String[] args) {
        int len = 0, oldlen = 0;
        Object[] a = new Object[0];
        try {
            for (;;) {
                ++len;
                Object[] temp = new Object[oldlen = len];
                temp[0] = a;
                a = temp;
            }
        } catch (Error e) {
            System.out.println(e + ", " + (oldlen==len));
        }
    }
}

prints:

java.lang.OutOfMemoryError, true

because the out-of-memory condition is detected after the argument expression oldlen = len is evaluated.

Compare this to class instance creation expressions (§15.8), which detect the out-of-memory condition before evaluating argument expressions (§15.8.2).


15.10 Field Access Expressions

A field access expression may access a field of an object or array, a reference to which is the value of either an expression or the special keyword super. (It is also possible to refer to a field of the current instance or current class by using a simple name; see §15.13.1.)

FieldAccess:

    Primary . Identifier

    super . Identifier

The meaning of a field access expression is determined using the same rules as for qualified names (§6.6), but limited by the fact that an expression cannot denote a package, class type, or interface type.


15.10.1 Field Access Using a Primary

The type of the Primary must be a reference type T, or a compile-time error occurs. The meaning of the field access expression is determined as follows:

  • If the identifier names several accessible member fields of type T, then the field access is ambiguous and a compile-time error occurs.
  • If the identifier does not name an accessible member field of type T, then the field access is undefined and a compile-time error occurs.
  • Otherwise, the identifier names a single accessible member field of type T and the type of the field access expression is the declared type of the field. At run time, the result of the field access expression is computed as follows:
    • If the field is static:
      • If the field is final, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
      • If the field is not final, then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
    • If the field is not static:
      • If the value of the Primary is null, then a NullPointerException is thrown.
      • If the field is final, then the result is the value of the specified instance variable in the object referenced by the value of the Primary.
      • If the field is not final, then the result is a variable, namely, the specified instance variable in the object referenced by the value of the Primary.

Note, specifically, that only the type of the Primary expression, not the class of the actual object referred to at run time, is used in determining which field to use.

Thus, the example:

class S { int x = 0; }
class T extends S { int x = 1; }
class Test {
    public static void main(String[] args) {

        T t = new T();
        System.out.println("t.x=" + t.x + when("t", t));

        S s = new S();
        System.out.println("s.x=" + s.x + when("s", s));

        s = t;
        System.out.println("s.x=" + s.x + when("s", s));

    }

    static String when(String name, Object t) {
        return " when " + name + " holds a "
            + t.getClass() + " at run time.";
    }
}

produces the output:

t.x=1 when t holds a class T at run time.
s.x=0 when s holds a class S at run time.
s.x=0 when s holds a class T at run time.

The last line shows that, indeed, the field that is accessed does not depend on the run-time class of the referenced object; even if s holds a reference to an object of class T, the expression s.x refers to the x field of class S, because the type of the expression s is S. Objects of class T contain two fields named x, one for class T and one for its superclass S.

This lack of dynamic lookup for field accesses allows Java to run efficiently with straightforward implementations. The power of late binding and overriding is available in Java, but only when instance methods are used. Consider the same example using instance methods to access the fields:

class S { int x = 0; int z() { return x; } }
class T extends S { int x = 1; int z() { return x; } }
class Test {

    public static void main(String[] args) {
        T t = new T();
        System.out.println("t.z()=" + t.z() + when("t", t));
        S s = new S();
        System.out.println("s.z()=" + s.z() + when("s", s));
        s = t;
        System.out.println("s.z()=" + s.z() + when("s", s));
    }

    static String when(String name, Object t) {
        return " when " + name + " holds a "
            + t.getClass() + " at run time.";
    }
}

Now the output is:

t.z()=1 when t holds a class T at run time.
s.z()=0 when s holds a class S at run time.
s.z()=1 when s holds a class T at run time.

The last line shows that, indeed, the method that is accessed does depend on the run-time class of referenced object; when s holds a reference to an object of class T, the expression s.z() refers to the z method of class T, despite the fact that the type of the expression s is S. Method z of class T overrides method z of class S.

The following example demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

class Test {
    static String mountain = "Chocorua";

    static Test favorite(){
        System.out.print("Mount ");
        return null;
    }

    public static void main(String[] args) {
        System.out.println(favorite().mountain);
    }
}

It compiles, executes, and prints:

Mount Chocorua

Even though the result of favorite() is null, a NullPointerException is not thrown. That "Mount " is printed demonstrates that the Primary expression is indeed fully evaluated at run time, despite the fact that only its type, not its value, is used to determine which field to access (because the field mountain is static).


15.10.2 Accessing Superclass Members using super

The special form using the keyword super is valid only in an instance method or constructor, or in the initializer of an instance variable of a class; these are exactly the same situations in which the keyword this may be used (§15.7.2). The form involving super may not be used anywhere in the class Object, since Object has no superclass; if super appears in class Object, then a compile-time error results.

Suppose that a field access expression super.name appears within class C, and the immediate superclass of C is class S. Then super.name is treated exactly as if it had been the expression ((S)this).name; thus, it refers to the field named name of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named name that is visible in class S, even if that field is hidden by a declaration of a field named name in class C.

The use of super is demonstrated by the following example:

interface I { int x = 0; }
class T1 implements I { int x = 1; }
class T2 extends T1 { int x = 2; }
class T3 extends T2 {
    int x = 3;
    void test() {
        System.out.println("x=\t\t"+x);
        System.out.println("super.x=\t\t"+super.x);
        System.out.println("((T2)this).x=\t"+((T2)this).x);
        System.out.println("((T1)this).x=\t"+((T1)this).x);
        System.out.println("((I)this).x=\t"+((I)this).x);
    }
}
class Test {
    public static void main(String[] args) {
        new T3().test();
    }
}

which produces the output:

x=					3
super.x=					2
((T2)this).x=					2
((T1)this).x=					1
((I)this).x=					0

Within class T3, the expression super.x is treated exactly as if it were:

((T2)this).x


15.11 Method Invocation Expressions

A method invocation expression is used to invoke a class or instance method.

MethodInvocation:

    MethodName ( ArgumentListopt )

    Primary . Identifier ( ArgumentListopt )

    super . Identifier ( ArgumentListopt )

The definition of ArgumentList from §15.8 is repeated here for convenience:

ArgumentList:

    Expression

    ArgumentList , Expression

Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.

Determining the method that will be invoked by a method invocation expression involves several steps. The following three sections describe the compile-time processing of a method invocation; the determination of the type of the method invocation expression is described in §15.11.3.


15.11.1 Compile-Time Step 1: Determine Class or Interface to Search

The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to check for definitions of methods of that name. There are several cases to consider, depending on the form that precedes the left parenthesis, as follows:

  • If the form is MethodName, then there are three subcases:
    • If it is a simple name, that is, just an Identifier, then the name of the method is the Identifier and the class or interface to search is the one whose declaration contains the method invocation.
    • If it is a qualified name of the form TypeName . Identifier, then the name of the method is the Identifier and the class to search is the one named by the TypeName. If TypeName is the name of an interface rather than a class, then a compile-time error occurs, because this form can invoke only static methods and interfaces have no static methods.
    • In all other cases, the qualified name has the form FieldName . Identifier; then the name of the method is the Identifier and the class or interface to search is the declared type of the field named by the FieldName.
  • If the form is Primary . Identifier, then the name of the method is the Identifier and the class or interface to be searched is the type of the Primary expression.
  • If the form is super . Identifier, then the name of the method is the Identifier and the class to be searched is the superclass of the class whose declaration contains the method invocation. A compile-time error occurs if such a method invocation occurs in an interface, or in the class Object, or in a static method, a static initializer, or the initializer for a static variable. It follows that a method invocation of this form may appear only in a class other than Object, and only in the body of an instance method, the body of a constructor, or an initializer for an instance variable.


15.11.2 Compile-Time Step 2: Determine Method Signature

The hand-writing experts were called upon for their opinion of the signature . . .
—Agatha Christie, The Mysterious Affair at Styles (1920), Chapter 11

The second step searches the class or interface determined in the previous step for method declarations. This step uses the name of the method and the types of the argument expressions to locate method declarations that are both applicable and accessible, that is, declarations that can be correctly invoked on the given arguments. There may be more than one such method declaration, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method declaration is one used at run time to do the method dispatch.

15.11.2.1 Find Methods that are Applicable and Accessible

A method declaration is applicable to a method invocation if and only if both of the following are true:

  • The number of parameters in the method declaration equals the number of argument expressions in the method invocation.
  • The type of each actual argument can be converted by method invocation conversion (§5.3) to the type of the corresponding parameter. Method invocation conversion is the same as assignment conversion (§5.2), except that constants of type int are never implicitly narrowed to byte, short, or char.

The class or interface determined by the process described in §15.11.1 is searched for all method declarations applicable to this method invocation; method definitions inherited from superclasses and superinterfaces are included in this search.

Whether a method declaration is accessible to a method invocation depends on the access modifier (public, none, protected, or private) in the method declaration and on where the method invocation appears.

If the class or interface has no method declaration that is both applicable and accessible, then a compile-time error occurs.

In the example program:

public class Doubler {
    static int two() { return two(1); }
    private static int two(int i) { return 2*i; }
}

class Test extends Doubler {
    public static long two(long j) {return j+j; }

    public static void main(String[] args) {
        System.out.println(two(3));
        System.out.println(Doubler.two(3));	// compile-time error
    }
}

for the method invocation two(1) within class Doubler, there are two accessible methods named two, but only the second one is applicable, and so that is the one invoked at run time. For the method invocation two(3) within class Test, there are two applicable methods, but only the one in class Test is accessible, and so that is the one to be invoked at run time (the argument 3 is converted to type long). For the method invocation Doubler.two(3), the class Doubler, not class Test, is searched for methods named two; the only applicable method is not accessible, and so this method invocation causes a compile-time error.

Another example is:

class ColoredPoint {
    int x, y;
    byte color;
    void setColor(byte color) { this.color = color; }
}

class Test {
    public static void main(String[] args) {
        ColoredPoint cp = new ColoredPoint();
        byte color = 37;
        cp.setColor(color);
        cp.setColor(37);											// compile-time error
    }
}

Here, a compile-time error occurs for the second invocation of setColor, because no applicable method can be found at compile time. The type of the literal 37 is int, and int cannot be converted to byte by method invocation conversion. Assignment conversion, which is used in the initialization of the variable color, performs an implicit conversion of the constant from type int to byte, which is permitted because the value 37 is small enough to be represented in type byte; but such a conversion is not allowed for method invocation conversion.

If the method setColor had, however, been declared to take an int instead of a byte, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from byte to int. However, a narrowing cast would then be required in the body of setColor:

    void setColor(int color) { this.color = (byte)color; }

15.11.2.2 Choose the Most Specific Method

If more than one method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. Java uses the rule that the most specific method is chosen.

The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

The precise definition is as follows. Let m be a name and suppose that there are two declarations of methods named m, each having n parameters. Suppose that one declaration appears within a class or interface T and that the types of the parameters are T1, . . . , Tn; suppose moreover that the other declaration appears within a class or interface U and that the types of the parameters are U1, . . . , Un. Then the method m declared in T is more specific than the method m declared in U if and only if both of the following are true:

  • T can be converted to U by method invocation conversion.
  • Tj can be converted to Uj by method invocation conversion, for all j from 1 to n.

A method is said to be maximally specific for a method invocation if it is applicable and accessible and there is no other applicable and accessible method that is more specific.

If there is exactly one maximally specific method, then it is in fact the most specific method; it is necessarily more specific than any other method that is applicable and accessible. It is then subjected to some further compile-time checks as described in §15.11.3.

It is possible that no method is the most specific, because there are two or more maximally specific method declarations. In this case, we say that the method invocation is ambiguous, and a compile-time error occurs.

15.11.2.3 Example: Overloading Ambiguity

Consider the example:

class Point { int x, y; }
class ColoredPoint extends Point { int color; }

class Test {

    static void test(ColoredPoint p, Point q) {
        System.out.println("(ColoredPoint, Point)");
    }

    static void test(Point p, ColoredPoint q) {
        System.out.println("(Point, ColoredPoint)");
    }

    public static void main(String[] args) {
        ColoredPoint cp = new ColoredPoint();
        test(cp, cp);											// compile-time error
    }
}

This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous.

If a third definition of test were added:

    static void test(ColoredPoint p, ColoredPoint q) {
        System.out.println("(ColoredPoint, ColoredPoint)");
    }

then it would be more specific than the other two, and the method invocation would no longer be ambiguous.

15.11.2.4 Example: Return Type Not Considered

As another example, consider:

class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {

    static int test(ColoredPoint p) {
        return color;
    }

    static String test(Point p) {
        return "Point";
    }

    public static void main(String[] args) {
        ColoredPoint cp = new ColoredPoint();
        String s = test(cp); // compile-time error
    }
}

Here the most specific declaration of method test is the one taking a parameter of type ColoredPoint. Because the result type of the method is int, a compile- time error occurs because an int cannot be converted to a String by assignment conversion. This example shows that, in Java, the result types of methods do not participate in resolving overloaded methods, so that the second test method, which returns a String, is not chosen, even though it has a result type that would allow the example program to compile without error.

15.11.2.5 Example: Compile-Time Resolution

The most applicable method is chosen at compile time; its descriptor determines what method is actually executed at run time. If a new method is added to a class, then Java code that was compiled with the old definition of the class might not use the new method, even if a recompilation would cause this method to be chosen.

So, for example, consider two compilation units, one for class Point:

package points;
public class Point {
    public int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    public String toString() { return toString(""); }

    public String toString(String s) {
        return "(" + x + "," + y + s + ")";
    }
}

and one for class ColoredPoint:

package points;
public class ColoredPoint extends Point {

    public static final int
        RED = 0, GREEN = 1, BLUE = 2;

    public static String[] COLORS =
        { "red", "green", "blue" };
    public byte color;

    public ColoredPoint(int x, int y, int color) {
        super(x, y); this.color = (byte)color;
    }

    /** Copy all relevant fields of the argument into
            this ColoredPoint object. */
    public void adopt(Point p) { x = p.x; y = p.y; }

    public String toString() {
        String s = "," + COLORS[color];
        return super.toString(s);
    }
}

Now consider a third compilation unit that uses ColoredPoint:

import points.*;
class Test {
    public static void main(String[] args) {
        ColoredPoint cp =
            new ColoredPoint(6, 6, ColoredPoint.RED);
        ColoredPoint cp2 =
            new ColoredPoint(3, 3, ColoredPoint.GREEN);
        cp.adopt(cp2);
        System.out.println("cp: " + cp);
    }
}

The output is:

cp: (3,3,red)

The application programmer who coded class Test has expected to see the word green, because the actual argument, a ColoredPoint, has a color field, and color would seem to be a "relevant field" (of course, the documentation for the package Points ought to have been much more precise!).

Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of adopt has a signature that indicates a method of one parameter, and the parameter is of type Point. This signature becomes part of the binary representation of class Test produced by the compiler and is used by the method invocation at run time.

Suppose the programmer reported this software error and the maintainer of the points package decided, after due deliberation, to correct it by adding a method to class ColoredPoint:

public void adopt(ColoredPoint p) {
    adopt((Point)p); color = p.color;
}

If the application programmer then runs the old binary file for Test with the new binary file for ColoredPoint, the output is still:

cp: (3,3,red)

because the old binary file for Test still has the descriptor "one parameter, whose type is Point; void" associated with the method call cp.adopt(cp2). If the source code for Test is recompiled, the compiler will then discover that there are now two applicable adopt methods, and that the signature for the more specific one is "one parameter, whose type is ColoredPoint; void"; running the program will then produce the desired output:

cp: (3,3,green)

With forethought about such problems, the maintainer of the points package could fix the ColoredPoint class to work with both newly compiled and old code, by adding defensive code to the old adopt method for the sake of old code that still invokes it on ColoredPoint arguments:

public void adopt(Point p) {
    if (p instanceof ColoredPoint)
        color = ((ColoredPoint)p).color;
    x = p.x; y = p.y;
}

A similar consideration applies if a method is to be moved from a class to a superclass. In this case a forwarding method can be left behind for the sake of old code. The maintainer of the points package might choose to move the adopt method that takes a Point argument up to class Point, so that all Point objects may enjoy the adopt functionality. To avoid compatibility problems with old binary code, the maintainer should leave a forwarding method behind in class ColoredPoint:

public void adopt(Point p) {
    if (p instanceof ColoredPoint)
        color = ((ColoredPoint)p).color;
    super.adopt(p);
}

Ideally, Java code should be recompiled whenever code that it depends on is changed. However, in an environment where different Java classes are maintained by different organizations, this is not always feasible. Defensive programming with careful attention to the problems of class evolution can make upgraded code much more robust. See §13 for a detailed discussion of binary compatibility and type evolution.


15.11.3 Compile-Time Step 3: Is the Chosen Method Appropriate?

If there is a most specific method declaration for a method invocation, it is called the compile-time declaration for the method invocation. Two further checks must be made on the compile-time declaration:

  • If the method invocation has, before the left parenthesis, a MethodName of the form Identifier, and the method invocation appears within a static method, a static initializer, or the initializer for a static variable, then the compile-time declaration must be static. If, instead, the compile-time declaration for the method invocation is for an instance method, then a compile-time error occurs. (The reason is that a method invocation of this form cannot be used to invoke an instance method in places where this (§15.7.2) is not defined.)
  • If the method invocation has, before the left parenthesis, a MethodName of the form TypeName . Identifier, then the compile-time declaration should be static. If the compile-time declaration for the method invocation is for an instance method, then a compile-time error occurs. (The reason is that a method invocation of this form does not specify a reference to an object that can serve as this within the instance method.)
  • If the compile-time declaration for the method invocation is void, then the method invocation must be a top-level expression, that is, the Expression in an expression statement (§14.7) or in the ForInit or ForUpdate part of a for statement (§14.12), or a compile-time error occurs. (The reason is that such a method invocation produces no value and so must be used only in a situation where a value is not needed.)

The following compile-time information is then associated with the method invocation for use at run time:

  • The name of the method.
  • The class or interface that contains the compile-time declaration.
  • The number of parameters and the types of the parameters, in order.
  • The result type, or void, as declared in the compile-time declaration.
  • The invocation mode, computed as follows:
    • If the compile-time declaration has the static modifier, then the invocation mode is static.
    • Otherwise, if the compile-time declaration has the private modifier, then the invocation mode is nonvirtual.
    • Otherwise, if the part of the method invocation before the left parenthesis is of the form super . Identifier, then the invocation mode is super.
    • Otherwise, if the compile-time declaration is in an interface, then the invocation mode is interface.
    • Otherwise, the invocation mode is virtual.

If the compile-time declaration for the method invocation is not void, then the type of the method invocation expression is the result type specified in the compile-time declaration.


15.11.4 Runtime Evaluation of Method Invocation

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

15.11.4.1 Compute Target Reference (If Necessary)

There are several cases to consider, depending on which of the three productions for MethodInvocation (§15.11) is involved:

  • If the first production for MethodInvocation, which includes a MethodName, is involved, then there are three subcases:
    • If the MethodName is a simple name, that is, just an Identifier, then there are two subcases:
      • If the invocation mode is static, then there is no target reference.
      • Otherwise, the target reference is the value of this.
    • If the MethodName is a qualified name of the form TypeName . Identifier, then there is no target reference.
    • If the MethodName is a qualified name of the form FieldName . Identifier, then there are two subcases:
      • If the invocation mode is static, then there is no target reference.
      • Otherwise, the target reference is the value of the expression FieldName.
  • If the second production for MethodInvocation, which includes a Primary, is involved, then there are two subcases:
    • If the invocation mode is static, then there is no target reference. The expression Primary is evaluated, but the result is then discarded.
    • Otherwise, the expression Primary is evaluated and the result is used as the target reference.

In either case, if the evaluation of the Primary expression completes abruptly, then no part of any argument expression appears to have been evaluated, and the method invocation completes abruptly for the same reason.

  • If the third production for MethodInvocation, which includes the keyword super, is involved, then the target reference is the value of this.

15.11.4.2 Evaluate Arguments

The argument expressions are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason.

15.11.4.3 Check Accessibility of Type and Method

Let C be the class containing the method invocation, and let T be the class or interface that contained the method being invoked, and m be the name of the method, as determined at compile time (§15.11.3).

A Java Virtual Machine must insure, as part of linkage, that the method m still exists in the type T. If this is not true, then a NoSuchMethodError (which is a subclass of IncompatibleClassChangeError) occurs. If the invocation mode is interface, then the virtual machine must also check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an IncompatibleClassChangeError occurs.

The virtual machine must also insure, during linkage, that the type T and the method m are accessible. For the type T:

  • If T is in the same package as C, then T is accessible.
  • If T is in a different package than C, and T is public, then T is accessible.

For the method m:

  • If m is public, then m is accessible. (All members of interfaces are public (§9.2)).
  • If m is protected, then m is accessible if and only if either T is in the same package as C, or C is T or a subclass of T.
  • If m has default (package) access, then m is accessible if and only if T is in the same package as C.
  • If m is private, then m is accessible if and only if and C is T.

If either T or m is not accessible, then an IllegalAccessError occurs (§12.3).

15.11.4.4 Locate Method to Invoke

The strategy for method lookup depends on the invocation mode.

If the invocation mode is static, no target reference is needed and overriding is not allowed. Method m of class T is the one to be invoked.

Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is null, a NullPointerException is thrown at this point. Otherwise, the target reference is said to refer to a target object and will be used as the value of the keyword this in the invoked method. The other four possibilities for the invocation mode are then considered.

If the invocation mode is nonvirtual, overriding is not allowed. Method m of class T is the one to be invoked.

Otherwise, the invocation mode is interface, virtual, or super, and overriding may occur. A dynamic method lookup is used. The dynamic lookup process starts from a class S, determined as follows:

  • If the invocation mode is interface or virtual, then S is initially the actual run-time class R of the target object. If the target object is an array, R is the class Object. (Note that for invocation mode interface, R necessarily implements T; for invocation mode virtual, R is necessarily either T or a subclass of T.)
  • If the invocation mode is super, then S is initially the superclass of the class C that contains the method invocation.

The dynamic method lookup uses the following procedure to search class S, and then the superclasses of class S, as necessary, for method m.

  • If class S contains a declaration for a method named m with the same descriptor (same number of parameters, the same parameter types, and the same return type) required by the method invocation as determined at compile time (§15.11.3), then this is the method to be invoked, and the procedure terminates. (We note that as part of the loading and linking process that the virtual machine checks that an overriding method is at least as accessible as the overridden method; an IncompatibleClassChangeError occurs if this is not the case.)
  • Otherwise, if S is not T, this same lookup procedure is performed using the superclass of S; whatever it comes up with is the result of this lookup.

This procedure will find a suitable method when it reaches class T, because otherwise an IllegalAccessError would have been thrown by the checks of the previous section §15.11.4.3.

We note that the dynamic lookup process, while described here explicitly, will often be implemented implicitly, for example as a side-effect of the construction and use of per-class method dispatch tables, or the construction of other per-class structures used for efficient dispatch.

15.11.4.5 Create Frame, Synchronize, Transfer Control

A method m in some class S has been identified as the one to be invoked.

Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation (stack pointer, program counter, reference to previous activation frame, and the like). If there is not sufficient memory available to create such an activation frame, an OutOfMemoryError is thrown.

The newly created activation frame becomes the current activation frame. The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as this, if there is a target reference.

If the method m is a native method but the necessary native, implementation-dependent binary code has not been loaded (§20.16.13, §20.16.14) or otherwise cannot be dynamically linked, then an UnsatisfiedLinkError is thrown.

If the method m is not synchronized, control is transferred to the body of the method m to be invoked.

If the method m is synchronized, then an object must be locked before the transfer of control. No further progress can be made until the current thread can obtain the lock. If there is a target reference, then the target must be locked; otherwise the Class object for class S, the class of the method m, must be locked. Control is then transferred to the body of the method m to be invoked. The object is automatically unlocked when execution of the body of the method has completed, whether normally or abruptly. The locking and unlocking behavior is exactly as if the body of the method were embedded in a synchronized statement (§14.17).

15.11.4.6 Implementation Note: Combining Frames

In order to allow certain kinds of code optimization, implementations are permitted some freedom to combine activation frames. Suppose that a method invocation within class C is to invoke a method m within class S. Then the current activation frame may be used to provide space for S instead of creating a new activation frame only if one of the following conditions is true:

  • Class C and class S have the same class loader (§20.14) and class S is not SecurityManager or a subclass of SecurityManager.
  • Class S has no class loader (this fact indicates that it is a system class); class S is not SecurityManager or a subclass of SecurityManager; and method m is known not to call, directly or indirectly, any method of SecurityManager (§20.17) or any of its subclasses.

15.11.4.7 Example: Target Reference and Static Methods

When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

class Test {
    static void mountain() {

        System.out.println("Monadnock");

    }

    static Test favorite(){
        System.out.print("Mount ");
        return null;
    }

    public static void main(String[] args) {
        favorite().mountain();
    }
}

which prints:

Mount Monadnock

Here favorite returns null, yet no NullPointerException is thrown.

15.11.4.8 Example: Evaluation Order

As part of an instance method invocation (§15.11), there is an expression that denotes the object to be invoked. This expression appears to be fully evaluated before any part of any argument expression to the method invocation is evaluated.

So, for example, in:

class Test {
    public static void main(String[] args) {
        String s = "one";
        if (s.startsWith(s = "two"))
            System.out.println("oops");
    }
}

the occurrence of s before ".startsWith" is evaluated first, before the argument expression s="two". Therefore, a reference to the string "one" is remembered as the target reference before the local variable s is changed to refer to the string "two". As a result, the startsWith method (§20.12.20) is invoked for target object "one" with argument "two", so the result of the invocation is false, as the string "one" does not start with "two". It follows that the test program does not print "oops".

15.11.4.9 Example: Overriding

In the example:

class Point {

    final int EDGE = 20;
    int x, y;

    void move(int dx, int dy) {
        x += dx; y += dy;
        if (Math.abs(x) >= EDGE || Math.abs(y) >= EDGE)
            clear();
    }

    void clear() {
        System.out.println("\tPoint clear");
        x = 0; y = 0;
    }
}

class ColoredPoint extends Point {
    int color;

    void clear() {
        System.out.println("\tColoredPoint clear");
        super.clear();
        color = 0;
    }
}

the subclass ColoredPoint extends the clear abstraction defined by its superclass Point. It does so by overriding the clear method with its own method, which invokes the clear method of its superclass, using the form super.clear.

This method is then invoked whenever the target object for an invocation of clear is a ColoredPoint. Even the method move in Point invokes the clear method of class ColoredPoint when the class of this is ColoredPoint, as shown by the output of this test program:

class Test {
    public static void main(String[] args) {
        Point p = new Point();
        System.out.println("p.move(20,20):");
        p.move(20, 20);
        ColoredPoint cp = new ColoredPoint();
        System.out.println("cp.move(20,20):");
        cp.move(20, 20);
        p = new ColoredPoint();
        System.out.println("p.move(20,20), p colored:");
        p.move(20, 20);
    }
}

which is:

p.move(20,20):
    Point clear
cp.move(20,20):
    ColoredPoint clear
    Point clear
p.move(20,20), p colored:
    ColoredPoint clear
    Point clear

Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to clear in the body of Point.move (which is really syntactic shorthand for this.clear) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by this) rather than a method chosen "early" (at compile time, based only on the type of this). This provides the Java programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.

15.11.4.10 Example: Method Invocation using super

An overridden instance method of a superclass may be accessed by using the keyword super to access the members of the immediate superclass, bypassing any overriding declaration in the class that contains the method invocation.

When accessing an instance variable, super means the same as a cast of this (§15.10.2), but this equivalence does not hold true for method invocation. This is demonstrated by the example:

class T1 {
    String s() { return "1"; }
}

class T2 extends T1 {
    String s() { return "2"; }
}

class T3 extends T2 {
    String s() { return "3"; }

    void test() {
        System.out.println("s()=\t\t"+s());
        System.out.println("super.s()=\t"+super.s());
        System.out.print("((T2)this).s()=\t");
            System.out.println(((T2)this).s());
        System.out.print("((T1)this).s()=\t");
            System.out.println(((T1)this).s());
    }
}

class Test {
    public static void main(String[] args) {
        T3 t3 = new T3();
        t3.test();
    }
}

which produces the output:

s()=					3
super.s()=					2
((T2)this).s()=					3
((T1)this).s()=					3

The casts to types T1 and T2 do not change the method that is invoked, because the instance method to be invoked is chosen according to the run-time class of the object referred to be this. A cast does not change the class of an object; it only checks that the class is compatible with the specified type.


15.12 Array Access Expressions

An array access expression refers to a variable that is a component of an array.

ArrayAccess:

    ExpressionName [ Expression ]

    PrimaryNoNewArray [ Expression ]

An array access expression contains two subexpressions, the array reference expression (before the left bracket) and the index expression (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression (§15.9).

The type of the array reference expression must be an array type (call it T[], an array whose components are of type T) or a compile-time error results. Then the type of the array access expression is T.

The index expression undergoes unary numeric promotion (§5.6.1); the promoted type must be int.

The result of an array reference is a variable of type T, namely the variable within the array selected by the value of the index expression. This resulting variable, which is a component of the array, is never considered final, even if the array reference was obtained from a final variable.


15.12.1 Run-time Evaluation

An array access expression is evaluated using the following procedure:

  • First, the array reference expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason and the index expression is not evaluated.
  • Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
  • Otherwise, if the value of the array reference expression is null, then a NullPointerException is thrown.
  • Otherwise, the value of the array reference expression indeed refers to an array. If the value of the index expression is less than zero, or greater than or equal to the array's length, then an IndexOutOfBoundsException is thrown.
  • Otherwise, the result of the array reference is the variable of type T, within the array, selected by the value of the index expression. (Note that this resulting variable, which is a component of the array, is never considered final, even if the array reference expression is a final variable.)


15.12.2 Examples: Array Access Evaluation Order

In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. For example, in the (admittedly monstrous) expression a[(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated. This array referenced by the original value of a is then subscripted by a value that is element 3 of another array (possibly the same array) that was referenced by b and is now also referenced by a.

Thus, the example:

class Test {
    public static void main(String[] args) {
        int[] a = { 11, 12, 13, 14 };
        int[] b = { 0, 1, 2, 3 };
        System.out.println(a[(a=b)[3]]);
    }
}

prints:

14

because the monstrous expression's value is equivalent to a[b[3]] or a[3] or 14.

If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated. Thus, the example:

class Test {
    public static void main(String[] args) {
        int index = 1;
        try {
            skedaddle()[index=2]++;
        } catch (Exception e) {
            System.out.println(e + ", index=" + index);
        }
    }
    static int[] skedaddle() throws Exception {
        throw new Exception("Ciao");
    }
}

prints:

java.lang.Exception: Ciao, index=1

because the embedded assignment of 2 to index never occurs.

If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at run time, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally. Thus, the example:

class Test {

    public static void main(String[] args) {
        int index = 1;
        try {
            nada()[index=2]++;
        } catch (Exception e) {
            System.out.println(e + ", index=" + index);
        }
    }
    static int[] nada() { return null; }
}

prints:

java.lang.NullPointerException, index=2

because the embedded assignment of 2 to index occurs before the check for a null pointer. As a related example, the program:

class Test {

    public static void main(String[] args) {
        int[] a = null;
        try {
            int i = a[vamoose()];
            System.out.println(i);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    static int vamoose() throws Exception {
        throw new Exception("Twenty-three skidoo!");
    }
}

always prints:

java.lang.Exception: Twenty-three skidoo!

A NullPointerException never occurs, because the index expression must be completely evaluated before any part of the indexing operation occurs, and that includes the check as to whether the value of the left-hand operand is null.


15.13 Postfix Expressions

Postfix expressions include uses of the postfix ++ and -- operators. Also, as discussed in §15.7, names are not considered to be primary expressions, but are handled separately in the grammar to avoid certain ambiguities. They become interchangeable only here, at the level of precedence of postfix expressions.

PostfixExpression:

    Primary

    ExpressionName

    PostIncrementExpression

    PostDecrementExpression


15.13.1 Names

A name occurring in an expression may be, syntactically, an ExpressionName (§6.5). The meaning of such an ExpressionName depends on its form:

  • If it is a simple name, that is, just an Identifier, then there are two cases:
    • If the Identifier occurs within the scope of a parameter or local variable named by that same Identifier, then the type of the ExpressionName is the declared type of the parameter or local variable; moreover, the value of the ExpressionName is a variable, namely, the parameter or local variable itself.
    • Otherwise, the ExpressionName is treated exactly as if it had been the field access expression (§15.10):
    this.Identifier containing the keyword this (§15.7.2).

  • Otherwise, if it is a qualified name of the form PackageName . Identifier, then a compile-time error occurs.
  • Otherwise, if it is a qualified name of the form TypeName . Identifier, then it is refers to a static field of the class or interface named by the TypeName. A compile-time error occurs if TypeName does not name a class or interface. A compile-time error occurs if the class or interface named by TypeName does not contain an accessible static field named by the Identifier. The type of the ExpressionName is the declared type of the static field. The value of the ExpressionName is a variable, namely, the static field itself.
  • Otherwise, it is a qualified name of the form Ename . Identifier, where Ename is itself an ExpressionName, and the ExpressionName is treated exactly as if it had been the field access expression (§15.10): (Ename).Identifier

    containing a parenthesized expression (§15.7.3).


15.13.2 Postfix Increment Operator ++

PostIncrementExpression:

    PostfixExpression ++

A postfix expression followed by a ++ operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.

At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.


15.13.3 Postfix Decrement Operator --

PostDecrementExpression:

    PostfixExpression --

A postfix expression followed by a -- operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.

At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.

A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix decrement operator.


15.14 Unary Operators

The unary operators include +, -, ++, --, ~, !, and cast operators. Expressions with unary operators group right-to-left, so that -~x means the same as -(~x).

UnaryExpression:

    PreIncrementExpression

    PreDecrementExpression

    + UnaryExpression

    - UnaryExpression

    UnaryExpressionNotPlusMinus

PreIncrementExpression:

    ++ UnaryExpression

PreDecrementExpression:

    -- UnaryExpression

UnaryExpressionNotPlusMinus:

    PostfixExpression

    ~ UnaryExpression

    ! UnaryExpression

    CastExpression

The following productions from §15.15 are repeated here for convenience:

CastExpression:

    ( PrimitiveType ) UnaryExpression

    ( ReferenceType ) UnaryExpressionNotPlusMinus

This portion of the Java grammar contains some tricks to avoid two potential syntactic ambiguities.

The first potential ambiguity would arise in expressions such as (p)+q, which looks, to a C or C++ programmer, as though it could be either be a cast to type p of a unary + operating on q, or a binary addition of two quantities p and q. In C and C++, the parser handles this problem by performing a limited amount of semantic analysis as it parses, so that it knows whether p is the name of a type or the name of a variable.

Java takes a different approach. The result of the + operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if p is a keyword naming a primitive type, then (p)+q can make sense only as a cast of a unary expression. However, if p is not a keyword naming a primitive type, then (p)+q can make sense only as a binary arithmetic operation. Similar remarks apply to the - operator. The grammar shown above splits CastExpression into two cases to make this distinction. The nonterminal UnaryExpression includes all unary operator, but the nonterminal UnaryExpressionNotPlusMinus excludes uses of all unary operators that could also be binary operators, which in Java are + and -.

The second potential ambiguity is that the expression (p)++ could, to a C or C++ programmer, appear to be either a postfix increment of a parenthesized expression or the beginning of a cast, for example, in (p)++q. As before, parsers for C and C++ know whether p is the name of a type or the name of a variable. But a parser using only one-token lookahead and no semantic analysis during the parse would not be able to tell, when ++ is the lookahead token, whether (p) should be considered a Primary expression or left alone for later consideration as part of a CastExpression.

In Java, the result of the ++ operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if p is a keyword naming a primitive type, then (p)++ can make sense only as a cast of a prefix increment expression, and there had better be an operand such as q following the ++. However, if p is not a keyword naming a primitive type, then (p)++ can make sense only as a postfix increment of p. Similar remarks apply to the -- operator. The nonterminal UnaryExpressionNotPlusMinus therefore also excludes uses of the prefix operators ++ and --.


15.14.1 Prefix Increment Operator ++

A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.

At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.

A variable that is declared final cannot be incremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix increment operator.


15.14.2 Prefix Decrement Operator --

He must increase, but I must decrease.
—John 3:30

A unary expression preceded by a -- operator is a prefix decrement expression. The result of the unary expression must be a variable of a numeric type, or a compile-time error occurs. The type of the prefix decrement expression is the type of the variable. The result of the prefix decrement expression is not a variable, but a value.

At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

A variable that is declared final cannot be decremented, because when an access of a final variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix decrement operator.


15.14.3 Unary Plus Operator +

The type of the operand expression of the unary + operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.

At run time, the value of the unary plus expression is the promoted value of the operand.


15.14.4 Unary Minus Operator -

The type of the operand expression of the unary - operator must be a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary minus expression is the promoted type of the operand.

At run time, the value of the unary plus expression is the arithmetic negation of the promoted value of the operand.

For integer values, negation is the same as subtraction from zero. Java uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x equals +0.0, but -x equals -0.0. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:

  • If the operand is NaN, the result is NaN (recall that NaN has no sign).
  • If the operand is an infinity, the result is the infinity of opposite sign.
  • If the operand is a zero, the result is the zero of opposite sign.


15.14.5 Bitwise Complement Operator ~

The type of the operand expression of the unary ~ operator must be a primitive integral type, or a compile-time error occurs. Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary bitwise complement expression is the promoted type of the operand.

At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.


15.14.6 Logical Complement Operator !

The type of the operand expression of the unary ! operator must be boolean, or a compile-time error occurs. The type of the unary logical complement expression is boolean.

At run time, the value of the unary logical complement expression is true if the operand value is false and false if the operand value is true.


15.15 Cast Expressions

My days among the dead are passed;
Around me I behold,
Where'er these casual eyes are cast,
The mighty minds of old . . .
—Robert Southey (1774-1843), Occasional Pieces, xviii

A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.

CastExpression:

    ( PrimitiveType Dimsopt ) UnaryExpression

    ( ReferenceType ) UnaryExpressionNotPlusMinus

See §15.14 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.

The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.

At run time, the operand value is converted by casting conversion (§5.4) to the type specified by the cast operator.

Not all casts are permitted by the Java language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. A ClassCastException is thrown if a cast is found at run time to be impermissible.


15.16 Multiplicative Operators

The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

MultiplicativeExpression:

    UnaryExpression

    MultiplicativeExpression * UnaryExpression

    MultiplicativeExpression / UnaryExpression

    MultiplicativeExpression % UnaryExpression

The type of each of the operands of a multiplicative operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). The type of a multiplicative expression is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.


15.16.1 Multiplication Operator *

Entia non sunt multiplicanda praeter necessitatem.
—William of Occam (c. 1320)

The binary * operator performs multiplication, producing the product of its operands. Multiplication is a commutative operation if the operand expressions have no side effects. While integer multiplication is associative when the operands are all of the same type, floating-point multiplication is not associative.

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result is positive if both operands have the same sign, and negative if the operands have different signs.
  • Multiplication of an infinity by a zero results in NaN.
  • Multiplication of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
  • In the remaining cases, where neither an infinity or NaN is involved, the product is computed. If the magnitude of the product is too large to represent, we say the operation overflows. The result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows; the result is then a zero of appropriate sign. Otherwise, the product is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 (§4.2.4).

Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator * never throws a run-time exception.


15.16.2 Division Operator /

Gallia est omnis divisa in partes tres.
—Julius Caesar, Commentaries on the Gallic Wars (58 B.C.)

The binary / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying [image]; moreover, q is positive when [image] and n and d have the same sign, but q is negative when [image] and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

The result of a floating-point division is determined by the specification of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
  • Division of an infinity by an infinity results in NaN.
  • Division of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
  • Division of a finite value by an infinity results in a signed zero. The sign is determined by the rule stated above.
  • Division of a zero by a zero results in NaN; division of zero by any other finite value results in a signed zero. The sign is determined by the rule stated above.
  • Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the quotient is computed. If the magnitude of the quotient is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows and the result is then a zero of appropriate sign. Otherwise, the quotient is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 (§4.2.4).

Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception.


15.16.3 Remainder Operator %

And on the pedestal these words appear:
"My name is Ozymandias, king of kings:
Look on my works, ye Mighty, and despair!"
Nothing beside remains.
—Percy Bysshe Shelley, Ozymandias (1817)

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

In C and C++, the remainder operator accepts only integral operands, but in Java, it also accepts floating-point operands.

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is 0, then an ArithmeticException is thrown.

Examples:

5%3 produces 2		(note that 5/3 produces 1)
5%(-3) produces 2		(note that 5/(-3) produces -1)
(-5)%3 produces -2		(note that (-5)/3 produces -1)
(-5)%(-3) produces -2		(note that (-5)/(-3) produces 1)

The result of a floating-point remainder operation as computed by the % operator is not the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is not analogous to that of the usual integer remainder operator. Instead, the Java language defines % on floating-point operations to behave in a manner analogous to that of the Java integer remainder operator; this may be compared with the C library function fmod. The IEEE 754 remainder operation may be computed by the Java library routine Math.IEEEremainder (§20.11.14).

The result of a Java floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation [image] where q is an integer that is negative only if [image] is negative and positive only if [image] is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

Evaluation of a floating-point remainder operator % never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.

Examples:

5.0%3.0 produces 2.0
5.0%(-3.0) produces 2.0
(-5.0)%3.0 produces -2.0
(-5.0)%(-3.0) produces -2.0


15.17 Additive Operators

The operators + and - are called the additive operators. They have the same precedence and are syntactically left-associative (they group left-to-right).

AdditiveExpression:

    MultiplicativeExpression

    AdditiveExpression + MultiplicativeExpression

    AdditiveExpression - MultiplicativeExpression

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a primitive numeric type, or a compile-time error occurs.

In every case, the type of each of the operands of the binary - operator must be a primitive numeric type, or a compile-time error occurs.


15.17.1 String Concatenation Operator +

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a newly created String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

15.17.1.1 String Conversion

Any type may be converted to type String by string conversion.

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:

  • If T is boolean, then use new Boolean(x) (§20.4).
  • If T is char, then use new Character(x) (§20.5).
  • If T is byte, short, or int, then use new Integer(x) (§20.7).
  • If T is long, then use new Long(x) (§20.8).
  • If T is float, then use new Float(x) (§20.9).
  • If T is double, then use new Double(x) (§20.10).

This reference value is then converted to type String by string conversion.

Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead. The toString method (§20.1.2) is defined by the primordial class Object (§20.1); many classes override it, notably Boolean, Character, Integer, Long, Float, Double, and String.

15.17.1.2 Optimization of String Concatenation

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class (§20.13) or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive objects, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

15.17.1.3 Examples of String Concatenation

The example expression:

"The square root of 2 is " + Math.sqrt(2)

produces the result:

"The square root of 2 is 1.4142135623730952"

The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:

a + b + c

is always regarded as meaning:

(a + b) + c

Therefore the result of the expression:

1 + 2 + " fiddlers"

is:

"3 fiddlers"

but the result of:

"fiddlers " + 1 + 2

is:

"fiddlers 12"

In this jocular little example:

class Bottles {

    static void printSong(Object stuff, int n) {
        String plural = "s";
        loop: while (true) {
            System.out.println(n + " bottle" + plural
                + " of " + stuff + " on the wall,");
            System.out.println(n + " bottle" + plural
                + " of " + stuff + ";");
            System.out.println("You take one down "
                + "and pass it around:");
            --n;
            plural = (n == 1) ? "" : "s";
            if (n == 0)
                break loop;
            System.out.println(n + " bottle" + plural
                + " of " + stuff + " on the wall!");
            System.out.println();
        }
        System.out.println("No bottles of " +
                                stuff + " on the wall!");
    }

}

the method printSong will print a version of a children's song. Popular values for stuff include "pop" and "beer"; the most popular value for n is 100. Here is the output that results from Bottles.printSong("slime", 3):

3 bottles of slime on the wall,
3 bottles of slime;
You take one down and pass it around:
2 bottles of slime on the wall!

2 bottles of slime on the wall,
2 bottles of slime;
You take one down and pass it around:
1 bottle of slime on the wall!

1 bottle of slime on the wall,
1 bottle of slime;
You take one down and pass it around:
No bottles of slime on the wall!

In the code, note the careful conditional generation of the singular "bottle" when appropriate rather than the plural "bottles"; note also how the string concatenation operator was used to break the long constant string:

"You take one down and pass it around:"

into two pieces to avoid an inconveniently long line in the source code.


15.17.2 Additive Operators (+ and -) for Numeric Types

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. The binary - operator performs subtraction, producing the difference of two numeric operands.

Binary numeric promotion is performed on the operands (§5.6.2). The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is int or long, then integer arithmetic is performed; if this promoted type is float or double, then floating-point arithmetic is performed.

Addition is a commutative operation if the operand expressions have no side effects. Integer addition is associative when the operands are all of the same type, but floating-point addition is not associative.

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

The result of a floating-point addition is determined using the following rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • The sum of two infinities of opposite sign is NaN.
  • The sum of two infinities of the same sign is the infinity of that sign.
  • The sum of an infinity and a finite value is equal to the infinite operand.
  • The sum of two zeros of opposite sign is positive zero.
  • The sum of two zeros of the same sign is the zero of that sign.
  • The sum of a zero and a nonzero finite value is equal to the nonzero operand.
  • The sum of two nonzero finite values of the same magnitude and opposite sign is positive zero.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the sum is computed. If the magnitude of the sum is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows; the result is then a zero of appropriate sign. Otherwise, the sum is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 (§4.2.4).

The binary - operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that a-b produces the same result as a+(-b). Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is not the same as negation, because if x is +0.0, then 0.0-x equals +0.0, but -x equals -0.0.

Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.


15.18 Shift Operators

What, I say, is to become of those wretches?
. . . What more can you say to them than "shift for yourselves?"
--Thomas Paine, The American Crisis (1780)

The shift operators include left shift <<, signed right shift >>, and unsigned right shift >>>; they are syntactically left-associative (they group left-to-right). The left- hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance.

ShiftExpression:

    AdditiveExpression

    ShiftExpression << AdditiveExpression

    ShiftExpression >> AdditiveExpression

    ShiftExpression >>> AdditiveExpression

The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion (§5.6.2) is not performed on the operands; rather, unary numeric promotion (§5.6.1) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.21.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.21.1) with the mask value 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.

The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.

The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is [image]. For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.

The value of n>>>s is n right-shifted s bit positions with zero-extension. If n is positive, then the result is the same as that of n>>s; if n is negative, the result is equal to that of the expression (n>>s)+(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)+(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value.)


15.19 Relational Operators

The relational operators are syntactically left-associative (they group left-to- right), but this fact is not useful; for example, a<b<c parses as (a<b)<c, which is always a compile-time error, because the type of a<b is always boolean and < is not an operator on boolean values.

RelationalExpression:

    ShiftExpression

    RelationalExpression < ShiftExpression

    RelationalExpression > ShiftExpression

    RelationalExpression <= ShiftExpression

    RelationalExpression >= ShiftExpression

    RelationalExpression instanceof ReferenceType

The type of a relational expression is always boolean.


15.19.1 Numerical Comparison Operators <, <=, >, and >=

The type of each of the operands of a numerical comparison operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:

  • If either operand is NaN, then the result is false.
  • All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.
  • Positive zero and negative zero are considered equal. Therefore, -0.0<0.0 is false, for example, but -0.0<=0.0 is true. (Note, however, that the methods Math.min (§20.11.27, §20.11.28) and Math.max (§20.11.31, §20.11.32) treat negative zero as being strictly smaller than positive zero.)

Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

  • The value produced by the < operator is true if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is false.
  • The value produced by the <= operator is true if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is false.
  • The value produced by the > operator is true if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is false.
  • The value produced by the >= operator is true if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is false.


15.19.2 Type Comparison Operator instanceof

The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.15) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

Consider the example program:

class Point { int x, y; }
class Element { int atomicNumber; }
class Test {
    public static void main(String[] args) {
        Point p = new Point();
        Element e = new Element();
        if (e instanceof Point) { // compile-time error
            System.out.println("I get your point!");
            p = (Point)e; // compile-time error
        }
    }
}

This example results in two compile-time errors. The cast (Point)e is incorrect because no instance of Element or any of its possible subclasses (none are shown here) could possibly be an instance of any subclass of Point. The instanceof expression is incorrect for exactly the same reason. If, on the other hand, the class Point were a subclass of Element (an admittedly strange notion in this example):

class Point extends Element { int x, y; }

then the cast would be possible, though it would require a run-time check, and the instanceof expression would then be sensible and valid. The cast (Point)e would never raise an exception because it would not be executed if the value of e could not correctly be cast to type Point.


15.20 Equality Operators

The equality operators are syntactically left-associative (they group left-to-right), but this fact is essentially never useful; for example, a==b==c parses as (a==b)==c. The result type of a==b is always boolean, and c must therefore be of type boolean or a compile-time error occurs. Thus, a==b==c does not test to see whether a, b, and c are all equal.

EqualityExpression:

    RelationalExpression

    EqualityExpression == RelationalExpression

    EqualityExpression != RelationalExpression

The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, a<b==c<d is true whenever a<b and c<d have the same truth value.

The equality operators may be used to compare two operands of numeric type, or two operands of type boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always boolean.

In all cases, a!=b produces the same result as !(a==b). The equality operators are commutative if the operand expressions have no side effects.


15.20.1 Numerical Equality Operators == and !=

If the operands of an equality operator are both of primitive numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

  • If either operand is NaN, then the result of == is false but the result of != is true. Indeed, the test x!=x is true if and only if the value of x is NaN. (The methods Float.isNaN (§20.9.19) and Double.isNaN (§20.10.17) may also be used to test whether a value is NaN.)
  • Positive zero and negative zero are considered equal. Therefore, -0.0==0.0 is true, for example.
  • Otherwise, two distinct floating-point values are considered unequal by the equality operators. In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.

Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:

  • The value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false.
  • The value produced by the != operator is true if the value of the left-hand operand is not equal to the value of the right-hand operand; otherwise, the result is false.


15.20.2 Boolean Equality Operators == and !=

If the operands of an equality operator are both of type boolean, then the operation is boolean equality. The boolean equality operators are associative.

The result of == is true if the operands are both true or both false; otherwise, the result is false.

The result of != is false if the operands are both true or both false; otherwise, the result is true. Thus != behaves the same as ^ (§15.21.2) when applied to boolean operands.


15.20.3 Reference Equality Operators == and !=

Things are more like they are now than they ever were before.
--Dwight D. Eisenhower

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.4). The run-time values of the two operands would necessarily be unequal.

At run time, the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false.

The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true.

While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t) (§20.12.9). See also §3.10.5 and §20.12.47.


15.21 Bitwise and Logical Operators

The bitwise operators and logical operators include the AND operator &, exclusive OR operator ^, and inclusive OR operator |. These operators have different precedence, with & having the highest precedence and | the lowest precedence. Each of these operators is syntactically left-associative (each groups left-to-right). Each operator is commutative if the operand expressions have no side effects. Each operator is associative.

AndExpression:

    EqualityExpression

    AndExpression & EqualityExpression

ExclusiveOrExpression:

    AndExpression

    ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:

    ExclusiveOrExpression

    InclusiveOrExpression | ExclusiveOrExpression

The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type boolean. All other cases result in a compile-time error.


15.21.1 Integer Bitwise Operators &, ^, and |

When both operands of an operator &, ^, or | are of primitive integral type, binary numeric promotion is first performed on the operands (§5.6.2). The type of the bitwise operator expression is the promoted type of the operands.

For &, the result value is the bitwise AND of the operand values.

For ^, the result value is the bitwise exclusive OR of the operand values.

For |, the result value is the bitwise inclusive OR of the operand values.

For example, the result of the expression 0xff00 & 0xf0f0 is 0xf000. The result of 0xff00 ^ 0xf0f0 is 0x0ff0.The result of 0xff00 | 0xf0f0 is 0xfff0.


15.21.2 Boolean Logical Operators &, ^, and |

When both operands of a &, ^, or | operator are of type boolean, then the type of the bitwise operator expression is boolean.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.


15.22 Conditional-And Operator &&

The && operator is like & (§15.21.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)&&(b))&&(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)&&((b)&&(c)).

ConditionalAndExpression:

    InclusiveOrExpression

    ConditionalAndExpression && InclusiveOrExpression

Each operand of && must be of type boolean, or a compile-time error occurs. The type of a conditional-and expression is always boolean.

At run time, the left-hand operand expression is evaluated first; if its value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.


15.23 Conditional-Or Operator ||

The || operator is like | (§15.21.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. It is syntactically left-associative (it groups left-to-right). It is fully associative with respect to both side effects and result value; that is, for any expressions a, b, and c, evaluation of the expression ((a)||(b))||(c) produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a)||((b)||(c)).

ConditionalOrExpression:

    ConditionalAndExpression

    ConditionalOrExpression || ConditionalAndExpression

Each operand of || must be of type boolean, or a compile-time error occurs. The type of a conditional-or expression is always boolean.

At run time, the left-hand operand expression is evaluated first; if its value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.


15.24 Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

ConditionalExpression:

    ConditionalOrExpression

    ConditionalOrExpression ? Expression : ConditionalExpression

The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.

The first expression must be of type boolean, or a compile-time error occurs.

The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type boolean, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.

Note that it is not permitted for either the second or the third operand expression to be an invocation of a void method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear (§14.7).

The type of a conditional expression is determined as follows:

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
  • Otherwise, if the second and third operands have numeric type, then there are several cases:
    • If one of the operands is of type byte and the other is of type short, then the type of the conditional expression is short.
    • If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
    • Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
  • If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
  • If the second and third operands are of different reference types, then it must be possible to convert one of the types to the other type (call this latter type T) by assignment conversion (§5.2); the type of the conditional expression is T. It is a compile-time error if neither type is assignment compatible with the other type.

At run time, the first operand expression of the conditional expression is evaluated first; its boolean value is then used to choose either the second or the third operand expression:

  • If the value of the first operand is true, then the second operand expression is chosen.
  • If the value of the first operand is false, then the third operand expression is chosen.

The chosen operand expression is then evaluated and the resulting value is converted to the type of the conditional expression as determined by the rules stated above. The operand expression not chosen is not evaluated for that particular evaluation of the conditional expression.


15.25 Assignment Operators

There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

AssignmentExpression:

    ConditionalExpression

    Assignment

Assignment:

    LeftHandSide AssignmentOperator AssignmentExpression

LeftHandSide:

    ExpressionName

    FieldAccess

    ArrayAccess

AssignmentOperator: one of

    = *= /= %= += -= <<= >>= >>>= &= ^= |=

The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access (§15.10) or an array access (§15.12). The type of the assignment expression is the type of the variable.

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

A variable that is declared final cannot be assigned to, because when an access of a final variable is used as an expression, the result is a value, not a variable, and so it cannot be used as the operand of an assignment operator.


15.25.1 Simple Assignment Operator =

A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion (§5.2).

At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then three steps are required:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the value of the right-hand operand is converted to the type of the left-hand variable and the result of the conversion is stored into the variable.

If the left-hand operand expression is an array access expression (§15.12), then many steps are required:

  • First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, if the value of the array reference subexpression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an IndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. This component is a variable; call its type SC. Also, let TC be the type of the left-hand operand of the assignment operator as determined at compile time.
    • If TC is a primitive type, then SC is necessarily the same as TC. The value of the right-hand operand is converted to a value of type TC and stored into the selected array component.
    • If T is a reference type, then SC may not be the same as T, but rather a type that extends or implements TC. Let RC be the class of the object referred to by the value of the right-hand operand at run time. The compiler may be able to prove at compile time that the array component will be of type TC exactly (for example, TC might be final). But if the compiler cannot prove at compile time that the array component will be of type TC exactly, then a check must be performed at run time to ensure that the class RC is assignment compatible (§5.2) with the actual type SC of the array component. This check is similar to a narrowing cast (§5.4, §15.15), except that if the check fails, an ArrayStoreException is thrown rather than a ClassCastException. Therefore:

      • If class RC is not assignable to type SC, then no assignment occurs and an ArrayStoreException is thrown.
      • Otherwise, the reference value of the right-hand operand is stored into the selected array component.

The rules for assignment to an array component are illustrated by the following example program:

class ArrayReferenceThrow extends RuntimeException { }

class IndexThrow extends RuntimeException { }

class RightHandSideThrow extends RuntimeException { }

class IllustrateSimpleArrayAssignment {

    static Object[] objects = { new Object(), new Object() };

    static Thread[] threads = { new Thread(), new Thread() };

    static Object[] arrayThrow() {
        throw new ArrayReferenceThrow();
    }

    static int indexThrow() { throw new IndexThrow(); }

    static Thread rightThrow() {
        throw new RightHandSideThrow();
    }

    static String name(Object q) {
        String sq = q.getClass().getName();
        int k = sq.lastIndexOf('.');
        return (k < 0) ? sq : sq.substring(k+1);
    }

    static void testFour(Object[] x, int j, Object y) {
        String sx = x == null ? "null" : name(x[0]) + "s";
        String sy = name(y);
        System.out.println();
        try {
            System.out.print(sx + "[throw]=throw => ");
            x[indexThrow()] = rightThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sx + "[throw]=" + sy + " => ");
            x[indexThrow()] = y;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sx + "[" + j + "]=throw => ");
            x[j] = rightThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sx + "[" + j + "]=" + sy + " => ");
            x[j] = y;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
    }

    public static void main(String[] args) {
        try {
            System.out.print("throw[throw]=throw => ");
            arrayThrow()[indexThrow()] = rightThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[throw]=Thread => ");
            arrayThrow()[indexThrow()] = new Thread();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]=throw => ");
            arrayThrow()[1] = rightThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]=Thread => ");
            arrayThrow()[1] = new Thread();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }

        testFour(null, 1, new StringBuffer());
        testFour(null, 1, new StringBuffer());
        testFour(null, 9, new Thread());
        testFour(null, 9, new Thread());
        testFour(objects, 1, new StringBuffer());
        testFour(objects, 1, new Thread());
        testFour(objects, 9, new StringBuffer());
        testFour(objects, 9, new Thread());
        testFour(threads, 1, new StringBuffer());
        testFour(threads, 1, new Thread());
        testFour(threads, 9, new StringBuffer());
        testFour(threads, 9, new Thread());
    }

}

This program prints:

throw[throw]=throw => ArrayReferenceThrow
throw[throw]=Thread => ArrayReferenceThrow
throw[1]=throw => ArrayReferenceThrow
throw[1]=Thread => ArrayReferenceThrow

null[throw]=throw => IndexThrow
null[throw]=StringBuffer => IndexThrow
null[1]=throw => RightHandSideThrow
null[1]=StringBuffer => NullPointerException

null[throw]=throw => IndexThrow
null[throw]=StringBuffer => IndexThrow
null[1]=throw => RightHandSideThrow
null[1]=StringBuffer => NullPointerException

null[throw]=throw => IndexThrow
null[throw]=Thread => IndexThrow
null[9]=throw => RightHandSideThrow
null[9]=Thread => NullPointerException

null[throw]=throw => IndexThrow
null[throw]=Thread => IndexThrow
null[9]=throw => RightHandSideThrow
null[9]=Thread => NullPointerException

Objects[throw]=throw => IndexThrow
Objects[throw]=StringBuffer => IndexThrow
Objects[1]=throw => RightHandSideThrow
Objects[1]=StringBuffer => Okay!

Objects[throw]=throw => IndexThrow
Objects[throw]=Thread => IndexThrow
Objects[1]=throw => RightHandSideThrow
Objects[1]=Thread => Okay!

Objects[throw]=throw => IndexThrow
Objects[throw]=StringBuffer => IndexThrow
Objects[9]=throw => RightHandSideThrow
Objects[9]=StringBuffer => IndexOutOfBoundsException

Objects[throw]=throw => IndexThrow
Objects[throw]=Thread => IndexThrow
Objects[9]=throw => RightHandSideThrow
Objects[9]=Thread => IndexOutOfBoundsException

Threads[throw]=throw => IndexThrow
Threads[throw]=StringBuffer => IndexThrow
Threads[1]=throw => RightHandSideThrow
Threads[1]=StringBuffer => ArrayStoreException

Threads[throw]=throw => IndexThrow
Threads[throw]=Thread => IndexThrow
Threads[1]=throw => RightHandSideThrow
Threads[1]=Thread => Okay!

Threads[throw]=throw => IndexThrow
Threads[throw]=StringBuffer => IndexThrow
Threads[9]=throw => RightHandSideThrow
Threads[9]=StringBuffer => IndexOutOfBoundsException

Threads[throw]=throw => IndexThrow
Threads[throw]=Thread => IndexThrow
Threads[9]=throw => RightHandSideThrow
Threads[9]=Thread => IndexOutOfBoundsException

The most interesting case of the lot is the one thirteenth from the end:

Threads[1]=StringBuffer => ArrayStoreException

which indicates that the attempt to store a reference to a StringBuffer into an array whose components are of type Thread throws an ArrayStoreException. The code is type-correct at compile time: the assignment has a left-hand side of type Object[] and a right-hand side of type Object. At run time, the first actual argument to method testFour is a reference to an instance of "array of Thread" and the third actual argument is a reference to an instance of class StringBuffer.


15.25.2 Compound Assignment Operators

All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left- hand operand is of type String.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. Note that the implied cast to type T may be either an identity conversion (§5.1.1) or a narrowing primitive conversion (§5.1.3). For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see §15.16.2), then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable and the result of the conversion is stored into the variable.

If the left-hand operand expression is an array access expression (§15.12), then many steps are required:

  • First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference subexpression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an IndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. (For a simple assignment operator, the evaluation of the right-hand operand occurs before the checks of the array reference subexpression and the index subexpression, but for a compound assignment operator, the evaluation of the right-hand operand occurs after these checks.)
  • Otherwise, consider the array component selected in the previous step, whose value was saved. This component is a variable; call its type S. Also, let T be the type of the left-hand operand of the assignment operator as determined at compile time.
    • If T is a primitive type, then S is necessarily the same as T.
      • The saved value of the array component and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see §15.16.2), then the assignment expression completes abruptly for the same reason and no assignment occurs.
      • Otherwise, the result of the binary operation is converted to the type of the array component and the result of the conversion is stored into the array component.
    • If T is a reference type, then it must be String. Because class String is a final class, S must also be String. Therefore the run-time check that is sometimes required for the simple assignment operator is never required for a compound assignment operator.
      • The saved value of the array component and the value of the right-hand operand are used to perform the binary operation (string concatenation) indicated by the compound assignment operator (which is necessarily +=). If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
      • Otherwise, the String result of the binary operation is stored into the array component.

The rules for compound assignment to an array component are illustrated by the following example program:

class ArrayReferenceThrow extends RuntimeException { }

class IndexThrow extends RuntimeException { }

class RightHandSideThrow extends RuntimeException { }

class IllustrateCompoundArrayAssignment {

    static String[] strings = { "Simon", "Garfunkel" };

    static double[] doubles = { Math.E, Math.PI };

    static String[] stringsThrow() {
        throw new ArrayReferenceThrow();
    }

    static double[] doublesThrow() {
        throw new ArrayReferenceThrow();
    }

    static int indexThrow() { throw new IndexThrow(); }

    static String stringThrow() {
        throw new RightHandSideThrow();
    }

    static double doubleThrow() {
        throw new RightHandSideThrow();
    }

    static String name(Object q) {
        String sq = q.getClass().getName();
        int k = sq.lastIndexOf('.');
        return (k < 0) ? sq : sq.substring(k+1);
    }

    static void testEight(String[] x, double[] z, int j) {
        String sx = (x == null) ? "null" : "Strings";
        String sz = (z == null) ? "null" : "doubles";
        System.out.println();
        try {
            System.out.print(sx + "[throw]+=throw => ");
            x[indexThrow()] += stringThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sz + "[throw]+=throw => ");
            z[indexThrow()] += doubleThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }

        try {
            System.out.print(sx + "[throw]+=\"heh\" => ");
            x[indexThrow()] += "heh";
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sz + "[throw]+=12345 => ");
            z[indexThrow()] += 12345;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sx + "[" + j + "]+=throw => ");
            x[j] += stringThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sz + "[" + j + "]+=throw => ");
            z[j] += doubleThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sx + "[" + j + "]+=\"heh\" => ");
            x[j] += "heh";
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print(sz + "[" + j + "]+=12345 => ");
            z[j] += 12345;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
    }

    public static void main(String[] args) {
        try {
            System.out.print("throw[throw]+=throw => ");
            stringsThrow()[indexThrow()] += stringThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[throw]+=throw => ");
            doublesThrow()[indexThrow()] += doubleThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[throw]+=\"heh\" => ");
            stringsThrow()[indexThrow()] += "heh";
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }

        try {
            System.out.print("throw[throw]+=12345 => ");
            doublesThrow()[indexThrow()] += 12345;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]+=throw => ");
            stringsThrow()[1] += stringThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]+=throw => ");
            doublesThrow()[1] += doubleThrow();
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]+=\"heh\" => ");
            stringsThrow()[1] += "heh";
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }
        try {
            System.out.print("throw[1]+=12345 => ");
            doublesThrow()[1] += 12345;
            System.out.println("Okay!");
        } catch (Throwable e) { System.out.println(name(e)); }

        testEight(null, null, 1);
        testEight(null, null, 9);
        testEight(strings, doubles, 1);
        testEight(strings, doubles, 9);
    }

}

This program prints:

throw[throw]+=throw => ArrayReferenceThrow
throw[throw]+=throw => ArrayReferenceThrow
throw[throw]+="heh" => ArrayReferenceThrow
throw[throw]+=12345 => ArrayReferenceThrow
throw[1]+=throw => ArrayReferenceThrow
throw[1]+=throw => ArrayReferenceThrow
throw[1]+="heh" => ArrayReferenceThrow
throw[1]+=12345 => ArrayReferenceThrow

null[throw]+=throw => IndexThrow
null[throw]+=throw => IndexThrow
null[throw]+="heh" => IndexThrow
null[throw]+=12345 => IndexThrow
null[1]+=throw => NullPointerException
null[1]+=throw => NullPointerException
null[1]+="heh" => NullPointerException
null[1]+=12345 => NullPointerException

null[throw]+=throw => IndexThrow
null[throw]+=throw => IndexThrow
null[throw]+="heh" => IndexThrow
null[throw]+=12345 => IndexThrow
null[9]+=throw => NullPointerException
null[9]+=throw => NullPointerException
null[9]+="heh" => NullPointerException
null[9]+=12345 => NullPointerException

Strings[throw]+=throw => IndexThrow
doubles[throw]+=throw => IndexThrow
Strings[throw]+="heh" => IndexThrow
doubles[throw]+=12345 => IndexThrow
Strings[1]+=throw => RightHandSideThrow
doubles[1]+=throw => RightHandSideThrow
Strings[1]+="heh" => Okay!
doubles[1]+=12345 => Okay!

Strings[throw]+=throw => IndexThrow
doubles[throw]+=throw => IndexThrow
Strings[throw]+="heh" => IndexThrow
doubles[throw]+=12345 => IndexThrow
Strings[9]+=throw => IndexOutOfBoundsException
doubles[9]+=throw => IndexOutOfBoundsException
Strings[9]+="heh" => IndexOutOfBoundsException
doubles[9]+=12345 => IndexOutOfBoundsException

The most interesting cases of the lot are tenth and eleventh from the end:

Strings[1]+=throw => RightHandSideThrow
doubles[1]+=throw => RightHandSideThrow

They are the cases where a right-hand side that throws an exception actually gets to throw the exception; moreover, they are the only such cases in the lot. This demonstrates that the evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.

The following program illustrates the fact that the value of the left-hand side of a compound assignment is saved before the right-hand side is evaluated:

class Test {
    public static void main(String[] args) {
        int k = 1;
        int[] a = { 1 };
        k += (k = 4) * (k + 2);
        a[0] += (a[0] = 4) * (a[0] + 2);
        System.out.println("k==" + k + " and a[0]==" + a[0]);
    }
}

This program prints:

k==25 and a[0]==25

The value 1 of k is saved by the compound assignment operator += before its right-hand operand (k = 4) * (k + 2) is evaluated. Evaluation of this right-hand operand then assigns 4 to k, calculates the value 6 for k + 2, and then multiplies 4 by 6 to get 24. This is added to the saved value 1 to get 25, which is then stored into k by the += operator. An identical analysis applies to the case that uses a[0]. In short, the statements

k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);

behave in exactly the same manner as the statements:

k = k + (k = 4) * (k + 2);
a[0] = a[0] + (a[0] = 4) * (a[0] + 2);


15.26 Expression

An Expression is any assignment expression:

Expression:

    AssignmentExpression

Unlike C and C++, the Java language has no comma operator.


15.27 Constant Expression

ConstantExpression:

    Expression

A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:

  • Literals of primitive type and literals of type String
  • Casts to primitive types and casts to type String
  • The unary operators +, -, ~, and ! (but not ++ or --)
  • The multiplicative operators *, /, and %
  • The additive operators + and -
  • The shift operators <<, >>, and >>>
  • The relational operators <, <=, >, and >= (but not instanceof)
  • The equality operators == and !=
  • The bitwise and logical operators &, ^, and |
  • The conditional-and operator && and the conditional-or operator ||
  • The ternary conditional operator ? :
  • Simple names that refer to final variables whose initializers are constant expressions
  • Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions

Compile-time constant expressions are used in case labels in switch statements (§14.9) and have a special significance for assignment conversion (§5.2).

Examples of constant expressions:

true
(short)(1*2*3*4*5*6)
Integer.MAX_VALUE / 2
2.0 * Math.PI
"The integer " + Long.MAX_VALUE + " is mighty big."

. . . when faces of the throng turned toward him and ambiguous eyes stared
into his, he assumed the most romantic of expressions . . .
--F. Scott Fitzgerald, This Side of Paradise (1920)


 16. Definite Assignment

CHAPTER 16

Definite Assignment

All the evolution we know of proceeds from the vague to the definite.
—Charles Pierce

Each local variable must have a definitely assigned value when any access of its value occurs. An access to its value consists of the simple name of the variable occurring anywhere in an expression except as the left-hand operand of the simple assignment operator =.

A Java compiler must carry out a specific conservative flow analysis to make sure that, for every access of a local variable, the local variable is definitely assigned before the access; otherwise a compile-time error must occur.

The remainder of this chapter is devoted to a precise explanation of the words "definitely assigned before". The idea is that an assignment to the local variable must occur on every possible execution path to the access from the beginning of the constructor, method, or static initializer that contains the access. The analysis takes into account the structure of statements and expressions; it also provides a special treatment of the expression operators !, &&, ||, and ? :, the operators &, |, ^, ==, and != with boolean operands, and boolean-valued constant expressions. For example, a Java compiler recognizes that k is definitely assigned before its access (as an argument of a method invocation) in the code:

{
    int k;
    if (v > 0 && (k = System.in.read()) >= 0)
        System.out.println(k);
}

because the access occurs only if the value of the expression:

v > 0 && (k = System.in.read()) >= 0

is true, and the value can be true only if the assignment to k is executed (more properly, evaluated). Similarly, a Java compiler will recognize that in the code:

{
    int k;
    while (true) {
        k = n;
        if (k >= 5) break;
        n = 6;
    }
    System.out.println(k);
}

the variable k is definitely assigned by the while statement because the condition expression true never has the value false, so only the break statement can cause the while statement to complete normally, and k is definitely assigned before the break statement.

Except for the special treatment of certain boolean operators and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis. For example, a Java compiler must produce a compile-time error for the code:

{
    int k;
    int n = 5;
    if (n > 2)
        k = 3;
    System.out.println(k); // k is not "definitely assigned" before this
}

even though the value of n is known at compile time, and in principle it can be known at compile time that the assignment to k will always be executed (more properly, evaluated). A Java compiler must operate according to the rules laid out in this section. The rules recognize only constant expressions; in this example, the expression n > 2 is not a constant expression as defined in §15.27.

As another example, a Java compiler will accept the code:

void flow(boolean flag) {
    int k;
    if (flag)
        k = 3;
    else
        k = 4;
    System.out.println(k);
}

as far as definite assignment of k is concerned, because the rules outlined in this section allow it to tell that k is assigned no matter whether the flag is true or false. But the rules do not accept the variation:

void flow(boolean flag) {
    int k;
    if (flag)
        k = 3;
    if (!flag)
        k = 4;
    System.out.println(k); // k is not "definitely assigned" before this
}

and so compiling this program must cause a compile-time error to occur.

In order to precisely specify all the cases of definite assignment, the rules in this section define two technical terms:

  • whether a local variable is definitely assigned before a statement or expression, and
  • whether a local variable is definitely assigned after a statement or expression.

In order to specify boolean-valued expressions, the latter notion is refined into two cases:

  • whether a local variable is definitely assigned after the expression when true, and
  • whether a local variable is definitely assigned after the expression when false.

Here when true and when false refer to the value of the expression. For example, the local variable k is definitely assigned a value after evaluation of the expression

a && ((k=m) > 5)

when the expression is true but not when the expression is false (because if a is false, then the assignment to k is not executed (more properly, evaluated)).

The statement "V is definitely assigned after X" (where V is a local variable and X is a statement or expression) means "V is definitely assigned after X if X completes normally". If X completes abruptly, the assignment may not have occurred, and the rules stated here take this into account. A peculiar consequence of this definition is that "V is definitely assigned after break;" is always true! Because a break statement never completes normally, it is vacuously true that V has been assigned a value if the break statement completes normally.

To shorten the rules, the customary abbreviation "iff" is used to mean "if and only if".

Let V be a local variable. Let a, b, c, and e be expressions. Let S and T be statements.


16.1 Definite Assignment and Expressions

See sections 16.1.1 through 16.1.16 for information on definite assignment and expressions.


16.1.1 Boolean Constant Expressions

V is definitely assigned after any constant expression whose value is true when false. V is definitely assigned after any constant expression whose value is false when true.

A constant expression whose value is true never has the value false, and a constant expression whose value is false never has the value true, these definitions are vacuously satisfied. They are helpful in analyzing expressions involving the boolean operators &&, ||, and ! ( §16.1.3, §16.1.4, §16.1.5).


16.1.2 Boolean-valued Expressions

For every boolean-valued expression:

  • If the expression has no subexpressions, V is definitely assigned after the expression iff V is definitely assigned before the expression. This case applies to literals and simple names.
  • Otherwise, V is definitely assigned after the expression iff V is definitely assigned after the expression when true and V is definitely assigned after the expression when false.


16.1.3 The Boolean Operator &&

  • V is definitely assigned after a && b when true iff V is definitely assigned after a when true or V is definitely assigned after b when true.
  • V is definitely assigned after a && b when false iff V is definitely assigned after a when false and V is definitely assigned after b when false.
  • V is definitely assigned before a iff V is definitely assigned before a && b.
  • V is definitely assigned before b iff V is definitely assigned after a when true.


16.1.4 The Boolean Operator ||

  • V is definitely assigned after a || b when true iff V is definitely assigned after a when true and V is definitely assigned after b when true.
  • V is definitely assigned after a || b when false iff V is definitely assigned after a when false or V is definitely assigned after b when false.
  • V is definitely assigned before a iff V is definitely assigned before a || b.
  • V is definitely assigned before b iff V is definitely assigned after a when false.


16.1.5 The Boolean Operator !

  • V is definitely assigned after !a when true iff V is definitely assigned after a when false.
  • V is definitely assigned after !a when false iff V is definitely assigned after a when true.
  • V is definitely assigned before a iff V is definitely assigned before !a.


16.1.6 The Boolean Operator &

  • V is definitely assigned after a & b when true iff V is definitely assigned after a when true or V is definitely assigned after b when true.
  • V is definitely assigned after a & b when false iff at least one of the following is true:
    • V is definitely assigned after b. (Note that if V is definitely assigned after a, it follows that V is definitely assigned after b.)
    • V is definitely assigned after a when false and V is definitely assigned after b when false.
  • V is definitely assigned before a iff V is definitely assigned before a & b.
  • V is definitely assigned before b iff V is definitely assigned after a.


16.1.7 The Boolean Operator |

  • V is definitely assigned after a | b when true iff at least one of the following is true:
    • V is definitely assigned after b. (Note that if V is definitely assigned after a, it follows that V is definitely assigned after b.)
    • V is definitely assigned after a when true and V is definitely assigned after b when true.
  • V is definitely assigned after a | b when false iff V is definitely assigned after a when false or V is definitely assigned after b when false.
  • V is definitely assigned before a iff V is definitely assigned before a | b.
  • V is definitely assigned before b iff V is definitely assigned after a.


16.1.8 The Boolean Operator ^

  • V is definitely assigned after a ^ b when true iff at least one of the following is true:
    • V is definitely assigned after b.
    • V is definitely assigned after a when true and V is definitely assigned after b when true.
    • V is definitely assigned after a when false and V is definitely assigned after b when false.
  • V is definitely assigned after a ^ b when false iff at least one of the following is true:
    • V is definitely assigned after b.
    • V is definitely assigned after a when true and V is definitely assigned after b when false.
    • V is definitely assigned after a when false and V is definitely assigned after b when true.
  • V is definitely assigned before a iff V is definitely assigned before a ^ b.
  • V is definitely assigned before b iff V is definitely assigned after a.


16.1.9 The Boolean Operator ==

  • V is definitely assigned after a == b when true iff at least one of the following is true:
    • V is definitely assigned after b.
    • V is definitely assigned after a when true and V is definitely assigned after b when false.
    • V is definitely assigned after a when false and V is definitely assigned after b when true.
  • V is definitely assigned after a == b when false iff at least one of the following is true:
    • V is definitely assigned after b.
    • V is definitely assigned after a when true and V is definitely assigned after b when true.
    • V is definitely assigned after a when false and V is definitely assigned after b when false.
  • V is definitely assigned before a iff V is definitely assigned before a == b.
  • V is definitely assigned before b iff V is definitely assigned after a.


16.1.10 The Boolean Operator !=

The rules for a != b are identical to the rules for a ^ b (§16.1.8).


16.1.11 The Boolean Operator ? :

Suppose that b and c are boolean-valued expressions.

  • V is definitely assigned after a ? b : c when true iff both of the following are true:
    • V is definitely assigned before b or V is definitely assigned after b when true.
    • V is definitely assigned before c or V is definitely assigned after c when true.
  • V is definitely assigned after a ? b : c when false iff both of the following are true:
    • V is definitely assigned before b or V is definitely assigned after b when false.
    • V is definitely assigned before c or V is definitely assigned after c when false.
  • V is definitely assigned before a iff V is definitely assigned before a ? b : c.
  • V is definitely assigned before b iff V is definitely assigned after a when true.
  • V is definitely assigned before c iff V is definitely assigned after a when false.


16.1.12 The Conditional Operator ? :

Suppose that b and c are expressions that are not boolean-valued.

  • V is definitely assigned after a ? b : c iff both of the following are true:
    • V is definitely assigned after b.
    • V is definitely assigned after c.
  • V is definitely assigned before a iff V is definitely assigned before a ? b : c.
  • V is definitely assigned before b iff V is definitely assigned after a when true.
  • V is definitely assigned before c iff V is definitely assigned after a when false.


16.1.13 Boolean Assignment Expressions

Suppose that an assignment expression a = b, a &= b, a |= b, or a ^= b is boolean- valued.

  • V is definitely assigned before a iff V is definitely assigned before the assignment expression.
  • V is definitely assigned before b iff V is definitely assigned after a.
  • V is definitely assigned after a = b when true iff either a is V or V is definitely assigned after the right-hand operand expression when true.
  • V is definitely assigned after a = b when false iff either a is V or V is definitely assigned after the right-hand operand expression when false.
  • V is definitely assigned after a &= b when true iff either a is V or V would be definitely assigned after a & b (in the same context) when true.
  • V is definitely assigned after a &= b when false iff either a is V or V would be definitely assigned after a & b (in the same context) when false.
  • V is definitely assigned after a |= b when true iff either a is V or V would be definitely assigned after a | b (in the same context) when true.
  • V is definitely assigned after a |= b when false iff either a is V or V would be definitely assigned after a | b (in the same context) when false.
  • V is definitely assigned after a ^= b when true iff either a is V or V would be definitely assigned after a ^ b (in the same context) when true.
  • V is definitely assigned after a ^= b when false iff either a is V or V would be definitely assigned after a ^ b (in the same context) when false.

Note that if a is V and V is not definitely assigned before a compound assignment such as a &= b, then a compile-time error will necessarily occur. The rules stated above include the disjunct "a is V" so that V will be considered to have been definitely assigned at later points in the code. Including the disjunct "a is V" does not affect the binary decision as to whether a program is acceptable or will result in a compile-time error, but it affects how many different points in the code may be regarded as erroneous, and so in practice it can improve the quality of error reporting.


16.1.14 Other Assignment Expressions

Suppose that an assignment expression a = b, a += b, a -= b, a *= b, a /= b, a %= b, a <<= b, a >>= b, a >>>= b, a &= b, a |= b, or a ^= b is not boolean-valued.

  • V is definitely assigned after the assignment expression iff either a is V or V is definitely assigned after b.
  • V is definitely assigned before a iff V is definitely assigned before the assignment expression.
  • V is definitely assigned before b iff V is definitely assigned after a.


16.1.15 Operators ++ and --

  • V is definitely assigned after a preincrement, predecrement, postincrement, or postdecrement expression iff either the operand expression is V or V is definitely assigned after the operand expression.
  • V is definitely assigned before the operand expression iff V is definitely assigned before the preincrement, predecrement, postincrement, or postdecrement expression.


16.1.16 Other Expressions

If an expression is not boolean-valued and is not a conditional-operator expression or assignment expression, the following rules apply:

  • If the expression has no subexpressions, V is definitely assigned after the expression iff V is definitely assigned before the expression. This case applies to literals, simple names, this, super, and null.
  • If the expression has subexpressions, V is definitely assigned after the expression iff V is definitely assigned after its rightmost immediate subexpression.

For any immediate subexpression y of an expression x, V is definitely assigned before y iff V is definitely assigned before x or one of the following situations is true:

  • y is the right-hand operand of a binary operator and V is definitely assigned after the left-hand operand.
  • x is an array reference, y is the subexpression within the brackets, and V is definitely assigned after the subexpression before the brackets.
  • x is a method invocation expression for an object; y is the first argument expression in the method invocation expression; there is a subexpression whose value is an object to the left of the dot, method name, and left parenthesis of the method invocation expression; and V is definitely assigned after this subexpression.
  • x is a method invocation expression or class instance creation expression; y is an argument expression, but not the first; and V is definitely assigned after the argument expression to the left of y.
  • x is an class instance creation expression; y is a dimension expression, but not the first; and V is definitely assigned after the dimension expression to the left of y.


16.2 Definite Assignment and Statements

See sections 16.2.1 through 16.2.13 for information on definite assignment and statements.


16.2.1 Empty Statements

  • V is definitely assigned after an empty statement iff it is definitely assigned before the empty statement.


16.2.2 Blocks

  • V is definitely assigned after an empty block iff it is definitely assigned before the empty block.
  • V is definitely assigned after a nonempty block iff it is definitely assigned after the last statement in the block.
  • V is definitely assigned before the first statement of the block iff it is definitely assigned before the block.
  • V is definitely assigned before any other statement S of the block iff it is definitely assigned after the statement immediately preceding S in the block.


16.2.3 Local Variable Declaration Statements

  • V is definitely assigned after a local variable declaration statement that contains no initializers iff it is definitely assigned before the local variable declaration statement.
  • V is definitely assigned after a local variable declaration statement that contains initializers iff either it is definitely assigned after the last initializer expression in the local variable declaration statement or the last initializer expression in the declaration is in the declarator that declares V.
  • V is definitely assigned before the first initializer expression iff it is definitely assigned before the local variable declaration statement.
  • V is definitely assigned before any other initializer expression e iff either it is definitely assigned after the initializer expression immediately preceding e in the local variable declaration statement or the initializer expression immediately preceding e in the local variable declaration statement is in the declarator that declares V.


16.2.4 Labeled Statements

  • V is definitely assigned after a labeled statement L:S (where L is a label) iff V is definitely assigned after S and V is definitely assigned before every break statement that may exit the labeled statement L:S.
  • V is definitely assigned before S iff V is definitely assigned before L:S.


16.2.5 Expression Statements

  • V is definitely assigned after an expression statement e; iff it is definitely assigned after e.
  • V is definitely assigned before e iff it is definitely assigned before e;.


16.2.6 if Statements

  • V is definitely assigned after if (e) S iff V is definitely assigned after S and V is definitely assigned after e when false.
  • V is definitely assigned before e iff V is definitely assigned before if (e) S. V is definitely assigned before S iff V is definitely assigned after e when true.
  • V is definitely assigned after if (e) S else T iff V is definitely assigned after S and V is definitely assigned after T.
  • V is definitely assigned before e iff V is definitely assigned before if (e) S else T. V is definitely assigned before S iff V is definitely assigned after e when true. V is definitely assigned before T iff V is definitely assigned after e when false.


16.2.7 switch Statements

  • V is definitely assigned after a switch statement iff both of the following are true:
    • Either the switch block is empty or V is definitely assigned after the last statement of the switch block.
    • V is definitely assigned before every break statement that may exit the switch statement.
  • V is definitely assigned before the switch expression iff V is definitely assigned before the switch statement.
  • V is definitely assigned before a statement or local variable declaration statement S in the switch block iff at least one of the following is true:
    • V is definitely assigned after the switch expression.
    • S is not labeled by a case or default label and V is definitely assigned after the preceding statement.


16.2.8 while Statements

  • V is definitely assigned after while (e) S iff V is definitely assigned after e when false and V is definitely assigned before every break statement that may exit the while statement.
  • V is definitely assigned before e iff V is definitely assigned before the while statement.
  • V is definitely assigned before S iff V is definitely assigned after e when true.


16.2.9 do Statements

  • V is definitely assigned after do S while (e); iff V is definitely assigned after e when false and V is definitely assigned before every break statement that may exit the do statement.
  • V is definitely assigned before S iff V is definitely assigned before the do statement.
  • V is definitely assigned before e iff V is definitely assigned after S and V is definitely assigned before every continue statement that may exit the body of the do statement.


16.2.10 for Statements

  • V is definitely assigned after a for statement iff both of the following are true:
    • Either a condition expression is not present or V is definitely assigned after the condition expression when false.
    • V is definitely assigned before every break statement that may exit the for statement.
  • V is definitely assigned before the initialization part of the for statement iff V is definitely assigned before the for statement.
  • V is definitely assigned before the condition part of the for statement iff V is definitely assigned after the initialization part of the for statement.
  • V is definitely assigned before the contained statement iff either of the following is true:
    • A condition expression is present and V is definitely assigned after the condition expression when true.
    • No condition expression is present and V is definitely assigned after the initialization part of the for statement.
  • V is definitely assigned before the incrementation part of the for statement iff V is definitely assigned after the contained statement and V is definitely assigned before every continue statement that may exit the body of the for statement.

16.2.10.1 Initialization Part

  • If the initialization part of the for statement is a local variable declaration statement, the rules of §16.2.3 apply.
  • Otherwise, if the initialization part is empty, then V is definitely assigned after the initialization part iff V is definitely assigned before the initialization part.
  • Otherwise, three rules apply:
    • V is definitely assigned after the initialization part iff V is definitely assigned after the last expression statement in the initialization part.
    • V is definitely assigned before the first expression statement in the initialization part iff V is definitely assigned before the initialization part.
    • V is definitely assigned before an expression statement E other than the first in the initialization part iff V is definitely assigned after the expression statement immediately preceding E.

16.2.10.2 Incrementation Part

  • If the incrementation part of the for statement is empty, then V is definitely assigned after the incrementation part iff V is definitely assigned before the incrementation part.
  • Otherwise, three rules apply:
    • V is definitely assigned after the incrementation part iff V is definitely assigned after the last expression statement in the incrementation part.
    • V is definitely assigned before the first expression statement in the incrementation part iff V is definitely assigned before the incrementation part.
    • V is definitely assigned before an expression statement E other than the first in the incrementation part iff V is definitely assigned after the expression statement immediately preceding E.


16.2.11 break, continue, return, and throw Statements

  • By convention, we say that V is definitely assigned after any break, continue, return, or throw statement. The notion that a variable is "definitely assigned after" a statement or expression really means "is definitely assigned after the statement or expression completes normally". Because a break, continue, return, or throw statement never completes normally, it vacuously satisfies this notion.
  • In a return statement with an expression or a throw statement, V is definitely assigned before the expression iff V is definitely assigned before the return or throw statement.


16.2.12 synchronized Statements

  • V is definitely assigned after synchronized (e) S iff V is definitely assigned after S.
  • V is definitely assigned before e iff V is definitely assigned before the statement synchronized (e) S.
  • V is definitely assigned before S iff V is definitely assigned after e.


16.2.13 try Statements

  • V is definitely assigned after a try statement iff one of the following is true:
    • V is definitely assigned after the try block and V is definitely assigned after every catch block in the try statement.
    • The try statement has a finally block and V is definitely assigned after the finally block.
  • V is definitely assigned before the try block iff V is definitely assigned before the try statement.
  • V is definitely assigned before a catch block iff V is definitely assigned before the try statement.

V is definitely assigned before a finally block iff V is definitely assigned before the try statement.

I resolved to assign Bartleby a corner by the folding doors . . .
—Herman Melville, Bartleby, the Scrivener (1853)

It does not strike me that there is anything definite about that.
—Herman Melville, Bartleby, the Scrivener (1853)


 17. Threads and Locks

CHAPTER 17

Threads and Locks

And oft-times in the most forbidding den
Of solitude, with love of science strong,
How patiently the yoke of thought they bear;
How subtly glide its finest threads along!
—William Wordsworth, Monks and Schoolmen,in Ecclesiastical Sonnets (1822)

While most of the discussion in the preceding chapters is concerned only with the behavior of Java code as executed a single statement or expression at a time, that is, by a single thread, each Java Virtual Machine can support many threads of execution at once. These threads independently execute Java code that operates on Java values and objects residing in a shared main memory. Threads may be supported by having many hardware processors, by time-slicing a single hardware processor, or by time-slicing many hardware processors.

Java supports the coding of programs that, though concurrent, still exhibit deterministic behavior, by providing mechanisms for synchronizing the concurrent activity of threads. To synchronize threads, Java uses monitors, which are a high-level mechanism for allowing only one thread at a time to execute a region of code protected by the monitor. The behavior of monitors is explained in terms of locks; there is a lock associated with each object.

The synchronized statement (§14.17) performs two special actions relevant only to multithreaded operation: (1) after computing a reference to an object but before executing its body, it locks a lock associated with the object, and (2) after execution of the body has completed, either normally or abruptly, it unlocks that same lock. As a convenience, a method may be declared synchronized; such a method behaves as if its body were contained in a synchronized statement.

The methods wait (§20.1.6, §20.1.7, §20.1.8), notify (§20.1.9), and notifyAll (§20.1.10) of class Object support an efficient transfer of control from one thread to another. Rather than simply "spinning" (repeatedly locking and unlocking an object to see whether some internal state has changed), which consumes computational effort, a thread can suspend itself using wait until such time as another thread awakens it using notify. This is especially appropriate in situations where threads have a producer-consumer relationship (actively cooperating on a common goal) rather than a mutual exclusion relationship (trying to avoid conflicts while sharing a common resource).

As a thread executes code, it carries out a sequence of actions. A thread may use the value of a variable or assign it a new value. (Other actions include arithmetic operations, conditional tests, and method invocations, but these do not involves variables directly.) If two or more concurrent threads act on a shared variable, there is a possibility that the actions on the variable will produce timing-dependent results. This dependence on timing is inherent in concurrent programming, producing one of the few places in Java where the result of executing a program is not determined solely by this specification.

Each thread has a working memory, in which it may keep copies of the values of variables from the main memory that is shared between all threads. To access a shared variable, a thread usually first obtains a lock and flushes its working memory. This guarantees that shared values will be thereafter be loaded from the shared main memory to the threads working memory. When a thread unlocks a lock it guarantees the values it holds in its working memory will be written back to the main memory.

This chapter explains the interaction of threads with the main memory, and thus with each other, in terms of certain low-level actions. There are rules about the order in which these actions may occur. These rules impose constraints on any implementation of Java, and a Java programmer may rely on the rules to predict the possible behaviors of a concurrent Java program. The rules do, however, intentionally give the implementor certain freedoms; the intent is to permit certain standard hardware and software techniques that can greatly improve the speed and efficiency of concurrent code.

Briefly put, these are the important consequences of the rules:

  • Proper use of synchronization constructs will allow reliable transmission of values or sets of values from one thread to another through shared variables.
  • When a thread uses the value of a variable, the value it obtains is in fact a value stored into the variable by that thread or by some other thread. This is true even if the program does not contain code for proper synchronization. For example, if two threads store references to different objects into the same reference value, the variable will subsequently contain a reference to one object or the other, not a reference to some other object or a corrupted reference value. (There is a special exception for long and double values; see §17.4.)
  • In the absence of explicit synchronization, a Java implementation is free to update the main memory in an order that may be surprising. Therefore the programmer who prefers to avoid surprises should use explicit synchronization.


17.1 Terminology and Framework

A variable is any location within a Java program that may be stored into. This includes not only class variables and instance variables but also components of arrays. Variables are kept in a main memory that is shared by all threads. Because it is impossible for one thread to access parameters or local variables of another thread, it doesn't matter whether parameters and local variables are thought of as residing in the shared main memory or in the working memory of the thread that owns them.

Every thread has a working memory in which it keeps its own working copy of variables that it must use or assign. As the thread executes a Java program, it operates on these working copies. The main memory contains the master copy of every variable. There are rules about when a thread is permitted or required to transfer the contents of its working copy of a variable into the master copy or vice versa

The main memory also contains locks; there is one lock associated with each object. Threads may compete to acquire a lock.

For the purposes of this chapter, the verbs use, assign, load, store, lock, and unlock name actions that a thread can perform. The verbs read, write, lock, and unlock name actions that the main memory subsystem can perform. Each of these actions is atomic (indivisible).

A use or assign action is a tightly coupled interaction between a thread's execution engine and the thread's working memory. A lock or unlock action is a tightly coupled interaction between a thread's execution engine and the main memory. But the transfer of data between the main memory and a thread's working memory is loosely coupled. When data is copied from the main memory to a working memory, two actions must occur: a read action performed by the main memory followed some time later by a corresponding load action performed by the working memory. When data is copied from a working memory to the main memory, two actions must occur: a store action performed by the working memory followed some time later by a corresponding write action performed by the main memory. There may be some transit time between main memory and a working memory, and the transit time may be different for each transaction; thus actions initiated by a thread on different variables may viewed by another thread as occurring in a different order. For each variable, however, the actions in main memory on behalf of any one thread are performed in the same order as the corresponding actions by that thread. (This is explained in greater detail below.)

A single Java thread issues a stream of use, assign, lock, and unlock actions as dictated by the semantics of the Java program it is executing. The underlying Java implementation is then required additionally to perform appropriate load, store, read, and write actions so as to obey a certain set of constraints, explained below. If the Java implementation correctly follows these rules and the Java application programmer follows certain other rules of programming, then data can be reliably transferred between threads through shared variables. The rules are designed to be "tight" enough to make this possible but "loose" enough to allow hardware and software designers considerable freedom to improve speed and throughput through such mechanisms as registers, queues, and caches.

Here are the detailed definitions of each of the actions:

  • A use action (by a thread) transfers the contents of the thread's working copy of a variable to the thread's execution engine. This action is performed whenever a thread executes a virtual machine instruction that uses the value of a variable.
  • An assign action (by a thread) transfers a value from the thread's execution engine into the thread's working copy of a variable. This action is performed whenever a thread executes a virtual machine instruction that assigns to a variable.
  • A read action (by the main memory) transmits the contents of the master copy of a variable to a thread's working memory for use by a later load action.
  • A load action (by a thread) puts a value transmitted from main memory by a read action into the thread's working copy of a variable.
  • A store action (by a thread) transmits the contents of the thread's working copy of a variable to main memory for use by a later write action.
  • A write action (by the main memory) puts a value transmitted from the thread's working memory by a store action into the master copy of a variable in main memory.
  • A lock action (by a thread tightly synchronized with main memory) causes a thread to acquire one claim on a particular lock.
  • An unlock action (by a thread tightly synchronized with main memory) causes a thread to release one claim on a particular lock.

Thus the interaction of a thread with a variable over time consists of a sequence of use, assign, load, and store actions. Main memory performs a read action for every load and a write action for every store. A thread's interactions with a lock over time consists of a sequence of lock and unlock actions. All the globally visible behavior of a thread thus comprises all the thread's actions on variables and locks.


17.2 Execution Order

The rules of execution order constrain the order in which certain events may occur. There are four general constraints on the relationships among actions:

  • The actions performed by any one thread are totally ordered; that is, for any two actions performed by a thread, one action precedes the other.
  • The actions performed by the main memory for any one variable are totally ordered; that is, for any two actions performed by the main memory on the same variable, one action precedes the other.
  • The actions performed by the main memory for any one lock are totally ordered; that is, for any two actions performed by the main memory on the same lock, one action precedes the other.
  • It is not permitted for an action to follow itself.

The last rule may seem trivial, but it does need to be stated separately and explicitly for completeness. Without it, it would be possible to propose a set of actions by two or more threads and precedence relationships among the actions that would satisfy all the other rules but would require an action to follow itself.

Threads do not interact directly; they communicate only through the shared main memory. The relationships between the actions of a thread and the actions of main memory are constrained in three ways:

  • Each lock or unlock action is performed jointly by some thread and the main memory.
  • Each load action by a thread is uniquely paired with a read action by the main memory such that the load action follows the read action.
  • Each store action by a thread is uniquely paired with a write action by the main memory such that the write action follows the store action.

Most of the rules in the following sections further constrain the order in which certain actions take place. A rule may state that one action must precede or follow some other action. Note that this relationship is transitive: if action A must precede action B, and B must precede C, then A must precede C. The programmer must remember that these rules are the only constraints on the ordering of actions; if no rule or combination of rules implies that action A must precede action B, then a Java implementation is free to perform action B before action A, or to perform action B concurrently with action A. This freedom can be the key to good performance. Conversely, an implementation is not required to take advantage of all the freedoms given it.

In the rules that follow, the phrasing "B must intervene between A and C" means that action B must follow action A and precede action C.


17.3 Rules about Variables

Let T be a thread and V be a variable. There are certain constraints on the actions performed by T with respect to V:

  • An use or assign by T of V is permitted only when dictated by execution by T of the Java program according to the standard Java execution model. For example, an occurrence of V as an operand of the + operator requires that a single use action occur on V; an occurrence of V as the left-hand operand of the assignment operator = requires that a single assign action occur. All use and assign actions by a given thread must occur in the order specified by the program being executed by the thread. If the following rules forbid T to perform a required use as its next action, it may be necessary for T to perform a load first in order to make progress.
  • A store action by T on V must intervene between an assign by T of V and a subsequent load by T of V. (Less formally: a thread is not permitted to lose its most recent assign.)
  • An assign action by T on V must intervene between a load or store by T of V and a subsequent store by T of V. (Less formally: a thread is not permitted to write data from its working memory back to main memory for no reason.)
  • After a thread is created, it must perform an assign or load action on a variable before performing a use or store action on that variable. (Less formally: a new thread starts with an empty working memory.)
  • After a variable is created, every thread must perform an assign or load action on that variable before performing a use or store action on that variable. (Less formally: a new variable is created only in main memory and is not initially in any thread's working memory.)

Provided that all the constraints above and below are obeyed, a load or store action may be issued at any time by any thread on any variable, at the whim of the implementation.

There are also certain constraints on the read and write actions performed by main memory:

  • For every load action performed by any thread T on its working copy of a variable V, there must be a corresponding preceding read action by the main memory on the master copy of V, and the load action must put into the working copy the data transmitted by the corresponding read action.
  • For every store action performed by any thread T on its working copy of a variable V, there must be a corresponding following write action by the main memory on the master copy of V, and the write action must put into the master copy the data transmitted by the corresponding store action.
  • Let action A be a load or store by thread T on variable V, and let action P be the corresponding read or write by the main memory on variable V. Similarly, let action B be some other load or store by thread T on that same variable V, and let action Q be the corresponding read or write by the main memory on variable V. If A precedes B, then P must precede Q. (Less formally: actions on the master copy of any given variable on behalf of a thread are performed by the main memory in exactly the order that the thread requested.)

Note that this last rule applies only to actions by a thread on the same variable. However, there is a more stringent rule for volatile variables (§17.7).


17.4 Nonatomic Treatment of double and long Variables

If a double or long variable is not declared volatile, then for the purposes of load, store, read, and write actions they are treated as if they were two variables of 32 bits each: wherever the rules require one of these actions, two such actions are performed, one for each 32-bit half. The manner in which the 64 bits of a double or long variable are encoded into two 32-bit quantities is implementation-dependent.

This matters only because a read or write of a double or long variable may be handled by an actual main memory as two 32-bit read or write actions that may be separated in time, with other actions coming between them. Consequently, if two threads concurrently assign distinct values to the same shared non-volatile double or long variable, a subsequent use of that variable may obtain a value that is not equal to either of the assigned values, but some implementation-dependent mixture of the two values.

An implementation is free to implement load, store, read, and write actions for double and long values as atomic 64-bit actions; in fact, this is strongly encouraged. The model divides them into 32-bit halves for the sake of several currently popular microprocessors that fail to provide efficient atomic memory transactions on 64-bit quantities. It would have been simpler for Java to define all memory transactions on single variables as atomic; this more complex definition is a pragmatic concession to current hardware practice. In the future this concession may be eliminated. Meanwhile, programmers are cautioned always to explicitly synchronize access to shared double and long variables.


17.5 Rules about Locks

By the pricking of my thumbs,
Something wicked this way comes.
Open, locks,
Whoever knocks!
—William Shakespeare, Macbeth, Act IV, scene i

Let T be a thread and L be a lock. There are certain constraints on the actions performed by T with respect to L:

  • A lock action by T on L may occur only if, for every thread S other than T, the number of preceding unlock actions by S on L equals the number of preceding lock actions by S on L. (Less formally: only one thread at a time is permitted to lay claim to a lock, and moreover a thread may acquire the same lock multiple times and doesn't relinquish ownership of it until a matching number of unlock actions have been performed.)
  • An unlock action by thread T on lock L may occur only if the number of preceding unlock actions by T on L is strictly less than the number of preceding lock actions by T on L. (Less formally: a thread is not permitted to unlock a lock it doesn't own.)

With respect to a lock, the lock and unlock actions performed by all the threads are performed in some total sequential order. This total order must be consistent with the total order on the actions of each thread.


17.6 Rules about the Interaction of Locks and Variables

Let T be any thread, let V be any variable, and let L be any lock. There are certain constraints on the actions performed by T with respect to V and L:

  • Between an assign action by T on V and a subsequent unlock action by T on L, a store action by T on V must intervene; moreover, the write action corresponding to that store must precede the unlock action, as seen by main memory. (Less formally: if a thread is to perform an unlock action on any lock, it must first copy all assigned values in its working memory back out to main memory.)
  • Between a lock action by T on L and a subsequent use or store action by T on a variable V, an assign or load action on V must intervene; moreover, if it is a load action, then the read action corresponding to that load must follow the lock action, as seen by main memory. (Less formally: a lock action acts as if it flushes all variables from the thread's working memory; before use they must be assigned or loaded from main memory .)


17.7 Rules for Volatile Variables

If a variable is declared volatile, then additional constraints apply to the actions of each thread. Let T be a thread and let V and W be volatile variables.

  • An use action by T on V is permitted only if the previous action by T on V was load, and a load action by T on V is permitted only if the next action by T on V is use. The use action is said to be "associated" with the read action that corresponds to the load.
  • A store action by T on V is permitted only if the previous action by T on V was assign, and an assign action by T on V is permitted only if the next action by T on V is store. The assign action is said to be "associated" with the write action that corresponds to the store.
  • Let action A be a use or assign by thread T on variable V, let action F be the load or store associated with A, and let action P be the read or write of V that corresponds to F. Similarly, let action B be a use or assign by thread T on variable W, let action G be the load or store associated with B, and let action Q be the read or write of V that corresponds to G. If A precedes B, then P must precede Q. (Less formally: actions on the master copies of volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.)


17.8 Prescient Store Actions

If a variable is not declared volatile, then the rules in the previous sections are relaxed slightly to allow store actions to occur earlier than would otherwise be permitted. The purpose of this relaxation is to allow optimizing Java compilers to perform certain kinds of code rearrangement that preserve the semantics of properly synchronized programs but might be caught in the act of performing memory actions out of order by programs that are not properly synchronized.

Suppose that a store by T of V would follow a particular assign by T of V according to the rules of the previous sections, with no intervening load or assign by T of V. Then that store action would send to the main memory the value that the assign action put into the working memory of thread T. The special rule allows the store action to instead occur before the assign action, if the following restrictions are obeyed:

  • If the store action occurs, the assign is bound to occur. (Remember, these are restrictions on what actually happens, not on what a thread plans to do. No fair performing a store and then throwing an exception before the assign occurs!)
  • No lock action intervenes between the relocated store and the assign.
  • No load of V intervenes between the relocated store and the assign.
  • No other store of V intervenes between the relocated store and the assign.
  • The store action sends to the main memory the value that the assign action will put into the working memory of thread T.

This last property inspires us to call such an early store action prescient: it has to know ahead of time, somehow, what value will be stored by the assign that it should have followed. In practice, optimized compiled code will compute such values early (which is permitted if, for example, the computation has no side effects and throws no exceptions), store them early (before entering a loop, for example), and keep them in working registers for later use within the loop.


17.9 Discussion

Any association between locks and variables is purely conventional. Locking any lock conceptually flushes all variables from a thread's working memory, and unlocking any lock forces the writing out to main memory of all variables that the thread has assigned. That a lock may be associated with a particular object or a class is purely a convention. In some applications, it may be appropriate always to lock an object before accessing any of its instance variables, for example; synchronized methods are a convenient way to follow this convention. In other applications, it may suffice to use a single lock to synchronize access to a large collection of objects.

If a thread uses a particular shared variable only after locking a particular lock and before the corresponding unlocking of that same lock, then the thread will read the shared value of that variable from main memory after the lock action, if necessary, and will copy back to main memory the value most recently assigned to that variable before the unlock action. This, in conjunction with the mutual exclusion rules for locks, suffices to guarantee that values are correctly transmitted from one thread to another through shared variables.

The rules for volatile variables effectively require that main memory be touched exactly once for each use or assign of a volatile variable by a thread, and that main memory be touched in exactly the order dictated by the thread execution semantics. However, such memory actions are not ordered with respect to read and write actions on nonvolatile variables.


17.10 Example: Possible Swap

Consider a class that has class variables a and b and methods hither and yon:

class Sample {
    int a = 1, b = 2;
    void hither() {
        a = b;
    }
    void yon() {
        b = a;
    }
}

Now suppose that two threads are created, and that one thread calls hither while the other thread calls yon. What is the required set of actions and what are the ordering constraints?

Let us consider the thread that calls hither. According to the rules, this thread must perform an use of b followed by an assign of a. That is the bare minimum required to execute a call to the method hither.

Now, the first action on variable b by the thread cannot be use. But it may be assign or load. An assign to b cannot occur because the program text does not call for such an assign action, so a load of b is required. This load action by the thread in turn requires a preceding read action for b by the main memory.

The thread may optionally store the value of a after the assign has occurred. If it does, then the store action in turn requires a following write action for a by the main memory.

The situation for the thread that calls yon is similar, but with the roles of a and b exchanged.

The total set of actions may be pictured as follows:

Here an arrow from action A to action B indicates that A must precede B.

In what order may the actions by the main memory occur? The only constraint is that it is not possible both for the write of a to precede the read of a and for the write of b to precede the read of b, because the causality arrows in the diagram would form a loop so that an action would have to precede itself, which is not allowed. Assuming that the optional store and write actions are to occur, there are three possible orderings in which the main memory might legitimately perform its actions. Let ha and hb be the working copies of a and b for the hither thread, let ya and yb be the working copies for the yon thread, and let ma and mb be the master copies in main memory. Initially ma=1 and mb=2. Then the three possible orderings of actions and the resulting states are as follows:

  • write a [image] read a, read b [image] write b (then ha=2, hb=2, ma=2, mb=2, ya=2, yb=2)
  • read a [image] write a, write b [image] read b (then ha=1, hb=1, ma=1, mb=1, ya=1, yb=1)
  • read a [image] write a, read b [image] write b (then ha=2, hb=2, ma=2, mb=1, ya=1, yb=1)

Thus the net result might be that, in main memory, b is copied into a, a is copied into b, or the values of a and b are swapped; moreover, the working copies of the variables might or might not agree. It would be incorrect, of course, to assume that any one of these outcomes is more likely than another. This is one place in which the behavior of a Java program is necessarily timing-dependent.

Of course, an implementation might also choose not to perform the store and write actions, or only one of the two pairs, leading to yet other possible results.

Now suppose that we modify the example to use synchronized methods:

class SynchSample {
    int a = 1, b = 2;
    synchronized void hither() {
        a = b;
    }
    synchronized void yon() {
        b = a;
    }
}

Let us again consider the thread that calls hither. According to the rules, this thread must perform a lock action (on the class object for class SynchSample) before the body of method hither is executed. This is followed by a use of b and then an assign of a. Finally, an unlock action on the class object must be performed after the body of method hither completes. That is the bare minimum required to execute a call to the method hither.

As before, a load of b is required, which in turn requires a preceding read action for b by the main memory. Because the load follows the lock action, the corresponding read must also follow the lock action.

Because an unlock action follows the assign of a, a store action on a is mandatory, which in turn requires a following write action for a by the main memory. The write must precede the unlock action.

The situation for the thread that calls yon is similar, but with the roles of a and b exchanged.

The total set of actions may be pictured as follows:

The lock and unlock actions provide further constraints on the order of actions by the main memory; the lock action by one thread cannot occur between the lock and unlock actions of the other thread. Moreover, the unlock actions require that the store and write actions occur. It follows that only two sequences are possible:

  • write a [image] read a, read b [image] write b (then ha=2, hb=2, ma=2, mb=2, ya=2, yb=2)
  • read a [image] write a, write b [image] read b (then ha=1, hb=1, ma=1, mb=1, ya=1, yb=1)

While the resulting state is timing-dependent, it can be seen that the two threads will necessarily agree on the values of a and b.


17.11 Example: Out-of-Order Writes

This example is similar to that in the preceding section, except that one method assigns to both variables and the other method reads both variables. Consider a class that has class variables a and b and methods to and fro:

class Simple {
    int a = 1, b = 2;
    void to() {
        a = 3;
        b = 4;
    }
    void fro() {
        System.out.println("a= " + a + ", b=" + b);
    }
}

Now suppose that two threads are created, and that one thread calls to while the other thread calls fro. What is the required set of actions and what are the ordering constraints?

Let us consider the thread that calls to. According to the rules, this thread must perform an assign of a followed by an assign of b. That is the bare minimum required to execute a call to the method to. Because there is no synchronization, it is at the option of the implementation whether or not to store the assigned values back to main memory! Therefore the thread that calls fro may obtain either 1 or 3 for the value of a, and independently may obtain either 2 or 4 for the value of b.

Now suppose that to is synchronized but fro is not:

class SynchSimple {
    int a = 1, b = 2;
    synchronized void to() {
        a = 3;
        b = 4;
    }
    void fro() {
        System.out.println("a= " + a + ", b=" + b);
    }
}

In this case the method to will be forced to store the assigned values back to main memory before the unlock action at the end of the method. The method fro must, of course, use a and b (in that order) and so must load values for a and b from main memory.

The total set of actions may be pictured as follows:

Here an arrow from action A to action B indicates that A must precede B.

In what order may the actions by the main memory occur? Note that the rules do not require that write a occur before write b; neither do they require that read a occur before read b. Also, even though method to is synchronized, method fro is not synchronized, so there is nothing to prevent the read actions from occurring between the lock and unlock actions. (The point is that declaring one method synchronized does not of itself make that method behave as if it were atomic.)

As a result, the method fro could still obtain either 1 or 3 for the value of a, and independently could obtain either 2 or 4 for the value of b. In particular, fro might observe the value 1 for a and 4 for b. Thus, even though to does an assign to a and then an assign to b, the write actions to main memory may be observed by another thread to occur as if in the opposite order.

Finally, suppose that to and fro are both synchronized:

class SynchSynchSimple {
    int a = 1, b = 2;
    synchronized void to() {
        a = 3;
        b = 4;
    }
    synchronized void fro() {
        System.out.println("a= " + a + ", b=" + b);
    }
}

In this case, the actions of method fro cannot be interleaved with the actions of method to, and so fro will print either "a=1, b=2" or "a=3, b=4".


17.12 Threads

They plant dead trees for living, and the dead
They string together with a living thread . . .
But in no hush they string it . . . With a laugh, . . .
They bring the telephone and telegraph.
—Robert Frost, The Line-gang (1920)

Threads are created and managed by the built-in classes Thread (§20.20) and ThreadGroup (§20.21). Creating a Thread object creates a thread and that is the only way to create a thread. When the thread is created, it is not yet active; it begins to run when its start method (§20.20.14) is called.

Every thread has a priority. When there is competition for processing resources, threads with higher priority are generally executed in preference to threads with lower priority. Such preference is not, however, a guarantee that the highest priority thread will always be running, and thread priorities cannot be used to reliably implement mutual exclusion.


17.13 Locks and Synchronization

There is a lock associated with every object. The Java language does not provide a way to perform separate lock and unlock actions; instead, they are implicitly performed by high-level constructs that arrange always to pair such actions correctly. (The Java Virtual Machine, however, provides separate monitorenter and monitorexit instructions that implement the lock and unlock actions.)

The synchronized statement (§14.17) computes a reference to an object; it then attempts to perform a lock action on that object and does not proceed further until the lock action has successfully completed. (A lock action may be delayed because the rules about locks can prevent the main memory from participating until some other thread is ready to perform one or more unlock actions.) After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same lock.

A synchronized method (§8.4.3.5) automatically performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed. If the method is an instance method, it locks the lock associated with the instance for which it was invoked (that is, the object that will be known as this during execution of the body of the method). If the method is static, it locks the lock associated with the Class object that represents the class in which the method is defined. If execution of the method's body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same lock.

Best practice is that if a variable is ever to be assigned by one thread and used or assigned by another, then all accesses to that variable should be enclosed in synchronized methods or synchronized statements.

Java does not prevent, nor require detection of, deadlock conditions. Programs where threads hold (directly or indirectly) locks on multiple objects should use conventional techniques for deadlock avoidance, creating higher-level locking primitives that don't deadlock, if necessary.


17.14 Wait Sets and Notification

Every object, in addition to having an associated lock, has an associated wait set, which is a set of threads. When an object is first created, its wait set is empty.

Wait sets are used by the methods wait (§20.1.6, §20.1.7, §20.1.8), notify (§20.1.9), and notifyAll (§20.1.10) of class Object. These methods also interact with the scheduling mechanism for threads (§20.20).

The method wait should be called for an object only when the current thread (call it T) has already locked the object's lock. Suppose that thread T has in fact performed N lock actions that have not been matched by unlock actions. The wait method then adds the current thread to the wait set for the object, disables the current thread for thread scheduling purposes, and performs N unlock actions to relinquish the lock. The thread T then lies dormant until one of three things happens:

  • Some other thread invokes the notify method for that object and thread T happens to be the one arbitrarily chosen as the one to notify.
  • Some other thread invokes the notifyAll method for that object.
  • If the call by thread T to the wait method specified a timeout interval, the specified amount of real time has elapsed.

The thread T is then removed from the wait set and re-enabled for thread scheduling. It then locks the object again (which may involve competing in the usual manner with other threads); once it has gained control of the lock, it performs [image] additional lock actions and then returns from the invocation of the wait method. Thus, on return from the wait method, the state of the object's lock is exactly as it was when the wait method was invoked.

The notify method should be called for an object only when the current thread has already locked the object's lock. If the wait set for the object is not empty, then some arbitrarily chosen thread is removed from the wait set and re-enabled for thread scheduling. (Of course, that thread will not be able to proceed until the current thread relinquishes the object's lock.)

The notifyAll method should be called for an object only when the current thread has already locked the object's lock. Every thread in the wait set for the object is removed from the wait set and re-enabled for thread scheduling. (Of course, those threads will not be able to proceed until the current thread relinquishes the object's lock.)

These pearls of thought in Persian gulfs were bred,
Each softly lucent as a rounded moon;
The diver Omar plucked them from their bed,
Fitzgerald strung them on an English thread.
—James Russell Lowell, in a copy of Omar Khayyam


 18. Documentation Comments

CHAPTER 18

Documentation Comments

The view that documentation is something that is
added to a program after it has been commissioned
seems to be wrong in principle, and counterproductive in practice.
Instead, documentation must be regarded as an
integral part of the process of design and coding.
—C. A. R. Hoare, Hints on Programming Language Design (1973)

Java programs can include documentation in their source code, in special documentation comments (§3.7). Such comments can appear before each class or interface declaration and before each method, constructor, or field declaration. Hypertext web pages can then be produced automatically from the source code of the program and these documentation comments.

This chapter gives an informal description of documentation comments. A complete formal specification would require a detailed description of those parts of the Hypertext Markup Language (HTML) that can be used within the documentation comments, which is beyond the scope of this specification.


18.1 The Text of a Documentation Comment

The text of a documentation comment consists of the characters between the /** that begins the comment and the */ that ends it. The text is divided into one or more lines. On each of these lines, leading * characters are ignored; for lines other than the first, blanks and tabs preceding the initial * characters are also discarded.

So, for example, in the comment:

/**XYZ
  ** Initialize to pre-trial defaults.
  123*/

the text of the comment has three lines. The first line consists of the text "XYZ"; the second line consists of the text " Initialize to pre-trial defaults." and the third line consists of the text "123"


18.2 HTML in a Documentation Comment

Text in a documentation comment may use HTML markers for formatting, with the exception that the specific markers <H1>, <H2>, <H3>, <H4>, <H5>, <H6>, and <HR> are reserved for use by the documentation generator and should not be used in the text. A complete description of HTML is available from the web site http://www.w3.org/ and also through the Internet documentation database at http://www.internic.net/, where the document "Hypertext Markup Language -Version 2.0" by T. Berners-Lee and D. Connolly may be found as RFC1866.


18.3 Summary Sentence and General Description

The first sentence of each documentation comment should be a summary sentence, containing a concise but complete description of the declared entity. This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first tagline (as defined below). This simple rule means that a first sentence such as:

This is a simulation of Prof. Knuth's MIX computer.

will not work properly, because the period after the abbreviation "Prof" ends the first sentence, as far as the Java documentation comment processor is concerned. Take care to avoid such difficulties.

Sentences following the summary sentence but preceding the first tagged paragraph (if any) form the general description part of the documentation comment.


18.4 Tagged Paragraphs

A line of a documentation comment that begins with the character @ followed by one of a few special keywords starts a tagged paragraph. The tagged paragraph also includes any following lines up to, but not including, either the first line of the next tagged paragraph or the end of the documentation comment.

Tagged paragraphs identify certain information that has a routine structure, such as the intended purpose of each parameter of a method, in a form that the documentation comment processor can easily marshal into standard typographical formats for purposes of presentation and cross-reference.

Different kinds of tagged paragraphs are available for class and interface declarations and for method, field, and constructor declarations.


18.4.1 The @see Tag

The following are examples of @see paragraphs, which may be used in any documentation comment to indicate a cross-reference to a class, interface, method, constructor, field, or URL:

@see java.lang.String
@see String
@see java.io.InputStream;
@see String#equals
@see java.lang.Object#wait(int)
@see java.io.RandomAccessFile#RandomAccessFile(File, String)
@see Character#MAX_RADIX
@see <a href="spec.html">Java Spec</a>

The character # separates the name of a class from the name of one of its fields, methods, or constructors. One of several overloaded methods or constructors may be selected by including a parenthesized list of argument types after the method or constructor name.

A documentation comment may contain more than one @see tag.


18.4.2 The @author Tag

The following are examples of @author taglines, which may be used in documentation comments for class and interface declarations:

@author Mary Wollstonecraft
@author Hildegard von Bingen
@author Dorothy Parker

The information in an @author paragraph has no special internal structure.

A documentation comment may contain more than one @author tag. Alternatively, a single @author paragraph may mention several authors:

@author Jack Kent, Peggy Parish, Crockett Johnson,
    James Marshall, Marjorie Weinman Sharmat,
    Robert McCloskey, and Madeleine L'Engle

However, we recommend specifying one author per @author paragraph, which allows the documentation processing tool to provide the correct punctuation in all circumstances.


18.4.3 The @version Tag

The following is an example of a @version paragraph, which may be used in documentation comments for class and interface declarations:

@version 493.0.1beta

The information in a @version paragraph has no special internal structure.

A documentation comment may contain at most one @version tag.


18.4.4 The @param Tag

The following are examples of @param paragraphs, which may be used in documentation comments for method and constructor declarations:

@param file the file to be searched
@param pattern
    the pattern to be matched during the search
@param count      the number of lines to print for each match

The information in a @param paragraph should consist of the name of the parameter followed by a short description.

A documentation comment may contain more than one @param tag. The usual convention is that if any @param paragraphs are present in a documentation comment, then there should be one @param paragraph for each parameter of the method or constructor, and the @param paragraphs should appear in the order in which the parameters are declared.


18.4.5 The @return Tag

The following is an example of a @return paragraph, which may be used in documentation comments for declarations of methods whose result type is not void:

@return the number of widgets that pass the quality test

The information in a @return paragraph has no special internal structure. The usual convention is that it consists of a short description of the returned value.

A documentation comment may contain at most one @return tag.


18.4.6 The @exception Tag

The following is an example of an @exception paragraph, which may be used in documentation comments for method and constructor declarations:

@exception IndexOutOfBoundsException
                the matrix is too large
@exception UnflangedWidgetException the widget does not
                have a flange, or its flange has size zero
@exception java.io.FileNotFoundException the file
                does not exist

The information in an @exception paragraph should consist of the name of an exception class (which may be a simple name or a qualified name) followed by a short description of the circumstances that cause the exception to be thrown.

A documentation comment may contain more than one @exception tag.


18.5 Example

Here, as an example, is a version of the source code for the class Object of the package java.lang, including its documentation comments.

/*
 * @(#)Object.java 1.37 96/06/26
 *
 * Copyright (c) 1994, 1995, 1996 Sun Microsystems, Inc.
 * All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this
 * software and its documentation for NON-COMMERCIAL purposes
 * and without fee is hereby granted provided that this
 * copyright notice appears in all copies. Please refer to
 * the file "copyright.html" for further important copyright
 * and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package java.lang;

/**
 * The root of the Class hierarchy.  Every Class in the
 * system has Object as its ultimate parent.  Every variable
 * and method defined here is available in every Object.
 * @see				Class
 * @version				1.37, 26 Jun 1996
 */

public class Object {
    /**
     * Returns the Class of this Object. Java has a runtime
     * representation for classes--a descriptor of type Class
     * --which the method getClass() returns for any Object.
     */
    public final native Class getClass();

    /**
     * Returns a hashcode for this Object.
     * Each Object in the Java system has a hashcode.
     * The hashcode is a number that is usually different
     * for different Objects. It is used when storing Objects
     * in hashtables.
     * Note: hashcodes can be negative as well as positive.
     * @see				java.util.Hashtable
     */
    public native int hashCode();

    /**
     * Compares two Objects for equality.
     * Returns a boolean that indicates whether this Object
     * is equivalent to the specified Object. This method is
     * used when an Object is stored in a hashtable.
     * @param				obj			the Object to compare with
     * @return				true if these Objects are equal;
     * 					false otherwise.
     * @see				java.util.Hashtable
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

    /**
     * Creates a clone of the object. A new instance is
     * allocated and a bitwise clone of the current object
     * is placed in the new object.
     * @return				a clone of this Object.
     * @exception					OutOfMemoryError If there is not enough
     * 						memory.
     * @exception					CloneNotSupportedException Object
     * 						explicitly does not want to be
     * 						cloned, or it does not support
     * 						the Cloneable interface.
     */
    protected native Object clone()
        throws CloneNotSupportedException;

    /**
     * Returns a String that represents this Object.
     * It is recommended that all subclasses override
     * this method.
     */
    public String toString() {
        return getClass().getName() + "@" +
            Integer.toHexString(hashCode());
    }

    /**
     * Notifies a single waiting thread on a change in
     * condition of another thread. The thread effecting
     * the change notifies the waiting thread using notify().
     * Threads that want to wait for a condition to change
     * before proceeding can call wait(). <p>
     * <em>The method notify() can be called only by the
     * thread that is the owner of the current object's
     * monitor lock.</em>
     *
     * @exception					IllegalMonitorStateException If the
     * 						current thread is not the owner
     * 						of the Object's monitor lock.
     * @see				Object#wait
     * @see				Object#notifyAll
     */
    public final native void notify();

    /**
     * Notifies all the threads waiting for a condition to
     * change. Threads that are waiting are generally waiting
     * for another thread to change some condition. Thus, the
     * thread effecting a change that more than one thread is
     * waiting for notifies all the waiting threads using
     * the method notifyAll(). Threads that want to wait for
     * a condition to change before proceeding can call
     * wait(). <p>
     * <em>The method notifyAll() can be called only by the
     * thread that is the owner of the current object's
     * monitor lock.</em>
     *
     * @exception					IllegalMonitorStateException If the
     * 						current thread is not the owner
     * 						of the Object's monitor lock.
     * @see				Object#wait
     * @see				Object#notify
     */
    public final native void notifyAll();

    /**
     * Causes a thread to wait until it is notified or the
     * specified timeout expires. <p>
     * <em>The method wait(millis) can be called only by
     * the thread that is the owner of the current object's
     * monitor lock.</em>
     *
     * @param 				millis			the maximum time to wait,
     * 								in milliseconds
     * @exception					IllegalMonitorStateException If the
     * 						current thread is not the owner
     * 						of the Object's monitor lock.
     * @exception 					InterruptedException Another thread has
     * 						interrupted this thread.
     */
    public final native void wait(long millis)
        throws InterruptedException;

    /**
     * More accurate wait.
     * <em>The method wait(millis, nanos) can be called only
     * by the thread that is the owner of the current
     * object's monitor lock.</em>
     *
     * @param millis						the maximum time to wait,
     * 							in milliseconds
     * @param nano						additional time to wait,
     * 							in nanoseconds
     * 							(range 0-999999)
     * @exception					IllegalMonitorStateException If the
     * 						current thread is not the owner
     * 						of the Object's monitor lock.
     * @exception 					InterruptedException Another thread has
     * 						interrupted this thread.
     */
    public final void wait(long millis, int nanos)
        throws InterruptedException
    {
        if (nanos >= 500000 || (nanos != 0 && millis==0))
            timeout++;
        wait(timeout);
    }

    /**
     * Causes a thread to wait forever until it is notified.
     * <p>
     * <em>The method wait() can be called only by the
     * thread that is the owner of the current object's
     * monitor lock.</em>
     *

     * @exception					IllegalMonitorStateException If the
     * 						current thread is not the owner
     * 						of the Object's monitor lock.
     * @exception 					InterruptedException Another thread has
     * 						interrupted this thread.
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

    /**
     * Code to perform when this object is garbage collected.
     * The default is that nothing needs to be performed.
     *
     * Any exception thrown by a finalize method causes the
     * finalization to halt.  But otherwise, it is ignored.
     */
    protected void finalize() throws Throwable { }

}

From this source code, the javadoc tool produced the following HTML file, which is available for browsing at http://java.sun.com/Series/, our Java Series web site:

<!--NewPage-->

<html>

<head>

<!-- Generated by javadoc on Wed Jun 26 11:40:38 EDT 1996 -->

<a name="_top_"></a>

<title>

  Class java.lang.Object

</title>

</head>

<body>

<pre>

<a href="packages.html">All Packages</a>  <a href="tree.html">Class Hierarchy¬
</a>  <a href="Package-java.lang.html">This Package</a>  <a href="java.lang.N¬
umber.html#_top_">Previous</a>  <a href="java.lang.OutOfMemoryError.html#_top¬
_">Next</a>  <a href="AllNames.html">Index</a></pre>

<hr>

<h1>

  Class java.lang.Object

</h1>

<pre>

java.lang.Object

</pre>

<hr>

<dl>

  <dt> public class <b>Object</b>

</dl>

The root of the Class hierarchy.  Every Class in the

system has Object as its ultimate parent.  Every variable

and method defined here is available in every Object.

<dl>

  <dt> <b>Version:</b>

  <dd> 1.37, 26 Jun 1996

    <dt> <b>See Also:</b>

    <dd> <a href="java.lang.Class.html#_top_">Class</a>

</dl>

<hr>

<a name="index"></a>

<h2>

  <img src="images/constructor-index.gif" width=275 height=38 alt="Constructo¬
r Index">

</h2>

<dl>

  <dt> <img src="images/yellow-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#Object()"><b>Object</b></a>()

  <dd>

</dl>

<h2>

  <img src="images/method-index.gif" width=207 height=38 alt="Method Index">

</h2>

<dl>

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#clone()"><b>clone</b></a>()

  <dd> Creates a clone of the object.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#equals(java.lang.Object)"><b>equals</b></a>(Object)

  <dd> Compares two Objects for equality.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#finalize()"><b>finalize</b></a>()

  <dd> Code to perform when this object is garbage collected.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#getClass()"><b>getClass</b></a>()

  <dd> Returns the Class of this Object.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#hashCode()"><b>hashCode</b></a>()

  <dd> Returns a hashcode for this Object.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#notify()"><b>notify</b></a>()

  <dd> Notifies a single waiting thread on a change in

condition of another thread.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#notifyAll()"><b>notifyAll</b></a>()

  <dd> Notifies all the threads waiting for a condition to

change.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#toString()"><b>toString</b></a>()

  <dd> Returns a String that represents this Object.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#wait()"><b>wait</b></a>()

  <dd> Causes a thread to wait forever until it is notified.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#wait(long)"><b>wait</b></a>(long)

  <dd> Causes a thread to wait until it is notified or the

specified timeout expires.

  <dt> <img src="images/red-ball-small.gif" width=6 height=6 alt=" o ">

    <a href="#wait(long, int)"><b>wait</b></a>(long, int)

  <dd> More accurate wait.

</dl>

<a name="constructors"></a>

<h2>

  <img src="images/constructors.gif" width=231 height=38 alt="Constructors">

</h2>

<a name="Object"></a>

<a name="Object()"><img src="images/yellow-ball.gif" width=12 height=12 alt="¬
o "></a>

<b>Object</b>

<pre>

  public Object()

</pre>

<a name="methods"></a>

<h2>

  <img src="images/methods.gif" width=151 height=38 alt="Methods">

</h2>

<a name="getClass()"><img src="images/red-ball.gif" width=12 height=12 alt=" ¬
o "></a>

<a name="getClass"><b>getClass</b></a>

<pre>

  public final <a href="java.lang.Class.html#_top_">Class</a> getClass()

</pre>

<dl>

  <dd> Returns the Class of this Object. Java has a runtime

representation for classes--a descriptor of type Class

--which the method getClass() returns for any Object.

</dl>

<a name="hashCode()"><img src="images/red-ball.gif" width=12 height=12 alt=" ¬
o "></a>

<a name="hashCode"><b>hashCode</b></a>

<pre>

  public int hashCode()

</pre>

<dl>

  <dd> Returns a hashcode for this Object.

Each Object in the Java system has a hashcode.

The hashcode is a number that is usually different

for different Objects. It is used when storing Objects

in hashtables.

Note: hashcodes can be negative as well as positive.

  <dl>

    <dt> <b>See Also:</b>

    <dd> <a href="java.util.Hashtable.html#_top_">Hashtable</a>

  </dl>

</dl>

<a name="equals(java.lang.Object)"><img src="images/red-ball.gif" width=12 he¬
ight=12 alt=" o "></a>

<a name="equals"><b>equals</b></a>

<pre>

  public boolean equals(<a href="#_top_">Object</a> obj)

</pre>

<dl>

  <dd> Compares two Objects for equality.

Returns a boolean that indicates whether this Object

is equivalent to the specified Object. This method is

used when an Object is stored in a hashtable.

  <dl>

    <dt> <b>Parameters:</b>

    <dd> obj - the Object to compare with

    <dt> <b>Returns:</b>

    <dd> true if these Objects are equal;

            false otherwise.

    <dt> <b>See Also:</b>

    <dd> <a href="java.util.Hashtable.html#_top_">Hashtable</a>

  </dl>

</dl>

<a name="clone()"><img src="images/red-ball.gif" width=12 height=12 alt=" o "¬
></a>

<a name="clone"><b>clone</b></a>

<pre>

  protected <a href="#_top_">Object</a> clone() throws <a href="java.lang.Clo¬
neNotSupportedException.html#_top_">CloneNotSupportedException</a>

</pre>

<dl>

  <dd> Creates a clone of the object. A new instance is

allocated and a bitwise clone of the current object

is placed in the new object.

  <dl>

    <dt> <b>Returns:</b>

    <dd> a clone of this Object.

    <dt> <b>Throws:</b> <a href="java.lang.OutOfMemoryError.html#_top_">OutOf¬
MemoryError</a>

    <dd> If there is not enough

            memory.

    <dt> <b>Throws:</b> <a href="java.lang.CloneNotSupportedException.html#_t¬
op_">CloneNotSupportedException</a>

    <dd> Object

            explicitly does not want to be

            cloned, or it does not support

            the Cloneable interface.

  </dl>

</dl>

<a name="toString()"><img src="images/red-ball.gif" width=12 height=12 alt=" ¬
o "></a>

<a name="toString"><b>toString</b></a>

<pre>

  public <a href="java.lang.String.html#_top_">String</a> toString()

</pre>

<dl>

  <dd> Returns a String that represents this Object.

It is recommended that all subclasses override

this method.

</dl>

<a name="notify()"><img src="images/red-ball.gif" width=12 height=12 alt=" o ¬
"></a>

<a name="notify"><b>notify</b></a>

<pre>

  public final void notify()

</pre>

<dl>

  <dd> Notifies a single waiting thread on a change in

condition of another thread. The thread effecting

the change notifies the waiting thread using notify().

Threads that want to wait for a condition to change

before proceeding can call wait(). <p>

<em>The method notify() can be called only by the

thread that is the owner of the current object's

monitor lock.</em>

  <dl>

    <dt> <b>Throws:</b> <a href="java.lang.IllegalMonitorStateException.html#¬
_top_">IllegalMonitorStateException</a>

    <dd> If the

            current thread is not the owner

            of the Object's monitor lock.

    <dt> <b>See Also:</b>

    <dd> <a href="#wait">wait</a>, <a href="#notifyAll">notifyAll</a>

  </dl>

</dl>

<a name="notifyAll()"><img src="images/red-ball.gif" width=12 height=12 alt="¬
o "></a>

<a name="notifyAll"><b>notifyAll</b></a>

<pre>

  public final void notifyAll()

</pre>

<dl>

  <dd> Notifies all the threads waiting for a condition to

change. Threads that are waiting are generally waiting

for another thread to change some condition. Thus, the

thread effecting a change that more than one thread is

waiting for notifies all the waiting threads using

the method notifyAll(). Threads that want to wait for

a condition to change before proceeding can call

wait(). <p>

<em>The method notifyAll() can be called only by the

thread that is the owner of the current object's

monitor lock.</em>

  <dl>

    <dt> <b>Throws:</b> <a href="java.lang.IllegalMonitorStateException.html#¬
_top_">IllegalMonitorStateException</a>

    <dd> If the

            current thread is not the owner

            of the Object's monitor lock.

    <dt> <b>See Also:</b>

    <dd> <a href="#wait">wait</a>, <a href="#notify">notify</a>

  </dl>

</dl>

<a name="wait(long)"><img src="images/red-ball.gif" width=12 height=12 alt=" ¬
o "></a>

<a name="wait"><b>wait</b></a>

<pre>

  public final void wait(long millis) throws <a href="java.lang.InterruptedEx¬
ception.html#_top_">InterruptedException</a>

</pre>

<dl>

  <dd> Causes a thread to wait until it is notified or the

specified timeout expires. <p>

<em>The method wait(millis) can be called only by

the thread that is the owner of the current object's

monitor lock.</em>

  <dl>

    <dt> <b>Parameters:</b>

    <dd> millis - the maximum time to wait,

                in milliseconds

    <dt> <b>Throws:</b> <a href="java.lang.IllegalMonitorStateException.html#¬
_top_">IllegalMonitorStateException</a>

    <dd> If the

            current thread is not the owner

            of the Object's monitor lock.

    <dt> <b>Throws:</b> <a href="java.lang.InterruptedException.html#_top_">I¬
nterruptedException</a>

    <dd> Another thread has

            interrupted this thread.

  </dl>

</dl>

<a name="wait(long, int)"><img src="images/red-ball.gif" width=12 height=12 a¬
lt=" o "></a>

<a name="wait"><b>wait</b></a>

<pre>

  public final void wait(long millis,

                         int nanos) throws <a href="java.lang.InterruptedExce¬
ption.html#_top_">InterruptedException</a>

</pre>

<dl>

  <dd> More accurate wait.

<em>The method wait(millis, nanos) can be called only

by the thread that is the owner of the current

object's monitor lock.</em>

  <dl>

    <dt> <b>Parameters:</b>

    <dd> millis - the maximum time to wait,

                in milliseconds

    <dd> nano - additional time to wait,

                in nanoseconds

                (range 0-999999)

    <dt> <b>Throws:</b> <a href="java.lang.IllegalMonitorStateException.html#¬
_top_">IllegalMonitorStateException</a>

    <dd> If the

            current thread is not the owner

            of the Object's monitor lock.

    <dt> <b>Throws:</b> <a href="java.lang.InterruptedException.html#_top_">I¬
nterruptedException</a>

    <dd> Another thread has

            interrupted this thread.

  </dl>

</dl>

<a name="wait()"><img src="images/red-ball.gif" width=12 height=12 alt=" o ">¬
</a>

<a name="wait"><b>wait</b></a>

<pre>

  public final void wait() throws <a href="java.lang.InterruptedException.htm¬
l#_top_">InterruptedException</a>

</pre>

<dl>

  <dd> Causes a thread to wait forever until it is notified.

<p>

<em>The method wait() can be called only by the

thread that is the owner of the current object's

monitor lock.</em>

  <dl>

    <dt> <b>Throws:</b> <a href="java.lang.IllegalMonitorStateException.html#¬
_top_">IllegalMonitorStateException</a>

    <dd> If the

            current thread is not the owner

            of the Object's monitor lock.

    <dt> <b>Throws:</b> <a href="java.lang.InterruptedException.html#_top_">I¬
nterruptedException</a>

    <dd> Another thread has

            interrupted this thread.

  </dl>

</dl>

<a name="finalize()"><img src="images/red-ball.gif" width=12 height=12 alt=" ¬
o "></a>

<a name="finalize"><b>finalize</b></a>

<pre>

  protected void finalize() throws <a href="java.lang.Throwable.html#_top_">T¬
hrowable</a>

</pre>

<dl>

  <dd> Code to perform when this object is garbage collected.

The default is that nothing needs to be performed.

Any exception thrown by a finalize method causes the

finalization to halt.  But otherwise, it is ignored.

</dl>

<hr>

<pre>

<a href="packages.html">All Packages</a>  <a href="tree.html">Class Hierarchy¬
</a>  <a href="Package-java.lang.html">This Package</a>  <a href="java.lang.N¬
umber.html#_top_">Previous</a>  <a href="java.lang.OutOfMemoryError.html#_top¬
_">Next</a>  <a href="AllNames.html">Index</a></pre>

</body>

</html>

Many of the lines in this HTML file are far too long to fit onto these pages. We have used the character "¬" at the end of a line to indicate that the following line of text on the page is part of the same line in the generated file.

This generated HTML file is meant only as an example, not as a specification of the behavior of the javadoc tool, which may be changed over time to improve the HTML presentation of the documentation information.

Very few facts are able to tell their own story,
without comments to bring out their meaning.
—John Stuart Mill, On Liberty (1869)


 19. LALR(1) Grammar

CHAPTER 19

LALR(1) Grammar

This chapter presents a grammar for Java. The grammar has been mechanically checked to insure that it is LALR(1).

The grammar for Java presented piecemeal in the preceding chapters is much better for exposition, but it cannot be parsed left-to-right with one token of lookahead because of certain syntactic peculiarities, some of them inherited from C and C++. These problems and the solutions adopted for the LALR(1) grammar are presented below, followed by the grammar itself.


19.1 Grammatical Difficulties

There are five problems with the grammar presented in preceding chapters.


19.1.1 Problem #1: Names Too Specific

Consider the two groups of productions:

PackageName:

    Identifier

    PackageName . Identifier

TypeName:

    Identifier

    PackageName . Identifier

and:

MethodName:

    Identifier

    AmbiguousName . Identifier

AmbiguousName:

    Identifier

    AmbiguousName . Identifier

Now consider the partial input:

class Problem1 { int m() { hayden.

When the parser is considering the token hayden, with one-token lookahead to symbol ".", it cannot yet tell whether hayden should be a PackageName that qualifies a type name, as in:

hayden.Dinosaur rex = new Hayden.Dinosaur(2);

or an AmbiguousName that qualifies a method name, as in:

hayden.print("Dinosaur Rex!");

Therefore, the productions shown above result in a grammar that is not LALR(1). There are also other problems with drawing distinctions among different kinds of names in the grammar.

The solution is to eliminate the nonterminals PackageName, TypeName, ExpressionName, MethodName, and AmbiguousName, replacing them all with a single nonterminal Name:

Name:

    SimpleName

    QualifiedName

SimpleName:

    Identifier

QualifiedName:

    Name . Identifier

A later stage of compiler analysis then sorts out the precise role of each name or name qualifier.

For related reasons, these productions in §4.3:

ClassOrInterfaceType:

    ClassType

    InterfaceType

ClassType:

    TypeName

InterfaceType:

    TypeName

were changed to:

ClassOrInterfaceType:

    Name

ClassType:

    ClassOrInterfaceType

InterfaceType:

    ClassOrInterfaceType


19.1.2 Problem #2: Modifiers Too Specific

Consider the two groups of productions:

FieldDeclaration:

    FieldModifiersopt Type VariableDeclarators ;

FieldModifiers:

    FieldModifier

    FieldModifiers FieldModifier

FieldModifier: one of

    public protected private

    final static transient volatile

and:

MethodHeader:

    MethodModifiersopt ResultType MethodDeclarator Throwsopt

MethodModifiers:

    MethodModifier

    MethodModifiers MethodModifier

MethodModifier: one of

    public protected private

    static

    abstract final native synchronized

Now consider the partial input:

class Problem2 { public static int

When the parser is considering the token static, with one-token lookahead to symbol int-or, worse yet, considering the token public with lookahead to static-it cannot yet tell whether this will be a field declaration such as:

public static int maddie = 0;

or a method declaration such as:

public static int maddie(String art) { return art.length(); }

Therefore, the parser cannot tell with only one-token lookahead whether static (or, similarly, public) should be reduced to FieldModifier or MethodModifier. Therefore, the productions shown above result in a grammar that is not LALR(1). There are also other problems with drawing distinctions among different kinds of modifiers in the grammar.

While not all contexts provoke the problem, the simplest solution is to combine all contexts in which such modifiers are used, eliminating all six of the nonterminals ClassModifiers (§8.1.2), FieldModifiers (§8.3.1), MethodModifiers (§8.4.3), ConstructorModifiers (§8.6.3), InterfaceModifiers (§9.1.2), and ConstantModifiers (§9.3) from the grammar, replacing them all with a single nonterminal Modifiers:

Modifiers:

    Modifier

    Modifiers Modifier

Modifier: one of

    public protected private

    static

    abstract final native synchronized transient volatile

A later stage of compiler analysis then sorts out the precise role of each modifier and whether it is permitted in a given context.


19.1.3 Problem #3: Field Declaration versus Method Declaration

Consider the two productions (shown after problem #2 has been corrected):

FieldDeclaration:

    Modifiersopt Type VariableDeclarators ;

and:

MethodHeader:

    Modifiersopt ResultType MethodDeclarator Throwsopt

where ResultType is defined as:

ResultType:

    Type

    void

Now consider the partial input:

class Problem3 { int julie

Note that, in this simple example, no Modifiers are present. When the parser is considering the token int, with one-token lookahead to symbol julie, it cannot yet tell whether this will be a field declaration such as:

int julie = 14;

or a method declaration such as:

int julie(String art) { return art.length(); }

Therefore, after the parser reduces int to the nonterminal Type, it cannot tell with only one-token lookahead whether Type should be further reduced to ResultType (for a method declaration) or left alone (for a field declaration). Therefore, the productions shown above result in a grammar that is not LALR(1).

The solution is to eliminate the ResultType production and to have separate alternatives for MethodHeader:

MethodHeader:

    Modifiersopt Type MethodDeclarator Throwsopt

    Modifiersopt void MethodDeclarator Throwsopt

This allows the parser to reduce int to Type and then leave it as is, delaying the decision as to whether a field declaration or method declaration is in progress.


19.1.4 Problem #4: Array Type versus Array Access

Consider the productions (shown after problem #1 has been corrected):

ArrayType:

    Type [ ]

and:

ArrayAccess:

    Name [ Expression ]

    PrimaryNoNewArray [ Expression ]

Now consider the partial input:

class Problem4 { Problem4() { peter[

When the parser is considering the token peter, with one-token lookahead to symbol [, it cannot yet tell whether peter will be part of a type name, as in:

peter[] team;

or part of an array access, as in:

peter[3] = 12;

Therefore, after the parser reduces peter to the nonterminal Name, it cannot tell with only one-token lookahead whether Name should be reduced ultimately to Type (for an array type) or left alone (for an array access). Therefore, the productions shown above result in a grammar that is not LALR(1).

The solution is to have separate alternatives for ArrayType:

ArrayType:

    PrimitiveType [ ]

    Name [ ]

    ArrayType [ ]

This allows the parser to reduce peter to Name and then leave it as is, delaying the decision as to whether an array type or array access is in progress.


19.1.5 Problem #5: Cast versus Parenthesized Expression

Consider the production:

CastExpression:

    ( PrimitiveType ) UnaryExpression

    ( ReferenceType ) UnaryExpressionNotPlusMinus

Now consider the partial input:

class Problem5 { Problem5() { super((matthew)

When the parser is considering the token matthew, with one-token lookahead to symbol ), it cannot yet tell whether (matthew) will be a parenthesized expression, as in:

super((matthew), 9);

or a cast, as in:

super((matthew)baz, 9);

Therefore, after the parser reduces matthew to the nonterminal Name, it cannot tell with only one-token lookahead whether Name should be further reduced to PostfixExpression and ultimately to Expression (for a parenthesized expression) or to ClassOrInterfaceType and then to ReferenceType (for a cast). Therefore, the productions shown above result in a grammar that is not LALR(1).

The solution is to eliminate the use of the nonterminal ReferenceType in the definition of CastExpression, which requires some reworking of both alternatives to avoid other ambiguities:

CastExpression:

    ( PrimitiveType Dimsopt ) UnaryExpression

    ( Expression ) UnaryExpressionNotPlusMinus

    ( Name Dims ) UnaryExpressionNotPlusMinus

This allows the parser to reduce matthew to Expression and then leave it there, delaying the decision as to whether a parenthesized expression or a cast is in progress. Inappropriate variants such as:

(int[])+3

and:

(matthew+1)baz

must then be weeded out and rejected by a later stage of compiler analysis.

The remaining sections of this chapter constitute a LALR(1) grammar for Java syntax, in which the five problems described above have been solved.


19.2 Grammar from §2.3: The Syntactic Grammar

19.2 Grammar from §2.3: The Syntactic Grammar §2.3

Goal:

    CompilationUnit


19.3 Grammar from §3: Lexical Structure

19.3 Grammar from §3: Lexical Structure §3

Literal:

    IntegerLiteral

    FloatingPointLiteral

    BooleanLiteral

    CharacterLiteral

    StringLiteral

    NullLiteral


19.4 Grammar from §4: Types, Values, and Variables

19.4 Grammar from §4: Types, Values, and Variables §4

Type:

    PrimitiveType

    ReferenceType

PrimitiveType:

    NumericType

    boolean

NumericType:

    IntegralType

    FloatingPointType

IntegralType: one of

    byte short int long char

FloatingPointType: one of

    float double

ReferenceType:

    ClassOrInterfaceType

    ArrayType

ClassOrInterfaceType:

    Name

ClassType:

    ClassOrInterfaceType

InterfaceType:

    ClassOrInterfaceType

ArrayType:

    PrimitiveType [ ]

    Name [ ]

    ArrayType [ ]


19.5 Grammar from §6: Names

19.5 Grammar from §6: Names §6

Name:

    SimpleName

    QualifiedName

SimpleName:

    Identifier

QualifiedName:

    Name . Identifier


19.6 Grammar from §7: Packages

19.6 Grammar from §7: Packages §7

CompilationUnit:

    PackageDeclarationopt ImportDeclarationsopt TypeDeclarationsopt

ImportDeclarations:

    ImportDeclaration

    ImportDeclarations ImportDeclaration

TypeDeclarations:

    TypeDeclaration

    TypeDeclarations TypeDeclaration

PackageDeclaration:

    package Name ;

ImportDeclaration:

    SingleTypeImportDeclaration

    TypeImportOnDemandDeclaration

SingleTypeImportDeclaration:

    import Name ;

TypeImportOnDemandDeclaration:

    import Name . * ;

TypeDeclaration:

    ClassDeclaration

    InterfaceDeclaration

    ;


19.7 Productions Used Only in the LALR(1) Grammar

Modifiers:

    Modifier

    Modifiers Modifier

Modifier: one of

    public protected private

    static

    abstract final native synchronized transient volatile


19.8 Grammar from §8: Classes

19.8 Grammar from §8: Classes §8


19.8.1 Grammar from §8.1: Class Declaration

19.8.1 Grammar from §8.1: Class Declaration §8.1

ClassDeclaration:

    Modifiersopt class Identifier Superopt Interfacesopt ClassBody

Super:

    extends ClassType

Interfaces:

    implements InterfaceTypeList

InterfaceTypeList:

    InterfaceType

    InterfaceTypeList , InterfaceType

ClassBody:

    { ClassBodyDeclarationsopt }

ClassBodyDeclarations:

    ClassBodyDeclaration

    ClassBodyDeclarations ClassBodyDeclaration

ClassBodyDeclaration:

    ClassMemberDeclaration

    StaticInitializer

    ConstructorDeclaration

ClassMemberDeclaration:

    FieldDeclaration

    MethodDeclaration


19.8.2 Grammar from §8.3: Field Declarations

19.8.2 Grammar from §8.3: Field Declarations §8.3

FieldDeclaration:

    Modifiersopt Type VariableDeclarators ;

VariableDeclarators:

    VariableDeclarator

    VariableDeclarators , VariableDeclarator

VariableDeclarator:

    VariableDeclaratorId

    VariableDeclaratorId = VariableInitializer

VariableDeclaratorId:

    Identifier

    VariableDeclaratorId [ ]

VariableInitializer:

    Expression

    ArrayInitializer


19.8.3 Grammar from §8.4: Method Declarations

19.8.3 Grammar from §8.4: Method Declarations §8.4

MethodDeclaration:

    MethodHeader MethodBody

MethodHeader:

    Modifiersopt Type MethodDeclarator Throwsopt

    Modifiersopt void MethodDeclarator Throwsopt

MethodDeclarator:

    Identifier ( FormalParameterListopt )

    MethodDeclarator [ ]

FormalParameterList:

    FormalParameter

    FormalParameterList , FormalParameter

FormalParameter:

    Type VariableDeclaratorId

Throws:

    throws ClassTypeList

ClassTypeList:

    ClassType

    ClassTypeList , ClassType

MethodBody:

    Block

    ;


19.8.4 Grammar from §8.5: Static Initializers

19.8.4 Grammar from §8.5: Static Initializers §8.5

StaticInitializer:

    static Block


19.8.5 Grammar from §8.6: Constructor Declarations

19.8.5 Grammar from §8.6: Constructor Declarations §8.6

ConstructorDeclaration:

    Modifiersopt ConstructorDeclarator Throwsopt ConstructorBody

ConstructorDeclarator:

    SimpleName ( FormalParameterListopt )

ConstructorBody:

    { ExplicitConstructorInvocationopt BlockStatementsopt }

ExplicitConstructorInvocation:

    this ( ArgumentListopt ) ;

    super ( ArgumentListopt ) ;


19.9 Grammar from §9: Interfaces

19.9 Grammar from §9: Interfaces §9


19.9.1 Grammar from §9.1: Interface Declarations

19.9.1 Grammar from §9.1: Interface Declarations §9.1

InterfaceDeclaration:

    Modifiersopt interface Identifier ExtendsInterfacesopt InterfaceBody

ExtendsInterfaces:

    extends InterfaceType

    ExtendsInterfaces , InterfaceType

InterfaceBody:

    { InterfaceMemberDeclarationsopt }

InterfaceMemberDeclarations:

    InterfaceMemberDeclaration

    InterfaceMemberDeclarations InterfaceMemberDeclaration

InterfaceMemberDeclaration:

    ConstantDeclaration

    AbstractMethodDeclaration

ConstantDeclaration:

    FieldDeclaration

AbstractMethodDeclaration:

    MethodHeader ;


19.10 Grammar from §10: Arrays

19.10 Grammar from §10: Arrays §10

ArrayInitializer:

    { VariableInitializersopt ,opt }

VariableInitializers:

    VariableInitializer

    VariableInitializers , VariableInitializer


19.11 Grammar from §14: Blocks and Statements

19.11 Grammar from §14: Blocks and Statements §14

Block:

    { BlockStatementsopt }

BlockStatements:

    BlockStatement

    BlockStatements BlockStatement

BlockStatement:

    LocalVariableDeclarationStatement

    Statement

LocalVariableDeclarationStatement:

    LocalVariableDeclaration ;

LocalVariableDeclaration:

    Type VariableDeclarators

Statement:

    StatementWithoutTrailingSubstatement

    LabeledStatement

    IfThenStatement

    IfThenElseStatement

    WhileStatement

    ForStatement

StatementNoShortIf:

    StatementWithoutTrailingSubstatement

    LabeledStatementNoShortIf

    IfThenElseStatementNoShortIf

    WhileStatementNoShortIf

    ForStatementNoShortIf

StatementWithoutTrailingSubstatement:

    Block

    EmptyStatement

    ExpressionStatement

    SwitchStatement

    DoStatement

    BreakStatement

    ContinueStatement

    ReturnStatement

    SynchronizedStatement

    ThrowStatement

    TryStatement

EmptyStatement:

    ;

LabeledStatement:

    Identifier : Statement

LabeledStatementNoShortIf:

    Identifier : StatementNoShortIf

ExpressionStatement:

    StatementExpression ;

StatementExpression:

    Assignment

    PreIncrementExpression

    PreDecrementExpression

    PostIncrementExpression

    PostDecrementExpression

    MethodInvocation

    ClassInstanceCreationExpression

IfThenStatement:

    if ( Expression ) Statement

IfThenElseStatement:

    if ( Expression ) StatementNoShortIf else Statement

IfThenElseStatementNoShortIf:

    if ( Expression ) StatementNoShortIf else StatementNoShortIf

SwitchStatement:

    switch ( Expression ) SwitchBlock

SwitchBlock:

    { SwitchBlockStatementGroupsopt SwitchLabelsopt }

SwitchBlockStatementGroups:

    SwitchBlockStatementGroup

    SwitchBlockStatementGroups SwitchBlockStatementGroup

SwitchBlockStatementGroup:

    SwitchLabels BlockStatements

SwitchLabels:

    SwitchLabel

    SwitchLabels SwitchLabel

SwitchLabel:

    case ConstantExpression :

    default :

WhileStatement:

    while ( Expression ) Statement

WhileStatementNoShortIf:

    while ( Expression ) StatementNoShortIf

DoStatement:

    do Statement while ( Expression ) ;

ForStatement:

    for ( ForInitopt ; Expressionopt ; ForUpdateopt )

        Statement

ForStatementNoShortIf:

    for ( ForInitopt ; Expressionopt ; ForUpdateopt )

        StatementNoShortIf

ForInit:

    StatementExpressionList

    LocalVariableDeclaration

ForUpdate:

    StatementExpressionList

StatementExpressionList:

    StatementExpression

    StatementExpressionList , StatementExpression

BreakStatement:

    break Identifieropt ;

ContinueStatement:

    continue Identifieropt ;

ReturnStatement:

    return Expressionopt ;

ThrowStatement:

    throw Expression ;

SynchronizedStatement:

    synchronized ( Expression ) Block

TryStatement:

    try Block Catches

    try Block Catchesopt Finally

Catches:

    CatchClause

    Catches CatchClause

CatchClause:

    catch ( FormalParameter ) Block

Finally:

    finally Block


19.12 Grammar from §15: Expressions

19.12 Grammar from §15: Expressions §15

Primary:

    PrimaryNoNewArray

    ArrayCreationExpression

PrimaryNoNewArray:

    Literal

    this

    ( Expression )

    ClassInstanceCreationExpression

    FieldAccess

    MethodInvocation

    ArrayAccess

ClassInstanceCreationExpression:

    new ClassType ( ArgumentListopt )

ArgumentList:

    Expression

    ArgumentList , Expression

ArrayCreationExpression:

    new PrimitiveType DimExprs Dimsopt

    new ClassOrInterfaceType DimExprs Dimsopt

DimExprs:

    DimExpr

    DimExprs DimExpr

DimExpr:

    [ Expression ]

Dims:

    [ ]

    Dims [ ]

FieldAccess:

    Primary . Identifier

    super . Identifier

MethodInvocation:

    Name ( ArgumentListopt )

    Primary . Identifier ( ArgumentListopt )

    super . Identifier ( ArgumentListopt )

ArrayAccess:

    Name [ Expression ]

    PrimaryNoNewArray [ Expression ]

PostfixExpression:

    Primary

    Name

    PostIncrementExpression

    PostDecrementExpression

PostIncrementExpression:

    PostfixExpression ++

PostDecrementExpression:

    PostfixExpression --

UnaryExpression:

    PreIncrementExpression

    PreDecrementExpression

    + UnaryExpression

    - UnaryExpression

    UnaryExpressionNotPlusMinus

PreIncrementExpression:

    ++ UnaryExpression

PreDecrementExpression:

    -- UnaryExpression

UnaryExpressionNotPlusMinus:

    PostfixExpression

    ~ UnaryExpression

    ! UnaryExpression

    CastExpression

CastExpression:

    ( PrimitiveType Dimsopt ) UnaryExpression

    ( Expression ) UnaryExpressionNotPlusMinus

    ( Name Dims ) UnaryExpressionNotPlusMinus

MultiplicativeExpression:

    UnaryExpression

    MultiplicativeExpression * UnaryExpression

    MultiplicativeExpression / UnaryExpression

    MultiplicativeExpression % UnaryExpression

AdditiveExpression:

    MultiplicativeExpression

    AdditiveExpression + MultiplicativeExpression

    AdditiveExpression - MultiplicativeExpression

ShiftExpression:

    AdditiveExpression

    ShiftExpression << AdditiveExpression

    ShiftExpression >> AdditiveExpression

    ShiftExpression >>> AdditiveExpression

RelationalExpression:

    ShiftExpression

    RelationalExpression < ShiftExpression

    RelationalExpression > ShiftExpression

    RelationalExpression <= ShiftExpression

    RelationalExpression >= ShiftExpression

    RelationalExpression instanceof ReferenceType

EqualityExpression:

    RelationalExpression

    EqualityExpression == RelationalExpression

    EqualityExpression != RelationalExpression

AndExpression:

    EqualityExpression

    AndExpression & EqualityExpression

ExclusiveOrExpression:

    AndExpression

    ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:

    ExclusiveOrExpression

    InclusiveOrExpression | ExclusiveOrExpression

ConditionalAndExpression:

    InclusiveOrExpression

    ConditionalAndExpression && InclusiveOrExpression

ConditionalOrExpression:

    ConditionalAndExpression

    ConditionalOrExpression || ConditionalAndExpression

ConditionalExpression:

    ConditionalOrExpression

    ConditionalOrExpression ? Expression : ConditionalExpression

AssignmentExpression:

    ConditionalExpression

    Assignment

Assignment:

    LeftHandSide AssignmentOperator AssignmentExpression

LeftHandSide:

    Name

    FieldAccess

    ArrayAccess

AssignmentOperator: one of

    = *= /= %= += -= <<= >>= >>>= &= ^= |=

Expression:

    AssignmentExpression

ConstantExpression:

    Expression


 20. The Package java.lang

CHAPTER 20

The Package java.lang

The java.lang package contains classes that are fundamental to the design of the Java language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time.

Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode.

The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String and StringBuffer similarly provide commonly used operations on character strings.

Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies.

Class Throwable encompasses objects that may be thrown by the throw statement (§14.16). Subclasses of Throwable represent errors and exceptions.

The hierarchy of classes defined in package java.lang is as follows.

Object §20.1
 interface Cloneable §20.2
    Class §20.3
    Boolean §20.4
    Character §20.5
    Number §20.6
        Integer §20.7
        Long §20.8
        Float §20.9
        Double §20.10
    Math §20.11
    String §20.12
    StringBuffer §20.13
    ClassLoader §20.14
    Process §20.15
    Runtime §20.16
    SecurityManager §20.17
    System §20.18
    interface Runnable §20.19
    Thread §20.20
    ThreadGroup §20.21
    Throwable §20.22
        Error
            LinkageError
                ClassCircularityError
                ClassFormatError
                ExceptionInInitializerError
                IncompatibleClassChangeError
                    AbstractMethodError
                    IllegalAccessError
                    InstantiationError
                    NoSuchFieldError
                    NoSuchMethodError
                NoClassDefFoundError
                UnsatisfiedLinkError
                VerifyError
            VirtualMachineError
                InternalError
                OutOfMemoryError
                StackOverflowError
                UnknownError
            ThreadDeath
        Exception
            ClassNotFoundException
            CloneNotSupportedException
            IllegalAccessException
            InstantiationException
            InterruptedException
            RuntimeException
                ArithmeticException
                ArrayStoreException
                ClassCastException
                IllegalArgumentException
                    IllegalThreadStateException
                    NumberFormatException
                IllegalMonitorStateException
                IndexOutOfBoundsException
                NegativeArraySizeException
                NullPointerException
                SecurityException


20.1 The Class java.lang.Object

The class Object is the single root of the class hierarchy. All objects, including arrays, implement the methods of this class.

public class Object {
    public final Class getClass();
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    protected Object clone()
        throws CloneNotSupportedException;
    public final void wait()

        throws IllegalMonitorStateException,

            InterruptedException;
    public final void wait(long millis)

        throws IllegalMonitorStateException,

            InterruptedException;
    public final void wait(long millis, int nanos)

        throws IllegalMonitorStateException,
            InterruptedException;
    public final void notify()
        throws IllegalMonitorStateException;
    public final void notifyAll()
        throws IllegalMonitorStateException;
    protected void finalize()

        throws Throwable;
}

20.1.1 public final Class getClass()

This method returns a reference to the unique object of type Class (§20.3) that represents the class of this object. That Class object is the object that is locked by static synchronized methods of the represented class.

20.1.2 public String toString()

The general contract of toString is that it returns a string that "textually represents" this object. The idea is to provide a concise but informative representation that will be useful to a person reading it.

The toString method defined by class Object returns a string consisting of the name of the class of which the object is an instance, a commercial at character '@', and the unsigned hexadecimal representation of the hashcode of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Overridden by Class (§20.3), Boolean (§20.4), Character (§20.5), Integer (§20.7), Long (§20.8), Float (§20.9), Double (§20.10), String (§20.12), StringBuffer (§20.13), Thread (§20.20), ThreadGroup (§20.21), Throwable (§20.22.4), and Bitset (§21.2).

20.1.3 public boolean equals(Object obj)

This method indicates whether some other object is "equal to" this one.

The general contract of equals is that it implements an equivalence relation:

  • It is reflexive: for any reference value x, x.equals(x) should return true.
  • It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used by x and y in equals comparisons is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method defined by class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, ((Object)x).equals(y) returns true if and only if x and y refer to the same object.

Overridden by Boolean (§20.4), Character (§20.5), Integer (§20.7), Long (§20.8), Float (§20.9), Double (§20.10), String (§20.12), and Bitset (§21.2).

20.1.4 public int hashCode()

This method is supported principally for the benefit of hash tables such as those provided by the Java library class java.util.Hashtable (§21.5).

The general contract of hashCode is as follows:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode must consistently return the same integer. The integer may be positive, negative, or zero. This integer does not, however, have to remain consistent from one Java application to another, or from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method (§20.1.3), then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method (§20.1.3), then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java language.)

Overridden by Boolean (§20.4), Character (§20.5), Integer (§20.7), Long (§20.8), Float (§20.9), Double (§20.10), String (§20.12), and Bitset (§21.2).

20.1.5 protected Object clone()
throws CloneNotSupportedException

The general contract of clone is that it creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x

will be true, and that the expression:

x.clone.getClass() == x.getClass()

will be true, but these are not absolute requirements. While it is typically the case that:

x.clone.equals(x)

will be true, this is not an absolute requirement. Copying an object will typically entail creating a new instance of its class, but it also may require copying of internal data structures as well.

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time. The clone method is implemented by the class Object as a convenient, general utility for subclasses that implement the interface Cloneable, possibly also overriding the clone method, in which case the overriding definition can refer to this utility definition by the call:

super.clone()

20.1.6 public final void wait()
throws IllegalMonitorStateException, InterruptedException

This method causes the current thread to wait until some other thread invokes the notify method (§20.1.9) or the notifyAll method (§20.1.10) for this object.

In other words, this method behaves exactly as if it simply performs the call wait(0) (§20.1.7).

20.1.7 public final void wait(long millis)
throws IllegalMonitorStateException, InterruptedException

This method causes the current thread to wait until either some other thread invokes the notify method (§20.1.9) or the notifyAll method (§20.1.10) for this object, or a certain amount of real time has elapsed.

This method may be called only when the current thread is already synchronized on this object. If the current thread does not own the lock on this object, an IllegalMonitorStateException is thrown.

This method causes the current thread (call it T) to place itself in the wait set (§17.14) for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts (§20.20.31) thread T.
  • The specified amount of real time has elapsed, more or less. The amount of real time, measured in milliseconds, is given by millis. If millis is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante-that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

20.1.8 public final void wait(long millis, int nanos)
throws IllegalMonitorStateException, InterruptedException

This method causes the current thread to wait until either some other thread invokes the notify method (§20.1.9) or the notifyAll method (§20.1.10) for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

The amount of real time, measured in nanoseconds, is given by:

1000000*millis+nanos

In all other respects, this method does the same thing as the method wait of one argument (§20.1.7). In particular, wait(0, 0) means the same thing as wait(0).

20.1.9 public final void notify()
throws IllegalMonitorStateException

If any threads are waiting (§20.1.7) on this object, one of them is chosen to be awakened. The choice is arbitrary and at the discretion of the implementation.

The notify method may be called only when the current thread is already synchronized on this object. If the current thread does not own the lock on this object, an IllegalMonitorStateException is thrown.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

20.1.10 public final void notifyAll()
throws IllegalMonitorStateException

All the threads waiting (§20.1.7) on this object are awakened.

The notifyAll method may be called only when the current thread is already synchronized on this object. If the current thread does not own the lock on this object, an IllegalMonitorStateException is thrown.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

20.1.11 protected void finalize() throws Throwable

The general contract of finalize is that it is invoked if and when the Java Virtual Machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died (§12.7), except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

Java does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java Virtual Machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java Virtual Machine for any given object.


20.2 The Interface java.lang.Cloneable

The Cloneable interface should be implemented by any class that is intended to support or override the method clone (§20.1.5).

public interface Cloneable { }

The interface Cloneable declares no methods.

I am disappointed in Japp. He has no method!
—Agatha Christie, The Mysterious Affair at Styles (1920), Chapter 8


20.3 The Class java.lang.Class

Instances of the class Class represent classes and interfaces in a way that can be manipulated by a running Java program. Every array also belongs to a class represented by a Class object that is shared among all arrays with the same element type and number of dimensions.

There is no public constructor for the class Class. The Java Virtual Machine automatically constructs Class objects as classes are loaded; such objects cannot be created by user programs.

public final class Class {
    public String toString();
    public String getName();
    public boolean isInterface();
    public Class getSuperclass();
    public Class[] getInterfaces();
    public Object newInstance()
        throws InstantiationException, IllegalAccessException;
    public static Class forName(String className)

        throws ClassNotFoundException;
    public ClassLoader getClassLoader();
}

20.3.1 public String toString()

If this Class object represents a class (which may be a declared class or an array class), a string is returned consisting of the word class, a space, and the name of the class as returned by the getName method (§20.3.2). If this Class object represents an interface, a string is returned consisting of the word interface, a space, and the name of the interface as returned by the getName method.

In other words, this method returns a string equal to the value of:

(isInterface() ? "interface " : "class ") + getName()

Overrides the toString method of Object (§20.1.2).

20.3.2 public String getName()

The fully qualified name of the class or interface represented by this Class object is returned as a String. For example:

new Object().getClass().getName()

returns "java.lang.Object".

If this class object represents a class of arrays, then the name consists of the name of the element type in Java signature format, preceded by one or more "[" characters representing the depth of array nesting. For example:

(new Object[3]).getClass().getName()

returns "[Ljava.lang.Object;" and:

(new int[3][4][5][6][7][8][9]).getClass().getName()

returns "[[[[[[[I". The encoding of element type names is as follows:

B				byte
C				char
D				double
F				float
I				int
J				long
Lclassname;				class or interface
S				short
Z				boolean

A class or interface name classname is given in fully qualified form as shown in the example above. For a full description of type descriptors see the chapter on the format of class files in the Java Virtual Machine Specification.

20.3.3 public boolean isInterface()

If this Class object represents an interface, true is returned. If this Class object represents a class, false is returned.

20.3.4 public Class getSuperclass()

If this Class object represents any class other than the class Object, then the Class that represents the superclass of that class is returned. If this Class object is the one that represents the class Object, or if it represents an interface, null is returned. If this Class object represents an array class, then the Class that represents class Object is returned.

20.3.5 public Class[] getInterfaces()

This method returns an array of objects that represent interfaces. The array may be empty.

If this Class object represents a class, the array contains objects representing all interfaces directly implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this Class object. For example, given the class declaration:

class Shimmer implements FloorWax, DessertTopping { ... }

suppose the value of s is an instance of Shimmer; the value of the expression:

s.getClass().getInterfaces()[0]

is the Class object that represents interface FloorWax; and the value of:

s.getClass().getInterfaces()[1]

is the Class object that represents interface DessertTopping.

If this Class object represents an interface, the array contains objects representing all interfaces directly extended by the interface-that is, the immediate superinterfaces of the interface. The order of the interface objects in the array corresponds to the order of the interface names in the extends clause of the declaration of the interface represented by this Class object.

20.3.6 public Object newInstance()
throws InstantiationException, IllegalAccessException

This method creates and returns a new instance of the class represented by this Class object. This is done exactly as if by a class instance creation expression (§15.8) with an empty argument list; for example, if t is the Class object that represents class Thread, then t.newInstance() does exactly the same thing as new Thread(). If evaluation of such a class instance creation expression would complete abruptly, then the call to the newInstance method will complete abruptly for the same reason. See also §11.5.1.2 for more on InstantiationException.

20.3.7 public ClassLoader getClassLoader()

This method returns a reference to the class loader (§20.14) that loaded this class. If this class has no class loader, then null is returned.

20.3.8 public static Class forName(String className)
throws ClassNotFoundException

Given the fully-qualified name of a class as a string, this method attempts to locate, load, and link the class (§12.2). If it succeeds, then a reference to the Class object for the class is returned. If it fails, then a ClassNotFoundException is thrown.


20.4 The Class java.lang.Boolean

Objects of type Boolean represent primitive values of type boolean.

public final class Boolean {
    public static final Boolean TRUE = new Boolean(true);
    public static final Boolean FALSE = new Boolean(false);
    public Boolean(boolean value);
    public Boolean(String s);
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public boolean booleanValue();
    public static Boolean valueOf(String s);
    public static boolean getBoolean(String name);
}

20.4.1 public static final Boolean TRUE = new Boolean(true);

The constant value of this field is a Boolean object corresponding to the primitive value true.

20.4.2 public static final Boolean FALSE = new Boolean(false);

The constant value of this field is a Boolean object corresponding to the primitive value false.

20.4.3 public Boolean(boolean value)

This constructor initializes a newly created Boolean object so that it represents the primitive value that is the argument.

20.4.4 public Boolean(String s)

This constructor initializes a newly created Boolean object so that it represents true if and only if the argument is not null and is equal, ignoring case, to the string "true".

Examples:

new Boolean("True") produces a Boolean object that represents true.
new Boolean("yes") produces a Boolean object that represents false.

20.4.5 public boolean booleanValue()

The primitive boolean value represented by this Boolean object is returned.

20.4.6 public String toString()

If this Boolean object represents true, a string equal to "true" is returned. If this Boolean object represents false, a string equal to "false" is returned.

Overrides the toString method of Object (§20.1.2).

20.4.7 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this Boolean object.

Overrides the equals method of Object (§20.1.3).

20.4.8 public int hashCode()

If this Boolean object represents true, the integer 1231 is returned. If this Boolean object represents false, the integer 1237 is returned.

Overrides the hashCode method of Object (§20.1.4).

20.4.9 public static boolean valueOf(String s)

The result is true if and only if the argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.

Example: Boolean.valueOf("yes") returns false.

20.4.10 public static boolean getBoolean(String name)

The result is true if and only if the value of the system property (§20.18.9) named by the argument is equal, ignoring case, to the string "true".

This above all: to thine own self be true,
And it must follow, as the night the day,
Thou canst not then be false to any man.
—William Shakespeare, Hamlet, Act I, scene iii


20.5 The Class java.lang.Character

Here is the whole set! a character dead at every word.
—Richard Brinsley Sheridan, The School for Scandal, Act 2, scene 2

Objects of type Character represent primitive values of type char.

public final class Character {
    public static final char MIN_VALUE = '\u0000';
    public static final char MAX_VALUE = '\uffff';
    public static final int MIN_RADIX = 2;
    public static final int MAX_RADIX = 36;
    public Character(char value);
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public char charValue();
    public static boolean isDefined(char ch);
    public static boolean isLowerCase(char ch);
    public static boolean isUpperCase(char ch);
    public static boolean isTitleCase(char ch);
    public static boolean isDigit(char ch);
    public static boolean isLetter(char ch);
    public static boolean isLetterOrDigit(char ch);
    public static boolean isJavaLetter(char ch);
    public static boolean isJavaLetterOrDigit(char ch);)
    public static boolean isSpace(char ch);
    public static char toLowerCase(char ch);
    public static char toUpperCase(char ch);
    public static char toTitleCase(char ch);
    public static int digit(char ch, int radix);
    public static char forDigit(int digit, int radix);
}

Many of the methods of class Character are defined in terms of a "Unicode attribute table" that specifies a name for every defined Unicode character as well as other possible attributes, such as a decimal value, an uppercase equivalent, a lowercase equivalent, and/or a titlecase equivalent. Prior to Java 1.1, these methods were internal to the Java compiler and based on Unicode 1.1.5, as described here. The most recent versions of these methods should be used in Java compilers that are to run on Java systems that do not yet include these methods.

The Unicode 1.1.5 attribute table is available on the World Wide Web as:

ftp://unicode.org/pub/MappingTables/UnicodeData-1.1.5.txt

However, this file contains a few errors. The term "Unicode attribute table" in the following sections refers to the contents of this file after the following corrections have been applied:

  • The following entries should have titlecase mappings as shown here:

    03D0;GREEK BETA SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER CURLED BETA;;0392;;0392

    03D1;GREEK THETA SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398

    03D5;GREEK PHI SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER SCRIPT PHI;;03A6;;03A6

    03D6;GREEK PI SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER OMEGA PI;;03A0;;03A0

    03F0;GREEK KAPPA SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER SCRIPT KAPPA;;039A;;039A

    03F1;GREEK RHO SYMBOL;Ll;0;L;;;;;N;GREEK SMALL LETTER TAILED RHO;;03A1;;03A1

  • The following entries should have numeric values as shown here:

    FF10;FULLWIDTH DIGIT ZERO;Nd;0;EN;0030;0;0;0;N;;;;;

    FF11;FULLWIDTH DIGIT ONE;Nd;0;EN;0031;1;1;1;N;;;;;

    FF12;FULLWIDTH DIGIT TWO;Nd;0;EN;0032;2;2;2;N;;;;;

    FF13;FULLWIDTH DIGIT THREE;Nd;0;EN;0033;3;3;3;N;;;;;

    FF14;FULLWIDTH DIGIT FOUR;Nd;0;EN;0034;4;4;4;N;;;;;

    FF15;FULLWIDTH DIGIT FIVE;Nd;0;EN;0035;5;5;5;N;;;;;

    FF16;FULLWIDTH DIGIT SIX;Nd;0;EN;0036;6;6;6;N;;;;;

    FF17;FULLWIDTH DIGIT SEVEN;Nd;0;EN;0037;7;7;7;N;;;;;

    FF18;FULLWIDTH DIGIT EIGHT;Nd;0;EN;0038;8;8;8;N;;;;;

    FF19;FULLWIDTH DIGIT NINE;Nd;0;EN;0039;9;9;9;N;;;;;

  • The following entries should have no lowercase equivalents:

    03DA;GREEK LETTER STIGMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER STIGMA;;;;

    03DC;GREEK LETTER DIGAMMA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER DIGAMMA;;;;

    03DE;GREEK LETTER KOPPA;Lu;0;L;;;;;N;GREEK CAPITAL LETTER KOPPA;;;;

    03E0;GREEK LETTER SAMPI;Lu;0;L;;;;;N;GREEK CAPITAL LETTER SAMPI;;;;

  • This entry should have uppercase and titlecase equivalents as shown here:

    03C2;GREEK SMALL LETTER FINAL SIGMA;Ll;0;L;;;;;N;;;03A3;;03A3

It is anticipated that these problems will be corrected for Unicode version 2.0.

Java 1.1 will include the methods defined here, either based on Unicode 1.1.5 or, we hope, updated versions of the methods that use the newer Unicode 2.0. The character attribute table for Unicode 2.0 is currently available on the World Wide Web as the file:

ftp://unicode.org/pub/MappingTables/UnicodeData-2.0.12.txt

If you are implementing a Java compiler or system, please refer to the page:

http://java.sun.com/Series/

which will be updated with information about the Unicode-dependent methods.

The biggest change in Unicode 2.0 is a complete rearrangement of the Korean Hangul characters. There are numerous smaller improvements as well.

It is our intention that Java will track Unicode as it evolves over time. Given that full Unicode support is just emerging in the marketplace, and that changes in Unicode are in areas which are not yet widely used, this should cause minimal problems and further Java's goal of worldwide language support.

20.5.1 public static final char MIN_VALUE = '\u0000';

The constant value of this field is the smallest value of type char.

[This field is scheduled for introduction in Java version 1.1.]

20.5.2 public static final char MAX_VALUE = '\uffff';

The constant value of this field is the smallest value of type char.

[This field is scheduled for introduction in Java version 1.1.]

20.5.3 public static final int MIN_RADIX = 2;

The constant value of this field is the smallest value permitted for the radix argument in radix-conversion methods such as the digit method (§20.5.23), the forDigit method (§20.5.24), and the toString method of class Integer (§20.7).

20.5.4 public static final int MAX_RADIX = 36;

The constant value of this field is the largest value permitted for the radix argument in radix-conversion methods such as the digit method (§20.5.23), the forDigit method (§20.5.24), and the toString method of class Integer (§20.7).

20.5.5 public Character(char value)

This constructor initializes a newly created Character object so that it represents the primitive value that is the argument.

20.5.6 public String toString()

The result is a String whose length is 1 and whose sole component is the primitive char value represented by this Character object.

Overrides the toString method of Object (§20.1.2).

20.5.7 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Character object that represents the same char value as this Character object.

Overrides the equals method of Object (§20.1.3).

20.5.8 public int hashCode()

The result is the primitive char value represented by this Character object, cast to type int.

Overrides the hashCode method of Object (§20.1.4).

20.5.9 public char charValue()

The primitive char value represented by this Character object is returned.

20.5.10 public static boolean isDefined(char ch)

The result is true if and only if the character argument is a defined Unicode character.

A character is a defined Unicode character if and only if at least one of the following is true:

  • It has an entry in the Unicode attribute table.
  • It is not less than \u3040 and not greater than \u9FA5.
  • It is not less than \uF900 and not greater than \uFA2D.

It follows, then, that for Unicode 1.1.5 as corrected above, the defined Unicode characters are exactly those with codes in the following list, which contains both single codes and inclusive ranges: 0000-01F5, 01FA-0217, 0250-02A8, 02B0-02DE, 02E0-02E9, 0300-0345, 0360-0361, 0374-0375, 037A, 037E, 0384-038A, 038C, 038E-03A1, 03A3-03CE, 03D0-03D6, 03DA, 03DC, 03DE, 03E0, 03E2-03F3, 0401-040C, 040E-044F, 0451-045C, 045E-0486, 0490-04C4, 04C7-04C8, 04CB-04CC, 04D0-04EB, 04EE-04F5, 04F8-04F9, 0531-0556, 0559-055F, 0561-0587, 0589, 05B0-05B9, 05BB-05C3, 05D0-05EA, 05F0-05F4, 060C, 061B, 061F, 0621-063A, 0640-0652, 0660-066D, 0670-06B7, 06BA-06BE, 06C0-06CE, 06D0-06ED, 06F0-06F9, 0901-0903, 0905-0939, 093C-094D, 0950-0954, 0958-0970, 0981-0983, 0985-098C, 098F-0990, 0993-09A8, 09AA-09B0, 09B2, 09B6-09B9, 09BC, 09BE-09C4, 09C7-09C8, 09CB-09CD, 09D7, 09DC-09DD, 09DF-09E3, 09E6-09FA, 0A02, 0A05-0A0A, 0A0F-0A10, 0A13-0A28, 0A2A-0A30, 0A32-0A33, 0A35-0A36, 0A38-0A39, 0A3C, 0A3E-0A42, 0A47-0A48, 0A4B-0A4D, 0A59-0A5C, 0A5E, 0A66-0A74, 0A81-0A83, 0A85-0A8B, 0A8D, 0A8F-0A91, 0A93-0AA8, 0AAA-0AB0, 0AB2-0AB3, 0AB5-0AB9, 0ABC-0AC5, 0AC7-0AC9, 0ACB-0ACD, 0AD0, 0AE0, 0AE6-0AEF, 0B01-0B03, 0B05-0B0C, 0B0F-0B10, 0B13-0B28, 0B2A-0B30, 0B32-0B33, 0B36-0B39, 0B3C-0B43, 0B47-0B48, 0B4B-0B4D, 0B56-0B57, 0B5C-0B5D, 0B5F-0B61, 0B66-0B70, 0B82-0B83, 0B85-0B8A, 0B8E-0B90, 0B92-0B95, 0B99-0B9A, 0B9C, 0B9E-0B9F, 0BA3-0BA4, 0BA8-0BAA, 0BAE-0BB5, 0BB7-0BB9, 0BBE-0BC2, 0BC6-0BC8, 0BCA-0BCD, 0BD7, 0BE7-0BF2, 0C01-0C03, 0C05-0C0C, 0C0E-0C10, 0C12-0C28, 0C2A-0C33, 0C35-0C39, 0C3E-0C44, 0C46-0C48, 0C4A-0C4D, 0C55-0C56, 0C60-0C61, 0C66-0C6F, 0C82-0C83, 0C85-0C8C, 0C8E-0C90, 0C92-0CA8, 0CAA-0CB3, 0CB5-0CB9, 0CBE-0CC4, 0CC6-0CC8, 0CCA-0CCD, 0CD5-0CD6, 0CDE, 0CE0-0CE1, 0CE6-0CEF, 0D02-0D03, 0D05-0D0C, 0D0E-0D10, 0D12-0D28, 0D2A-0D39, 0D3E-0D43, 0D46-0D48, 0D4A-0D4D, 0D57, 0D60-0D61, 0D66-0D6F, 0E01-0E3A, 0E3F-0E5B, 0E81-0E82, 0E84, 0E87-0E88, 0E8A, 0E8D, 0E94-0E97, 0E99-0E9F, 0EA1-0EA3, 0EA5, 0EA7, 0EAA-0EAB, 0EAD-0EB9, 0EBB-0EBD, 0EC0-0EC4, 0EC6, 0EC8-0ECD, 0ED0-0ED9, 0EDC-0EDD, 10A0-10C5, 10D0-10F6, 10FB, 1100-1159, 115F-11A2, 11A8-11F9, 1E00-1E9A, 1EA0-1EF9, 1F00-1F15, 1F18-1F1D, 1F20-1F45, 1F48-1F4D, 1F50-1F57, 1F59, 1F5B, 1F5D, 1F5F-1F7D, 1F80-1FB4, 1FB6-1FC4, 1FC6-1FD3, 1FD6-1FDB, 1FDD-1FEF, 1FF2-1FF4, 1FF6-1FFE, 2000-202E, 2030-2046, 206A-2070, 2074-208E, 20A0-20AA, 20D0-20E1, 2100-2138, 2153-2182, 2190-21EA, 2200-22F1, 2300, 2302-237A, 2400-2424, 2440-244A, 2460-24EA, 2500-2595, 25A0-25EF, 2600-2613, 261A-266F, 2701-2704, 2706-2709, 270C-2727, 2729-274B, 274D, 274F-2752, 2756, 2758-275E, 2761-2767, 2776-2794, 2798-27AF, 27B1-27BE, 3000-3037, 303F, 3041-3094, 3099-309E, 30A1-30FE, 3105-312C, 3131-318E, 3190-319F, 3200-321C, 3220-3243, 3260-327B, 327F-32B0, 32C0-32CB, 32D0-32FE, 3300-3376, 337B-33DD, 33E0-33FE, 3400-9FA5, F900-FA2D, FB00-FB06, FB13-FB17, FB1E-FB36, FB38-FB3C, FB3E, FB40-FB41, FB43-FB44, FB46-FBB1, FBD3-FD3F, FD50-FD8F, FD92-FDC7, FDF0-FDFB, FE20-FE23, FE30-FE44, FE49-FE52, FE54-FE66, FE68-FE6B, FE70-FE72, FE74, FE76-FEFC, FEFF, FF01-FF5E, FF61-FFBE, FFC2-FFC7, FFCA-FFCF, FFD2-FFD7, FFDA-FFDC, FFE0-FFE6, FFE8-FFEE, FFFD.

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.11 public static boolean isLowerCase(char ch)

The result is true if and only if the character argument is a lowercase character.

A character is considered to be lowercase if and only if all of the following are true:

  • The character ch is not in the range \u2000 through \u2FFF.
  • The Unicode attribute table does not specify a mapping to lowercase for this character (the purpose of this requirement is to exclude titlecase characters).
  • At least one of the following is true:
    • The Unicode attribute table specifies a mapping to uppercase for this character.
    • The name for the character in the Unicode attribute table contains the words SMALL LETTER or the words SMALL LIGATURE.

It follows, then, that for Unicode 1.1.5 as corrected above, the lowercase Unicode characters are exactly those with codes in the following list, which contains both single codes and inclusive ranges: 0061-007A, 00DF-00F6, 00F8-00FF, 0101-0137 (odds only), 0138-0148 (evens only), 0149-0177 (odds only), 017A-017E (evens only), 017F-0180, 0183, 0185, 0188, 018C-018D, 0192, 0195, 0199-019B, 019E, 01A1-01A5 (odds only), 01A8, 01AB, 01AD, 01B0, 01B4, 01B6, 01B9-01BA, 01BD, 01C6, 01C9, 01CC-01DC (evens only), 01DD-01EF (odds only), 01F0, 01F3, 01F5, 01FB-0217 (odds only), 0250-0261, 0263-0269, 026B-0273, 0275, 0277-027F, 0282-028E, 0290-0293, 029A, 029D-029E, 02A0, 02A3-02A8, 0390, 03AC-03CE, 03D0-03D1, 03D5-03D6, 03E3-03EF (odds only), 03F0-03F1, 0430-044F, 0451-045C, 045E-045F, 0461-0481 (odds only), 0491-04BF (odds only), 04C2, 04C4, 04C8, 04CC, 04D1-04EB (odds only), 04EF-04F5 (odds only), 04F9, 0561-0587, 1E01-1E95 (odds only), 1E96-1E9A, 1EA1-1EF9 (odds only), 1F00-1F07, 1F10-1F15, 1F20-1F27, 1F30-1F37, 1F40-1F45, 1F50-1F57, 1F60-1F67, 1F70-1F7D, 1F80-1F87, 1F90-1F97, 1FA0-1FA7, 1FB0-1FB4, 1FB6-1FB7, 1FC2-1FC4, 1FC6-1FC7, 1FD0-1FD3, 1FD6-1FD7, 1FE0-1FE7, 1FF2-1FF4, 1FF6-1FF7, FB00-FB06, FB13-FB17, FF41-FF5A.

Of the first 128 Unicode characters, exactly 26 are considered to be lowercase:

abcdefghijklmnopqrstuvwxyz

[This specification for the method isLowerCase is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns false for all arguments larger than \u00FF.]

20.5.12 public static boolean isUpperCase(char ch)

The result is true if and only if the character argument is an uppercase character.

A character is considered to be uppercase if and only if all of the following are true:

  • The character ch is not in the range \u2000 through \u2FFF.
  • The Unicode attribute table does not specify a mapping to uppercase for this character (the purpose of this requirement is to exclude titlecase characters).
  • At least one of the following is true:
    • The Unicode attribute table specifies a mapping to lowercase for this character.
    • The name for the character in the Unicode attribute table contains the words CAPITAL LETTER or the words CAPITAL LIGATURE.

It follows, then, that for Unicode 1.1.5 as corrected above, the uppercase Unicode characters are exactly those with codes in the following list, which contains both single codes and inclusive ranges: 0041-005A, 00C0-00D6, 00D8-00DE, 0100-0136 (evens only), 0139-0147 (odds only), 014A-0178 (evens only), 0179-017D (odds only), 0181-0182, 0184, 0186, 0187, 0189-018B, 018E-0191, 0193-0194, 0196-0198, 019C-019D, 019F-01A0, 01A2, 01A4, 01A7, 01A9, 01AC, 01AE, 01AF, 01B1-01B3, 01B5, 01B7, 01B8, 01BC, 01C4, 01C7, 01CA, 01CD-01DB (odds only), 01DE-01EE (evens only), 01F1, 01F4, 01FA-0216 (evens only), 0386, 0388-038A, 038C, 038E, 038F, 0391-03A1, 03A3-03AB, 03E2-03EE (evens only), 0401-040C, 040E-042F, 0460-0480 (evens only), 0490-04BE (evens only), 04C1, 04C3, 04C7, 04CB, 04D0-04EA (evens only), 04EE-04F4 (evens only), 04F8, 0531-0556, 10A0-10C5, 1E00-1E94 (evens only), 1EA0-1EF8 (evens only), 1F08-1F0F, 1F18-1F1D, 1F28-1F2F, 1F38-1F3F, 1F48-1F4D, 1F59-1F5F (odds only), 1F68-1F6F, 1F88-1F8F, 1F98-1F9F, 1FA8-1FAF, 1FB8-1FBC, 1FC8-1FCC, 1FD8-1FDB, 1FE8-1FEC, 1FF8-1FFC, FF21-FF3A.

Of the first 128 Unicode characters, exactly 26 are considered to be uppercase:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

[This specification for the method isUpperCase is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns false for all arguments larger than \u00FF.]

20.5.13 public static boolean isTitleCase(char ch)

The result is true if and only if the character argument is a titlecase character.

The notion of "titlecase" was introduced into Unicode to handle a peculiar situation: there are single Unicode characters whose appearance in each case looks exactly like two ordinary Latin letters. For example, there is a single Unicode character `LJ' (\u01C7) that looks just like the characters `L' and `J' put together. There is a corresponding lowercase letter `lj' (\u01C9) as well. These characters are present in Unicode primarily to allow one-to-one translations from the Cyrillic alphabet, as used in Serbia, for example, to the Latin alphabet. Now suppose the word "LJUBINJE" (which has six characters, not eight, because two of them are the single Unicode characters `LJ' and `NJ', perhaps produced by one-to-one translation from the Cyrillic) is to be written as part of a book title, in capitals and lowercase. The strategy of making the first letter uppercase and the rest lowercase results in "LJubinje"-most unfortunate. The solution is that there must be a third form, called a titlecase form. The titlecase form of `LJ' is `Lj' (\u01C8) and the titlecase form of `NJ' is `Nj'. A word for a book title is then best rendered by converting the first letter to titlecase if possible, otherwise to uppercase; the remaining letters are then converted to lowercase.

A character is considered to be titlecase if and only if both of the following are true:

  • The character ch is not in the range \u2000 through \u2FFF.
  • The Unicode attribute table specifies a mapping to uppercase and a mapping to lowercase for this character.

There are exactly four Unicode 1.1.5 characters for which isTitleCase returns true:

\u01C5	    LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON
\u01C8	    LATIN CAPITAL LETTER L WITH SMALL LETTER J
\u01CB	    LATIN CAPITAL LETTER N WITH SMALL LETTER J
\u01F2	    LATIN CAPITAL LETTER D WITH SMALL LETTER Z

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.14 public static boolean isDigit(char ch)

The result is true if and only if the character argument is a digit.

A character is considered to be a digit if and only if both of the following are true:

  • The character ch is not in the range \u2000 through \u2FFF.
  • The name for the character in the Unicode attribute table contains the word DIGIT.

The digits are those characters with the following codes:

0030-0039	ISO-Latin-1 (and ASCII) digits ('0'-'9')
0660-0669	Arabic-Indic digits
06F0-06F9	Eastern Arabic-Indic digits
0966-096F	Devanagari digits
09E6-09EF	Bengali digits
0A66-0A6F	Gurmukhi digits
0AE6-0AEF	Gujarati digits
0B66-0B6F	Oriya digits
0BE7-0BEF	Tamil digits (there are only nine of these-no zero digit)
0C66-0C6F	Telugu digits
0CE6-0CEF	Kannada digits
0D66-0D6F	Malayalam digits
0E50-0E59	Thai digits
0ED0-0ED9	Lao digits
FF10-FF19	Fullwidth digits

Of the first 128 Unicode characters, exactly 10 are considered to be digits:

0123456789

[This specification for the method isDigit is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns false for all arguments larger than \u00FF.]

20.5.15 public static boolean isLetter(char ch)

The result is true if and only if the character argument is a letter.

A character is considered to be a letter if and only if it is a letter or digit (§20.5.16) but is not a digit (§20.5.14).

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.16 public static boolean isLetterOrDigit(char ch)

The result is true if and only if the character argument is a letter-or-digit.

A character is considered to be a letter-or-digit if and only if it is a defined Unicode character (§20.5.10) and its code lies in one of the following ranges:

0030-0039	ISO-Latin-1 (and ASCII) digits ('0'-'9')
0041-005A	ISO-Latin-1 (and ASCII) uppercase Latin letters ('A'-'Z')
0061-007A	ISO-Latin-1 (and ASCII) lowercase Latin letters ('a'-'z')
00C0-00D6	ISO-Latin-1 supplementary letters
00D8-00F6	ISO-Latin-1 supplementary letters
00F8-00FF	ISO-Latin-1 supplementary letters
0100-1FFF	Latin extended-A, Latin extended-B, IPA extensions,
spacing modifier letters, combining diacritical marks, basic
Greek, Greek symbols and Coptic, Cyrillic, Armenian,
Hebrew extended-A, Basic Hebrew, Hebrew extended-B,
Basic Arabic, Arabic extended, Devanagari, Bengali,
Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,
Malayalam, Thai, Lao, Basic Georgian, Georgian extended,
Hanguljamo, Latin extended additional, Greek extended
3040-9FFF	Hiragana, Katakana, Bopomofo, Hangul compatibility
Jamo, CJK miscellaneous, enclosed CJK characters and
months, CJK compatibility, Hangul, Hangul
supplementary-A, Hangul supplementary-B, CJK unified
ideographs
F900-FDFF	CJK compatibility ideographs, alphabetic presentation
forms, Arabic presentation forms-A
FE70-FEFE	Arabic presentation forms-B
FF10-FF19	Fullwidth digits
FF21-FF3A	Fullwidth Latin uppercase
FF41-FF5A	Fullwidth Latin lowercase
FF66-FFDC	Halfwidth Katakana and Hangul

It follows, then, that for Unicode 1.1.5 as corrected above, the Unicode letters and digits are exactly those with codes in the following list, which contains both single codes and inclusive ranges:

0030-0039, 0041-005A, 0061-007A, 00C0-00D6, 00D8-00F6, 00F8-01F5, 01FA-0217, 0250-02A8, 02B0-02DE, 02E0-02E9, 0300-0345, 0360-0361, 0374-0375, 037A, 037E, 0384-038A, 038C, 038E, 038F-03A1, 03A3-03CE, 03D0-03D6, 03DA-03E2, 03DA, 03DC, 03DE, 03E0, 03E2-03F3, 0401-040C, 040E-044F, 0451-045C, 045E-0486, 0490-04C4, 04C7-04C8, 04CB-04CC, 04D0-04EB, 04EE-04F5, 04F8-04F9, 0531-0556, 0559-055F, 0561-0587, 0589, 05B0-05B9, 05BB-05C3, 05D0-05EA, 05F0-05F4, 060C, 061B, 061F, 0621, 0622-063A, 0640-0652, 0660-066D, 0670-06B7, 06BA-06BE, 06C0-06CE, 06D0-06ED, 06F0-06F9, 0901-0903, 0905-0939, 093C-094D, 0950-0954, 0958-0970, 0981-0983, 0985-098C, 098F-0990, 0993-09A8, 09AA-09B0, 09B2, 09B6-09B9, 09BC, 09BE, 09BF-09C4, 09C7-09C8, 09CB-09CD, 09D7, 09DC-09DD, 09DF-09E3, 09E6-09FA, 0A02, 0A05-0A0A, 0A0F-0A10, 0A13-0A28, 0A2A-0A30, 0A32-0A33, 0A35-0A36, 0A38-0A39, 0A3C, 0A3E, 0A3F-0A42, 0A47-0A48, 0A4B-0A4D, 0A59-0A5C, 0A5E, 0A66-0A74, 0A81-0A83, 0A85-0A8B, 0A8D, 0A8F, 0A90-0A91, 0A93-0AA8, 0AAA-0AB0, 0AB2-0AB3, 0AB5-0AB9, 0ABC-0AC5, 0AC7-0AC9, 0ACB-0ACD, 0AD0, 0AE0, 0AE6-0AEF, 0B01-0B03, 0B05-0B0C, 0B0F-0B10, 0B13-0B28, 0B2A-0B30, 0B32-0B33, 0B36-0B39, 0B3C-0B43, 0B47-0B48, 0B4B-0B4D, 0B56-0B57, 0B5C-0B5D, 0B5F-0B61, 0B66-0B70, 0B82-0B83, 0B85-0B8A, 0B8E-0B90, 0B92-0B95, 0B99-0B9A, 0B9C, 0B9E, 0B9F, 0BA3-0BA4, 0BA8-0BAA, 0BAE-0BB5, 0BB7-0BB9, 0BBE-0BC2, 0BC6-0BC8, 0BCA-0BCD, 0BD7, 0BE7-0BF2, 0C01-0C03, 0C05-0C0C, 0C0E-0C10, 0C12-0C28, 0C2A-0C33, 0C35-0C39, 0C3E-0C44, 0C46-0C48, 0C4A-0C4D, 0C55-0C56, 0C60-0C61, 0C66-0C6F, 0C82-0C83, 0C85-0C8C, 0C8E-0C90, 0C92-0CA8, 0CAA-0CB3, 0CB5-0CB9, 0CBE-0CC4, 0CC6-0CC8, 0CCA-0CCD, 0CD5-0CD6, 0CDE, 0CE0, 0CE1, 0CE6-0CEF, 0D02-0D03, 0D05-0D0C, 0D0E-0D10, 0D12-0D28, 0D2A-0D39, 0D3E-0D43, 0D46-0D48, 0D4A-0D4D, 0D57, 0D60-0D61, 0D66-0D6F, 0E01-0E3A, 0E3F-0E5B, 0E81-0E82, 0E84, 0E87-0E88, 0E8A, 0E8D, 0E94-0E97, 0E99-0E9F, 0EA1-0EA3, 0EA5, 0EA7, 0EAA-0EAB, 0EAD-0EB9, 0EBB-0EBD, 0EC0-0EC4, 0EC6, 0EC8, 0EC9-0ECD, 0ED0-0ED9, 0EDC-0EDD, 10A0-10C5, 10D0-10F6, 10FB, 1100-1159, 115F-11A2, 11A8-11F9, 1E00-1E9A, 1EA0-1EF9, 1F00-1F15, 1F18-1F1D, 1F20-1F45, 1F48-1F4D, 1F50-1F57, 1F59, 1F5B, 1F5D, 1F5F-1F7D, 1F80-1FB4, 1FB6-1FC4, 1FC6-1FD3, 1FD6-1FDB, 1FDD-1FEF, 1FF2-1FF4, 1FF6-1FFE, 3041-3094, 3099-309E, 30A1-30FE, 3105-312C, 3131-318E, 3190-319F, 3200-321C, 3220-3243, 3260-327B, 327F-32B0, 32C0-32CB, 32D0-32FE, 3300-3376, 337B-33DD, 33E0-33FE, 3400-9FA5, F900-FA2D, FB00-FB06, FB13-FB17, FB1E-FB36, FB38-FB3C, FB3E, FB40, FB41, FB43, FB44, FB46, FB47-FBB1, FBD3-FD3F, FD50-FD8F, FD92-FDC7, FDF0-FDFB, FE70-FE72, FE74, FE76, FE77-FEFC, FF10-FF19, FF21-FF3A, FF41-FF5A, FF66-FFBE, FFC2-FFC7, FFCA-FFCF, FFD2-FFD7, FFDA-FFDC.

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.17 public static boolean isJavaLetter(char ch)

The result is true if and only if the character argument is a character that can begin a Java identifier.

A character is considered to be a Java letter if and only if it is a letter (§20.5.15) or is the dollar sign character '$' (\u0024) or the underscore ("low line") character '_' (\u005F).

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.18 public static boolean isJavaLetterOrDigit(char ch)

The result is true if and only if the character argument is a character that can occur in a Java identifier after the first character.

A character is considered to be a Java letter-or-digit if and only if it is a letter-or-digit (§20.5.16) or is the dollar sign character '$' (\u0024) or the underscore ("low line") character '_' (\u005F).

[This method is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5.]

20.5.19 public static boolean isSpace(char ch)

The result is true if the argument ch is one of the following characters:

'\t'		\u0009			HT		HORIZONTAL TABULATION
'\n'		\u000A			LF		LINE FEED (also known as NEW LINE)
'\f'		\u000C			FF		FORM FEED
'\r'		\u000D			CR		CARRIAGE RETURN
' '		\u0020			SP		SPACE

Otherwise, the result is false.

20.5.20 public static char toLowerCase(char ch)

If the character ch has a lowercase equivalent specified in the Unicode attribute table, then that lowercase equivalent character is returned. Otherwise, the argument ch is returned.

The lowercase equivalents specified in the Unicode attribute table, for Unicode 1.1.5 as corrected above, are as follows, where character codes to the right of arrows are the lowercase equivalents of character codes to the left of arrows: 0041-005A [image] 0061-007A, 00C0-00D6 [image] 00E0-00F6, 00D8-00DE [image] 00F8-00FE, 0100-012E [image] 0101-012F (evens to odds), 0132-0136 [image] 0133-0137 (evens to odds), 0139-0147 [image] 013A-0148 (odds to evens), 014A-0176 [image] 014B-0177 (evens to odds), 0178 [image] 00FF, 0179-017D [image] 017A-017E (odds to evens), 0181 [image] 0253, 0182 [image] 0183, 0184 [image] 0185, 0186 [image] 0254, 0187 [image] 0188, 018A [image] 0257, 018B [image] 018C, 018E [image] 0258, 018F [image] 0259, 0190 [image] 025B, 0191 [image] 0192, 0193 [image] 0260, 0194 [image] 0263, 0196 [image] 0269, 0197 [image] 0268, 0198 [image] 0199, 019C [image] 026F, 019D [image] 0272, 01A0-01A4 [image] 01A1-01A5 (evens to odds), 01A7 [image] 01A8, 01A9 [image] 0283, 01AC [image] 01AD, 01AE [image] 0288, 01AF [image] 01B0, 01B1 [image] 028A, 01B2 [image] 028B, 01B3 [image] 01B4, 01B5 [image] 01B6, 01B7 [image] 0292, 01B8 [image] 01B9, 01BC [image] 01BD, 01C4 [image] 01C6, 01C5 [image] 01C6, 01C7 [image] 01C9, 01C8 [image] 01C9, 01CA [image] 01CC, 01CB-01DB [image] 01CC-01DC (odds to evens), 01DE-01EE [image] 01DF-01EF (evens to odds), 01F1 [image] 01F3, 01F2 [image] 01F3, 01F4 [image] 01F5, 01FA-0216 [image] 01FB-0217 (evens to odds), 0386 [image] 03AC, 0388-038A [image] 03AD-03AF, 038C [image] 03CC, 038E [image] 03CD, 038F [image] 03CE, 0391-03A1 [image] 03B1-03C1, 03A3-03AB [image] 03C3-03CB, 03E2-03EE [image] 03E3-03EF (evens to odds), 0401-040C [image] 0451-045C, 040E [image] 045E, 040F [image] 045F, 0410-042F [image] 0430-044F, 0460-0480 [image] 0461-0481 (evens to odds), 0490-04BE [image] 0491-04BF (evens to odds), 04C1 [image] 04C2, 04C3 [image] 04C4, 04C7 [image] 04C8, 04CB [image] 04CC, 04D0-04EA [image] 04D1-04EB (evens to odds), 04EE-04F4 [image] 04EF-04F5 (evens to odds), 04F8 [image] 04F9, 0531-0556 [image] 0561-0586, 10A0-10C5 [image] 10D0-10F5, 1E00-1E94 [image] 1E01-1E95 (evens to odds), 1EA0-1EF8 [image] 1EA1-1EF9 (evens to odds), 1F08-1F0F [image] 1F00-1F07, 1F18-1F1D [image] 1F10-1F15, 1F28-1F2F [image] 1F20-1F27, 1F38-1F3F [image] 1F30-1F37, 1F48-1F4D [image] 1F40-1F45, 1F59 [image] 1F51, 1F5B [image] 1F53, 1F5D [image] 1F55, 1F5F [image] 1F57, 1F68-1F6F [image] 1F60-1F67, 1F88-1F8F [image] 1F80-1F87, 1F98-1F9F [image] 1F90-1F97, 1FA8-1FAF [image] 1FA0-1FA7, 1FB8 [image] 1FB0, 1FB9 [image] 1FB1, 1FBA [image] 1F70, 1FBB [image] 1F71, 1FBC [image] 1FB3, 1FC8-1FCB [image] 1F72-1F75, 1FCC [image] 1FC3, 1FD8 [image] 1FD0, 1FD9 [image] 1FD1, 1FDA [image] 1F76, 1FDB [image] 1F77, 1FE8 [image] 1FE0, 1FE9 [image] 1FE1, 1FEA [image] 1F7A, 1FEB [image] 1F7B, 1FEC [image] 1FE5, 1FF8 [image] 1F78, 1FF9 [image] 1F79, 1FFA [image] 1F7C, 1FFB [image] 1F7D, 1FFC [image] 1FF3, 2160-216F [image] 2170-217F, 24B6-24CF [image] 24D0-24E9, FF21-FF3A [image] FF41-FF5A.

Note that the method isLowerCase (§20.5.11) will not necessarily return true when given the result of the toLowerCase method.

[This specification for the method toLowerCase is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns its argument for all arguments larger than \u00FF.]

20.5.21 public static char toUpperCase(char ch)

If the character ch has an uppercase equivalent specified in the Unicode attribute table, then that uppercase equivalent character is returned. Otherwise, the argument ch is returned.

The uppercase equivalents specified in the Unicode attribute table for Unicode 1.1.5 as corrected above, are as follows, where character codes to the right of arrows are the uppercase equivalents of character codes to the left of arrows:

0061-007A [image] 0041-005A, 00E0-00F6 [image] 00C0-00D6, 00F8-00FE [image] 00D8-00DE, 00FF [image] 0178, 0101-012F [image] 0100-012E (odds to evens), 0133-0137 [image] 0132-0136 (odds to evens), 013A-0148 [image] 0139-0147 (evens to odds), 014B-0177 [image] 014A-0176 (odds to evens), 017A-017E [image] 0179-017D (evens to odds), 017F [image] 0053, 0183-0185 [image] 0182-0184 (odds to evens), 0188 [image] 0187, 018C [image] 018B, 0192 [image] 0191, 0199 [image] 0198, 01A1-01A5 [image] 01A0-01A4 (odds to evens), 01A8 [image] 01A7, 01AD [image] 01AC, 01B0 [image] 01AF, 01B4 [image] 01B3, 01B6 [image] 01B5, 01B9 [image] 01B8, 01BD [image] 01BC, 01C5 [image] 01C4, 01C6 [image] 01C4, 01C8 [image] 01C7, 01C9 [image] 01C7, 01CB [image] 01CA, 01CC [image] 01CA, 01CE-01DC [image] 01CD-01DB (evens to odds), 01DF-01EF [image] 01DE-01EE (odds to evens), 01F2 [image] 01F1, 01F3 [image] 01F1, 01F5 [image] 01F4, 01FB-0217 [image] 01FA-0216 (odds to evens), 0253 [image] 0181, 0254 [image] 0186, 0257 [image] 018A, 0258 [image] 018E, 0259 [image] 018F, 025B [image] 0190, 0260 [image] 0193, 0263 [image] 0194, 0268 [image] 0197, 0269 [image] 0196, 026F [image] 019C, 0272 [image] 019D, 0283 [image] 01A9, 0288 [image] 01AE, 028A [image] 01B1, 028B [image] 01B2, 0292 [image] 01B7, 03AC [image] 0386, 03AD-03AF [image] 0388-038A, 03B1-03C1 [image] 0391-03A1, 03C2 [image] 03A3, 03C3-03CB [image] 03A3-03AB, 03CC [image] 038C, 03CD [image] 038E, 03CE [image] 038F, 03D0 [image] 0392, 03D1 [image] 0398, 03D5 [image] 03A6, 03D6 [image] 03A0, 03E3-03EF [image] 03E2-03EE (odds to evens), 03F0 [image] 039A, 03F1 [image] 03A1, 0430-044F [image] 0410-042F, 0451-045C [image] 0401-040C, 045E [image] 040E, 045F [image] 040F, 0461-0481 [image] 0460-0480 (odds to evens), 0491-04BF [image] 0490-04BE (odds to evens), 04C2 [image] 04C1, 04C4 [image] 04C3, 04C8 [image] 04C7, 04CC [image] 04CB, 04D1-04EB [image] 04D0-04EA (odds to evens), 04EF-04F5 [image] 04EE-04F4 (odds to evens), 04F9 [image] 04F8, 0561-0586 [image] 0531-0556, 1E01-1E95 [image] 1E00-1E94 (odds to evens), 1EA1-1EF9 [image] 1EA0-1EF8 (odds to evens), 1F00-1F07 [image] 1F08-1F0F, 1F10-1F15 [image] 1F18-1F1D, 1F20-1F27 [image] 1F28-1F2F, 1F30-1F37 [image] 1F38-1F3F, 1F40-1F45 1F48-1F4D, 1F51 1F59, 1F53 1F5B, 1F55 1F5D, 1F57 1F5F, 1F60-1F67 1F68-1F6F, 1F70 1FBA, 1F71 1FBB, 1F72-1F75 1FC8-1FCB, 1F76 1FDA, 1F77 1FDB, 1F78 1FF8, 1F79 1FF9, 1F7A 1FEA, 1F7B 1FEB, 1F7C 1FFA, 1F7D 1FFB, 1F80-1F87 1F88-1F8F, 1F90-1F97 1F98-1F9F, 1FA0-1FA7 1FA8-1FAF, 1FB0 1FB8, 1FB1 1FB9, 1FB3 1FBC, 1FC3 1FCC, 1FD0 1FD8, 1FD1 1FD9, 1FE0 1FE8, 1FE1 1FE9, 1FE5 1FEC, 1FF3 1FFC, 2170-217F 2160-216F, 24D0-24E9 24B6-24CF, FF41-FF5A FF21-FF3A.

Note that the method isUpperCase (§20.5.12) will not necessarily return true when given the result of the toUpperCase method.

[This specification for the method toUpperCase is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns its argument for all arguments larger than \u00FE. Note that although \u00FF is a lowercase character, its uppercase equivalent is \u0178; toUpperCase in versions of Java prior to version 1.1 simply do not consistently handle or use Unicode character codes above \u00FF.]

20.5.22 public static char toTitleCase(char ch)

If the character ch has a titlecase equivalent specified in the Unicode attribute table, then that titlecase equivalent character is returned; otherwise, the argument ch is returned.

Note that the method isTitleCase (§20.5.13) will not necessarily return true when given the result of the toTitleCase method. The Unicode attribute table always has the titlecase attribute equal to the uppercase attribute for characters that have uppercase equivalents but no separate titlecase form.

Example: Character.toTitleCase('a') returns 'A'

Example: Character.toTitleCase('Q') returns 'Q'

Example: Character.toTitleCase('lj') returns 'Lj' where 'lj' is the Unicode character \u01C9 and 'Lj' is its titlecase equivalent character \u01C8.

[This method is scheduled for introduction in Java version 1.1.]

20.5.23 public static int digit(char ch, int radix)

Returns the numeric value of the character ch considered as a digit in the specified radix. If the value of radix is not a valid radix, or the character ch is not a valid digit in the specified radix, then -1 is returned.

A radix is valid if and only if its value is not less than Character.MIN_RADIX (§20.5.3) and not greater than Character.MAX_RADIX (§20.5.4).

A character is a valid digit if and only if one of the following is true:

  • The method isDigit returns true for the character, and the decimal digit value of the character, as specified in the Unicode attribute table, is less than the specified radix. In this case, the decimal digit value is returned.
  • The character is one of the uppercase Latin letters 'A'-'Z' (\u0041-\u005A) and its code is less than radix+'A'-10. In this case ch-'A'+10 is returned.
  • The character is one of the lowercase Latin letters 'a'-'z' (\u0061-\u007A) and its code is less than radix+'a'-10. In this case ch-'a'+10 is returned.

[This specification for the method digit is scheduled for introduction in Java version 1.1, either as defined here, or updated for Unicode 2.0; see §20.5. In previous versions of Java, this method returns -1 for all character codes larger than \u00FF.]

20.5.24 public static char forDigit(int digit, int radix)

Returns a character that represents the given digit in the specified radix. If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character '\u0000' is returned.

A radix is valid if and only if its value is not less than Character.MIN_RADIX (§20.5.3) and not greater than Character.MAX_RADIX (§20.5.4).

A digit is valid if and only if it is nonnegative and less than the radix.

If the digit is less than 10, then the character value '0'+digit is returned; otherwise, 'a'+digit-10 is returned. Thus, the digits produced by forDigit, in increasing order of value, are the ASCII characters:

0123456789abcdefghijklmnopqrstuvwxyz

(these are '\u0030' through '\u0039' and '\u0061' through '\u007a'). If uppercase letters are desired, the toUpperCase method may be called on the result:

Character.toUpperCase(Character.forDigit(digit, radix))


20.6 The Class java.lang.Number

The abstract class Number has subclasses Integer, Long, Float, and Double which wrap primitive types, defining abstract methods to convert the represented numeric value to int, long, float, and double.

public abstract class Number {
    public abstract int intValue();
    public abstract long longValue();
    public abstract float floatValue();
    public abstract double doubleValue();
}

20.6.1 public abstract int intValue()

The general contract of the intValue method is that it returns the numeric value represented by this Number object after converting it to type int.

Overridden by Integer (§20.7.8), Long (§20.8.8), Float (§20.9.12), and Double (§20.10.11).

20.6.2 public abstract long longValue()

The general contract of the longValue method is that it returns the numeric value represented by this Number object after converting it to type long.

Overridden by Integer (§20.7.9), Long (§20.8.9), Float (§20.9.13), and Double (§20.10.12).

20.6.3 public abstract float floatValue()

The general contract of the floatValue method is that it returns the numeric value represented by this Number object after converting it to type float.

Overridden by Integer (§20.7.10), Long (§20.8.10), Float (§20.9.14), and Double (§20.10.13).

20.6.4 public abstract double doubleValue()

The general contract of the doubleValue method is that it returns the numeric value represented by this Number object after converting it to type double.

Overridden by Integer (§20.7.11), Long (§20.8.11), Float (§20.9.15), and Double (§20.10.14).


20.7 The Class java.lang.Integer

public final class Integer extends Number {
    public static final int MIN_VALUE = 0x80000000;
    public static final int MAX_VALUE = 0x7fffffff;
    public Integer(int value);
    public Integer(String s)

        throws NumberFormatException;
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public int intValue();
    public long longValue();
    public float floatValue();
    public double doubleValue();
    public static String toString(int i);
    public static String toString(int i, int radix);
    public static String toHexString(long i);
    public static String toOctalString(long i);
    public static String toBinaryString(long i);
    public static int parseInt(String s)

        throws NumberFormatException;
    public static int parseInt(String s, int radix)

        throws NumberFormatException;
    public static Integer valueOf(String s)

        throws NumberFormatException;
    public static Integer valueOf(String s, int radix)

        throws NumberFormatException;
    public static Integer getInteger(String nm);
    public static Integer getInteger(String nm, int val);
    public static Integer getInteger(String nm, Integer val);
}

20.7.1 public static final int MIN_VALUE = 0x80000000;

The constant value of this field is -2147483648, the lowest value of type int.

20.7.2 public static final int MAX_VALUE = 0x7fffffff;

The constant value of this field is 2147483647, the highest value of type int.

20.7.3 public Integer(int value)

This constructor initializes a newly created Integer object so that it represents the primitive value that is the argument.

20.7.4 public Integer(String s) throws NumberFormatException

This constructor initializes a newly created Integer object so that it represents the integer represented by the string in decimal form. The string is converted to an int in exactly the manner used by the parseInt method (§20.7.18) for radix 10.

20.7.5 public String toString()

The integer value represented by this Integer object is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to the toString method that takes one argument (§20.7.12).

Overrides the toString method of Object (§20.1.2).

20.7.6 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is an Integer object that represents the same int value as this Integer object.

Overrides the equals method of Object (§20.1.3).

20.7.7 public int hashCode()

The result is the primitive int value represented by this Integer object.

Overrides the hashCode method of Object (§20.1.4).

20.7.8 public int intValue()

The int value represented by this Integer object is returned.

Overrides the intValue method of Number (§20.6.1).

20.7.9 public long longValue()

The int value represented by this Integer object is converted (§5.1.2) to type long and the result of the conversion is returned.

Overrides the longValue method of Number (§20.6.2).

20.7.10 public float floatValue()

The int value represented by this Integer object is converted (§5.1.2) to type float and the result of the conversion is returned.

Overrides the floatValue method of Number (§20.6.3).

20.7.11 public double doubleValue()

The int value represented by this Integer object is converted (§5.1.2) to type double and the result of the conversion is returned.

Overrides the doubleValue method of Number (§20.6.4).

20.7.12 public static String toString(int i)

The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and the radix 10 were given as arguments to the toString method that takes two arguments (§20.7.13).

20.7.13 public static String toString(int i, int radix)

The first argument is converted to a signed representation in the radix specified by the second argument; this representation is returned as a string.

If the radix is smaller than Character.MIN_RADIX (§20.5.3) or larger than Character.MAX_RADIX (§20.5.4), then the value 10 is used instead.

If the first argument is negative, the first character of the result will be the character '-' ('\u002d'). If the first argument is not negative, no sign character appears in the result.

The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the magnitude will not be the zero character.The following ASCII characters are used as digits:

0123456789abcdefghijklmnopqrstuvwxyz

These are '\u0030' through '\u0039' and '\u0061' through '\u007a'. If the radix is N, then the first N of these characters are used as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are 0123456789abcdef. If uppercase letters are desired, the toUpperCase method (§20.12.36) of class String may be called on the result:

Integer.toString(n, 16).toUpperCase()

20.7.14 public static String toHexString(int i)

The argument is converted to an unsigned representation in hexadecimal radix (base 16); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:

0123456789abcdef

These are the characters '\u0030' through '\u0039' and '\u0061' through '\u0066'. If uppercase letters are desired, the toUpperCase method (§20.12.36) of class String may be called on the result:

Long.toHexString(n).toUpperCase()

20.7.15 public static String toOctalString(int i)

The argument is converted to an unsigned representation in octal radix (base 8); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The octal digits are:

01234567

These are the characters '\u0030' through '\u0037'.

20.7.16 public static String toBinaryString(int i)

The argument is converted to an unsigned representation in binary radix (base 2); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.

20.7.17 public static int parseInt(String s)
throws NumberFormatException

The argument is interpreted as representing a signed decimal integer. The components of the string must all be decimal digits, except that the first character may be '-' ('\u002d') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt method that takes two arguments (§20.7.18).

20.7.18 public static int parseInt(String s, int radix)
throws NumberFormatException

The first argument is interpreted as representing a signed integer in the radix specified by the second argument. The components of the string must all be digits of the specified radix (as determined by whether Character.digit (§20.5.23) returns a nonnegative value), except that the first character may be '-' ('\u002d') to indicate a negative value. The resulting integer value is returned.

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX (§20.5.3) or larger than Character.MAX_RADIX (§20.5.4).
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002d') provided that the string is longer than length 1.
  • The integer value represented by the string is not a value of type int.

Examples:

parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10) throws a NumberFormatException
parseInt("99", 8) throws a NumberFormatException
parseInt("Kona", 10) throws a NumberFormatException
parseInt("Kona", 27) returns 411787

20.7.19 public static Integer valueOf(String s)
throws NumberFormatException

The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt method that takes one argument (§20.7.17). The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of:

new Integer(Integer.parseInt(s))

20.7.20 public static Integer valueOf(String s, int radix)
throws NumberFormatException

The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt method that takes two arguments (§20.7.18). The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of:

new Integer(Integer.parseInt(s, radix))

20.7.21 public static Integer getInteger(String nm)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. If there is no property of the specified name, or if the property does not have the correct numeric format, then null is returned.

In other words, this method returns an Integer object equal to the value of:

getInteger(nm, null)

20.7.22 public static Integer getInteger(String nm, int val)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. If the property does not have the correct numeric format, then an Integer object that represents the value of the second argument is returned.

In other words, this method returns an Integer object equal to the value of:

getInteger(nm, new Integer(val))

but in practice it may be implemented in a manner such as:

Integer result = getInteger(nm, null);
return (result == null) ? new Integer(val) : result;

to avoid the unnecessary allocation of an Integer object when the default value is not needed.

20.7.23 public static Integer getInteger(String nm, Integer val)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned.

  • If the property value begins with the two ASCII characters 0x or the ASCII character #, not followed by a minus sign, then the rest of it is parsed as a hexadecimal integer exactly as for the method Integer.valueOf (§20.7.20) with radix 16.
  • If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as for the method Integer.valueOf (§20.7.20) with radix 8.
  • Otherwise, the property value is parsed as a decimal integer exactly as for the method Integer.valueOf (§20.7.20) with radix 10.

The second argument serves as a default value. If there is no property of the specified name, or if the property does not have the correct numeric format, then the second argument is returned.


20.8 The Class java.lang.Long

public final class Long extends Number {
    public static final long MIN_VALUE = 0x8000000000000000L;
    public static final long MAX_VALUE = 0x7fffffffffffffffL;
    public Long(long value);
    public Long(String s)

        throws NumberFormatException;
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public int intValue();
    public long longValue();
    public float floatValue();
    public double doubleValue();
    public static String toString(long i);
    public static String toString(long i, int radix);
    public static String toHexString(long i);
    public static String toOctalString(long i);
    public static String toBinaryString(long i);
    public static long parseLong(String s)

        throws NumberFormatException;
    public static long parseLong(String s, int radix)

        throws NumberFormatException;
    public static Long valueOf(String s)

        throws NumberFormatException;
    public static Long valueOf(String s, int radix)

        throws NumberFormatException;
    public static Long getLong(String nm);
    public static Long getLong(String nm, long val);
    public static Long getLong(String nm, Long val);
}

20.8.1 public static final long MIN_VALUE = 0x8000000000000000L;

The constant value of this field is the lowest value of type long.

20.8.2 public static final long MAX_VALUE = 0x7fffffffffffffffL;

The constant value of this field is the highest value of type long.

20.8.3 public Long(long value)

This constructor initializes a newly created Long object so that it represents the primitive value that is the argument.

20.8.4 public Long(String s) throws NumberFormatException

This constructor initializes a newly created Long object so that it represents the integer represented by the string in decimal form. The string is converted to a long value in exactly the manner used by the parseLong method (§20.8.17) for radix 10.

20.8.5 public String toString()

The long integer value represented by this Long object is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to the toString method that takes one argument (§20.7.12).

Overrides the toString method of Object (§20.1.2).

20.8.6 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Long object that represents the same long value as this Long object.

Overrides the equals method of Object (§20.1.3).

20.8.7 public int hashCode()

The result is the exclusive OR of the two halves of the primitive long value represented by this Long object. That is, the hashcode is the value of the expression:

(int)(this.longValue()^(this.longValue()>>>32))

Overrides the hashCode method of Object (§20.1.4).

20.8.8 public int intValue()

The long value represented by this Long object is converted (§5.1.3) to type int and the result of the conversion is returned.

Overrides the intValue method of Number (§20.6.1).

20.8.9 public long longValue()

The long value represented by this Long object is returned.

Overrides the longValue method of Number (§20.6.2).

20.8.10 public float floatValue()

The long value represented by this Long object is converted (§5.1.2) to type float and the result of the conversion is returned.

Overrides the floatValue method of Number (§20.6.3).

20.8.11 public double doubleValue()

The long value represented by this Long object is converted (§5.1.2) to type double and the result of the conversion is returned.

Overrides the doubleValue method of Number (§20.6.4).

20.8.12 public static String toString(long i)

The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and the radix 10 were given as arguments to the toString method that takes two arguments (§20.8.13).

20.8.13 public static String toString(long i, int radix)

The first argument is converted to a signed representation in the radix specified by the second argument; this representation is returned as a string.

If the radix is smaller than Character.MIN_RADIX (§20.5.3) or larger than Character.MAX_RADIX (§20.5.4), then the value 10 is used instead.

If the first argument is negative, the first character of the result will be the character '-' ('\u002d'). If the first argument is not negative, no sign character appears in the result.

The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:

0123456789abcdefghijklmnopqrstuvwxyz

These are '\u0030' through '\u0039' and '\u0061' through '\u007a'. If the radix is N, then the first N of these characters are used as radix-N digits in the order shown. Thus, the digits for hexadecimal (radix 16) are 0123456789abcdef. If uppercase letters are desired, the toUpperCase method (§20.12.36) of class String may be called on the result:

Long.toString(n, 16).toUpperCase()

20.8.14 public static String toHexString(long i)

The argument is converted to an unsigned representation in hexadecimal radix (base 16); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:

0123456789abcdef

These are the characters '\u0030' through '\u0039' and '\u0061' through '\u0066'. If uppercase letters are desired, the toUpperCase method (§20.12.36) of class String may be called on the result:

Long.toHexString(n).toUpperCase()

20.8.15 public static String toOctalString(long i)

The argument is converted to an unsigned representation in octal radix (base 8); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as octal digits:

01234567

These are the characters '\u0030' through '\u0037'.

20.8.16 public static String toBinaryString(long i)

The argument is converted to an unsigned representation in binary radix (base 2); this representation is returned as a string.

The result represents the unsigned magnitude of the argument. This equals the argument plus [image] if the argument is negative; otherwise, it equals the argument.

If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.

20.8.17 public static long parseLong(String s)
throws NumberFormatException

The argument is interpreted as representing a signed decimal integer. The components of the string must all be decimal digits, except that the first character may be '-' ('\u002d') to indicate a negative value. The resulting long value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseLong method that takes two arguments (§20.8.18).

Note that neither L nor l is permitted to appear at the end of the string as a type indicator, as would be permitted in Java source code (§3.10.1).

20.8.18 public static long parseLong(String s, int radix)
throws NumberFormatException

The first argument is interpreted as representing a signed integer in the radix specified by the second argument. The components of the string must all be digits of the specified radix (as determined by whether Character.digit (§20.5.23) returns a nonnegative value), except that the first character may be '-' ('\u002d') to indicate a negative value. The resulting long value is returned.

Note that neither L nor l is permitted to appear at the end of the string as a type indicator, as would be permitted in Java source code (§3.10.1)-except that either L or l may appear as a digit for a radix greater than 22.

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX (§20.5.3) or larger than Character.MAX_RADIX (§20.5.4).
  • The first character of the string is not a digit of the specified radix and is not a minus sign '-' ('\u002d').
  • The first character of the string is a minus sign and the string is of length 1.
  • Any character of the string after the first is not a digit of the specified radix.
  • The integer value represented by the string cannot be represented as a value of type long.

Examples:

parseLong("0", 10) returns 0L
parseLong("473", 10) returns 473L
parseLong("-0", 10) returns 0L
parseLong("-FF", 16) returns -255L
parseLong("1100110", 2) returns 102L
parseLong("99", 8) throws a NumberFormatException
parseLong("Hazelnut", 10) throws a NumberFormatException
parseLong("Hazelnut", 36) returns 1356099454469L

20.8.19 public static Long valueOf(String s)
throws NumberFormatException

The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseLong method that takes one argument (§20.8.17). The result is a Long object that represents the integer value specified by the string.

In other words, this method returns a Long object equal to the value of:

new Long(Long.parseLong(s))

20.8.20 public static Long valueOf(String s, int radix)
throws NumberFormatException

The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseLong method that takes two arguments (§20.8.18). The result is a Long object that represents the integer value specified by the string.

In other words, this method returns a Long object equal to the value of:

new Long(Long.parseLong(s, radix))

20.8.21 public static Long getLong(String nm)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and a Long object representing this value is returned. If there is no property of the specified name, or if the property does not have the correct numeric format, then null is returned.

In other words, this method returns a Long object equal to the value of:

getLong(nm, null)

20.8.22 public static Long getLong(String nm, long val)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and a Long object representing this value is returned. If there is no property of the specified name, or if the property does not have the correct numeric format, then a Long object that represents the value of the second argument is returned.

In other words, this method returns a Long object equal to the value of:

getLong(nm, new Long(val))

but in practice it may be implemented in a manner such as:

Long result = getLong(nm, null);
return (result == null) ? new Long(val) : result;

to avoid the unnecessary allocation of a Long object when the default value is not needed.

20.8.23 public static Long getLong(String nm, Long val)

The first argument is treated as the name of a system property to be obtained as if by the method System.getProperty (§20.18.9). The string value of this property is then interpreted as an integer value and a Long object representing this value is returned.

  • If the property value begins with the two ASCII characters 0x or the ASCII character #, not followed by a minus sign, then the rest of it is parsed as a hexadecimal integer exactly as for the method Long.valueOf (§20.7.20) with radix 16.
  • If the property value begins with the character 0 followed by another character, it is parsed as an octal integer exactly as for the method Long.valueOf (§20.7.20) with radix 8.
  • Otherwise the property value is parsed as a decimal integer exactly as for the method Long.valueOf (§20.7.20) with radix 10.

Note that, in every case, neither L nor l is permitted to appear at the end of the property value as a type indicator, as would be permitted in Java source code (§3.10.1).

The second argument serves as a default value. If there is no property of the specified name, or if the property does not have the correct numeric format, then the second argument is returned.


20.9 The Class java.lang.Float

public final class Float extends Number {
    public static final float MIN_VALUE = 1.4e-45f;
    public static final float MAX_VALUE = 3.4028235e+38f;
    public static final float NEGATIVE_INFINITY = -1.0f/0.0f;
    public static final float POSITIVE_INFINITY = 1.0f/0.0f;
    public static final float NaN = 0.0f/0.0f;
    public Float(float value);
    public Float(double value);
    public Float(String s)
        throws NumberFormatException;
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public int intValue();
    public long longValue();
    public float floatValue();
    public double doubleValue();
    public static String toString(float f);
    public static Float valueOf(String s)
        throws NullPointerException, NumberFormatException;
    public boolean isNaN();
    public static boolean isNaN(float v);
    public boolean isInfinite();
    public static boolean isInfinite(float v);
    public static int floatToIntBits(float value);
    public static float intBitsToFloat(int bits);
}

20.9.1 public static final float MIN_VALUE = 1.4e-45f;

The constant value of this field is the smallest positive nonzero value of type float. It is equal to the value returned by Float.intBitsToFloat(0x1).

20.9.2 public static final float MAX_VALUE = 3.4028235e+38f;

The constant value of this field is the largest positive finite value of type float. It is equal to the value returned by Float.intBitsToFloat(0x7f7fffff).

20.9.3 public static final float NEGATIVE_INFINITY =
-1.0f/0.0f;

The constant value of this field is the negative infinity of type float. It is equal to the value returned by Float.intBitsToFloat(0xff800000).

20.9.4 public static final float POSITIVE_INFINITY =
1.0f/0.0f;

The constant value of this field is the positive infinity of type float. It is equal to the value returned by Float.intBitsToFloat(0x7f800000).

20.9.5 public static final float NaN = 0.0f/0.0f;

The constant value of this field is the Not-a-Number value of type float. It is equal to the value returned by Float.intBitsToFloat(0x7fc00000).

20.9.6 public Float(float value)

This constructor initializes a newly created Float object so that it represents the primitive value that is the argument.

20.9.7 public Float(double value)

This constructor initializes a newly created Float object so that it represents the result of narrowing (§5.1.3) the argument from type double to type float.

20.9.8 public Float(String s) throws NumberFormatException

This constructor initializes a newly created Float object so that it represents the floating-point value of type float represented by the string. The string is converted to a float value in exactly the manner used by the valueOf method (§20.9.17).

20.9.9 public String toString()

The primitive float value represented by this Float object is converted to a string exactly as if by the method toString of one argument (§20.9.16).

Overrides the toString method of Object (§20.1.2).

20.9.10 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Float object that represents the same float value as this Float object. For this purpose, two float values are considered to be the same if and only if the method floatToIntBits (§20.9.22) returns the same int value when applied to each. Note that even though the == operator returns false if both operands are NaN, this equals method will return true if this Float object and the argument are both Float objects that represent NaN. On the other hand, even though the == operator returns true if one operand is positive zero and the other is negative zero, this equals method will return false if this Float object and the argument represent zeroes of different sign. This definition allows hashtables to operate properly.

Overrides the equals method of Object (§20.1.3).

20.9.11 public int hashCode()

The result is the integer bit representation, exactly as produced by the method floatToIntBits (§20.9.22), of the primitive float value represented by this Float object.

Overrides the hashCode method of Object (§20.1.4).

20.9.12 public int intValue()

The float value represented by this Float object is converted (§5.1.3) to type int and the result of the conversion is returned.

Overrides the intValue method of Number (§20.6.1).

20.9.13 public long longValue()

The float value represented by this Float object is converted (§5.1.3) to type long and the result of the conversion is returned.

Overrides the longValue method of Number (§20.6.2).

20.9.14 public float floatValue()

The float value represented by this Float object is returned.

Overrides the floatValue method of Number (§20.6.3).

20.9.15 public double doubleValue()

The float value represented by this Float object is converted (§5.1.2) to type double and the result of the conversion is returned.

Overrides the doubleValue method of Number (§20.6.4).

20.9.16 public static String toString(float f)

The argument is converted to a readable string format as follows. All characters and characters in strings mentioned below are ASCII characters.

  • If the argument is NaN, the result is the string "NaN".
  • Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('\u002d'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
    • If m is infinity, it is represented by the characters "Infinity"; thus, positive infinity produces the result "Infinity" and negative infinity produces the result "-Infinity".
    • If m is zero, it is represented by the characters "0.0"; thus, negative zero produces the result "-0.0" and positive zero produces the result "0.0".
    • If m is greater than or equal to [image] but less than [image], then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' (\u002E), followed by one or more decimal digits representing the fractional part of m.
    • If m is less than [image] or not less than [image], then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that [image]; then let a be the mathematically exact quotient of m and [image] so that [image]. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (\u002E), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (\u0045), followed by a representation of n as a decimal integer, as produced by the method Integer.toString of one argument (§20.7.12).

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument f. Then f must be the float value nearest to x; or, if two float values are equally close to x, then f must be one of them and the least significant bit of the significand of f must be 0.

[This specification for the method toString is scheduled for introduction in Java version 1.1. In previous versions of Java, this method produces Inf instead of Infinity for infinite values. Also, it renders finite values in the same form as the %g format of the printf function in the C programming language, which can lose precision because it produces at most six digits after the decimal point.]

20.9.17 public static Float valueOf(String s)
throws NullPointerException, NumberFormatException

The string s is interpreted as the representation of a floating-point value and a Float object representing that value is created and returned.

If s is null, then a NullPointerException is thrown.

Leading and trailing whitespace (§20.5.19) characters in s are ignored. The rest of s should constitute a FloatValue as described by the lexical syntax rules:

FloatValue:

    Signopt Digits . Digitsopt ExponentPartopt

    Signopt . Digits ExponentPartopt

where Sign, Digits, and ExponentPart are as defined in §3.10.2. If it does not have the form of a FloatValue, then a NumberFormatException is thrown. Otherwise, it is regarded as representing an exact decimal value in the usual "computerized scientific notation"; this exact decimal value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type float by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic. Finally, a new object of class Float is created to represent this float value.

Note that neither F nor f is permitted to appear in s as a type indicator, as would be permitted in Java source code (§3.10.1).

20.9.18 public boolean isNaN()

The result is true if and only if the value represented by this Float object is NaN.

20.9.19 public static boolean isNaN(float v)

The result is true if and only if the value of the argument is NaN.

20.9.20 public boolean isInfinite()

The result is true if and only if the value represented by this Float object is positive infinity or negative infinity.

20.9.21 public static boolean isInfinite(float v)

The result is true if and only if the value of the argument is positive infinity or negative infinity.

20.9.22 public static int floatToIntBits(float value)

The result is a representation of the floating-point argument according to the IEEE 754 floating-point "single format" bit layout:

  • Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number.
  • Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent.
  • Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
  • If the argument is positive infinity, the result will be 0x7f800000.
  • If the argument is negative infinity, the result will be 0xff800000.
  • If the argument is NaN, the result will be 0x7fc00000.

In all cases, the result is an integer that, when given to the intBitsToFloat method (§20.9.23), will produce a floating-point value equal to the argument to floatToIntBits.

20.9.23 public static float intBitsToFloat(int bits)

The argument is considered to be a representation of a floating-point value according to the IEEE 754 floating-point "single format" bit layout. That floating-point value is returned as the result.

  • If the argument is 0x7f800000, the result will be positive infinity.
  • If the argument is 0xff800000, the result will be negative infinity.
  • If the argument is any value in the range 0x7f800001 through 0x7fffffff or in the range 0xff800001 through 0xffffffff, the result will be NaN. (All IEEE 754 NaN values are, in effect, lumped together by the Java language into a single value called NaN.)
  • In all other cases, let s, e, and m be three values that can be computed from the argument:

int s = ((bits >> 31) == 0) ? 1 : -1;
int e = ((bits >> 23) & 0xff);
int m = (e == 0) ?
        (bits & 0x7fffff) << 1 :
        (bits & 0x7fffff) | 0x800000;

Then the floating-point result equals the value of the mathematical expression [image].


20.10 The Class java.lang.Double

public final class Double extends Number {
    public static final double MIN_VALUE =

            5e-324;
    public static final double MAX_VALUE =
              1.7976931348623157e+308;
    public static final double NEGATIVE_INFINITY = -1.0/0.0;
    public static final double POSITIVE_INFINITY = 1.0/0.0;
    public static final double NaN = 0.0/0.0;
    public Double(double value);
    public Double(String s)

        throws NumberFormatException;
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public int intValue();
    public long longValue();
    public float floatValue();
    public double doubleValue();
    public static String toString(double d);
    public static Double valueOf(String s)

        throws NullPointerException, NumberFormatException;
    public boolean isNaN();
    public static boolean isNaN(double v);
    public boolean isInfinite();
    public static boolean isInfinite(double v);
    public static long doubleToLongBits(double value);
    public static double longBitsToDouble(long bits);
}

20.10.1 public static final double MIN_VALUE = 5e-324;

The constant value of this field is the smallest positive nonzero value of type double. It is equal to the value returned by Double.longBitsToDouble(0x1L).

20.10.2 public static final double MAX_VALUE = 1.7976931348623157e+308;

The constant value of this field is the largest positive finite value of type double. It is equal to the returned by:

Double.longBitsToDouble(0x7fefffffffffffffL)

20.10.3 public static final double NEGATIVE_INFINITY = -1.0/0.0;

The constant value of this field is the negative infinity of type double. It is equal to the value returned by Double.longBitsToDouble(0xfff0000000000000L).

20.10.4 public static final double POSITIVE_INFINITY = 1.0/0.0;

The constant value of this field is the positive infinity of type double. It is equal to the value returned by Double.longBitsToDouble(0x7ff0000000000000L).

20.10.5 public static final double NaN = 0.0/0.0;

The constant value of this field is the Not-a-Number of type double. It is equal to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).

20.10.6 public Double(double value)

This constructor initializes a newly created Double object so that it represents the primitive value that is the argument.

20.10.7 public Double(String s)
throws NumberFormatException

This constructor initializes a newly created Double object so that it represents the floating-point value of type double represented by the string. The string is converted to a double value in exactly the manner used by the valueOf method (§20.9.17).

20.10.8 public String toString()

The primitive double value represented by this Double object is converted to a string exactly as if by the method toString of one argument (§20.10.15).

Overrides the toString method of Object (§20.1.2).

20.10.9 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Double object that represents the same double value as this Double object. For this purpose, two double values are considered to be the same if and only if the method doubleToLongBits (§20.10.21) returns the same long value when applied to each. Note that even though the == operator returns false if both operands are NaN, this equals method will return true if this Double object and the argument are both Double objects that represent NaN. On the other hand, even though the == operator returns true if one operand is positive zero and the other is negative zero, this equals method will return false if this Double object and the argument represent zeroes of different sign. This allows hashtables to operate properly.

Overrides the equals method of Object (§20.1.3).

20.10.10 public int hashCode()

The result is the exclusive OR of the two halves of the long integer bit representation, exactly as produced by the method doubleToLongBits (§20.10.21), of the primitive double value represented by this Double object. That is, the hashcode is the value of the expression:

(int)(v^(v>>>32))

where v is defined by:

long v = Double.doubleToLongBits(this.longValue());

Overrides the hashCode method of Object (§20.1.4).

20.10.11 public int intValue()

The double value represented by this Double object is converted (§5.1.3) to type int and the result of the conversion is returned.

Overrides the intValue method of Number (§20.6.1).

20.10.12 public long longValue()

The double value represented by this Double object is converted (§5.1.3) to type long and the result of the conversion is returned.

Overrides the longValue method of Number (§20.6.2).

20.10.13 public float floatValue()

The double value represented by this Double object is converted (§5.1.3) to type float and the result of the conversion is returned.

Overrides the floatValue method of Number (§20.6.3).

20.10.14 public double doubleValue()

The double value represented by this Double object is returned.

Overrides the doubleValue method of Number (§20.6.4).

20.10.15 public static String toString(double d)

The argument is converted to a readable string format as follows. All characters mentioned below are ASCII characters.

  • If the argument is NaN, the result is the string "NaN".
  • Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('\u002d'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
    • If m is infinity, it is represented by the characters "Infinity"; thus, positive infinity produces the result "Infinity" and negative infinity produces the result "-Infinity".
    • If m is zero, it is represented by the characters "0.0"; thus, negative zero produces the result "-0.0" and positive zero produces the result "0.0".
    • If m is greater than or equal to [image] but less than [image], then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' (\u002E), followed by one or more decimal digits representing the fractional part of m.
    • If m is less than [image] or not less than [image], then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that [image]; then let a be the mathematically exact quotient of m and [image] so that [image]. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (\u002E), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (\u0045), followed by a representation of n as a decimal integer, as produced by the method Integer.toString of one argument (§20.7.12).

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

[This specification for the method toString is scheduled for introduction in Java version 1.1. In previous versions of Java, this method produces Inf instead of Infinity for infinite values. Also, it rendered finite values in the same form as the %g format of the printf function in the C programming language, which can lose information because it produces at most six digits after the decimal point.]

20.10.16 public static Double valueOf(String s)
throws NullPointerException, NumberFormatException

The string s is interpreted as the representation of a floating-point value and a Double object representing that value is created and returned.

If s is null, then a NullPointerException is thrown.

Leading and trailing whitespace (§20.5.19) characters in s are ignored. The rest of s should constitute a FloatValue as described by the lexical syntax rule:

FloatValue:

    Signopt Digits . Digitsopt ExponentPartopt

    Signopt . Digits ExponentPartopt

where Sign, Digits, and ExponentPart are as defined in §3.10.2. If it does not have the form of a FloatValue, then a NumberFormatException is thrown. Otherwise, it is regarded as representing an exact decimal value in the usual "computerized scientific notation"; this exact decimal value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic. Finally, a new object of class Double is created to represent the double value.

Note that neither D nor d is permitted to appear in s as a type indicator, as would be permitted in Java source code (§3.10.1).

20.10.17 public boolean isNaN()

The result is true if and only if the value represented by this Double object is NaN.

20.10.18 public static boolean isNaN(double v)

The result is true if and only if the value of the argument is NaN.

20.10.19 public boolean isInfinite()

The result is true if and only if the value represented by this Double object is positive infinity or negative infinity.

20.10.20 public static boolean isInfinite(double v)

The result is true if and only if the value of the argument is positive infinity or negative infinity.

20.10.21 public static long doubleToLongBits(double value)

The result is a representation of the floating-point argument according to the IEEE 754 floating-point "double format" bit layout:

  • Bit 63 (the bit that is selected by the mask 0x8000000000000000L) represents the sign of the floating-point number.
  • Bits 62-52 (the bits that are selected by the mask 0x7ff0000000000000L) represent the exponent.
  • Bits 51-0 (the bits that are selected by the mask 0x000fffffffffffffL) represent the significand (sometimes called the mantissa) of the floating-point number.
  • If the argument is positive infinity, the result will be 0x7ff0000000000000L.
  • If the argument is negative infinity, the result will be 0xfff0000000000000L.
  • If the argument is NaN, the result will be 0x7ff8000000000000L.

In all cases, the result is a long integer that, when given to the longBitsToDouble method (§20.10.22), will produce a floating-point value equal to the argument to doubleToLongBits.

20.10.22 public static double longBitsToDouble(long bits)

The argument is considered to be a representation of a floating-point value according to the IEEE 754 floating-point "double format" bit layout. That floating-point value is returned as the result.

  • If the argument is 0x7f80000000000000L, the result will be positive infinity.
  • If the argument is 0xff80000000000000L, the result will be negative infinity.
  • If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result will be NaN. (All IEEE 754 NaN values are, in effect, lumped together by the Java language into a single value called NaN.)
  • In all other cases, let s, e, and m be three values that can be computed from the argument:

int s = ((bits >> 63) == 0) ? 1 : -1;
int e = (int)((bits >> 52) & 0x7ffL);
long m = (e == 0) ?
        (bits & 0xfffffffffffffL) << 1 :
        (bits & 0xfffffffffffffL) | 0x10000000000000L;

Then the floating-point result equals the value of the mathematical expression [image].

Let beeves and home-bred kine partake
The sweets of Burn-mill meadow;
The swan on still St. Mary's Lake
Float double, swan and shadow!
—William Wordsworth, Yarrow Unvisited (1803)


20.11 The Class java.lang.Math

Oh, back to the days that were free from care in the 'Ology 'varsity shop,
With nothing to do but analyse air in an anemometrical top,
Or the differentiation of the trigonometrical pow'rs
Of the constant pi that made me sigh in those happy days of ours!
—I. W. Litchfield, Take Me Back to Tech (1885)

The class Math contains useful basic numerical constants and methods.

public final class Math {
    public static final double E = 2.7182818284590452354;
    public static final double PI = 3.14159265358979323846;
    public static double sin(double a);
    public static double cos(double a);
    public static double tan(double a);
    public static double asin(double a);
    public static double acos(double a);
    public static double atan(double a);
    public static double atan2(double a, double b);
    public static double exp(double a);
    public static double log(double a);
    public static double sqrt(double a);
    public static double pow(double a, double b);
    public static double IEEEremainder(double f1, double f2);
    public static double ceil(double a);
    public static double floor(double a);
    public static double rint(double a);
    public static int round(float a);
    public static long round(double a);
    public static double random();
    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 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 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);
}

To ensure portability of Java programs, the specifications of many of the numerical functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package fdlibm ("Freely Distributable Math Library"). These algorithms, which are written in the C programming language, are to be understood as if executed in Java execution order with all floating-point operations following the rules of Java floating-point arithmetic.

The network library may be found at http://netlib.att.com/ on the World Wide Web; then perform a keyword search for fdlibm. The library may also be retrieved by E-mail; to begin the process, send a message containing the line:

send index from fdlibm

to netlib@research.att.com. The Java math library is defined with respect to the version of fdlibm dated 95/01/04. Where fdlibm provides more than one definition for a function (such as acos), the "IEEE754 core function" version is to be used (residing in a file whose name begins with the letter e).

A complete and self-contained description of the algorithms to be used for these functions will be provided in a future version of this specification. It is also anticipated that the algorithms will be coded in Java to provide a reference implementation that is not tied to fdlibm.

20.11.1 public static final double E = 2.7182818284590452354;

The constant value of this field is the double value that is closer than any other to e, the base of the natural logarithms.

20.11.2 public static final double PI = 3.14159265358979323846;

The constant value of this field is the double value that is closer than any other to [image], the ratio of the circumference of a circle to its diameter.

20.11.3 public static double sin(double a)

This method computes an approximation to the sine of the argument, using the sin algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN or an infinity, then the result is NaN.
  • If the argument is positive zero, then the result is positive zero; if the argument is negative zero, then the result is negative zero.

20.11.4 public static double cos(double a)

This method computes an approximation to the cosine of the argument, using the cos algorithm as published in fdlibm (see the introduction to this section).

Special case:

  • If the argument is NaN or an infinity, then the result is NaN.

20.11.5 public static double tan(double a)

This method computes an approximation to the tangent of the argument, using the tan algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN or an infinity, then the result is NaN.
  • If the argument is positive zero, then the result is positive zero; if the argument is negative zero, then the result is negative zero.

20.11.6 public static double asin(double a)

This method computes an approximation to the arc sine of the argument, using the asin algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN or its absolute value is greater than 1, then the result is NaN.
  • If the argument is positive zero, then the result is positive zero; if the argument is negative zero, then the result is negative zero.

20.11.7 public static double acos(double a)

This method computes an approximation to the arc cosine of the argument, using the acos algorithm as published in fdlibm (see the introduction to this section).

Special case:

  • If the argument is NaN or its absolute value is greater than 1, then the result is NaN.

20.11.8 public static double atan(double a)

This method computes an approximation to the arc tangent of the argument, using the atan algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN, then the result is NaN.
  • If the argument is positive zero, then the result is positive zero; if the argument is negative zero, then the result is negative zero.

20.11.9 public static double atan2(double y, double x)

This method computes an approximation to the arc tangent of the quotient [image] of the arguments, using the atan2 algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If either argument is NaN, then the result is NaN.
  • If the first argument is positive zero and the second argument is positive, or the first argument is positive and finite and the second argument is positive infinity, then the result is positive zero.
  • If the first argument is negative zero and the second argument is positive, or the first argument is negative and finite and the second argument is positive infinity, then the result is negative zero.
  • If the first argument is positive zero and the second argument is negative, or the first argument is positive and finite and the second argument is negative infinity, then the result is the double value closest to [image].
  • If the first argument is negative zero and the second argument is negative, or the first argument is negative and finite and the second argument is negative infinity, then the result is the double value closest to [image].
  • If the first argument is positive and the second argument is positive zero or negative zero, or the first argument is positive infinity and the second argument is finite, then the result is the double value closest to [image].
  • If the first argument is negative and the second argument is positive zero or negative zero, or the first argument is negative infinity and the second argument is finite, then the result is the double value closest to [image].
  • If both arguments are positive infinity, then the result is the double value closest to [image].
  • If the first argument is positive infinity and the second argument is negative infinity, then the result is the double value closest to [image].
  • If the first argument is negative infinity and the second argument is positive infinity, then the result is the double value closest to [image].
  • If both arguments are negative infinity, then the result is the double value closest to [image].

20.11.10 public static double exp(double a)

This method computes an approximation to the exponential function of the argument (e raised to the power of the argument, where e is the base of the natural logarithms (§20.11.1)), using the exp algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is negative infinity, then the result is positive zero.

20.11.11 public static double log(double a)

This method computes an approximation to the natural logarithm of the argument, using the log algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero or negative zero, then the result is negative infinity.

20.11.12 public static double sqrt(double a)

Whan that Aprill with his shoures soote
The droghte of March hath perced to the roote . . .
—Geoffrey Chaucer (1328-1400), The Canterbury Tales, General Prologue

This method computes an approximation to the square root of the argument.

Special cases:

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero or negative zero, then the result is the same as the argument.

Otherwise, the result is the double value closest to the true mathematical square root of the argument value.

20.11.13 public static double pow(double a, double b)

This method computes an approximation to the mathematical operation of raising the first argument to the power of the second argument, using the pow algorithm as published in fdlibm (see the introduction to this section).

Special cases:

  • If the second argument is positive or negative zero, then the result is 1.0.
  • If the second argument is 1.0, then the result is the same as the first argument.
  • If the second argument is NaN, then the result is NaN.
  • If the first argument is NaN and the second argument is nonzero, then the result is NaN.
  • If the absolute value of the first argument is greater than 1 and the second argument is positive infinity, or the absolute value of the first argument is less than 1 and the second argument is negative infinity, then the result is positive infinity.
  • If the absolute value of the first argument is greater than 1 and the second argument is negative infinity, or the absolute value of the first argument is less than 1 and the second argument is positive infinity, then the result is positive zero.
  • If the absolute value of the first argument equals 1 and the second argument is infinite, then the result is NaN.
  • If the first argument is positive zero and the second argument is greater than zero, or the first argument is positive infinity and the second argument is less than zero, then the result is positive zero.
  • If the first argument is positive zero and the second argument is less than zero, or the first argument is positive infinity and the second argument is greater than zero, then the result is positive infinity.
  • If the first argument is negative zero and the second argument is greater than zero but not a finite odd integer, or the first argument is negative infinity and the second argument is less than zero but not a finite odd integer, then the result is positive zero.
  • If the first argument is negative zero and the second argument is a positive finite odd integer, or the first argument is negative infinity and the second argument is a negative finite odd integer, then the result is negative zero.
  • If the first argument is negative zero and the second argument is less than zero but not a finite odd integer, or the first argument is negative infinity and the second argument is greater than zero but not a finite odd integer, then the result is positive infinity.
  • If the first argument is negative zero and the second argument is a negative finite odd integer, or the first argument is negative infinity and the second argument is a positive finite odd integer, then the result is negative infinity.
  • If the first argument is less than zero and the second argument is a finite even integer, then the result is equal to the result of raising the absolute value of the first argument to the power of the second argument.
  • If the first argument is less than zero and the second argument is a finite odd integer, then the result is equal to the negative of the result of raising the absolute value of the first argument to the power of the second argument.
  • If the first argument is finite and less than zero and the second argument is finite and not an integer, then the result is NaN.
  • If both arguments are integers, then the result is exactly equal to the mathematical result of raising the first argument to the power of the second argument if that result can in fact be represented exactly as a double value.

(In the foregoing descriptions, a floating-point value is considered to be an integer if and only if it is a fixed point of the method ceil (§20.11.15) or, which is the same thing, a fixed point of the method floor (§20.11.16). A value is a fixed point of a one-argument method if and only if the result of applying the method to the value is equal to the value.)

20.11.14 public static double IEEEremainder(double x, double y)

This method computes the remainder operation on two arguments as prescribed by the IEEE 754 standard: the remainder value is mathematically equal to [image] where [image] is the mathematical integer closest to the exact mathematical value of the quotient [image]; if two mathematical integers are equally close to [image] then n is the integer that is even. If the remainder is zero, its sign is the same as the sign of the first argument.

Special cases:

  • If either argument is NaN, or the first argument is infinite, or the second argument is positive zero or negative zero, then the result is NaN.
  • If the first argument is finite and the second argument is infinite, then the result is the same as the first argument.

20.11.15 public static double ceil(double a)

The result is the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer.

Special cases:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
  • If the argument value is less than zero but greater than -1.0, then the result is negative zero.

Note that the value of Math.ceil(x) is exactly the value of -Math.floor(-x).

20.11.16 public static double floor(double a)

The result is the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer.

Special cases:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

20.11.17 public static double rint(double a)

The result is the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close to the value of the argument, the result is the integer value that is even.

Special cases:

  • If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
  • If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.

20.11.18 public static int round(float a)

Round numbers are always false.
—Samuel Johnson (1709-1784)

The result is rounded to an integer by adding [image], taking the floor of the result, and casting the result to type int.

In other words, the result is equal to the value of the expression:

(int)Math.floor(a + 0.5f)

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity, or indeed any value less than or equal to the value of Integer.MIN_VALUE (§20.7.1), the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity, or indeed any value greater than or equal to the value of Integer.MAX_VALUE (§20.7.2), the result is equal to the value of Integer.MAX_VALUE.

20.11.19 public static long round(double a)

The result is rounded to an integer by adding [image], taking the floor of the result, and casting the result to type long.

In other words, the result is equal to the value of the expression:

(long)Math.floor(a + 0.5d)

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity, or indeed any value less than or equal to the value of Long.MIN_VALUE (§20.7.1), the result is equal to the value of Long.MIN_VALUE.
  • If the argument is positive infinity, or indeed any value greater than or equal to the value of Long.MAX_VALUE (§20.7.2), the result is equal to the value of Long.MAX_VALUE.

20.11.20 public static double random()

The result is a double value with positive sign, greater than or equal to zero but less than 1.0, chosen pseudorandomly with (approximately) uniform distribution from that range.

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random()

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom number generator.

20.11.21 public static int abs(int a)

The result is the absolute value of the argument, if possible.

If the argument is not negative, the argument is returned.

If the argument is negative, the negation of the argument is returned. Note that if the argument is equal to the value of Integer.MIN_VALUE (§20.7.1), the most negative representable int value, the result will be that same negative value.

20.11.22 public static long abs(long a)

The result is the absolute value of the argument, if possible.

If the argument is not negative, the argument is returned.

If the argument is negative, the negation of the argument is returned. Note that if the argument is equal to the value of Long.MIN_VALUE (§20.8.1), the most negative representable long value, the result will be that same negative value.

20.11.23 public static float abs(float a)

The argument is returned with its sign changed to be positive.

Special cases:

  • If the argument is positive zero or negative zero, the result is positive zero.
  • If the argument is infinite, the result is positive infinity.
  • If the argument is NaN, the result is NaN.

In other words, the result is equal to the value of the expression:

Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))

[This specification for the method abs is scheduled for introduction in Java version 1.1. In previous versions of Java, abs(-0.0f) returns -0.0f, which is not correct.]

20.11.24 public static double abs(double a)

The argument is returned with its sign changed to be positive.

Special cases:

  • If the argument is positive zero or negative zero, the result is positive zero.
  • If the argument is infinite, the result is positive infinity.
  • If the argument is NaN, the result is NaN.

In other words, the result is equal to the value of the expression:

Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)

[This specification for the method abs is scheduled for introduction in Java version 1.1. In previous versions of Java, abs(-0.0d) returns -0.0d, which is not correct.]

20.11.25 public static int min(int a, int b)

E duobus malis minimum eligendum.
—Marcus Tullius Cicero (106-43 B. C.), De officiis, iii

The result is the smaller of the two arguments-that is, the one closer to the value of Integer.MIN_VALUE (§20.7.1). If the arguments have the same value, the result is that same value.

20.11.26 public static long min(long a, long b)

Of harmes two the lesse is for to cheese.
—Geoffrey Chaucer (1328-1400), Troilus and Criseyde, Book ii

The result is the smaller of the two arguments-that is, the one closer to the value of Long.MIN_VALUE (§20.8.1). If the arguments have the same value, the result is that same value.

20.11.27 public static float min(float a, float b)

Of two evils, the less is always to be chosen.
—Thomas a Kempis (1380-1471), Imitation of Christ, Book iii, chapter 12

The result is the smaller of the two arguments-that is, the one closer to negative infinity. If the arguments have the same value, the result is that same value.

Special cases:

  • If one argument is positive zero and the other is negative zero, the result is negative zero.
  • If either argument is NaN, the result is NaN.

[This specification for the method min is scheduled for introduction in Java version 1.1. In previous versions of Java, min(0.0f, -0.0f) returns 0.0f, which is not correct.]

20.11.28 public static double min(double a, double b)

Of two evils I have chose the least.
—Matthew Prior (1664-1721), Imitation of Horace

The result is the smaller of the two arguments-that is, the one closer to negative infinity. If the arguments have the same value, the result is that same value.

Special cases:

  • If one argument is positive zero and the other is negative zero, the result is negative zero.
  • If either argument is NaN, the result is NaN.

[This specification for the method min is scheduled for introduction in Java version 1.1. In previous versions of Java, min(0.0d, -0.0d) returns 0.0d, which is not correct.]

20.11.29 public static int max(int a, int b)

The result is the larger of the two arguments-that is, the one closer to the value of Integer.MAX_VALUE (§20.7.2). If the arguments have the same value, the result is that same value.

20.11.30 public static long max(long a, long b)

The result is the larger of the two arguments-that is, the one closer to the value of Long.MAX_VALUE (§20.8.2). If the arguments have the same value, the result is that same value.

20.11.31 public static float max(float a, float b)

The result is the larger of the two arguments-that is, the one closer to positive infinity. If the arguments have the same value, the result is that same value.

Special cases:

  • If one argument is positive zero and the other is negative zero, the result is positive zero.
  • If either argument is NaN, the result is NaN.

[This specification for the method max is scheduled for introduction in Java version 1.1. In previous versions of Java, max(-0.0f, 0.0f) returns -0.0f, which is not correct.]

20.11.32 public static double max(double a, double b)

The result is the larger of the two arguments-that is, the one closer to positive infinity. If the arguments have the same value, the result is that same value.

Special cases:

  • If one argument is positive zero and the other is negative zero, the result is positive zero.
  • If either argument is NaN, the result is NaN.

[This specification for the method max is scheduled for introduction in Java version 1.1. In previous versions of Java, max(-0.0d, 0.0d) returns -0.0d, which is not correct.].

In mathematics he was greater
Than Tycho Brahe or Erra Pater
For he, by geometric scale,
Could take the size of pots of ale;
Resolve, by sines and tangents straight
Whether bread or butter wanted weight;
And wisely tell what hour o' the day
The clock does strike, by algebra.
—Samuel Butler, Hudibras, Part I, canto i


20.12 The Class java.lang.String

An object of type String, once created, is immutable. It represents a fixed-length sequence of characters. Compare this to the class StringBuffer (§20.13), which represents a modifiable, variable-length sequence of characters.

The class String has methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, for creating a copy of a string with all characters translated to uppercase or to lowercase, and so on.

public final class String {
    public String();
    public String(String value)
        throws NullPointerException;
    public String(StringBuffer buffer)
        throws NullPointerException;
    public String(char[] value)
        throws NullPointerException;
    public String(char[] value, int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
    public String(byte[] ascii, int hibyte)
        throws NullPointerException;
    public String(byte[] ascii, int hibyte,
            int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
    public String toString();
    public boolean equals(Object anObject);
    public int hashCode();
    public int length();
    public char charAt(int index);
    public void getChars(int srcBegin, int srcEnd,
            char dst[], int dstBegin)

        throws NullPointerException, IndexOutOfBoundsException;
    public void getBytes(int srcBegin, int srcEnd,
            byte dst[], int dstBegin)
        throws NullPointerException, IndexOutOfBoundsException;
    public char[] toCharArray();
    public boolean equalsIgnoreCase(String anotherString);
    public int compareTo(String anotherString)
        throws NullPointerException;
    public boolean regionMatches(int toffset, String other,

            int ooffset, int len)
        throws NullPointerException;
    public boolean regionMatches(boolean ignoreCase, int toffset,

            String other, int ooffset, int len)
        throws NullPointerException;
    public boolean startsWith(String prefix)
        throws NullPointerException;
    public boolean startsWith(String prefix, int toffset)
        throws NullPointerException;
    public boolean endsWith(String suffix)
        throws NullPointerException;
    public int indexOf(int ch);
    public int indexOf(int ch, int fromIndex);
    public int indexOf(String str)
        throws NullPointerException;
    public int indexOf(String str, int fromIndex)
        throws NullPointerException;
    public int lastIndexOf(int ch);
    public int lastIndexOf(int ch, int fromIndex);
    public int lastIndexOf(String str)
        throws NullPointerException;
    public int lastIndexOf(String str, int fromIndex)
        throws NullPointerException;
    public String substring(int beginIndex);
    public String substring(int beginIndex, int endIndex);
    public String concat(String str)
        throws NullPointerException;
    public String replace(char oldChar, char newChar);
    public String toLowerCase();
    public String toUpperCase();
    public String trim();
    public static String valueOf(Object obj);
    public static String valueOf(char[] data)
        throws NullPointerException;
    public static String valueOf(char[] data,
            int offset, int count)
        throws NullPointerException, IndexOutOfBoundsException;
    public static String valueOf(boolean b);
    public static String valueOf(char c);
    public static String valueOf(int i);
    public static String valueOf(long l);
    public static String valueOf(float f);
    public static String valueOf(double d);
    public String intern();
}

20.12.1 public String()

This constructor initializes a newly created String object so that it represents an empty character sequence.

20.12.2 public String(String value)

This constructor initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

20.12.3 public String(StringBuffer buffer)
throws NullPointerException

This constructor initializes a newly created String object so that it represents the sequence of characters that is currently contained in the StringBuffer argument (§20.13). The contents of the string buffer are copied; subsequent modification of the string buffer does not affect the newly created string.

If buffer is null, then a NullPointerException is thrown.

20.12.4 public String(char[] data)
throws NullPointerException

This constructor initializes a newly created String object so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

20.12.5 public String(char[] data, int offset, int count)
throws NullPointerException, IndexOutOfBoundsException

This constructor initializes a newly created String object so that it represents the sequence of characters currently contained in a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than data.length, then an IndexOutOfBoundsException is thrown.

20.12.6 public String(byte[] ascii, int hibyte)
throws NullPointerException

This constructor initializes a newly created String object so that it represents a sequence of characters constructed from an array of 8-bit integer values. Each character c in the result string is constructed from the corresponding element b of the byte array in such a way that:

c == ((hibyte & 0xff) << 8) | (b & 0xff)

If ascii is null, then a NullPointerException is thrown.

20.12.7 public String(byte[] ascii, int hibyte,
int offset, int count)
throws NullPointerException,
IndexOutOfBoundsException

This constructor initializes a newly created String object so that it represents the sequence of characters constructed from a subarray of an array of 8-bit integer values. The offset argument is the index of the first byte of the subarray and the count argument specifies the length of the subarray. Each character c in the result string is constructed from the corresponding element b of the byte subarray in such a way that:

c == ((hibyte & 0xff) << 8) | (b & 0xff)

If ascii is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than ascii.length, then an IndexOutOfBoundsException is thrown.

20.12.8 public String toString()

A reference to this object (which is, after all, already a String) is returned.

Overrides the toString method of Object (§20.1.2).

20.12.9 public boolean equals(Object anObject)

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object.

Overrides the equals method of Object (§20.1.3).

See also the methods equalsIgnoreCase (§20.12.16) and compareTo (§20.12.17).

20.12.10 public int hashCode()

The hashcode for a String object is computed in one of two ways, depending on its length. Let n be the length (§20.12.11) of the character sequence and let [image] mean the character with index i.

  • If [image], then the hashcode is computed as
    using int arithmetic.
  • If [image], then the hashcode is computed as
    using int arithmetic, where [image] and [image], sampling only eight or nine characters of the string.

Overrides the hashCode method of Object (§20.1.4).

20.12.11 public int length()

The length of the sequence of characters represented by this String object is returned.

20.12.12 public char charAt(int index)
throws IndexOutOfBoundsException

This method returns the character indicated by the index argument within the sequence of characters represented by this String. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the index argument is negative or not less than the length (§20.12.11) of this string, then an IndexOutOfBoundsException is thrown.

20.12.13 public void getChars(int srcBegin, int srcEnd,
char dst[], int dstBegin)
throws NullPointerException,
IndexOutOfBoundsException

Characters are copied from this String object into the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1.

If dst is null, then a NullPointerException is thrown.

An IndexOutOfBoundsException is thrown if any of the following is true:

  • srcBegin is negative
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this String
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

20.12.14 public void getBytes(int srcBegin, int srcEnd,
byte dst[], int dstBegin)
throws NullPointerException,
IndexOutOfBoundsException

Characters are copied from this String object into the destination byte array dst. Each byte receives only the eight low-order bits of the corresponding character. The eight high-order bits of each character are not copied and do not participate in the transfer in any way. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters, converted to bytes, are copied into the subarray of dst starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1.

If dst is null, then a NullPointerException is thrown.

An IndexOutOfBoundsException is thrown if any of the following is true:

  • srcBegin is negative
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this String
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

20.12.15 public char[] toCharArray()

A new character array is created and returned. The length of the array is equal to the length (§20.12.11) of this String object. The array is initialized to contain the character sequence represented by this String object.

20.12.16 public boolean equalsIgnoreCase(String anotherString)

The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this String object, where case is ignored.

Two characters are considered the same, ignoring case, if at least one of the following is true:

  • The two characters are the same (as compared by the == operator).
  • Applying the method Character.toUppercase (§20.5.21) to each character produces the same result.
  • Applying the method Character.toLowercase (§20.5.20) to each character produces the same result.

Two sequences of characters are the same, ignoring case, if the sequences have the same length and corresponding characters are the same, ignoring case.

See also the method equals (§20.12.9).

20.12.17 public int compareTo(String anotherString)
throws NullPointerException

The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals method (§20.12.9) would return true.

If anotherString is null, then a NullPointerException is thrown.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two strings- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings-that is, the value:

this.length()-anotherString.length()

20.12.18 public boolean regionMatches(int toffset,
String other, int ooffset, int len)
throws NullPointerException

A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent identical character sequences. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true:

  • toffset is negative.
  • ooffset is negative.
  • toffset+len is greater than the length of this String object.
  • ooffset+len is greater than the length of the other argument.
  • There is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k)

If other is null, then a NullPointerException is thrown.

20.12.19 public boolean regionMatches(boolean ignoreCase,
int toffset, String other, int ooffset, int len)
throws NullPointerException

A substring of this String object is compared to a substring of the argument other. The result is true if these substrings represent character sequences that are the same, ignoring case if and only if ignoreCase is true. The substring of this String object to be compared begins at index toffset and has length len. The substring of other to be compared begins at index ooffset and has length len. The result is false if and only if at least one of the following is true:

  • toffset is negative.
  • ooffset is negative.
  • toffset+len is greater than the length of this String object.
  • ooffset+len is greater than the length of the other argument.
  • There is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k)
  • ignoreCase is true and there is some nonnegative integer k less than len such that:

Character.toLowerCase(this.charAt(toffset+k)) !=
    Character.toLowerCase(other.charAt(ooffset+k))

    and:

Character.toUpperCase(this.charAt(toffset+k)) !=
    Character.toUpperCase(other.charAt(ooffset+k))

If other is null, then a NullPointerException is thrown.

20.12.20 public boolean startsWith(String prefix)
throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a prefix of the character sequence represented by this String object.

If prefix is null, a NullPointerException is thrown.

Note that the result will be true if the argument is an empty string or is equal to this String object as determined by the equals method (§20.12.9).

20.12.21 public boolean startsWith(String prefix, int toffset)
throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a prefix of the substring of this String object starting at index toffset.

If prefix is null, then a NullPointerException is thrown.

The result is false if toffset is negative or greater than the length of this String object; otherwise, the result is the same as the result of the expression

this.subString(toffset).startsWith(prefix)

20.12.22 public boolean endsWith(String suffix)
throws NullPointerException

The result is true if and only if the character sequence represented by the argument is a suffix of the character sequence represented by this String object.

If suffix is null, then a NullPointerException is thrown.

Note that the result will be true if the argument is an empty string or is equal to this String object as determined by the equals method (§20.12.9).

20.12.23 public int indexOf(int ch)

If a character with value ch occurs in the character sequence represented by this String object, then the index of the first such occurrence is returned-that is, the smallest value k such that:

this.charAt(k) == ch

is true. If no such character occurs in this string, then -1 is returned.

20.12.24 public int indexOf(int ch, int fromIndex)

If a character with value ch occurs in the character sequence represented by this String object at an index no smaller than fromIndex, then the index of the first such occurrence is returned-that is, the smallest value k such that:

(this.charAt(k) == ch) && (k >= fromIndex)

is true. If no such character occurs in this string at or after position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

20.12.25 public int indexOf(String str)
throws NullPointerException

If the string str occurs as a substring of this String object, then the index of the first character of the first such substring is returned-that is, the smallest value k such that:

this.startsWith(str, k)

is true. If str does not occur as a substring of this string, then -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.26 public int indexOf(String str, int fromIndex)
throws NullPointerException

If the string str occurs as a substring of this String object starting at an index no smaller than fromIndex, then the index of the first character of the first such substring is returned-that is, the smallest value k such that:

this.startsWith(str, k) && (k >= fromIndex)

is true. If str does not occur as a substring of this string at or after position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is negative, it has the same effect as if it were zero: this entire string may be searched. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.27 public int lastIndexOf(int ch)

If a character with value ch occurs in the character sequence represented by this String object, then the index of the last such occurrence is returned-that is, the largest value k such that:

this.charAt(k) == ch

is true. If no such character occurs in this string, then -1 is returned.

20.12.28 public int lastIndexOf(int ch, int fromIndex)

If a character with value ch occurs in the character sequence represented by this String object at an index no larger than fromIndex, then the index of the last such occurrence is returned-that is, the largest value k such that:

(this.charAt(k) == ch) && (k <= fromIndex)

is true. If no such character occurs in this string at or before position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is greater than or equal to the length of this string, it has the same effect as if it were equal to one less than the length of this string: this entire string may be searched. If it is negative, it has the same effect as if it were -1: -1 is returned.

20.12.29 public int lastIndexOf(String str)
throws NullPointerException

If the string str occurs as a substring of this String object, then the index of the first character of the last such substring is returned-that is, the largest value k such that:

this.startsWith(str, k)

is true. If str does not occur as a substring of this string, then -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.30 public int lastIndexOf(String str, int fromIndex)
throws NullPointerException

If the string str occurs as a substring of this String object starting at an index no larger than fromIndex, then the index of the first character of the last such substring is returned-that is, the largest value k such that:

this.startsWith(str, k) && (k <= fromIndex)

is true. If str does not occur as a substring of this string at or before position fromIndex, then -1 is returned.

There is no restriction on the value of fromIndex. If it is greater than the length of this string, it has the same effect as if it were equal to the length of this string: this entire string may be searched. If it is negative, it has the same effect as if it were -1: -1 is returned.

If str is null, a NullPointerException is thrown.

20.12.31 public String substring(int beginIndex)
throws IndexOutOfBoundsException

The result is a newly created String object that represents a subsequence of the character sequence represented by this String object; this subsequence begins with the character at position beginIndex and extends to the end of the character sequence.

If beginIndex is negative or larger than the length of this String object, then an IndexOutOfBoundsException is thrown.

Examples:

"unhappy".substring(2) returns "happy"

"Harbison".substring(3) returns "bison"

"emptiness".substring(9) returns "" (an empty string)

20.12.32 public String substring(int beginIndex, int endIndex)
throws IndexOutOfBoundsException

The result is a newly created String object that represents a subsequence of the character sequence represented by this String object; this subsequence begins with the character at position beginIndex and ends with the character at position endIndex-1. Thus, the length of the subsequence is endIndex-beginIndex.

If beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex, then this method throws an IndexOutOfBoundsException.

Examples:

"hamburger".substring(4, 8) returns "urge"

"smiles".substring(1, 5) returns "mile"

20.12.33 public String concat(String str)
throws NullPointerException

If the length of the argument string is zero, then a reference to this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Examples:

"cares".concat("s") returns "caress"
"to".concat("get").concat("her") returns "together"

If str is null, a NullPointerException is thrown.

20.12.34 public String replace(char oldChar, char newChar)

If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

Examples:

"mesquite in your cellar".replace('e', 'o')
                    returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
                    returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
                    returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)

20.12.35 public String toLowerCase()

If this String object does not contain any character that is mapped to a different character by the method Character.toLowerCase (§20.5.20), then a reference to this String object is returned. Otherwise, this method creates a new String object that represents a character sequence identical in length to the character sequence represented by this String object, with every character equal to the result of applying the method Character.toLowerCase to the corresponding character of this String object.

Examples:

"French Fries".toLowerCase() returns "french fries"
"          ".toLowerCase() returns "          "

20.12.36 public String toUpperCase()

If this String object does not contain any character that is mapped to a different character by the method Character.toUpperCase (§20.5.21), then a reference to this String object is returned. Otherwise, this method creates a new String object representing a character sequence identical in length to the character sequence represented by this String object and with every character equal to the result of applying the method Character.toUpperCase to the corresponding character of this String object.

Examples:

"Fahrvergnügen".toUpperCase() returns "FAHRVERGNÜGEN"

"Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!"

20.12.37 public String trim()

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than \u0020 (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than \u0020 in the string, then a new String object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than \u0020, and let m be the index of the last character in the string whose code is greater than \u0020. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).

This method may be used to trim whitespace (§20.5.19) from the beginning and end of a string; in fact, it trims all ASCII control characters as well.

20.12.38 public static String valueOf(Object obj)

If the argument is null, then a string equal to "null" is returned. Otherwise, the value of obj.toString() is returned. See the toString method (§20.1.2).

20.12.39 public static String valueOf(char[] data)
throws NullPointerException

A string is created and returned. The string represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

20.12.40 public static String valueOf(char[] data,
int offset, int count)
throws NullPointerException,
IndexOutOfBoundsException

A string is created and returned. The string represents the sequence of characters currently contained in a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are copied; subsequent modification of the character array does not affect the newly created string.

If data is null, then a NullPointerException is thrown.

If offset is negative, or count is negative, or offset+count is larger than data.length, then an IndexOutOfBoundsException is thrown.

20.12.41 public static String valueOf(boolean b)

A string representation of b is returned.

If the argument is true, the string "true" is returned.

If the argument is false, the string "false" is returned.

20.12.42 public static String valueOf(char c)

A string is created and returned. The string contains one character, equal to c.

20.12.43 public static String valueOf(int i)

A string is created and returned. The string is computed exactly as if by the method Integer.toString of one argument (§20.7.12).

20.12.44 public static String valueOf(long l)

A string is created and returned. The string is computed exactly as if by the method Long.toString of one argument (§20.8.12).

20.12.45 public static String valueOf(float f)

A string is created and returned. The string is computed exactly as if by the method Float.toString of one argument (§20.9.16).

20.12.46 public static String valueOf(double d)

A string is created and returned. The string is computed exactly as if by the method Double.toString of one argument (§20.10.15).

20.12.47 public String intern()

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals method (§20.12.9), then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned (§3.10.5).


20.13 The Class java.lang.StringBuffer

A string buffer is like a String (§20.12), but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

public class StringBuffer {
    public StringBuffer();
    public StringBuffer(int length)

        throws NegativeArraySizeException;
    public StringBuffer(String str);
    public String toString();
    public int length();
    public void setLength(int newLength)
        throws IndexOutOfBoundsException;
    public int capacity();
    public void ensureCapacity(int minimumCapacity);
    public char charAt(int index)
        throws IndexOutOfBoundsException;
    public void setCharAt(int index, char ch)
        throws IndexOutOfBoundsException;
    public void getChars(int srcBegin, int srcEnd,
            char[] dst, int dstBegin)

        throws NullPointerException, IndexOutOfBoundsException;
    public StringBuffer append(Object obj);
    public StringBuffer append(String str);
    public StringBuffer append(char[] str)
        throws NullPointerException;
    public StringBuffer append(char[] str, int offset, int len)
        throws NullPointerException, IndexOutOfBoundsException;
    public StringBuffer append(boolean b);
    public StringBuffer append(char c);
    public StringBuffer append(int i);
    public StringBuffer append(long l);
    public StringBuffer append(float f);
    public StringBuffer append(double d);
    public StringBuffer insert(int offset, Object obj)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, String str)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, char[] str)
        throws NullPointerException, IndexOutOfBoundsException;
    public StringBuffer insert(int offset, boolean b)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, char c)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, int i)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, long l)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, float f)
        throws IndexOutOfBoundsException;
    public StringBuffer insert(int offset, double d)
        throws IndexOutOfBoundsException;
    public StringBuffer reverse();
}

A string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to create a new internal buffer array.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

String buffers can be used by a compiler to implement the binary string concatenation operator + (§15.17.1). For example, suppose k has type int and a has type Object. Then the expression:

k + "/" + a

can be compiled as if it were the expression:

new StringBuffer().append(k).append("/").

                                        append(a).toString()

which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then adds the characters of that string to the contents of the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are the characters "start", then the method call z.append("le") would alter the string buffer to contain the characters "startle", but z.insert(4, "le") would alter the string buffer to contain the characters "starlet".

In general, if sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).

20.13.1 public StringBuffer()

This constructor initializes a newly created StringBuffer object so that it initially represents an empty character sequence and has capacity 16.

20.13.2 public StringBuffer(int length)
throws NegativeArraySizeException

This constructor initializes a newly created StringBuffer object so that it initially represents an empty character sequence, but has the capacity specified by the argument.

If the argument is negative, a NegativeArraySizeException is thrown.

20.13.3 public StringBuffer(String str)

This constructor initializes a newly created StringBuffer object so that it represents the same sequence of characters as the argument; in other words, the initial contents of the string buffer is a copy of the argument string. The initial capacity of the string buffer is 16 plus the length of the argument string.

20.13.4 public String toString()

A new String object is created and initialized to contain the character sequence currently represented by the string buffer; the new String is then returned. Any subsequent changes to the string buffer do not affect the contents of the returned string.

Implementation advice: This method can be coded so as to create a new String object without allocating new memory to hold a copy of the character sequence. Instead, the string can share the memory used by the string buffer. Any subsequent operation that alters the content or capacity of the string buffer must then make a copy of the internal buffer at that time. This strategy is effective for reducing the amount of memory allocated by a string concatenation operation (§15.17.1) when it is implemented using a string buffer.

Overrides the toString method of Object (§20.1.2).

20.13.5 public int length()

This method returns the length of the sequence of characters currently represented by this StringBuffer object.

20.13.6 public int capacity()

The current capacity of this StringBuffer object is returned.

20.13.7 public void ensureCapacity(int minimumCapacity)

If the current capacity of this StringBuffer object is less than the argument, then a new internal buffer is created with greater capacity. The new capacity will be the larger of:

  • the minimumCapacity argument
  • twice the old capacity, plus 2

If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

20.13.8 public void setLength(int newLength)
throws IndexOutOfBoundsException

This string buffer is altered to represent a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character '\u0000'. This method also calls the ensureCapacity method (§20.13.7) with argument newLength.

If the argument is negative, an IndexOutOfBoundsException is thrown.

20.13.9 public char charAt(int index)
throws IndexOutOfBoundsException

The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

If the index argument is negative or not less than the current length (§20.13.5) of the string buffer, an IndexOutOfBoundsException is thrown.

20.13.10 public void setCharAt(int index, char ch)
throws IndexOutOfBoundsException

The string buffer is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.

If the index argument is negative or not less than the current length (§20.13.5) of the string buffer, an IndexOutOfBoundsException is thrown.

20.13.11 public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
throws NullPointerException,
IndexOutOfBoundsException

Characters are copied from this StringBuffer object into the destination array dst. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus, the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index dstbegin+(srcEnd-srcBegin)-1.

If dst is null, then a NullPointerException is thrown.

Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:

  • The srcBegin argument is negative.
  • The srcBegin argument is greater than the srcEnd argument.
  • srcEnd is greater than this.length(), the current length of this string buffer.
  • dstBegin+srcEnd-srcBegin is greater than dst.length.

20.13.12 public StringBuffer append(Object obj)

The argument is converted to a string as if by the method String.valueOf (§20.12.38) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.13 public StringBuffer append(String str)

The characters of the String argument are appended, in order, to the contents of this string buffer, increasing the length of this string buffer by the length of the argument. If str is null, then the four characters "null" are appended to this string buffer. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the append method. Then the character at index k in the new character sequence is equal to the character at index k in the old character sequence, if k is less than n; otherwise, it is equal to the character at index k-n in the argument str.

20.13.14 public StringBuffer append(char[] str)
throws NullPointerException

The characters of the array argument are appended, in order, to the contents of this string buffer, increasing the length of this string buffer by the length of the argument. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

The overall effect is exactly as if the argument were converted to a string by the method String.valueOf (§20.12.39) and the characters of that string were then appended (§20.13.13) to this StringBuffer object.

20.13.15 public StringBuffer append(char[] str,
int offset, int len)
throws NullPointerException,
IndexOutOfBoundsException

Characters of the character array str, starting at index offset, are appended, in order, to the contents of this string buffer, increasing the length of this string buffer by len. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

The overall effect is exactly as if the arguments were converted to a string by the method String.valueOf of three arguments (§20.12.40) and the characters of that string were then appended (§20.13.13) to this StringBuffer object.

20.13.16 public StringBuffer append(boolean b)

The argument is converted to a string as if by the method String.valueOf (§20.12.41) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.17 public StringBuffer append(char c)

The argument is appended to the contents of this string buffer, increasing the length of this string buffer by 1. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

The overall effect is exactly as if the argument were converted to a string by the method String.valueOf (§20.12.42) and the character in that string were then appended (§20.13.13) to this StringBuffer object.

20.13.18 public StringBuffer append(int i)

The argument is converted to a string as if by the method String.valueOf (§20.12.43) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.19 public StringBuffer append(long l)

The argument is converted to a string as if by the method String.valueOf (§20.12.44) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.20 public StringBuffer append(float f)

The argument is converted to a string as if by the method String.valueOf (§20.12.45) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.21 public StringBuffer append(double d)

The argument is converted to a string as if by the method String.valueOf (§20.12.46) and the characters of that string are then appended (§20.13.13) to this StringBuffer object. A reference to this StringBuffer object is returned.

20.13.22 public StringBuffer insert(int offset, Object obj)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.38) and the characters of that string are then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.23 public StringBuffer insert(int offset, String str)
throws IndexOutOfBoundsException

The characters of the String argument are inserted, in order, into the string buffer at the position indicated by offset, moving up any characters originally above that position and increasing the length of the string buffer by the length of the argument. If str is null, then the four characters "null" are inserted into this string buffer. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the append method. Then the character at index k in the new character sequence is equal to:

  • the character at index k in the old character sequence, if k is less than offset
  • the character at index k-offset in the argument str, if k is not less than offset but is less than offset+str.length()
  • the character at index k-str.length() in the old character sequence, if k is not less than offset+str.length()

20.13.24 public StringBuffer insert(int offset, char[] str)
throws NullPointerException,
IndexOutOfBoundsException

The characters of the array argument, taken in order, are inserted into this string buffer, increasing the length of the string buffer by the length of the argument. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

The overall effect is exactly as if the argument were converted to a string by the method String.valueOf (§20.12.39) and the characters of that string were then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset.

Note that while the StringBuffer class provides an append method that takes an offset, a character array, and two other arguments (§20.13.15), it does not currently provide an insert method that takes an offset, a character array, and two other arguments.

20.13.25 public StringBuffer insert(int offset, boolean b)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.41) and the characters of that string are then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.26 public StringBuffer insert(int offset, char c)
throws IndexOutOfBoundsException

The argument is inserted into the contents of this string buffer at the position indicated by offset, increasing the length of this string buffer by 1. The method ensureCapacity (§20.13.7) is first called with this new string buffer length as its argument. A reference to this StringBuffer object is returned.

The overall effect is exactly as if the argument were converted to a string by the method String.valueOf (§20.12.42) and the character in that string were then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset.

20.13.27 public StringBuffer insert(int offset, int i)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.43) and the characters of that string are then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.28 public StringBuffer insert(int offset, long l)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.44) and the characters of that string are inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.29 public StringBuffer insert(int offset, float f)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.45) and the characters of that string are then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.30 public StringBuffer insert(int offset, double d)
throws IndexOutOfBoundsException

The argument is converted to a string as if by the method String.valueOf (§20.12.46) and the characters of that string are then inserted (§20.13.23) into this StringBuffer object at the position indicated by offset. A reference to this StringBuffer object is returned.

20.13.31 public StringBuffer reverse()

The character sequence contained in this StringBuffer object is replaced by the reverse of that sequence. A reference to this StringBuffer object is returned.

Let n be the length of the old character sequence, the one contained in the string buffer just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.


20.14 The Class java.lang.ClassLoader

A class loader is an object that is responsible for loading classes. Given the name of a class, it should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

Every Class object contains a reference to the ClassLoader that defined it (§20.3.7). Whenever executable Java code needs to use a class that has not yet been loaded, the loadClass method is invoked for the class loader of the class containing the code in question.

Class objects for array classes are not created by class loaders, but are created automatically as required by the Java runtime. The class loader for an array class, as returned by the getClassLoader method of class Class (§20.3.7), is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader.

Class loaders may typically be used by security managers (§20.17) to indicate security domains: two classes may considered to be "friendly" or "related" to each other only if they were defined by the same class loader.

public abstract class ClassLoader {
    protected ClassLoader()

        throws SecurityException;
    protected abstract Class loadClass(String name,
              boolean resolve)

        throws ClassNotFoundException;
    protected final Class defineClass(byte data[],
              int offset, int length)

        throws NullPointerException, IndexOutOfBoundsException,
            ClassFormatError;
    protected final void resolveClass(Class c);
    protected final Class findSystemClass(String name)

        throws ClassNotFoundException;
}

20.14.1 protected ClassLoader() throws SecurityException

This constructor is invoked for every newly created class loader. Because the class ClassLoader is abstract, it is not possible to create a new instance of the class ClassLoader itself; however, every constructor for a subclass of ClassLoader necessarily invokes this constructor, explicitly or implicitly, directly or indirectly.

All this constructor does is to enforce a security check: if there is a security manager, its checkCreateClassLoader method (§20.17.10) is called.

20.14.2 protected abstract Class loadClass(String name,
boolean link)
throws ClassNotFoundException

Every subclass of ClassLoader that is not itself abstract must provide an implementation of the method loadClass.

The general contract of loadClass is that, given the name of a class, it either returns the Class object for the class or throws a ClassNotFoundException.

If a Class object is to be returned and link is true, then the Class object should be linked (§12.3, §20.14.4) before it is returned.

In most cases, it is wise for a subclass of ClassLoader (§20.14) to implement the loadClass method as a synchronized method.

20.14.3 protected final Class defineClass(byte data[],
int offset, int length)
throws NullPointerException, IndexOutOfBoundsException, ClassFormatError

This method may be used by a class loader to define a new class.

The bytes in the array data in positions offset through offset+length-1 should have the format of a valid class file as defined by the Java Virtual Machine Specification.

If data is null, then a NullPointerException is thrown.

An IndexOutOfBoundsException is thrown if any of the following are true:

  • offset is negative
  • length is negative
  • offset+length is greater than data.length

If the indicated bytes of data do not constitute a valid class definition, then a ClassFormatError is thrown. Otherwise, this method creates and returns a Class object as described by the data bytes

20.14.4 protected final void resolveClass(Class c)
throws NullPointerException

This (misleadingly named) method may be used by a class loader to link (§12.3, §20.14.4) a class.

If c is null, then a NullPointerException is thrown.

If the Class object c has already been linked, then this method simply returns.

Otherwise, the class is linked as described in §12.3.

20.14.5 protected final Class findSystemClass(String name)
throws ClassNotFoundException

This method may be used by a class loader to locate a class that has no class loader. This includes built-in classes such as java.lang.Object, as well as classes that the host implementation may keep in, for example, a local file system.

Given the name of a class, this method, like the loadClass method, either returns the Class object for the class or throws a ClassNotFoundException.


20.15 The Class java.lang.Process

The method exec (§20.16.3) of class Runtime returns a reference to a Process object. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

Dropping the last reference to a Process instance, thus allowing the Process object to be reclaimed, does not automatically kill the associated process.

There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object.

public abstract class Process {
    public abstract OutputStream getOutputStream();
    public abstract InputStream getInputStream();
    public abstract InputStream getErrorStream();
    public abstract int waitFor()

        throws InterruptedException;
    public abstract int exitValue()

        throws IllegalThreadStateException;
    public abstract void destroy();
}

20.15.1 public abstract OutputStream getOutputStream()

This method returns an OutputStream. Output to the stream is piped into the standard input stream of the process represented by this Process object.

Implementation note: It is a good idea for the output stream to be buffered.

20.15.2 public abstract InputStream getInputStream()

This method returns an InputStream. The stream obtains data piped from the standard output stream of the process represented by this Process object.

Implementation note: It is a good idea for the input stream to be buffered.

20.15.3 public abstract InputStream getErrorStream()

This method returns an InputStream. The stream obtains data piped from the error output stream of the process represented by this Process object.

Implementation note: It is a good idea for the input stream to be buffered.

20.15.4 public abstract int waitFor()
throws InterruptedException

This method causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. Then the exit value of the process is returned. By convention, the value 0 indicates normal termination.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.15.5 public abstract int exitValue()
throws IllegalThreadStateException

If the process represented by this Process object has not yet terminated, then an IllegalThreadStateException is thrown. Otherwise, the exit value of the process is returned. By convention, the value 0 indicates normal termination.

20.15.6 public abstract void destroy()

The process represented by this Process object is forcibly terminated.

It was my hint to speak—such was the process.
—William Shakespeare, Othello, Act I, scene iii


20.16 The Class java.lang.Runtime

public class Runtime {
    public static Runtime getRuntime();
    public void exit(int status);
    public Process exec(String command)

        throws IOException, SecurityException;
    public Process exec(String command, String envp[])

        throws IOException, SecurityException;
    public Process exec(String cmdarray[])

        throws IOException, SecurityException;
    public Process exec(String cmdarray[], String envp[])

        throws IOException, SecurityException;
    public long totalMemory();
    public long freeMemory();
    public void gc();
    public void runFinalization();
    public void traceInstructions(boolean on);
    public void traceMethodCalls(boolean on);
    public void load(String filename)
        throws SecurityException, UnsatisfiedLinkError;
    public void loadLibrary(String libname)
        throws SecurityException, UnsatisfiedLinkError;
    public InputStream getLocalizedInputStream(InputStream in);
    public OutputStream

        getLocalizedOutputStream(OutputStream out);
}

20.16.1 public static Runtime getRuntime()

This method returns the current Runtime object. Most of the methods of class Runtime are instance methods and must be invoked with respect to the current runtime object.

20.16.2 public void exit(int status)
throws SecurityException

First, if there is a security manager, its checkExit method (§20.17.13) is called with the status value as its argument.

This method terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method never returns normally.

See also the method exit (§20.18.11) of class System, which is the conventional and convenient means of invoking this method.

20.16.3 public Process exec(String command)
throws IOException, SecurityException,
IndexOutOfBoundsException

The command argument is parsed into tokens and then executed as a command in a separate process. The token parsing is done by a StringTokenizer (§21.10) created by the call:

new StringTokenizer(command)

with no further modification of the character categories.

This method behaves exactly as if it performs the call:

exec(command, null)

See §20.16.4.

20.16.4 public Process exec(String command, String envp[])
throws IOException, SecurityException,
IndexOutOfBoundsException

The command argument is parsed into tokens and then executed as a command in a separate process with an environment specified by envp. The token parsing is done by a StringTokenizer (§21.10) created by the call:

new StringTokenizer(command)

with no further modification of the character categories.

This method breaks the command string into tokens and creates a new array cmdarray containing the tokens in the order that they were produced by the string tokenizer; it then behaves exactly as if it performs the call:

exec(cmdarray, envp)

See §20.16.6.

20.16.5 public Process exec(String cmdarray[])
throws IOException, SecurityException,
NullPointerException, IndexOutOfBoundsException

The command specified by the tokens in cmdarray is executed as a command in a separate process.

This method behaves exactly as if it performs the call:

exec(cmdarray, null)

See §20.16.6.

20.16.6 public Process exec(String cmdarray[], String envp[])
throws IOException, SecurityException,
NullPointerException, IndexOutOfBoundsException

First, if there is a security manager, its checkExec method (§20.17.14) is called with the first component of the array cmdarray as its argument.

If cmdarray is null, a NullPointerException is thrown. If cmdarray is an empty array (has length 0), an IndexOutOfBoundsException is thrown.

Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing an "environment" that defines system properties, this method creates a new process in which to execute the specified command and returns a Process object (§20.15) representing the new process.

20.16.7 public long totalMemory()

The total amount of memory currently available for current and future created objects, measured in bytes, is returned. The value returned by this method may vary over time, depending on the host environment.

Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

20.16.8 public long freeMemory()

An approximation to the total amount of memory currently available for future created objects, measured in bytes, is returned. This value is always less than the current value returned by the totalMemory method. Calling the gc method may increase the value returned by freeMemory.

20.16.9 public void gc()

Calling this method suggests that the Java Virtual Machine expend effort toward recycling discarded objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to recycle all discarded objects. (The name gc stands for "garbage collector.")

The Java runtime system will perform this recycling process automatically as needed, in a separate thread, if the gc method is not invoked explicitly.

See also the method gc (§20.18.12) of class System, which is the conventional and convenient means of invoking this method.

20.16.10 public void runFinalization()

Calling this method suggests that the Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

The Java runtime system will perform the finalization process automatically as needed, in a separate thread, if the runFinalization method is not invoked explicitly.

See also the method runFinalization (§20.18.13) of class System, which is the conventional and convenient means of invoking this method.

20.16.11 public void traceInstructions(boolean on)

Calling this method with argument true suggests that the Java Virtual Machine emit debugging information for every instruction it executes. The format of this information, and the file or other output stream to which it is emitted, depends on the host environment.

Calling this method with argument false suggests that the Java Virtual Machine cease emitting per-instruction debugging information.

20.16.12 public void traceMethodCalls(boolean on)

Calling this method with argument true suggests that the Java Virtual Machine emit debugging information for every method call it executes. The format of this information, and the file or other output stream to which it is emitted, depends on the host environment.

Calling this method with argument false suggests that the Java Virtual Machine cease emitting per-call debugging information.

20.16.13 public void loadLibrary(String libname)

First, if there is a security manager, its checkLink method (§20.17.17) is called with the libname as its argument.

A file containing native code is loaded from the local file system from a place where library files are conventionally obtained. The details of this process are implementation-dependent.

See also the method loadLibrary (§20.18.15) of class System, which is the conventional and convenient means of invoking this method. If native methods are to be used in the implementation of a class, a standard strategy is to put the native code in a library file (call it LibFile) and then to put a static initializer:

static { System.loadLibrary("LibFile"); }

within the class declaration. When the class is loaded and initialized (§12.4), the necessary native code implementation for the native methods will then be loaded as well.

20.16.14 public void load(String filename)

First, if there is a security manager, its checkLink method (§20.17.17) is called with the filename as its argument.

This is similar to the method loadLibrary (§20.16.13), but accepts a general file name as an argument rather than just a library name, allowing any file of native code to be loaded.

See also the method load (§20.18.14) of class System, which is the conventional and convenient means of invoking this method.

20.16.15 public InputStream
getLocalizedInputStream(InputStream in)

This method takes an InputStream (§22.3) and returns an InputStream equivalent to the argument in all respects except that it is localized: as data is read from the stream, it is automatically converted from the local format to Unicode. If the argument is already a localized stream, then it will be returned as the result.

20.16.16 public OutputStream
getLocalizedOutputStream(OutputStream out)

This method takes an OutputStream (§22.15) and returns an OutputStream equivalent to the argument in all respects except that it is localized: as data is written to the stream, it is automatically converted from Unicode to the local format. If the argument is already a localized stream, then it will be returned as the result.


20.17 The Class java.lang.SecurityManager

public abstract class SecurityManager {
    protected boolean inCheck;
    protected SecurityManager()

        throws SecurityException;
    protected Class[] getClassContext();
    protected int classDepth(String name);
    protected boolean inClass(String name);
    protected ClassLoader currentClassLoader();
    protected int classLoaderDepth();
    protected boolean inClassLoader();
    public boolean getInCheck();
    public void checkCreateClassLoader()

        throws SecurityException;
    public void checkAccess(Thread t)

        throws SecurityException;
    public void checkAccess(ThreadGroup g)

        throws SecurityException;
    public void checkExit(int status)

        throws SecurityException;
    public void checkExec(String cmd)

        throws SecurityException;
    public void checkPropertiesAccess()

        throws SecurityException;
    public void checkPropertyAccess(String key)

        throws SecurityException;
    public void checkLink(String libname)

        throws SecurityException;
    public void checkRead(int fd)

        throws SecurityException;
    public void checkRead(String file)

        throws SecurityException;
    public void checkWrite(int fd)

        throws SecurityException;
    public void checkWrite(String file)

        throws SecurityException;
    public void checkDelete(String file)

        throws SecurityException;
    public void checkConnect(String host, int port)

        throws SecurityException;
    public void checkListen(int port)

        throws SecurityException;
    public void checkAccept(String host, int port)

        throws SecurityException;
    public void checkSetFactory()

        throws SecurityException;
    public boolean checkTopLevelWindow()

        throws SecurityException;
    public void checkPackageAccess(String packageName)

        throws SecurityException;
    public void checkPackageDefinition(String packageName)

        throws SecurityException;
}

A running Java program may have a security manager, which is an instance of class SecurityManager. The current security manager is the one returned by the method invocation System.getSecurityManager() (§20.18.4).

The SecurityManager class contains a large number of methods whose names begin with "check". They are called by various methods throughout the Java libraries before those methods perform certain sensitive operations. The invocation of such a check method typically looks like this:

SecurityManager security = System.getSecurityManager();
if (security != null) {
    security.checkXXX(arguments);
}

The security manager is thereby given an opportunity to prevent completion of the operation by throwing an exception. The usual convention is that a security manager checking routine simply returns if the operation is permitted, or throws a SecurityException if the operation is not permitted. In one case, namely checkTopLevelWindow (§20.17.27), the checking routine must return a boolean value to indicate one of two levels of permission.

20.17.1 protected boolean inCheck = false;

By convention, this field should be assigned the value true whenever a security check is in progress. This matters when one of the checking routines needs to call outside code to do its work. Outside code can then use the method getInCheck (§20.17.9) to test the status of this flag.

20.17.2 protected SecurityManager()
throws SecurityException

This constructor checks to see whether a security manager has already been installed (§20.18.5); if so, creation of another security manager is not permitted, and so a SecurityException is thrown.

20.17.3 protected Class[] getClassContext()

This utility method for security managers scans the execution stack for the current thread and returns an array with one component for each stack frame. The component at position 0 corresponds to the top of the stack. If a component is a Class object, then the corresponding stack frame is for an invocation of a method of the class represented by that Class object.

20.17.4 protected int classDepth(String name)

This utility method for security managers searches the execution stack for the current thread to find the most recently invoked method whose execution has not yet completed and whose class has name as its fully qualified name. If such a method is found, its distance from the top of the stack is returned as a nonnegative integer; otherwise, -1 is returned.

20.17.5 protected boolean inClass(String name)

This utility method for security managers searches the execution stack for the current thread to find the most recently invoked method whose execution has not yet completed and whose class has name as its fully qualified name. If such a method is found, true is returned; otherwise, false is returned.

20.17.6 protected ClassLoader currentClassLoader()

This utility method for security managers searches the execution stack for the current thread to find the most recently invoked method whose execution has not yet completed and whose class was created by a class loader (§20.14). If such a method is found, a reference to the ClassLoader object for its class is returned; otherwise, null is returned.

20.17.7 protected int classLoaderDepth()

This utility method for security managers searches the execution stack for the current thread to find the most recently invoked method whose execution has not yet completed and whose class was created by a class loader (§20.14). If such a method is found, its distance from the top of the stack is returned as a nonnegative integer; otherwise, -1 is returned.

20.17.8 protected boolean inClassLoader()

This utility method for security managers searches the execution stack for the current thread to find the most recently invoked method whose execution has not yet completed and whose class was created by a class loader (§20.14). If such a method is found, true is returned; otherwise false is returned.

20.17.9 public boolean getInCheck()

The value of the inCheck field (§20.17.1) is returned.

20.17.10 public void checkCreateClassLoader()
throws SecurityException

The general contract of this method is that it should throw a SecurityException if creation of a class loader is not permitted.

This method is invoked for the current security manager (§20.18.4) by the constructor for class ClassLoader (§20.14.1).

The checkCreateClassLoader method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a class loader creation operation is to be permitted with a security manager installed.

20.17.11 public void checkAccess(Thread t)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if an operation that would modify the thread t is not permitted.

This method is invoked for the current security manager (§20.18.4) by method checkAccess (§20.20.12) of class Thread.

The checkAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a thread modification operation is to be permitted with a security manager installed.

20.17.12 public void checkAccess(ThreadGroup g)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if an operation that would modify the thread group g is not permitted.

This method is invoked for the current security manager (§20.18.4) by method checkAccess (§20.21.4) of class ThreadGroup.

The checkAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a thread group modification operation is to be permitted with a security manager installed.

20.17.13 public void checkExit(int status)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if an exit operation that would terminate the running Java Virtual Machine is not permitted.

This method is invoked for the current security manager (§20.18.4) by method exit (§20.16.2) of class Runtime.

The checkExit method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if the exit operation is to be permitted with a security manager installed.

20.17.14 public void checkExec(String cmd)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if a command exec operation is not permitted. The argument cmd is the name of the command to be executed.

This method is invoked for the current security manager (§20.18.4) by method exec (§20.16.6) of class Runtime.

The checkExec method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a command exec operation is to be permitted with a security manager installed.

20.17.15 public void checkPropertiesAccess()
throws SecurityException

The general contract of this method is that it should throw a SecurityException if getting or setting the system properties data structure is not permitted.

This method is invoked for the current security manager (§20.18.4) by the methods getProperties (§20.18.7) and setProperties (§20.18.8) of class System.

The checkPropertiesAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a properties access operation is to be permitted with a security manager installed.

20.17.16 public void checkPropertyAccess(String key)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if getting the value of the system property named by the key is not permitted.

This method is invoked for the current security manager (§20.18.4) by the methods getProperty of one argument (§20.18.9) and getProperty of two arguments (§20.18.10) of class System.

The checkPropertyAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if accessing the value of a system property is to be permitted with a security manager installed.

20.17.17 public void checkLink(String libname)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if dynamic linking of the specified library code file is not permitted. The argument may be a simple library name or a complete file name.

This method is invoked for the current security manager (§20.18.4) by methods load (§20.16.14) and loadLibrary (§20.16.13) of class Runtime.

The checkLink method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a dynamic code linking operation is to be permitted with a security manager installed.

20.17.18 public void checkRead(int fd)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if creating an input stream using the specified file descriptor is not permitted.

This method is invoked for the current security manager (§20.18.4) by one constructor for java.io.FileInputStream (§22.4.3).

The checkRead method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if creating an input stream from an existing file descriptor is to be permitted with a security manager installed.

20.17.19 public void checkRead(String file)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if reading the specified file or directory, or examining associated file-system information, or testing for its existence, is not permitted.

This method is invoked for the current security manager (§20.18.4) by two constructors for java.io.FileInputStream (§22.4.1, §22.4.2); by two constructors for java.io.RandomAccessFile (§22.23.1, §22.23.2); and by methods exists (§22.24.16), canRead (§22.24.17), isFile (§22.24.19), isDirectory (§22.24.20), lastModified (§22.24.21), length (§22.24.22), list with no arguments (§22.24.25), and list with one argument (§22.24.26) of the class java.io.File.

The checkRead method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if read access to a file is to be permitted with a security manager installed.

20.17.20 public void checkWrite(int fd)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if creating an output stream using the specified file descriptor is not permitted.

This method is invoked for the current security manager (§20.18.4) by one constructor for java.io.FileOutputStream (§22.16.3).

The checkWrite method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if creating an output stream from an existing file descriptor is to be permitted with a security manager installed.

20.17.21 public void checkWrite(String file)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if writing, modifying, creating (for output), or renaming the specified file or directory is not permitted.

This method is invoked for the current security manager (§20.18.4) by two constructors for java.io.FileOutputStream (§22.16.1, §22.16.2); by two constructors for java.io.RandomAccessFile (§22.23.1, §22.23.2); and by methods canWrite (§22.24.18), mkdir (§22.24.23), and renameTo (§22.24.27) of class java.io.File.

The checkWrite method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if write access to a file is to be permitted with a security manager installed.

20.17.22 public void checkDelete(String file)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if deleting the specified file is not permitted.

This method is invoked for the current security manager (§20.18.4) by method delete (§22.24.28) of class java.io.File.

The checkDelete method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a file deletion operation is to be permitted with a security manager installed.

20.17.23 public void checkConnect(String host, int port)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if connecting to the indicated port of the indicated network host is not permitted.

This method is invoked for the current security manager (§20.18.4) by two constructors for class java.net.Socket, methods send and receive of class java.net.DatagramSocket, and methods getByName and getAllByName of class java.net.InetAddress. (These classes are not documented in this specification. See The Java Application Programming Interface.)

The checkConnect method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a network connection is to be permitted with a security manager installed.

20.17.24 public void checkListen(int port)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if listening to the specified local network port is not permitted.

This method is invoked for the current security manager (§20.18.4) by the constructor of one argument for class java.net.DatagramSocket and by the constructors for class java.net.ServerSocket. (These classes are not documented in this specification. See The Java Application Programming Interface.)

The checkListen method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if listening to a local network port is to be permitted with a security manager installed.

20.17.25 public void checkAccept(String host, int port)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if accepting a connection from the indicated port of the indicated network host is not permitted.

This method is invoked for the current security manager (§20.18.4) by method accept of class java.net.ServerSocket. (This class is not documented in this specification. See The Java Application Programming Interface.)

The checkAccept method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if accepting a network connection is to be permitted with a security manager installed.

20.17.26 public void checkSetFactory()
throws SecurityException

The general contract of this method is that it should throw a SecurityException if installing a "factory" for a socket, server socket, URL, or URL connection is not permitted.

This method is invoked for the current security manager (§20.18.4) by:

    method setSocketFactory of class java.net.ServerSocket
    method setSocketImplFactory of class java.net.Socket
    method setURLStreamHandlerFactory of class java.net.URL
    method setContentHandlerFactory of class java.net.URLConnection

(These classes are not documented in this specification. See The Java Application Programming Interface.)

The checkSetFactory method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if a factory installation operation is to be permitted with a security manager installed.

20.17.27 public boolean checkTopLevelWindow()
throws SecurityException

The general contract of this method is that it should throw a SecurityException if creation of a top-level window is not permitted. If creation of a top-level window is permitted, then this method should return false if the window ought to bear a clear warning that it is a window for an executable applet. A returned value of true means that the security manager places no restriction on window creation.

This method is invoked for the current security manager (§20.18.4) by the constructors for class java.awt.Window. (This class is not documented in this specification. See The Java Application Programming Interface.)

The checkTopLevelWindow method defined by class SecurityManager always returns false. A subclass must override this method if a window creation operation is to be unrestricted or forbidden with a security manager installed.

20.17.28 public void checkPackageAccess(String packageName)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if the current applet is not permitted to access the package named by the argument. This method is intended for use by Java-capable web browsers.

The checkPackageAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if package access by an applet is to be permitted with a security manager installed.

20.17.29 public void checkPackageDefinition(String packageName)
throws SecurityException

The general contract of this method is that it should throw a SecurityException if the current applet is not permitted to define a class (or interface) in the package named by the argument. This method is intended for use by Java-capable web browsers.

The checkPackageAccess method defined by class SecurityManager always throws a SecurityException. A subclass must override this method if class definition by an applet is to be permitted with a security manager installed.


20.18 The Class java.lang.System

The System class contains a number of useful class variables and class methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, output, and error output streams; access to externally defined "properties"; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

public final class System {
    public static InputStream in;
    public static PrintStream out;
    public static PrintStream err;
    public static SecurityManager getSecurityManager();
    public static void setSecurityManager(SecurityManager s)
        throws SecurityException;
    public static long currentTimeMillis();
    public static Properties getProperties()
        throws SecurityException;
    public static void setProperties(Properties props)
        throws SecurityException;
    public static String getProperty(String key)
        throws SecurityException;
    public static String getProperty(String key, String default)
        throws SecurityException;
    public static void exit(int status) throws SecurityException;
    public static void gc();
    public static void runFinalization();
    public static void load(String filename)
        throws SecurityException, UnsatisfiedLinkError;
    public static void loadLibrary(String libname)
        throws SecurityException, UnsatisfiedLinkError;
    public static void arraycopy(Object src, int srcOffset,
            Object dst, int dstOffset, int length)

        throws NullPointerException,
            ArrayStoreException, IndexOutOfBoundsException;
}

20.18.1 public static InputStream in;

The initial value of this variable is a "standard" input stream, already open and ready to supply input data. Typically, this corresponds to keyboard input or another input source specified by the host environment or user. Note that this field is not final, so its value may be updated if necessary.

20.18.2 public static PrintStream out;

The initial value of this variable is a "standard" output stream, already open and ready to accept output data. Typically, this corresponds to display output or another output destination specified by the host environment or user. Note that this field is not final, so its value may be updated if necessary.

For simple Java applications, a typical way to write a line of output data is:

System.out.println(data)

See the println method of class PrintStream (§22.22).

20.18.3 public static PrintStream err;

The initial value of this variable is a "standard" error output stream, already open and ready to accept output data. Typically, this corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out, has been redirected to a file or other destination that is typically not continuously monitored. Note that this field is not final, so its value may be updated if necessary.

20.18.4 public static SecurityManager getSecurityManager()

If a security manager has already been established for the currently running Java system, a reference to that security manager is returned. Otherwise, null is returned.

20.18.5 public static void setSecurityManager(SecurityManager s)
throws SecurityException

If a security manager has already been established for the currently running Java system, a SecurityException is thrown. Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns normally.

20.18.6 public static long currentTimeMillis()

Returns the difference, measured in milliseconds, between the current time and the standard base time known as "the epoch," 00:00:00 GMT on January 1, 1970. See the description of the class Date (§21.3) for a discussion of slight discrepancies that may arise between "computer time" and UTC (Coordinated Universal Time).

20.18.7 public static Properties getProperties()
throws SecurityException

First, if there is a security manager, its checkPropertiesAccess method (§20.17.15) is called with no arguments.

The current set of system properties for use by the getProperty method is returned as a Properties object (§21.6). If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties always includes values for the following keys:

Key							Description of associated value
java.version							Java version number
java.vendor							Java-vendor-specific string
java.vendor.url							Java vendor URL
java.home							Java installation directory
java.class.version							Java class format version number
java.class.path							Java classpath
os.name							Operating system name
os.arch							Operating system architecture
os.version							Operating system version
file.separator							File separator (/ on UNIX)
path.separator							Path separator (: on UNIX)
line.separator							Line separator (\n on UNIX)
user.name							User account name
user.home							User home directory
user.dir							User's current working directory

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty operation (§20.18.9).

20.18.8 public static void setProperties(Properties props)
throws SecurityException

First, if there is a security manager, its checkPropertiesAccess method (§20.17.15) is called with no arguments.

The argument becomes the current set of system properties for use by the getProperty method. See the class Properties (§21.6). If the argument is null, then the current set of system properties is forgotten.

20.18.9 public static String getProperty(String key)
throws SecurityException

First, if there is a security manager, its checkPropertyAccess method (§20.17.16) is called with the key as its argument.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method (§20.18.7).

The system property value associated with the specified key string is returned. If there is no property with that key, then null is returned.

20.18.10 public static String getProperty(String key,
String default)
throws SecurityException

First, if there is a security manager, its checkPropertyAccess method (§20.17.16) is called with the key as its argument.

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method (§20.18.7).

The system property value associated with the specified key string is returned. If there is no property with that key, then the argument default is returned.

20.18.11 public static void exit(int status)
throws SecurityException

This method terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

For a more complete description, see the exit method of class Runtime (§20.16.2).

20.18.12 public static void gc()

Calling this method suggests that the Java Virtual Machine expend effort toward recycling discarded objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to recycle all discarded objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

For a more complete description, see the gc method of class Runtime (§20.16.9).

20.18.13 public static void runFinalization()

Calling this method suggests that the Java Virtual Machine expend effort toward running the finalization methods of objects that have been found to be discarded but whose finalization methods have not yet been run. When control returns from the method call, the Java Virtual Machine has made a best effort to complete all outstanding finalizations.

The call System.runFinalization() is effectively equivalent to the call:

Runtime.getRuntime().runFinalization()

For a more complete description, see the runFinalization method of class Runtime (§20.16.10).

20.18.14 public static void load(String filename)
throws SecurityException, UnsatisfiedLinkError

This method loads a code file with the specified file name from the local file system.

The call System.load(name) is effectively equivalent to the call:

Runtime.getRuntime().load(name)

For a more complete description, see the load method of class Runtime (§20.16.14).

20.18.15 public static void loadLibrary(String libname)
throws SecurityException, UnsatisfiedLinkError

This method loads a library code file with the specified library name from the local file system.

The call System.loadLibrary(name) is effectively equivalent to the call

Runtime.getRuntime().loadLibrary(name)

For a more complete description, see the loadLibrary method of class Runtime (§20.16.13).

20.18.16 public static void arraycopy(Object src, int srcOffset,
Object dst, int dstOffset, int length)
throws NullPointerException, ArrayStoreException,
IndexOutOfBoundsException

A subsequence of array components is copied from the source array referenced by src to the destination array referenced by dst. The number of components copied is equal to the length argument. The components at the positions srcOffset through srcOffset+length-1 in the source array are copied into the positions dstOffset through dstOffset+length-1, respectively, of the destination array.

If the src and dst arguments refer to the same array object, then copying is performed as if the components of the source array at positions srcOffset through srcOffset+length-1 were first copied to a temporary array of length length and then the contents of the temporary array were copied into positions dstOffset through dstOffset+length-1 of the destination array.

If dst is null, then a NullPointerException is thrown.

If src is null, then a NullPointerException is thrown and the destination array is not modified.

Otherwise, if any of the following is true, then an ArrayStoreException is thrown and the destination is not modified:

  • The src argument refers to an object that is not an array.
  • The dst argument refers to an object that is not an array.
  • The src argument and dst argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array of primitive component type and the dst argument refers to an array of reference component type.
  • The src argument refers to an array of reference component type and the dst argument refers to an array of primitive component type.

Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:

  • The srcOffset argument is negative.
  • The dstOffset argument is negative.
  • The length argument is negative.
  • srcOffset+length is greater than src.length, the length of the src array.
  • dstOffset+length is greater than dst.length, the length of the dst array.

Otherwise, if the actual value of any component of the source array from position srcOffset through srcOffset+length-1 cannot be converted to the component type of the destination array by assignment conversion, then an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcOffset+k] cannot be converted to the component type of the destination array. When the exception is thrown, the source array components from positions srcOffset through srcOffset+k-1 have been copied to destination array positions dstOffset through dstOffset+k-1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)


20.19 The Interface java.lang.Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a new thread. All that is required of such a class is that it implement a method of no arguments called run.

public interface Runnable {
    public abstract void run();
}

20.19.1 public abstract void run()

The general contract of the method run is that it may take any action whatsoever.

If an object implementing interface Runnable is used to create a thread (§20.20), then starting the thread will (normally) lead to the invocation of the object's run method in that separately executing thread.


20.20 The Class java.lang.Thread

A thread is a single sequential flow of control. Thread objects allow multithreaded Java programming; a single Java Virtual Machine can execute many threads in an interleaved or concurrent manner.

In the method descriptions that follow, it is very important to distinguish among "the current thread" (the thread executing the method), "this Thread" (the object for which the method was invoked), and "this thread" (the thread that is represented by the Thread object for which the method was invoked).

public class Thread implements Runnable {
    public final static int MIN_PRIORITY = 1;
    public final static int MAX_PRIORITY = 10;
    public final static int NORM_PRIORITY = 5;
    public Thread();
    public Thread(String name);
    public Thread(Runnable target);
    public Thread(Runnable target, String name);
    public Thread(ThreadGroup group, String name)
        throws SecurityException, IllegalThreadStateException;
    public Thread(ThreadGroup group, Runnable target)
        throws SecurityException, IllegalThreadStateException;
    public Thread(ThreadGroup group, Runnable target,
            String name)
        throws SecurityException, IllegalThreadStateException;
    public String toString();
    public void checkAccess();
    public void run();
    public void start()
        throws IllegalThreadStateException;
    public final void stop()
        throws SecurityException;
    public final void stop(Throwable o)
        throws SecurityException;
    public final void suspend()
        throws SecurityException;
    public final void resume()
        throws SecurityException;
    public void destroy();
    public final boolean isAlive();
    public void interrupt();
    public static boolean interrupted();
    public boolean isInterrupted();
    public final String getName();
    public final void setName(String name)
        throws SecurityException;
    public final ThreadGroup getThreadGroup();
    public final int getPriority();
    public final void setPriority(int newPriority)
        throws SecurityException, IllegalArgumentException;
    public final boolean isDaemon();
    public final void setDaemon(boolean on)
        throws SecurityException;
    public int countStackFrames();
    public final void join()
        throws InterruptedException;
    public final void join(long millis)
        throws InterruptedException;
    public final void join(long millis, int nanos)
        throws InterruptedException;
    public void interrupt();
    public boolean isInterrupted();
    public static boolean interrupted();
    public static Thread currentThread();
    public static int activeCount();															// deprecated
    public static int enumerate(Thread tarray[]);															// deprecated
    public static void dumpStack();
    public static void yield();
    public static void sleep(long millis)

        throws InterruptedException;
    public static void sleep(long millis, int nanos)

        throws InterruptedException;
}

When a new Thread object is created, the thread it represents is not yet active. It is activated when some other thread calls the start method (§20.20.14) of the Thread object. This causes the thread represented by the Thread object to invoke the run method (§20.20.13) of the Thread object. The newly activated thread then remains alive until it stops because one of five things occurs:

  • The initial invocation of the run method by the newly activated thread completes normally through a normal return from the run method.
  • The initial invocation of the run method by the newly activated thread completes abruptly because an exception was thrown.
  • The thread invokes the stop method (§20.20.15) of the Thread object (and the security manager (§20.17.11) approves execution of the stop operation).
  • Some other thread invokes the stop method of the Thread object (and the security manager (§20.17.11) approves execution of the stop operation).
  • Some thread invokes the exit method (§20.16.2) of class Runtime (and the security manager (§20.17.13) approves execution of the exit operation); this stops every thread being run by the Java Virtual Machine that is running the thread that invokes the exit method.

As a thread dies, the notifyAll method (§20.1.10) is invoked for the Thread object that represents it; this fact is important for the proper operation of the join methods (§20.20.28, §20.20.29, §20.20.30). A thread is also removed from its thread group as it dies. Once a thread has been stopped, it is no longer alive and it cannot be restarted.

A thread that is alive can be suspended and resumed. A suspended thread is considered to be alive, but it performs no work, makes no progress, executes no virtual machine instructions. Resumption restores a thread to the state of active execution. A thread is suspended when it or another thread calls the suspend method (§20.20.17) of the Thread object that represents it (and the security manager (§20.17.11) approves execution of the suspend operation). A thread is resumed when another thread calls the resume method (§20.20.18) of the Thread object that represents it (and the security manager (§20.17.11) approves execution of the resume operation).

Every thread has a priority. When there is competition for processing resources, threads with higher priority are generally executed in preference to threads with lower priority. Such preference is not, however, a guarantee that the highest priority thread will always be running, and thread priorities cannot be used to implement mutual exclusion. When code running in some thread creates a new Thread object, the newly created thread has its priority initially set equal to the priority of the creating thread. But the priority of a thread T may be changed at any time if some thread invokes the setPriority method of the Thread object that represents T (and the security manager (§20.17.11) approves execution of the setPriority operation).

Each thread may or may not be marked as a daemon. When code running in some thread creates a new Thread object, the newly created thread is a daemon thread if and only if the creating thread is a daemon. But the daemonhood of a thread T may be changed before it is activated if some other thread invokes the setDaemon method of the Thread object that represents T (and the security manager (§20.17.11) approves execution of the setDaemon operation).

When a Java Virtual Machine starts up, there is usually a single non-daemon thread, which typically begins by invoking the method main of some designated class. The Java Virtual Machine continues to execute threads according to the thread execution model until all threads that are not daemon threads have stopped.

There are two ways to create a new thread of execution. One is to declare some class to be a subclass of Thread; this subclass should override the run method of class Thread. An instance of the subclass can then be created and started. For example, consider code for a thread whose job is to compute primes larger than a stated value:

class PrimeThread extends Thread {

    long minPrime;

    PrimeThread(long minPrime) {
        this.minPrime = minPrime;
    }

    public void run() {
         // compute primes larger than minPrime
        ...
    }

}

The following code would then create a thread and start it running:

PrimeThread p = new PrimeThread(143);
p.start();

The other way to create a thread is to is to declare some class to implement the Runnable interface, which also requires that the class implement the run method. An instance of the class can then be created, used to create a Thread, and started. The same example in this other style looks like this:

class PrimeRun implements Runnable {

    long minPrime;

    PrimeRun(long minPrime) {
        this.minPrime = minPrime;
    }

    public void run() {
         // compute primes larger than minPrime
        ...
    }

}

The following code would then create a thread and start it running:

PrimeRun p = new PrimeRun(143);
new Thread(p).start();

Every thread has a name, which is a String, for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

Every thread that has not yet been stopped belongs to a thread group (§20.21). A thread can always create a new thread in its own thread group. To create a thread in some other thread group requires the approval of the checkAccess method (§20.21.4) of that thread group, which forwards the decision to the security manager (§20.17.11).

20.20.1 public final static int MIN_PRIORITY = 1;

The constant value of this field is 1, the smallest allowed priority for a thread.

20.20.2 public final static int MAX_PRIORITY = 10;

The constant value of this field is 10, the largest allowed priority value for a thread.

20.20.3 public final static int NORM_PRIORITY = 5;

The constant value of this field is 5, the normal priority for a thread that is not a daemon.

20.20.4 public Thread()

This constructor initializes a newly created Thread object so that it has no separate run object, has a newly generated name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null, null, gname) (§20.20.10), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer.

20.20.5 public Thread(String name)

This constructor initializes a newly created Thread object so that it has no separate run object, has the specified name as its name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null, null, name) (§20.20.10).

20.20.6 public Thread(Runnable runObject)

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has a newly generated name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null, runObject, gname) (§20.20.10) where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n where n is an integer.

20.20.7 public Thread(Runnable runObject, String name)

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has the specified name as its name, and belongs to the same thread group as the thread that is creating the new thread.

This constructor has exactly the same effect as the explicit constructor call this(null, runObject, name) (§20.20.10).

20.20.8 public Thread(ThreadGroup group, String name)
throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments.

This constructor initializes a newly created Thread object so that it has no separate run object, has the specified name as its name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy (§20.21.11), then an IllegalThreadStateException is thrown.

This constructor has exactly the same effect as the explicit constructor call Thread(group, null, name) (§20.20.10).

20.20.9 public Thread(ThreadGroup group, Runnable runObject)
throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments.

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has a newly generated name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy (§20.21.11), then an IllegalThreadStateException is thrown.

This constructor has exactly the same effect as the explicit constructor call this(group, runObject, gname) (§20.20.10) where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n where n is an integer.

20.20.10 public Thread(ThreadGroup group, Runnable target,
String name)
throws SecurityException, IllegalThreadStateException

First, if group is not null, the checkAccess method (§20.21.4) of that thread group is called with no arguments; this may result in a SecurityException being thrown.

This constructor initializes a newly created Thread object so that it has the given runObject as its separate run object, has the specified name as its name, and belongs to the thread group referred to by group (but if group is null, then the new thread will belong to the same thread group as the thread that is creating the new thread).

If group is a ThreadGroup that has been destroyed by method destroy (§20.21.11), then an IllegalThreadStateException is thrown.

The priority of the newly created thread is set equal to the priority of the creating thread-that is, the currently running thread. The method setPriority (§20.20.23) may be used to change the priority to a new value.

The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is a daemon thread. The method setDaemon (§20.20.25) may be used to change whether or not a thread is a daemon.

20.20.11 public String toString()

The returned value is a concatenation of the following seven strings:

  • "Thread["
  • The current name of the thread (§20.20.19)
  • ","
  • The current priority of the thread (§20.20.22), as a decimal numeral
  • ","
  • The name (§20.21.5) of the thread group (§20.20.21) that contains this thread
  • "]"

All literal characters mentioned above are from the ACSII subset of Unicode.

Overrides the toString method of Object (§20.1.3).

20.20.12 public void checkAccess() throws SecurityException

If there is a security manager, its checkAccess method (§20.17.11) is called with this Thread object as its argument. This may result in a SecurityException being thrown in the current thread,.

This method is called by methods stop of no arguments (§20.20.15), stop of one argument (§20.20.16), suspend (§20.20.17), resume (§20.20.18), setName (§20.20.20), setPriority (§20.20.23), and setDaemon (§20.20.25).

20.20.13 public void run()

The general contract of this method is that it should perform the intended action of the thread.

The run method of class Thread simply calls the run method of the separate run object, if there is one; otherwise, it does nothing.

20.20.14 public void start()
throws IllegalThreadStateException

Invoking this method causes this thread to begin execution; this thread calls the run method of this Thread object. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the thread represented by this Thread object (which executes its run method).

20.20.15 public final void stop()
throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

This thread is forced to complete abnormally whatever it was doing and to throw a ThreadDeath object as an exception. For this purpose, this thread is resumed if it had been suspended, and is awakened if it had been asleep.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it will immediately terminate.

User code should not normally try to catch ThreadDeath unless some extraordinary cleanup operation is necessary (note that the process of throwing a ThreadDeath exception will cause finally clauses of try statements to be executed before the thread officially dies). If a catch clause does catch a ThreadDeath object, it is important to rethrow the object so that the thread will actually die. The top-level error handler that reacts to otherwise uncaught exceptions will not print a message or otherwise signal or notify the user if the uncaught exception is an instance of ThreadDeath.

20.20.16 public final void stop(Throwable thr)
throws SecurityException, NullPointerException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the argument thr is null, then a NullPointerException is thrown (in the current thread).

This thread is forced to complete abnormally whatever it was doing and to throw the Throwable object thr as an exception. For this purpose, this thread is resumed if it had been suspended, and is awakened if it had been asleep. This is an unusual action to take; normally, the stop method that takes no arguments (§20.20.15) should be used.

It is permitted to stop a thread that has not yet been started. If the thread is eventually started, it will immediately terminate.

20.20.17 public final void suspend()
throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive (§20.20.26), it is suspended and makes no further progress unless and until it is resumed. It is permitted to suspend a thread that is already in a suspended state; it remains suspended. Suspensions are not tallied; even if a thread is suspended more than once, only one call to resume is required to resume it.

20.20.18 public final void resume()
throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive (§20.20.26) but suspended, it is resumed and is permitted to make progress in its execution. It is permitted to resume a thread that has never been suspended or has already been resumed; it continues to make progress in its execution. Resumptions are not tallied; even if a thread is resumed more than once, only one call to suspend is required to suspend it.

20.20.19 public final String getName()

The current name of this Thread object is returned as a String.

20.20.20 public final void setName(String name)
throws SecurityException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

The name of this Thread object is changed to be equal to the argument name.

20.20.21 public final ThreadGroup getThreadGroup()

If this thread is alive, this method returns a reference to the ThreadGroup object that represents the thread group to which this thread belongs. If this thread has died (has been stopped), this method returns null.

20.20.22 public final int getPriority()

The current priority of this Thread object is returned.

20.20.23 public final void setPriority(int newPriority)
throws SecurityException, IllegalArgumentException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If the newPriority argument is less than MIN_PRIORITY (§20.20.1) or greater than MAX_PRIORITY (§20.20.2), then an IllegalArgumentException is thrown.

Otherwise, the priority of this Thread object is set to the smaller of the specified newPriority and the maximum permitted priority (§20.21.12) of the thread's thread group (§20.20.21).

20.20.24 public final boolean isDaemon()

The result is true if and only if this thread is marked as a daemon thread.

20.20.25 public final void setDaemon(boolean on)
throws SecurityException, IllegalThreadStateException

First, the checkAccess method (§20.20.12) of this Thread object is called with no arguments. This may result in throwing a SecurityException (in the current thread).

If this thread is alive, an IllegalThreadStateException is thrown. Otherwise, this thread is marked as being a daemon thread if the argument is true, and as not being a daemon thread if the argument is false.

20.20.26 public final boolean isAlive()

The result is true if and only if this thread is alive (it has been started and has not yet died).

20.20.27 public int countStackFrames()

This method returns the number of Java Virtual Machine stack frames currently active for this thread.

20.20.28 public final void join() throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.6) of class Object) until this thread is no longer alive.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.29 public final void join(long millis)
throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.7) of class Object) until either this thread is no longer alive or a certain amount of real time has elapsed, more or less.

The amount of real time, measured in milliseconds, is given by millis. If millis is zero, however, then real time is not taken into consideration and this method simply waits until this thread is no longer alive.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.30 public final void join(long millis, int nanos)
throws InterruptedException

This method causes the current thread to wait (using the wait method (§20.1.8) of class Object) until either this thread is no longer alive or a certain amount of real time has elapsed, more or less.

The amount of real time, measured in nanoseconds, is given by:

1000000*millis+nanos

In all other respects, this method does the same thing as the method join of one argument (§20.20.29). In particular, join(0, 0) means the same thing as join(0).

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.

20.20.31 public void interrupt()

An interrupt request is posted for this thread. This thread does not necessarily react immediately to the interrupt, however. If this thread is waiting, it is awakened and it then throws an InterruptedException.

[This method is scheduled for introduction in Java version 1.1.]

20.20.32 public boolean isInterrupted()

The result is true if and only if an interrupt request has been posted for this thread.

[This method is scheduled for introduction in Java version 1.1.]

20.20.33 public static boolean interrupted()

The result is true if and only if an interrupt request has been posted for the current thread.

[This method is scheduled for introduction in Java version 1.1.]

20.20.34 public static Thread currentThread()

The Thread object that represents the current thread is returned.

20.20.35 public static int activeCount()

This method returns the number of active threads in the thread group to which the current thread belongs. This count includes threads in subgroups of that thread group. This is the same as the value of the expression:

Threads.currentThread().getThreadGroup().activeCount()

[This method is deprecated for use in new code after Java version 1.1 becomes available. Instead, an expression equivalent to:

Threads.currentThread().getThreadGroup().allThreadsCount()

should be used. See the method allThreadsCount of class ThreadGroup.]

20.20.36 public static int enumerate(Thread tarray[])

The active threads in the thread group to which the current thread belongs, including threads in subgroups of that thread group, are enumerated and their Thread objects are put into the array tarray. The number of threads actually put into the array is returned. Call this value n; then the threads have been put into elements 0 through n-1 of tarray. If the number of threads exceeds the length of tarray, then some of the threads, tarray.length of them, are chosen arbitrarily and used to fill the array tarray.

[This method is deprecated for use in new code after Java version 1.1 becomes available. Instead, an expression equivalent to:

Threads.currentThread().getThreadGroup().allThreads()

should be used. See the method allThreads of class ThreadGroup.]

20.20.37 public static void dumpStack()

This is a utility method that makes it easy to print a stack dump for the current thread. It is equivalent in effect to:

new Exception("Stack trace").printStackTrace()

See the printStackTrace method (§20.22.6) of class Throwable.

20.20.38 public static void yield()

This method causes the current thread to yield, allowing the thread scheduler to choose another runnable thread for execution.

20.20.39 public static void sleep(long millis)
throws InterruptedException

This method causes the current thread to yield and not to be scheduled for further execution until a certain amount of real time has elapsed, more or less.

The amount of real time, measured in milliseconds, is given by millis.

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the sleep is ended and an InterruptedException is thrown.

20.20.40 public static void sleep(long millis, int nanos)
throws InterruptedException

This method causes the current thread to yield and not to be scheduled for further execution until a certain amount of real time has elapsed, more or less.

The amount of real time, measured in nanoseconds, is given by:

1000000*millis+nanos

In all other respects, this method does the same thing as the method sleep of one argument (§20.20.39). In particular, sleep(0, 0) means the same thing as sleep(0).

If the current thread is interrupted (§20.20.31) by another thread while it is waiting, then the sleep is ended and an InterruptedException is thrown.


20.21 The Class java.lang.ThreadGroup

A thread group is a set of threads and thread groups. Every thread belongs to exactly one thread group, and every thread group but one (called the "system thread group") belongs to some other thread group. Thus thread groups form a tree with the system thread group at the root.

Thread groups provide a way to manage threads and to impose security boundaries; for example, a thread may always create a new thread within its own thread group, but creating a thread in another thread group requires the approval of the security manager (§20.17), as does the creation of a new thread group.

public class ThreadGroup {
    public ThreadGroup(String name)
        throws SecurityException;
    public ThreadGroup(ThreadGroup parent, String name)
        throws NullPointerExpression, SecurityException,
            IllegalThreadStateException;
    public String toString();
    public final void checkAccess();
    public final String getName();
    public final ThreadGroup getParent();
    public final boolean parentOf(ThreadGroup g);
    public final void stop()
        throws SecurityException;
    public final void suspend()
        throws SecurityException;
    public final void resume()
        throws SecurityException;
    public final void destroy()
        throws SecurityException, IllegalThreadStateException;
    public final int getMaxPriority();
    public final void setMaxPriority(int newMaxPriority)
        throws SecurityException, IllegalArgumentException;
    public final boolean isDaemon();
    public final void setDaemon(boolean daemon)
        throws SecurityException;
    public 	int threadsCount();
    public int allThreadsCount()		;
    public int groupsCount();
    public int allGroupsCount();
    public Thread[] threads();
    public ThreadGroup[] groups();
    public 	Thread[] allThreads();
    public 	ThreadGroup[] allGroups();
    public int activeCount();															// deprecated
    public int activeGroupCount();															// deprecated
    public int enumerate(Thread list[]);															// deprecated
    public int enumerate(Thread list[],															// deprecated
            boolean recurse);
    public int enumerate(ThreadGroup list[]);															// deprecated
    public int enumerate(ThreadGroup list[],															// deprecated
            boolean recurse);
    public void list();
    public void uncaughtException(Thread t, Throwable e);
}

Every thread group has a maximum priority. The priority of a thread cannot be set (§20.20.23) higher than the maximum priority of its thread group.

Each thread group may or may not be marked as a daemon. When a new ThreadGroup object is created, the newly created thread group is marked as a daemon thread group if and only if the thread group to which it belongs is currently a daemon thread group. But the daemonhood of a thread group G may be changed at any time by calling the setDaemon method of the ThreadGroup object that represents G (provided that the security manager (§20.17.12) approves execution of the setDaemon operation).

Every thread group has a name, which is a String, for identification purposes. More than one thread group may have the same name.

Creation of a thread group requires the approval of the checkAccess method (§20.21.4) of its proposed parent thread group, which forwards the decision to the security manager (§20.17.11).

20.21.1 public ThreadGroup(String name)
throws SecurityException

First, the checkAccess method (§20.21.4) of the thread group to which the current thread belongs is called with no arguments.

This constructor initializes a newly created ThreadGroup object so that it has the specified name as its name and belongs to the same thread group as the thread that is creating the new thread group.

This constructor has exactly the same effect as the explicit constructor call this(Thread.currentThread().getThreadGroup(), name) (§20.21.2).

20.21.2 public ThreadGroup(ThreadGroup parent, String name)
throws NullPointerExpression, SecurityException, IllegalThreadStateException

First, the checkAccess method (§20.21.4) of the parent thread group is called with no arguments.

If parent is null, then a NullPointerExpression is thrown. If parent is a ThreadGroup that has been destroyed by method destroy (§20.21.11), then an IllegalThreadStateException is thrown.

This constructor initializes a newly created ThreadGroup object so that it has the specified name as its name and belongs to the thread group represented by parent.

The maximum priority for the newly created thread group is set equal to the maximum priority of parent. The method setMaxPriority (§20.21.13) may be used to change the maximum priority to a lower value.

The newly created thread group is initially marked as being a daemon thread group if and only parent is a daemon thread group. The method setDaemon (§20.21.15) may be used to change whether or not a thread group is a daemon thread group.

20.21.3 public String toString()

The returned value is a concatenation of the following six strings:

  • The name of the class of this thread group object
  • "[name="
  • The name (§20.21.5) of this thread group
  • ",maxpri="
  • The current maximum priority (§20.21.12) for this thread group, as a decimal numeral
  • "]"

All literal characters mentioned above are from the ASCII subset of Unicode.

Overrides the toString method of Object (§20.1.3).

20.21.4 public final void checkAccess()

If there is a security manager, its checkAccess method (§20.17.12) is called with this ThreadGroup object as its argument. This may result in throwing, in the current thread, a SecurityException.

This method is called by methods stop (§20.21.8), suspend (§20.21.9), resume (§20.21.10), destroy (§20.21.11), setMaxPriority (§20.21.13), and setDaemon (§20.21.15).

20.21.5 public final String getName()

The current name of this ThreadGroup object is returned as a String.

20.21.6 public final ThreadGroup getParent()

This method returns the ThreadGroup object that represents the thread group to which this thread group belongs. If this thread group is the system thread group, which is at the root of the thread group hierarchy, then null is returned.

20.21.7 public final boolean parentOf(ThreadGroup g)

This method returns true if and only if either this thread group is g or this method is true when applied to the parent of g. In other words, this method says whether this thread group is an ancestor of g or perhaps g itself.

(This method arguably is misnamed; a more accurate, if clumsy and abstruse, name would be parentOfReflexiveTransitiveClosure.)

20.21.8 public final void stop() throws SecurityException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

Every thread in this thread group or any of its subgroups is stopped. More precisely, the method stop is called for every ThreadGroup and every Thread (§20.20.15) that belongs to this ThreadGroup.

20.21.9 public final void suspend() throws SecurityException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

Every thread in this thread group or any of its subgroups is suspended. More precisely, the method suspend is called for every ThreadGroup and every Thread (§20.20.17) that belongs to this ThreadGroup.

20.21.10 public final void resume() throws SecurityException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

Every thread in this thread group or any of its subgroups is resumed. More precisely, the method resume is called for every ThreadGroup and every Thread (§20.20.18) that belongs to this ThreadGroup.

20.21.11 public final void destroy()
throws SecurityException, IllegalThreadStateException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

This thread group is destroyed. If it has already been destroyed, or if any threads belong to it directly, then an IllegalThreadStateException is thrown. Otherwise, this method is called recursively for every thread group that belongs to this thread group, and this thread group is removed from its parent thread group.

A thread group that is currently marked as a daemon thread group is destroyed automatically if both of the following conditions are true:

  • A thread or thread group has just been removed from it (because the thread has died or the thread group has been destroyed).
  • The thread group now contains no more threads or thread groups.

20.21.12 public final int getMaxPriority()

The current maximum priority of this ThreadGroup object is returned.

20.21.13 public final void setMaxPriority(int newMaxPriority)
throws SecurityException, IllegalArgumentException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

If the newMaxPriority argument is less than MIN_PRIORITY (§20.20.1) or greater than MAX_PRIORITY (§20.20.2), then an IllegalArgumentException is thrown.

Otherwise, the priority of this ThreadGroup object is set to the smaller of the specified newMaxPriority and the maximum permitted priority (§20.21.12) of the parent of this thread group (§20.21.12). (If this thread group is the system thread group, which has no parent, then its maximum priority is simply set to newMaxPriority.) Then this method is called recursively, with newMaxPriority as its argument, for every thread group that belongs to this thread group.

20.21.14 public final boolean isDaemon()

The result is true if and only if this thread group is currently marked as a daemon thread group.

20.21.15 public final void setDaemon(boolean daemon)
throws SecurityException

First, the checkAccess method (§20.21.4) of this ThreadGroup object is called with no arguments. This may result in a SecurityException being thrown (in the current thread).

This thread group is marked as being a daemon thread group if the argument is true, and as not being a daemon thread group if the argument is false.

20.21.16 public int threadsCount()

This method returns the number of threads that directly belong to this thread group.

20.21.17 public int allThreadsCount()

This method returns the number of threads that belong to this thread group or to any of its subgroups.

20.21.18 public int groupsCount()

This method returns the number of thread groups that directly belong to this thread group.

20.21.19 public int allGroupsCount()

This method returns the number of thread groups that belong to this thread group or to any of its subgroups.

20.21.20 public Thread[] threads()

This method returns a newly created array containing the Thread objects for all threads that directly belong to this thread group.

20.21.21 public Thread[] allThreads()

This method returns a newly created array containing the Thread objects for all threads that belong to this thread group or to any of its subgroups.

20.21.22 public ThreadGroup[] groups()

This method returns a newly created array containing the ThreadGroup objects for all thread groups that directly belong to this thread group.

20.21.23 public ThreadGroup[] allGroups()

This method returns a newly created array containing the ThreadGroup objects for all thread groups that belong to this thread group or to any of its subgroups.

20.21.24 public int activeCount()

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the equivalent method allThreadsCount instead.]

20.21.25 public int activeGroupCount()

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the equivalent method allGroupsCount instead.]

20.21.26 public int enumerate(Thread list[])

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the method allThreads instead.]

20.21.27 public int enumerate(Thread list[], boolean recurse)

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the method threads or allThreads instead.]

20.21.28 public int enumerate(ThreadGroup list[])

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the method allGroups instead.]

20.21.29 public int enumerate(ThreadGroup list[], boolean recurse)

[This method is deprecated for use in new code after Java version 1.1 becomes available. Use the method groups or allGroups instead.]

20.21.30 public void list()

This method prints a detailed description of this thread group to the output stream System.out (§20.18.2). It is intended as a convenient utility for debugging.

The output is a series of lines; each line contains some space characters (for indentation) followed by the toString representation of one thread (§20.20.11) or one thread group (§20.21.3).

The first line gives the toString representation for this thread group, with no indentation spaces. Following lines are then generated by a recursive rule: whenever a line is printed for a thread group G with n leading spaces, it is immediately followed by one line for each thread that directly belongs to G, with [image] spaces of indentation; then one line is printed for each thread group that directly belongs to G, with [image] spaces of indentation, using the recursive case.

20.21.31 public void uncaughtException(Thread t, Throwable e)

The general contract of uncaughtException is that it is called whenever a thread that belongs directly to this thread group dies because an exception was thrown in that thread and not caught. The arguments are the Thread object for the thread in question and the Throwable object that was thrown. The uncaughtException method may then take any appropriate action.

The call to uncaughtException is performed by the thread that failed to catch the exception, so t is the current thread. The call to uncaughtException is the last action of the thread before it dies. If the call to uncaughtException itself results in an (uncaught) exception, this fact is ignored and the thread merely goes on to die.

The method uncaughtException defined by class ThreadGroup takes one of two actions. If this thread group has a parent thread group, then this method is invoked for that parent thread group, with the same arguments. If this thread group is the system thread group (which has no parent), then if the exception e is not an instance of ThreadDeath (§20.22), a stack trace (§20.22.6) for e is printed on the error output stream that is the value of the field System.err (§20.18.3).

Subclasses of ThreadGroup may override the uncaughtException method.


20.22 Classes for Exceptions and Errors

The throw statement (§14.16) is permitted to throw only instances of the class Throwable and its subclasses. Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

The following list shows the hierarchical relationships of all the exception classes predefined in package java.lang by the Java language:

Throwable
    Error
        LinkageError
            ClassCircularityError
            ClassFormatError
            ExceptionInInitializerError

            IncompatibleClassChangeError
                AbstractMethodError
                IllegalAccessError
                InstantiationError
                NoSuchFieldError
                NoSuchMethodError
            NoClassDefFoundError
            UnsatisfiedLinkError
            VerifyError
        VirtualMachineError
            InternalError
            OutOfMemoryError
            StackOverflowError
            UnknownError
        ThreadDeath
    Exception
        ClassNotFoundException
        CloneNotSupportedException
        IllegalAccessException
        InstantiationException
        InterruptedException
        RuntimeException
            ArithmeticException
            ArrayStoreException
            ClassCastException
            IllegalArgumentException
                IllegalThreadStateException
                NumberFormatException
            IllegalMonitorStateException
            IndexOutOfBoundsException
            NegativeArraySizeException
            NullPointerException
            SecurityException

By convention, class Throwable and all its subclasses have two constructors, one that takes no arguments and one that takes a String argument that can be used to produce an error message. This is true of all the classes shown above, with one exception: ExceptionInInitializerError. These predefined classes otherwise have no new content; they merely inherit methods from class Throwable.

public class Throwable {
    public Throwable();
    public Throwable(String message);
    public String toString();
    public String getMessage();
    public Throwable fillInStackTrace();
    public void printStackTrace();
    public void printStackTrace(java.io.PrintStream s);
}

20.22.1 public Throwable()

This constructor initializes a newly created Throwable object with null as its error message string. Also, the method fillInStackTrace (§20.22.5) is called for this object.

20.22.2 public Throwable(String message)

This constructor initializes a newly created Throwable object by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3). Also, the method fillInStackTrace (§20.22.5) is called for this object.

20.22.3 public String getMessage()

If this Throwable object was created with an error message string (§20.22.2), then a reference to that string is returned.

If this Throwable object was created with no error message string (§20.22.1), then null is returned.

20.22.4 public String toString()

If this Throwable object was created with an error message string (§20.22.2), then the result is the concatenation of three strings:

  • The name of the actual class of this object
  • ": " (a colon and a space)
  • The result of the getMessage method (§20.22.3) for this object

If this Throwable object was created with no error message string (§20.22.1), then the name of the actual class of this object is returned.

20.22.5 public Throwable fillInStackTrace()

This method records within this Throwable object information about the current state of the stack frames for the current thread.

20.22.6 public void printStackTrace()

This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err (§20.18.3). The first line of output contains the result of the toString method (§20.22.4) for this object. Remaining lines represent data previously recorded by the method fillInStackTrace (§20.22.5). The format of this information depends on the implementation, but the following example may be regarded as typical:

java.lang.NullPointerException
    at MyClass.mash(MyClass.java:9)
    at MyClass.crunch(MyClass.java:6)
    at MyClass.main(MyClass.java:3)

This example was produced by running the program:

class MyClass {

    public static void main(String[] argv) {
        crunch(null);
    }

    static void crunch(int[] a) {
        mash(a);
    }

    static void mash(int[] b) {
        System.out.println(b[0]);
    }

}


20.23 The Class java.lang.ExceptionInInitializerError

An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable (§12.4.2).

public class ExceptionInInitializerError
        extends RuntimeException {
    public ExceptionInInitializerError();
    public ExceptionInInitializerError(String s);
    public ExceptionInInitializerError(Throwable thrown);
    public Throwable getException();
}

20.23.1 public ExceptionInInitializerError()

This constructor initializes a newly created ExceptionInInitializerError with null as its error message string and with a no saved throwable object.

20.23.2 public ExceptionInInitializerError(String s)

This constructor initializes a newly created ExceptionInInitializerError by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3). There is no saved throwable object.

20.23.3 public ExceptionInInitializerError(Throwable thrown)

This constructor initializes a newly created ExceptionInInitializerError by saving a reference to the Throwable object thrown for later retrieval by the getException method (§20.22.3). The error message string is set to null.

20.23.4 public Throwable getException(Throwable thrown)

The saved throwable object of this ExceptionInInitializerError is returned; null is returned if this ExceptionInInitializerError has no saved throwable object.


 21. The Package java.util

CHAPTER 21

The Package java.util

The java.util package contains various utility classes and interfaces.

Notable among these utilities is the Enumeration interface. An object that implements this interface will generate a series of items, delivering them on demand, one by one. Container classes such as Dictionary and Vector provide one or more methods that return an Enumeration.

A BitSet contains an indexed collection of bits that may be used to represent a set of nonnegative integers.

The class Date provides a convenient way to represent and manipulate time and date information. Dates may be constructed from a year, month, day of month, hour, minute, and second, and those six components, as well as the day of the week, may be extracted from a date. Time zones and daylight saving time are properly accounted for.

The abstract class Dictionary represents a collection of key-value pairs and allows a value to be fetched given the key. The class Hashtable is one concrete implementation of Dictionary. The class Properties extends Hashtable by allowing one table to provide default values for another and by providing standard means for reading entries from files and writing entries to files.

The class Observable provides a mechanism for notifying other objects, called "observers," whenever an Observable object is changed. An observer object may be any object that implements the Observer interface. (This notification mechanism is distinct from that provided by the wait and notify methods of class Object (§20.1) and is not connected with the thread scheduling mechanism.)

The class Random provides an extensive set of methods for pseudorandomly generating numeric values of various primitive types and with various distributions. Each instance of class Random is an independent pseudorandom generator.

A StringTokenizer provides an easy way to divide strings into tokens. The set of characters that delimit tokens is programmable. The tokenizing method is much simpler than the one used by the class java.io.StreamTokenizer. For example, a StringTokenizer does not distinguish among identifiers, numbers, and quoted strings; moreover, it does not recognize and skip comments.

The classes Vector and Stack are simple container classes that provide extensions to the capabilities of Java arrays. A Vector, unlike a Java array, can change its size, and many convenient methods are provided for adding, removing, and searching for items. A Stack is a Vector with additional operations such as push and pop.

The hierarchy of classes defined in package java.util is as follows. (Classes whose names are shown here in boldface are in package java.util; the others are in package java.lang and are shown here to clarify subclass relationships.)

Object	§20.1
    interface Enumeration	§21.1
    BitSet	§21.2
    Date	§21.3
    Dictionary	§21.4
        Hashtable	§21.5
            Properties	§21.6
    Observable	§21.7
    interface Observer	§21.8
    Random	§21.9
    StringTokenizer	§21.10
    Vector	§21.11
        Stack	§21.12
    Throwable	§20.22
        Exception
            RuntimeException
                EmptyStackException	§21.13
                NoSuchElementException	§21.14


21.1 The Interface java.util.Enumeration

An object that implements the Enumeration interface will generate a series of elements, one at a time. Successive calls to the nextElement method will return successive elements of the series.

public interface Enumeration {
    public boolean hasMoreElements();
    public Object nextElement() throws NoSuchElementException;
}

21.1.1 public boolean hasMoreElements()

The result is true if and only if this enumeration object has at least one more element to provide.

21.1.2 public Object nextElement()
throws NoSuchElementException

If this enumeration object has at least one more element to provide, such an element is returned; otherwise, a NoSuchElementException is thrown.

As an example, the following code prints every key in the hashtable ht and its length. The method keys returns an enumeration that will deliver all the keys, and we suppose that the keys are, in this case, known to be strings:

Enumeration e = ht.keys();
while (e.hasMoreElements()) {
    String key = (String)e.nextElement();
    System.out.println(key + " " + key.length());
}


21.2 The Class java.util.BitSet

'T is an old maxim in the schools,
That flattery's the food of fools;
Yet now and then your men of wit
Will condescend to take a bit.
—Jonathan Swift, Cadenus and Vanessa

A BitSet object is a set of bits that grows as needed. The bits of a BitSet are indexed by nonnegative integers. Each bit can be individually examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

public final class BitSet implements Cloneable {
    public BitSet();
    public BitSet(int nbits);
    public String toString();
    public boolean equals(Object obj)
    public int hashCode();
    public Object clone();
    public boolean get(int bitIndex);
    public void set(int bitIndex);
    public void clear(int bitIndex);
    public void and(BitSet set);
    public void or(BitSet set);
    public void xor(BitSet set);
    public int size();
}

21.2.1 public BitSet()

This constructor initializes a newly created BitSet so that all bits are clear.

21.2.2 public BitSet(int nbits)

This constructor initializes a newly created BitSet so that all bits are clear. Enough space is reserved to explicitly represent bits with indices in the range 0 through nbits-1.

21.2.3 public String toString()

For every index for which this BitSet contains a bit in the set state, the decimal representation of that index is included in the result. Such indices are listed in order from lowest to highest, separated by ", " (a comma and a space) and surrounded by braces, resulting in the usual mathematical notation for a set of integers.

Overrides the toString method of Object (§20.1.2).

Example:

BitSet drPepper = new BitSet();

Now drPepper.toString() returns "{}".

drPepper.set(2);

Now drPepper.toString() returns "{2}".

drPepper.set(4);
drPepper.set(10);

Now drPepper.toString() returns "{2, 4, 10}".

21.2.4 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a BitSet object such that, for every nonnegative int index k:

((BitSet)obj).get(k) == this.get(k)

Overrides the equals method of Object (§20.1.3).

21.2.5 public int hashCode()

The hash code depends only on which bits have been set within this BitSet. The algorithm used to compute it may be described as follows.

Suppose the bits in the BitSet were to be stored in an array of long integers called, say, bits, in such a manner that bit k is set in the BitSet (for nonnegative values of k) if and only if the expression:

((k>>6) < bits.length) &&
                ((bits[k>>6] & (1L << (bit & 0x3F))) != 0)

is true. Then the following definition of the hashCode method would be a correct implementation of the actual algorithm:

public synchronized int hashCode() {
    long h = 1234;
    for (int i = bits.length; --i >= 0; ) {
        h ^= bits[i] * (i + 1);
    }
    return (int)((h >> 32) ^ h);
}

Note that the hash code value changes if the set of bits is altered.

Overrides the hashCode method of Object (§20.1.4).

21.2.6 public Object clone()

Cloning this BitSet produces a new BitSet that is equal to it.

Overrides the clone method of Object (§20.1.5).

21.2.7 public boolean get(int bit)

The result is true if the bit with index bit is currently set in this BitSet; otherwise, the result is false.

If bit is negative, an IndexOutOfBoundsException is thrown.

21.2.8 public void set(int bit)

The bit with index bit in this BitSet is changed to the "set" (true) state.

If bit is negative, an IndexOutOfBoundsException is thrown.

If bit is not smaller than the value that would be returned by the size method (§21.2.13), then the size of this BitSet is increased to be larger than bit.

21.2.9 public void clear(int bit)

The bit with index bit in this BitSet is changed to the "clear" (false) state.

If bit is negative, an IndexOutOfBoundsException is thrown.

If bit is not smaller than the value that would be returned by the size method (§21.2.13), then the size of this BitSet is increased to be larger than bit.

21.2.10 public void and(BitSet set)

This BitSet may be modified by clearing some of its bits. For every nonnegative int index k, bit k of this BitSet is cleared if bit k of set is clear.

21.2.11 public void or(BitSet set)

This BitSet may be modified by setting some of its bits. For every nonnegative int index k, bit k of this BitSet is set if bit k of set is set.

21.2.12 public void xor(BitSet set)

This BitSet may be modified by inverting some of its bits. For every nonnegative int index k, bit k of this BitSet is inverted if bit k of set is set.

21.2.13 public int size()

This method returns the number of bits of space actually in use by this BitSet to represent bit values.

At Mooneen he had leaped a place
So perilous that half the astonished meet
Had shut their eyes, and where was it
He rode a race without a bit?
—William Butler Yeats, In Memory of Major Robert Gregory (1919)


21.3 The Class java.util.Date

The class Date provides a system-independent abstraction of dates and times, to a millisecond precision. Dates may be constructed from a year, month, date (day of month), hour, minute, and second; those six components and the day of the week, may be extracted; and dates may be compared and converted to a readable string.

public class Date {
    public Date();
    public Date(long time);
    public Date(int year, int month, int date);
    public Date(int year, int month, int date,
            int hours, int minutes);
    public Date(int year, int month, int date,
            int hours, int minutes, int seconds);
    public Date(String s) throws IllegalArgumentException;
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public int getYear();
    public void setYear(int year);
    public int getMonth();
    public void setMonth(int month);
    public int getDate();
    public void setDate(int date);
    public int getDay();
    public int getHours();
    public void setHours(int hours);
    public int getMinutes();
    public void setMinutes(int minutes);
    public int getSeconds();
    public void setSeconds(int seconds);
    public long getTime();
    public void setTime(long time);
    public boolean before(Date when);
    public boolean after(Date when);
    public String toLocaleString();
    public String toGMTString();
    public int getTimezoneOffset();
    public static long UTC(int year, int month, int date,
            int hours, int minutes, int seconds);
    public static long parse(String s)
        throws IllegalArgumentException;
}

Examples:

  • To print today's date: System.out.println("today = " + new Date());
  • To find out the day of the week for some particular date, for example, January 16, 1963: new Date(63, 0, 16).getDay()

While the Date class is intended to reflect UTC (Coordinated Universal Time), it may not do so exactly, depending on the host environment of the Java system. Nearly all modern operating systems assume that 1 day = [image] = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and nearly always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second.

Most computer clocks are currently not accurate enough to be able to reflect the leap-second distinction. Some computer standards are defined in terms of GMT (Greenwich Mean Time), which is equivalent to UT (Universal Time). GMT is the "civil" name for the standard; UT is the "scientific" name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth's rotation is not uniform-it slows down and speeds up in complicated ways-UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by GPS (the satellite-based Global Positioning System) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the U. S. Naval Observatory, particularly the Directorate of Time at:

http://tycho.usno.navy.mil/

and their definitions of "Systems of Time" at:

http://tycho.usno.navy.mil/systime.html

In all methods of class Date that accept or return year, month, day of month, hours, minutes, and seconds values, the following representations are used:

  • A year y is represented by the integer [image].
  • A month is represented by an integer form 0 to 11; 0 is January, 1 is February, and so on; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus the hour from midnight to 1 AM is hour 0, and the hour from noon to 1 PM is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 61. The values 60 and 61 will occur only for leap seconds, and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.

In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and will be interpreted as meaning February 1.

21.3.1 public Date()

This constructor initializes a newly created Date object so that it represents the instant of time that it was created, measured to the nearest millisecond.

21.3.2 public Date(long time)

This constructor initializes a newly created Date object so that it represents the instant of time that is time milliseconds after the standard base time known as "the epoch," namely 00:00:00 GMT on January 1, 1970. See also the method currentTimeMillis (§20.18.6) of class System.

21.3.3 public Date(int year, int month, int date)

This constructor initializes a newly created Date object so that it represents midnight at the beginning of the day specified by the year, month, and date arguments, in the local time zone. Thus, it has the same effect as the constructor call (§21.3.5):

Date(year, month, date, 0, 0, 0)

21.3.4 public Date(int year, int month, int date,
int hours, int minutes)

This constructor initializes a newly created Date object so that it represents the instant at the start of the minute specified by the year, month, date, hours, and minutes arguments, in the local time zone. Thus, it has the same effect as the constructor call (§21.3.5):

Date(year, month, date, hours, minutes, 0)

21.3.5 public Date(int year, int month, int date,
int hours, int minutes, int seconds)

This constructor initializes a newly created Date object so that it represents the instant at the start of the second specified by the year, month, date, hours, minutes, and seconds arguments, in the local time zone.

21.3.6 public Date(String s)
throws IllegalArgumentException

This constructor initializes a newly created Date object so that it represents the date and time indicated by the string s, which is interpreted as if by the parse method (§21.3.31).

21.3.7 public String toString()

This Date object is converted to a String of the form:

"dow mon dd hh:mm:ss zzz yyyy"

where:

  • dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
  • mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
  • dd is the day of the month (01 through 31), as two decimal digits.
  • hh is the hour of the day (00 through 23), as two decimal digits.
  • mm is the minute within the hour (00 through 59), as two decimal digits.
  • ss is the second within the minute (00 through 61), as two decimal digits.
  • zzz is the time zone (and may reflect daylight saving time). Standard time zone abbreviations include those recognized by the method parse (§21.3.31). If time zone information is not available, then zzz is empty-that is, it consists of no characters at all.
  • yyyy is the year, as four decimal digits.

See also methods toLocaleString (§21.3.27) and toGMTString (§21.3.28).

Overrides the toString method of Object (§20.1.2).

21.3.8 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this Date object. Thus two Date objects are equal if and only if the getTime method (§21.3.23) returns the same long value from both.

Overrides the equals method of Object (§20.1.3).

21.3.9 public int hashCode()

The result is the exclusive OR of the two halves of the primitive long value returned by the getTime method (§21.3.23). That is, the hash code is the value of the expression:

(int)(this.getTime()^(this.getTime()>>>32))

Overrides the hashCode method of Object (§20.1.4).

21.3.10 public int getYear()

The returned value is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.11 public void setYear(int year)

This Date object is modified so that it represents a point in time within the specified year, with the month, date, hour, minute, and second the same as before, as interpreted in the local time zone. (Of course, if the date was February 29, for example, and the year is set to a non-leap year, then the new date will be treated as if it were on March 1.)

21.3.12 public int getMonth()

The returned value is a number (0 through 11) representing the month that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.13 public void setMonth(int month)

This Date object is modified so that it represents a point in time within the specified month, with the year, date, hour, minute, and second the same as before, as interpreted in the local time zone. If the date was October 31, for example, and the month is set to June, then the new date will be treated as if it were on July 1, because June has only 30 days.

21.3.14 public int getDate()

The returned value is a number (1 through 31) representing day of the month that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.15 public void setDate(int date)

This Date object is modified so that it represents a point in time within the specified day of the month, with the year, month, hour, minute, and second the same as before, as interpreted in the local time zone.If the date was April 30, for example, and the date is set to 31, then it will be treated as if it were on May 1, because April has only 30 days.

21.3.16 public int getDay()

The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.17 public int getHours()

The returned value is a number (0 through 23) representing the hour within the day that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.18 public void setHours(int hours)

This Date object is modified so that it represents a point in time within the specified hour of the day, with the year, month, date, minute, and second the same as before, as interpreted in the local time zone.

21.3.19 public int getMinutes()

The returned value is a number (0 through 59) representing the minute within the hour that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.20 public void setMinutes(int minutes)

This Date object is modified so that it represents a point in time within the specified minute of the hour, with the year, month, date, hour, and second the same as before, as interpreted in the local time zone.

21.3.21 public int getSeconds()

The returned value is a number (0 through 61) representing the second within the minute that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

21.3.22 public void setSeconds(int seconds)

This Date object is modified so that it represents a point in time within the specified second of the minute, with the year, month, date, hour, and minute the same as before, as interpreted in the local time zone.

21.3.23 public long getTime()

This method returns the time represented by this Date object, represented as the distance, measured in milliseconds, of that time from the epoch (00:00:00 GMT on January 1, 1970).

21.3.24 public void setTime(long time)

This Date object is modified so that it represents a point in time that is time milliseconds after the epoch (00:00:00 GMT on January 1, 1970).

21.3.25 public boolean before(Date when)

The result is true if and only if the instant represented by this Date object is strictly earlier than the instant represented by when.

21.3.26 public boolean after(Date when)

The result is true if and only if the instant represented by this Date object is strictly later than the instant represented by when.

21.3.27 public String toLocaleString()

This Date object is converted to a String of an implementation-dependent form. The general intent is that the form should be familiar to the user of the Java application, wherever it may happen to be running. The intent is comparable to that of the %c format supported by the strftime function of ISO C.

See also methods toString (§21.3.7) and toGMTString (§21.3.28).

21.3.28 public String toGMTString()

This Date object is converted to a String of length 23 or 24 of the form:

"d mon yyyy hh:mm:ss GMT"

where:

  • d is the day of the month (1 through 31), as one or two decimal digits.
  • mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
  • yyyy is the year, as four decimal digits.
  • hh is the hour of the day (00 through 23), as two decimal digits.
  • mm is the minute within the hour (00 through 59), as two decimal digits.
  • ss is the second within the minute (00 through 61), as two decimal digits.
  • GMT is exactly the ASCII letters "GMT" to indicate Greenwich Mean Time.

The result does not depend on the local time zone.

See also methods toString (§21.3.7) and toLocaleString (§21.3.27).

21.3.29 public int getTimezoneOffset()

This method returns the offset, measured in minutes, for the local time zone relative to UTC that is appropriate for the time represented by this Date object.

For example, in Massachusetts, five time zones west of Greenwich:

new Date(96, 1, 14).getTimezoneOffset() returns 300

because on February 14, 1996, standard time (Eastern Standard Time) is in use, which is offset five hours from UTC; but:

new Date(96, 5, 1).getTimezoneOffset() returns 240

because on May 1, 1996, daylight saving time (Eastern Daylight Time) is in use, which is offset only four hours from UTC.

This method produces the same result as if it computed:

(this.getTime() - UTC(this.getYear(),
                            this.getMonth(),
                            this.getDate(),
                            this.getHours(),
                            this.getMinutes(),
                            this.getSeconds())) / (60 * 1000)

21.3.30 public static long UTC(int year, int month, int date,
int hours, int minutes, int seconds)

The arguments are interpreted as a year, month, day of the month, hour of the day, minute within the hour, and second within the minute, exactly as for the Date constructor of six arguments (§21.3.5), except that the arguments are interpreted relative to UTC rather than to the local time zone. The time indicated is returned represented as the distance, measured in milliseconds, of that time from the epoch (00:00:00 GMT on January 1, 1970).

21.3.31 public static long parse(String s)
throws IllegalArgumentException

An attempt is made to interpret the string s as a representation of a date and time. If the attempt is successful, the time indicated is returned represented as the distance, measured in milliseconds, of that time from the epoch (00:00:00 GMT on January 1, 1970). If the attempt fails, an IllegalArgumentException is thrown.

The string s is processed from left to right, looking for data of interest.

Any material in s that is within the ASCII parenthesis characters ( and ) is ignored. Parentheses may be nested. Otherwise, the only characters permitted within s are these ASCII characters:

abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789,+-:/

and whitespace characters (§20.5.19).

A consecutive sequence of decimal digits is treated as a decimal number:

  • If a number is preceded by + or - and a year has already been recognized, then the number is a time-zone offset. If the number is less than 24, it is an offset measured in hours. Otherwise, it is regarded as an offset in minutes, expressed in 24-hour time format without punctuation. A preceding + means an eastward offset and a preceding - means a westward offset. Time zone offsets are always relative to UTC (Greenwich). Thus, for example, -5 occurring in the string would mean "five hours west of Greenwich" and +0430 would mean "four hours and thirty minutes east of Greenwich." It is permitted for the string to specify GMT, UT, or UTC redundantly-for example, GMT-5 or utc+0430.
  • If a number is greater than 70, it is regarded as a year number. It must be followed by a space, comma, slash, or end of string. If it is greater than 1900, then 1900 is subtracted from it.
  • If the number is followed by a colon, it is regarded as an hour, unless an hour has already been recognized, in which case it is regarded as a minute.
  • If the number is followed by a slash, it is regarded as a month (it is decreased by 1 to produce a number in the range 0 to 11), unless a month has already been recognized, in which case it is regarded as a day of the month.
  • If the number is followed by whitespace, a comma, a hyphen, or end of string, then if an hour has been recognized but not a minute, it is regarded as a minute; otherwise, if a minute has been recognized but not a second, it is regarded as a second; otherwise, it is regarded as a day of the month.

A consecutive sequence of letters is regarded as a word and treated as follows:

  • A word that matches AM, ignoring case, is ignored (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
  • A word that matches PM, ignoring case, adds 12 to the hour (but the parse fails if an hour has not been recognized or is less than 1 or greater than 12).
  • Any word that matches any prefix of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, or SATURDAY, ignoring case, is ignored. For example, sat, Friday, TUE, and Thurs are ignored.
  • Otherwise, any word that matches any prefix of JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, or DECEMBER, ignoring case, and considering them in the order given here, is recognized as specifying a month and is converted to a number (0 to 11). For example, aug, Sept, april, and NOV are recognized as months. So is Ma, which is recognized as MARCH, not MAY.
  • Any word that matches GMT, UT, or UTC, ignoring case, is treated as referring to UTC.
  • Any word that matches EST, CST, MST, or PST, ignoring case, is recognized as referring to the time zone in North America that is five, six, seven, or eight hours west of Greenwich, respectively. Any word that matches EDT, CDT, MDT, or PDT, ignoring case, is recognized as referring to the same time zone, respectively, during daylight saving time. (In the future, this method may be upgraded to recognize other time zone designations.)

Once the entire string s has been scanned, it is converted to a time result in one of two ways. If a time zone or time-zone offset has been recognized, then the year, month, day of month, hour, minute, and second are interpreted in UTC (§21.3.30) and then the time-zone offset is applied. Otherwise, the year, month, day of month, hour, minute, and second are interpreted in the local time zone.


21.4 The Class java.util.Dictionary

A Dictionary is an object that associates elements with keys. Every key and every element is an object. In any one Dictionary, every key is associated at most one element. Given a Dictionary and a key, the associated element can be looked up.

public abstract class Dictionary {
    abstract public int size();
    abstract public boolean isEmpty();
    abstract public Object get(Object key)
        throws NullPointerException;
    abstract public Object put(Object key, Object element)
        throws NullPointerException;
    abstract public Object remove(Object key)
        throws NullPointerException;
    abstract public Enumeration keys();
    abstract public Enumeration elements();
}

As a rule, the equals method (§20.1.3) should be used by implementations of the class Dictionary to decide whether two keys are the same.

21.4.1 abstract public int size()

The general contract for the size method is that it returns the number of entries (distinct keys) in this dictionary.

21.4.2 abstract public boolean isEmpty()

The general contract for the isEmpty method is that the result is true if and only if this dictionary contains no entries.

21.4.3 abstract public Object get(Object key)
throws NullPointerException

The general contract for the isEmpty method is that if this dictionary contains an entry for the specified key, the associated element is returned; otherwise, null is returned.

If the key is null, a NullPointerException is thrown.

21.4.4 abstract public Object put(Object key, Object element)
throws NullPointerException

The general contract for the put method is that it adds an entry to this dictionary.

If this dictionary already contains an entry for the specified key, the element already in this dictionary for that key is returned, after modifying the entry to contain the new element.

If this dictionary does not already have an entry for the specified key, an entry is created for the specified key and element, and null is returned.

If the key or the element is null, a NullPointerException is thrown.

21.4.5 abstract public Object remove(Object key)
throws NullPointerException

The general contract for the remove method is that it removes an entry from this dictionary.

If this dictionary contains an entry for the specified key, the element in this dictionary for that key is returned, after removing the entry from this dictionary.

If this dictionary does not already have an entry for the specified key, null is returned.

If the key is null, a NullPointerException is thrown.

21.4.6 abstract public Enumeration keys()

The general contract for the keys method is that an Enumeration (§21.1) is returned that will generate all the keys for which this dictionary contains entries.

21.4.7 abstract public Enumeration elements()

The general contract for the elements method is that an Enumeration (§21.1) is returned that will generate all the elements contained in entries in this dictionary.


21.5 The Class java.util.Hashtable

. . . never did they seem to have new experiences in common . . . and the things they had for dissection—college, contemporary personality, and the like—they had hashed and rehashed for many a frugal conversational meal.
—F. Scott Fitzgerald, This Side of Paradise (1920)

The class Hashtable implements the abstract class Dictionary (§21.4), with some additional functionality.

public class Hashtable extends Dictionary implements Cloneable {
    public Hashtable(int initialCapacity, float loadFactor);
    public Hashtable(int initialCapacity);
    public Hashtable();
    public String toString();
    public Object clone();
    public int size();
    public boolean isEmpty();
    public Object get(Object key)
        throws NullPointerException;
    public Object put(Object key, Object value)
        throws NullPointerException;
    public Object remove(Object key)
        throws NullPointerException;
    public Enumeration keys();
    public Enumeration elements();
    public boolean contains(Object value);
    public boolean containsKey(Object key);
    protected void rehash();
    public void clear();
}

A Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased, using the rehash method. Larger load factors use memory more efficiently at the expense of larger expected time per lookup. If many entries are to be made in a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

21.5.1 public Hashtable(int initialCapacity, float loadFactor)

This constructor initializes a newly created Hashtable object so that its capacity is initialCapacity and its load factor is loadFactor. Initially, there are no entries in the table.

21.5.2 public Hashtable(int initialCapacity)

This constructor initializes a newly created Hashtable object so that its capacity is initialCapacity and its load factor is 0.75. Initially, there are no entries in the table.

21.5.3 public Hashtable()

This constructor initializes a newly created Hashtable object so that its load factor is 0.75. Initially, there are no entries in the table.

21.5.4 public String toString()

This Hashtable is represented in string form as a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). Each entry is rendered as the key, an equals sign =, and the associated element, where the toString method is used to convert the key and element to strings.

Overrides the toString method of Object (§21.2.3).

21.5.5 public Object clone()

A copy of this Hashtable is constructed and returned. All the structure of the hashtable itself is copied, but the keys and elements are not cloned.

Overrides the clone method of Object (§21.2.6).

21.5.6 public int size()

Implements the size method of Dictionary (§21.4.1).

21.5.7 public boolean isEmpty()

Implements the isEmpty method of Dictionary (§21.4.2).

21.5.8 public Object get(Object key)

Implements the get method of Dictionary (§21.4.3).

21.5.9 public Object put(Object key, Object value)

Implements the put method of Dictionary (§21.4.4).

21.5.10 public Object remove(Object key)

Implements the remove method of Dictionary (§21.4.5).

21.5.11 public Enumeration keys()

Implements the keys method of Dictionary (§21.4.6).

21.5.12 public Enumeration elements()

Implements the elements method of Dictionary (§21.4.7).

21.5.13 public boolean contains(Object value)

The result is true if and only if this Hashtable contains at least one entry for which the element is equal to value, as determined by the equals method (§20.1.3).

21.5.14 public boolean containsKey(Object key)

The result is true if and only if this Hashtable contains an entry for which the key is equal to key, as determined by the equals method (§20.1.3). In other words, this method produces the same result as the expression:

get(key) != null

21.5.15 protected void rehash()

This Hashtable is increased in capacity and reorganized internally, in order to accommodate and access its entries more efficiently.

21.5.16 public void clear()

The clear method removes all entries from this Hashtable.

Twelve sphered tables, by silk seats insphered,
High as the level of a man's breast rear'd
On libbard's paws, upheld the heavy gold
Of cups and goblets, and the store thrice told
Of Ceres' horn, and, in huge vessels, wine
Came from the gloomy tun with merry shine.
Thus loaded with a feast the tables stood . . .
—John Keats, Lamia Part II


21.6 The Class java.util.Properties

A Properties table is a kind of Hashtable with two functionality extensions and with the restriction that keys and elements must be strings. First, there are methods for reading entries into the table from an input stream and writing all the entries in the table to an output stream. Second, a Properties table may refer to another Properties table that provides default values. The getProperty method is much like the get method (§21.4.3), but if an entry is not found in this table, then the defaults table is searched (and that defaults table may itself refer to another defaults table, and so on, recursively).

public class Properties extends Hashtable {
    protected Properties defaults;
    public Properties();
    public Properties(Properties defaults);
    public String getProperty(String key);
    public String getProperty(String key, String defaultValue);
    public Enumeration propertyNames();
    public void load(InputStream in) throws IOException;
    public void save(OutputStream out, String header);
    public void list(PrintStream out);
}

21.6.1 protected Properties defaults;

If the defaults field is not null, it is another Properties table that provides default values for this Properties table.

21.6.2 public Properties()

This constructor initializes a newly created Properties table so that it has no defaults table. Initially, there are no entries in the newly created table.

21.6.3 public Properties(Properties defaults)

This constructor initializes a newly created Properties table so its defaults table is defaults. The argument defaults may be null, in which case the newly created Properties table will not have a defaults table. Initially, there are no entries in the newly created table.

21.6.4 public String getProperty(String key)

If there is an entry in this Properties table with key as its key, the associated element is returned. Otherwise, if this Properties table has a defaults table, then whatever its getProperty method returns is returned. Otherwise, null is returned.

21.6.5 public String getProperty(String key,
String defaultValue)

If there is an entry in this Properties table with key as its key, the associated element is returned. Otherwise, if this Properties table has a defaults table, then whatever its getProperty method returns is returned. Otherwise, defaultValue is returned.

21.6.6 public Enumeration propertyNames()

An Enumeration (§21.1) is returned that will generate all the keys for which this Properties table could supply an associated element. If this Properties table has a defaults table (§21.6.1), then keys for which the defaults table has entries are also supplied by the Enumeration, and so on, recursively; but no key is supplied by the Enumeration more than once.

21.6.7 public void load(InputStream in) throws IOException

Properties (key and element pairs) are read from the input stream:

Runtime.getRuntime().getLocalizedInputStream(in)

and added to this Properties table. See the getLocalizedInputStream method of Runtime (§20.16.15).

Every property occupies one line of the input stream. Each line is terminated by a line terminator (\n or \r or \r\n). Lines from the input stream are processed until end of file is reached on the input stream.

A line that contains only whitespace (§20.5.19) or whose first non-whitespace character is an ASCII # or ! is ignored (thus, # or ! indicate comment lines).

Every line other than a blank line or a comment line describes one property to be added to the table (except that if a line ends with \, then the following line is treated as a continuation line, as described below). The key consists of all the characters in the line starting with the first non-whitespace character and up to, but not including, the first ASCII =, :, or whitespace character. Any whitespace after the key is skipped; if the first non-whitespace character after the key is = or :, then it is ignored and any whitespace characters after it are also skipped. All remaining characters on the line become part of the associated element string. Within the element string (but not the key), the ASCII escape sequences \t, \n, \r, \\, \", \', \ (a backslash and a space), and \u xxxx are recognized and converted to single characters. Moreover, if the last character on the line is \, then the next line is treated as a continuation of the current line; the \ and line terminator are simply discarded, and any leading whitespace characters on the continuation line are also discarded and are not part of the element string.

As an example, each of the following four lines specifies the key "Truth" and the associated element value "Beauty":

Truth Beauty
Truth = Beauty
    Truth:Beauty
Truth			:Beauty

As another example, the following three lines specify a single property:

fruits				apple, banana, pear, \
                cantaloupe, watermelon, \
                kiwi, mango

The key is "fruit" and the associated element is:

"apple, banana, pear, cantaloupe, watermelon, kiwi, mango"

Note that a space appears before each \ so that a space will appear after each comma in the final result; the \, line terminator, and leading whitespace on the continuation line are merely discarded and are not replaced by one or more other characters.

As a third example, the line:

cheeses

specifies that the key is "cheeses" and the associated element is the empty string.

21.6.8 public void save(OutputStream out, String header)

All the properties (key and element pairs) in this Properties table are written to the output stream:

Runtime.getRuntime().getLocalizedOutputStream(out)

in a format suitable for loading into a Properties table using the load method (§21.6.7). See the getLocalizedOutputStream method of Runtime (§20.16.16).

Properties from the defaults table of this Properties table (if any) are not written out by this method.

If the header argument is not null, then an ASCII # character, the header string, and a newline are first written to the output stream. Thus, the header can serve as an identifying comment.

Next, a comment line is always written, consisting of an ASCII # character, the current date and time (as if produced by the toString method of Date (§21.3.7) for the current time), and a newline.

Then every entry in this Properties table is written out, one per line. For each entry the key string is written, then an ASCII =, then the associated element string. Each character of the element string is examined to see whether it should be rendered as an escape sequence. The ASCII characters \, tab, newline, and carriage return are written as \\, \t, \n, and \r, respectively. Characters less than \u0020 and characters greater than \u007E (if necessary, depending on the needs of the localized output stream) are written as \u xxxx for the appropriate hexadecimal value xxxx. Leading space characters, but not embedded or trailing space characters, are written with a preceding \.

21.6.9 public void list(PrintStream out)

Properties (key and element pairs) in this Properties table are written to the output stream out in a possibly abbreviated form that may be more convenient for use in debugging than the output of the save method. No header is written, and element values longer than 40 character are truncated to the first 37 characters, to which the characters "..." are appended. Thus, if the names of the keys are not too long, there is a fighting chance that each property will fit into the space of one line of a physical output device.


21.7 The Class java.util.Observable

Each instance of class Observable maintains a set of "observers" that are notified whenever the Observable object changes in some significant way. An observer may be any object that implements interface Observer (§21.8).

Note that this notification mechanism is has nothing to do with threads (§20.20) and is completely separate from the wait and notify mechanism of class Object (§20.1).

public class Observable {
    public void addObserver(Observer o);
    public void deleteObserver(Observer o);
    public void deleteObservers();
    public int countObservers();
    public void notifyObservers();
    public void notifyObservers(Object arg);
    protected void setChanged();
    protected void clearChanged();
    public boolean hasChanged();
}

When an observable object is newly created, its set of observers is empty.

Two observers are considered the same if and only if the equals method (§20.1.3) returns true for them.

21.7.1 public void addObserver(Observer o)

The observer o is added to this Observable object's set of observers, provided that it is not the same as some observer already in the set.

21.7.2 public void deleteObserver(Observer o)

The observer o is removed from this Observable object's set of observers.

21.7.3 public void deleteObservers()

All observers are removed from this Observable object's set of observers.

21.7.4 public int countObservers()

The number of observers in this Observable object's set of observers is returned.

21.7.5 public void notifyObservers()

If this Observable object has been marked as changed, this method causes all observers to be notified with null as the second argument; in other words, this method is equivalent to:

notifyObservers(null)

21.7.6 public void notifyObservers(Object arg)

If this Observable object has been marked as changed (§21.7.9), this method causes all observers to be notified with arg as the second argument. An observer is notified by calling its update method (§21.8.1) on two arguments: this Observable object and arg. The mark on this object is then cleared (§21.7.8).

21.7.7 protected void setChanged()

This Observable object is marked as having been changed; the hasChanged method will now return true.

21.7.8 protected void clearChanged()

This Observable object is marked as not having been changed; the hasChanged method will now return false.

21.7.9 public boolean hasChanged()

The result is true if and only if the setChanged method has been called for this Observable object more recently than either the clearChanged method or the notifyObservers method.


21.8 The Interface java.util.Observer

A class should implement the Observer interface if it is to be notified whenever an Observable object has been changed. See the Observable class (§21.7) for a discussion of how Observer objects are notified.

public interface Observer {
    public void update(Observable o, Object arg);
}

21.8.1 public void update(Observable o, Object arg)

When an Observable object has been changed and its notifyObservers method (§21.7.6) is called, every Observer object in its set of observers is notified by invoking its update method, passing it two arguments: the Observable object and another argument specified by the call to the notifyObservers method.


21.9 The Class java.util.Random

Oh, many a shaft at random sent
Finds mark the archer little meant!
And many a word at random spoken
May soothe, or wound, a heart that's broken!
—Sir Walter Scott, The Lady of the Lake, Canto V, stanza 18

Each instance of class Random serves as a separate, independent pseudorandom generator of primitive values.

public class Random {
    protected long seed;
    protected double nextNextGaussian;
    protected boolean haveNextNextGaussian = false;
    public Random();
    public Random(long seed);
    protected int next(int bits);
    public void setSeed(long seed);
    public int nextInt();
    public long nextLong();
    public float nextFloat();
    public double nextDouble();
    public double nextGaussian();
}

If two Random objects are created with the same seed and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers in all Java implementations. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use three state variables, which are protected. They also use a protected utility method that on each invocation can supply up to up to 32 pseudorandomly generated bits.

21.9.1 protected long seed;

A variable used by method next (§21.9.7) to hold the state of the pseudorandom number generator.

21.9.2 protected double nextNextGaussian;

A variable used by method nextGaussian (§21.9.12) to hold a precomputed value to be delivered by that method the next time it is called.

21.9.3 p rotected boolean haveNextNextGaussian = false;

A variable used by method nextGaussian (§21.9.12) to keep track of whether it has precomputed and stashed away the next value to be delivered by that method.

21.9.4 public Random()

This constructor initializes a newly created Random number generator by using the current time of day (§20.18.6) as a seed.

public Random() { this(System.currentTimeMillis()); }

21.9.5 public Random(long seed)

This constructor initializes a newly created Random number generator by using the argument seed as a seed.

public Random(long seed) { setSeed(seed); }

21.9.6 public void setSeed(long seed)

The general contract of setSeed is that it alters the state of this random number generator object so as to be in exactly the same state as if it had just been created with the argument seed as a seed.

The method setSeed is implemented by class Random as follows:

synchronized public void setSeed(long seed) {
    this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
    haveNextNextGaussian = false;
}

The implementation of setSeed by class Random happens to use only 48 bits of the given seed. In general, however, an overriding method may use all 64 bits of the long argument as a seed value.

[In certain early versions of Java, the setSeed method failed to reset the value of haveNextNextGaussian to false; this flaw could lead to failure to produce repeatable behavior.]

21.9.7 protected int next(int bits)

The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1.

The method next is implemented by class Random as follows:

synchronized protected int next(int bits) {
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int)(seed >>> (48 - bits));
}

This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.2.1.

21.9.8 public int nextInt()

The general contract of nextInt is that one int value is pseudorandomly generated and returned. All [image] possible int values are produced with (approximately) equal probability.

The method setSeed is implemented by class Random as follows:

public int nextInt() {  return next(32); }

21.9.9 public long nextLong()

The general contract of nextLong is that one long value is pseudorandomly generated and returned. All [image] possible long values are produced with (approximately) equal probability.

The method setSeed is implemented by class Random as follows:

public long nextLong() {
    return ((long)next(32) << 32) + next(32);
}

21.9.10 public float nextFloat()

The general contract of nextFloat is that one float value, chosen (approximately) uniformly from the range 0.0f (inclusive) to 1.0f (exclusive), is pseudorandomly generated and returned. All [image] possible float values of the form [image], where m is a positive integer less than [image], are produced with (approximately) equal probability.

The method setSeed is implemented by class Random as follows:

public float nextFloat() {
    return next(24) / ((float)(1 << 24));
}

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source or randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as:

    return next(30) / ((float)(1 << 30));

This might seem to be equivalent, if not better, but in fact it introduced a slight nonuniformity because of the bias in the rounding of floating-point numbers: it was slightly more likely that the low-order bit of the significand would be 0 than that it would be 1.]

21.9.11 public double nextDouble()

The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned. All [image] possible float values of the form [image], where m is a positive integer less than [image], are produced with (approximately) equal probability.

The method setSeed is implemented by class Random as follows:

public double nextDouble() {
    return (((long)next(26) << 27) + next(27))
                / (double)(1L << 53);
}

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source or randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as:

    return (((long)next(27) << 27) + next(27))
                / (double)(1L << 54);

This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity because of the bias in the rounding of floating-point numbers: it was three times as likely that the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity probably doesn't matter much in practice, but we strive for perfection.]

21.9.12 public double nextGaussian()

The general contract of nextGaussian is that one double value, chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0, is pseudorandomly generated and returned.

The method setSeed is implemented by class Random as follows:

synchronized public double nextGaussian() {
    if (haveNextNextGaussian) {
        haveNextNextGaussian = false;
        return nextNextGaussian;
    } else {
        double v1, v2, s;
        do {
            v1 = 2 * nextDouble() - 1; 	// between -1.0 and 1.0
            v2 = 2 * nextDouble() - 1; 	// between -1.0 and 1.0
            s = v1 * v1 + v2 * v2;
        } while (s >= 1);
        double norm = Math.sqrt(-2 * Math.log(s)/s);
        nextNextGaussian = v2 * norm;
        haveNextNextGaussian = true;
        return v1 * norm;
    }
}

This uses the polar method of G. E. P. Box, M. E. Muller, and G. Marsaglia, as described by Donald E. Knuth in The Art of Computer Programming, Volume 2: Seminumerical Algorithms, section 3.4.1, subsection C, algorithm P. Note that it generates two independent values at the cost of only one call to Math.log and one call to Math.sqrt.

. . . who can tell what may be the event? . . .
The mind of the multitude is left at random . . .
—Thomas Paine, Common Sense (1776), Appendix A


21.10 The Class java.util.StringTokenizer

The StringTokenizer class provides a way to break a String into tokens. The tokenizing method used by this class is much simpler than the one used by the class java.io.StreamTokenizer. For example, a StringTokenizer does not distinguish among identifiers, numbers, and quoted strings; moreover, it does not recognize and skip comments.

A StringTokenizer can serve as an Enumeration (§21.1).

public class StringTokenizer implements Enumeration {
    public StringTokenizer(String str, String delim,
        boolean returnTokens);
    public StringTokenizer(String str, String delim);
    public StringTokenizer(String str);
    public boolean hasMoreTokens();
    public String nextToken();
    public String nextToken(String delim);
    public boolean hasMoreElements();
    public Object nextElement();
    public int countTokens();
}

A StringTokenizer simply divides characters into classes: delimiters and other characters. The tokenizer behaves in one of two ways, depending on whether it was created with returnTokens having the value true or false.

If returnTokens is false, delimiter characters merely serve to separate tokens of interest. A token is thus a maximal sequence of consecutive characters that are not delimiters.

If returnTokens is true, delimiter characters are themselves considered to be tokens of interest. A token is thus either one delimiter character or a maximal sequence of consecutive characters that are not delimiters.

A StringTokenizer internally maintains a current position within the String to be tokenized. Some operations advance this current position past the characters processed.

A token is returned by taking a substring (§20.12.32) of the string that was used to create the StringTokenizer.

21.10.1 public StringTokenizer(String str, String delim,
boolean returnTokens)

This constructor initializes a newly created StringTokenizer so that it will recognize tokens within the given string str. All characters in the string delim will be considered delimiters. The argument returnTokens specifies whether delimiter characters themselves are to be considered tokens.

21.10.2 public StringTokenizer(String str, String delim)

This constructor initializes a newly created StringTokenizer so that it will recognize tokens within the given string str. All characters in the string delim will be considered delimiters. Delimiter characters themselves will not be treated as tokens.

21.10.3 public StringTokenizer(String str)

This constructor initializes a newly created StringTokenizer so that it will recognize tokens within the given string str. All whitespace characters (§20.5.19) will be considered delimiters. Delimiter characters themselves will not be treated as tokens.

21.10.4 public boolean hasMoreTokens()

The result is true if and only if there is at least one token in the string after the current position. If this method returns true, then a subsequent call to nextToken with no argument will successfully return a token.

21.10.5 public String nextToken()

The next token in the string after the current position is returned. The current position is advanced beyond the recognized token.

21.10.6 public String nextToken(String delim)

First, the set of characters considered to be delimiters by this StringTokenizer is changed to be the characters in the string delim. Then the next token in the string after the current position is returned. The current position is advanced beyond the recognized token.

21.10.7 public boolean hasMoreElements()

This method has exactly the same behavior as hasMoreTokens (§21.10.4). It is provided so that a StringTokenizer can serve as an Enumeration (§21.1).

21.10.8 public Object nextElement()

This method has exactly the same behavior as nextToken (§21.10.5). It is provided so that a StringTokenizer can serve as an Enumeration (§21.1).

21.10.9 public int countTokens()

The result is the number of tokens in the string after the current position, using the current set of delimiter characters. The current position is not advanced.


21.11 The Class java.util.Vector

A Vector, like an array, contains items that can be accessed using an integer index. However, the size of a Vector can grow and shrink as needed to accommodate adding and removing items after the Vector has been created.

public class Vector implements Cloneable {
    protected Object[] elementData;
    protected int elementCount;
    protected int capacityIncrement;
    public Vector(int initialCapacity, int capacityIncrement);
    public Vector(int initialCapacity);
    public Vector();
    public final String toString();
    public Object clone();
    public final Object elementAt(int index)
        throws IndexOutOfBoundsException;
    public final void setElementAt(Object obj, int index)
        throws IndexOutOfBoundsException;
    public final Object firstElement()
        throws NoSuchElementException;
    public final Object lastElement()
        throws NoSuchElementException;
    public final void addElement(Object obj);
    public final void insertElementAt(Object obj, int index)
        throws IndexOutOfBoundsException;
    public final boolean removeElement(Object obj);
    public final void removeElementAt(int index)
        throws IndexOutOfBoundsException;
    public final void removeAllElements();
    public final boolean isEmpty();
    public final int size();
    public final void setSize(int newSize);
    public final int capacity();
    public final void ensureCapacity(int minCapacity);
    public final void trimToSize();
    public final void copyInto(Object anArray[])
        throws IndexOutOfBoundsException;
    public final Enumeration elements();
    public final boolean contains(Object elem);
    public final int indexOf(Object elem);
    public final int indexOf(Object elem, int index)
        throws IndexOutOfBoundsException;
    public final int lastIndexOf(Object elem);
    public final int lastIndexOf(Object elem, int index)
        throws IndexOutOfBoundsException;
}

21.11.1 protected Object[] elementData;

Internally, a Vector keeps its elements in an array that is at least large enough to contain all the elements.

21.11.2 protected int elementCount;

This field holds the number of items currently in this Vector object. Components elementData[0] through elementData[elementCount-1] are the actual items.

21.11.3 protected int capacityIncrement;

When the method ensureCapacity (§21.11.22) must increase the size of the data array in the field elementData (by creating a new array), it increases the size by at least the amount in capacityIncrement; but if capacityIncrement is zero, then it at least doubles the size of the data array.

21.11.4 public Vector(int initialCapacity, int capacityIncrement)

This constructor initializes a newly created Vector so that its internal data array has size initialCapacity and its standard capacity increment is the value of capacityIncrement. Initially, the Vector contains no items.

21.11.5 public Vector(int initialCapacity)

This constructor initializes a newly created Vector so that its internal data array has size initialCapacity and its standard capacity increment is zero. Initially, the Vector contains no items.

21.11.6 public Vector()

This constructor initializes a newly created Vector so that its internal data array has size 10 and its standard capacity increment is zero. Initially the Vector contains no items.

21.11.7 public final String toString()

This Vector is represented in string form as a list of its items, enclosed in ASCII square brackets and separated by the ASCII characters ", " (comma and space). The toString method is used to convert the items to strings; a null reference is rendered as the string "null".

The example fragment:

Vector v = new Vector();
v.addElement("Canberra");
v.addElement("Cancun");
v.addElement("Canandaigua");
System.out.println(v.toString());

produces the output:

[Canberra, Cancun, Canandaigua]

Overrides the toString method of Object (§20.1.2).

21.11.8 public Object clone()

A copy of this Vector is constructed and returned. The copy will contains a reference to a clone of the internal data array, not a reference to the original internal data array of this Vector.

Overrides the clone method of Object (§20.1.5).

21.11.9 public final Object elementAt(int index)
throws IndexOutOfBoundsException

The item of this Vector with the specified index is returned.

If the index is negative or not less than the current size of this Vector, an IndexOutOfBoundsException is thrown.

21.11.10 public final void setElementAt(Object obj, int index)
throws IndexOutOfBoundsException

The item of this Vector with the specified index is replaced with obj, so that obj is now the item at the specified index within this Vector.

If the index is negative or not less than the current size of this Vector, an IndexOutOfBoundsException is thrown.

21.11.11 public final Object firstElement()
throws NoSuchElementException

If this Vector is empty, a NoSuchElementException is thrown. Otherwise, the first item (the item at index 0) is returned.

21.11.12 public final Object lastElement()
throws NoSuchElementException

If this Vector is empty, a NoSuchElementException is thrown. Otherwise, the last item (the item at index size()-1) is returned.

21.11.13 public final void addElement(Object obj)

The size of this Vector is increased by 1 and obj becomes the new last item.

21.11.14 public final void insertElementAt(Object obj, int index)
throws IndexOutOfBoundsException

The size of this Vector is increased by 1 and obj becomes the new item at the specified index. Any item in this Vector that was previously at index k is first moved to index k+1 if and only if k is not less than index.

21.11.15 public final boolean removeElement(Object obj)

If this Vector contains an occurrence of obj, then the first (lowest-indexed) such occurrence is removed, as if by the method removeElementAt (§21.11.16), and true is returned. If this Vector contains no occurrence of obj, this Vector is not modified and false is returned.

21.11.16 public final void removeElementAt(int index)
throws IndexOutOfBoundsException

The size of this Vector is decreased by 1 and the item at the specified index is removed from this Vector. Any item in this Vector that was previously at index k is first moved to index k-1 if and only if k is greater than index.

21.11.17 public final void removeAllElements()

All elements are removed from this Vector, making it empty.

21.11.18 public final boolean isEmpty()

The result is true if and only if this Vector is empty, that is, its size is zero.

21.11.19 public final int size()

The size of this Vector (the number of items it currently contains) is returned.

21.11.20 public final void setSize(int newSize)

The size of this Vector is changed to newSize. If the new size is smaller than the old size, then items are removed from the end and discarded. If the new size is larger than the old size, then the new items are set to null.

21.11.21 public final int capacity()

The current capacity of this Vector (the length of its internal data array, kept in the field elementData) is returned.

21.11.22 public final void ensureCapacity(int minCapacity)

If the current capacity of this Vector is less than minCapacity, then its capacity is increased by replacing its internal data array, kept in the field elementData (§21.11.1), with a larger one. The size of the new data array will be the old size plus capacityIncrement (§21.11.3), unless the value of capacityIncrement is nonpositive, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.

21.11.23 public final void trimToSize()

If the capacity of this Vector is larger than its current size (§21.11.19), then the capacity is changed to equal the size by replacing its internal data array, kept in the field elementData, with a smaller one.

21.11.24 public final void copyInto(Object anArray[])
throws IndexOutOfBoundsException

All the items in this Vector are copied into the array anArray. The item at index k in this Vector is copied into component k of anArray. If the length of anArray is smaller than the size of this Vector, an IndexOutOfBoundsException is thrown.

21.11.25 public final Enumeration elements()

An Enumeration (§21.1) is returned that will generate all items in this Vector. The first item generated is the item at index 0, then the item at index 1, and so on.

21.11.26 public final boolean contains(Object elem)

The result is true if and only if some item in this Vector is the same as elem, as determined by the equals method (§20.1.3).

21.11.27 public final int indexOf(Object elem)

If an item equal to elem is in this Vector, then the index of the first such occurrence is returned, that is, the smallest value k such that:

elem.equals(elementData[k])

is true. If no such item occurs in this Vector, then -1 is returned.

21.11.28 public final int indexOf(Object elem, int index)
throws IndexOutOfBoundsException

If an item equal to elem is in this Vector at position k or higher, then the index of the first such occurrence is returned, that is, the smallest value k such that:

elem.equals(elementData[k]) && (k >= index)

is true. If no such item occurs in this Vector, then -1 is returned.

21.11.29 public final int lastIndexOf(Object elem)

If an item equal to elem is in this Vector, then the index of the last such occurrence is returned, that is, the largest value k such that:

elem.equals(elementData[k])

is true. If no such item occurs in this Vector, then -1 is returned.

21.11.30 public final int lastIndexOf(Object elem, int index)
throws IndexOutOfBoundsException

If an item equal to elem is in this Vector at position k or lower, then the index of the last such occurrence is returned, that is, the largest value k such that:

elem.equals(elementData[k]) && (k <= index)

is true. If no such item occurs in this Vector, then -1 is returned.


21.12 The Class java.util.Stack

. . . and from the stack a thin blue wreath of smoke
Curled through the air across the ripening oats . . .
—Oscar Wilde, Charmides (1881)

The class Stack extends Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.

public class Stack extends Vector {
    public Object push(Object item);
    public Object pop() throws EmptyStackException;
    public Object peek() throws EmptyStackException;
    public boolean empty();
    public int search(Object o);
}

When a stack is first created, it contains no items.

21.12.1 public Object push(Object item)

The item is pushed onto the top of this stack. This has exactly the same effect as:

addElement(item)

See method addElement of Vector (§21.11.13).

21.12.2 public Object pop() throws EmptyStackException

If the stack is empty, an EmptyStackException is thrown. Otherwise, the topmost item (last item of the Vector) is removed and returned.

21.12.3 public Object peek() throws EmptyStackException

If the stack is empty, an EmptyStackException is thrown. Otherwise, the topmost item (last item of the Vector) is returned but not removed.

21.12.4 public boolean empty()

The result is true if and only if the stack contains no items.

21.12.5 public int search(Object o)

If the object o occurs as an item in this Stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack; the topmost item on the stack is considered to be at distance 1. The equals method (§20.1.3) is used to compare o to the items in this Stack.

. . . And overhead in circling listlessness
The cawing rooks whirl round the frosted stacks . . .
—Oscar Wilde, Humanitad (1881)


21.13 The Class java.util.EmptyStackException

A EmptyStackException is thrown to indicate an attempt to pop (§21.12.2) or peek (§21.12.3) an empty Stack object.

public class EmptyStackException extends RuntimeException {
    public EmptyStackException();
}

21.13.1 public EmptyStackException()

This constructor initializes a newly created EmptyStackException with null as its error message string.


21.14 The Class java.util.NoSuchElementException

A NoSuchElementException is thrown to indicate that another element was requested from an Enumeration object that has no more elements to supply. See method nextElement of interface Enumeration (§21.1.2).

public class NoSuchElementException extends RuntimeException {
    public NoSuchElementException();
    public NoSuchElementException(String s);
}

21.14.1 public NoSuchElementException()

This constructor initializes a newly created NoSuchElementException with null as its error message string.

21.14.2 public NoSuchElementException(String s)

This constructor initializes a newly created NoSuchElementException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


 22. The Package java.io

CHAPTER 22

The Package java.io

Input and output in Java is organized around the concept of streams. A stream is a sequence of items, usually 8-bit bytes, read or written over the course of time.

In the java.io package, all input is done through subclasses of the abstract class InputStream, and all output is done through subclasses of the abstract class OutputStream. The one exception to this rule is the class RandomAccessFile, which handles files that allow random access and perhaps intermixed reading and writing of the file.

For an input stream, the source of data might be a file, a String, an array of bytes, or bytes written to an output stream (typically by another thread). There are also "filter input streams" that take data from another input stream and transform or augment the data before delivering it as input. For example, a LineNumberInputStream passes bytes through verbatim but counts line terminators as they are read.

For an output stream, the sink of data might be a file, an array of bytes, or a buffer to be read as an input stream (typically by another thread). There are also "filter output streams" that transform or augment data before writing it to some other output stream.

An instance of class File represents a path name (a string) that might identify a particular file within a file system. Certain operations on the file system, such as renaming and deleting files, are done by this class rather than through streams.

An instance of class FileDescriptor represents an abstract indication of a particular file within a file system; such file descriptors are created internally by the Java I/O system.

There are two interfaces, DataInput and DataOutput, that support the transfer of data other than bytes or characters, such as long integers, floating-point numbers and strings. The class DataInputStream implements DataInput; the class DataOutputStream implements DataOutput; and RandomAccessFile implements both DataInput and DataOutput.

The class StreamTokenizer provides some simple support for parsing bytes or characters from an input stream into tokens such as identifiers, numbers, and strings, optionally ignoring comments and optionally recognizing or ignoring line terminators.

The hierarchy of classes defined in package java.io is as follows. (Classes whose names are shown here in boldface are in package java.io; the others are in package java.lang and are shown here to clarify subclass relationships.)

Object	§20.1
    interface DataInput	§22.1
    interface DataOutput	§22.2
    InputStream	§22.3
        FileInputStream	§22.4
        PipedInputStream	§22.5
        ByteArrayInputStream	§22.6
        StringBufferInputStream	§22.7
        SequenceInputStream	§22.8
        FilterInputStream	§22.9
            BufferedInputStream	§22.10
            DataInputStream	§22.11
            LineNumberInputStream	§22.12
            PushBackInputStream	§22.13
    StreamTokenizer	§22.14
    OutputStream	§22.15
        FileOutputStream	§22.16
        PipedOutputStream	§22.17
        ByteArrayOutputStream	§22.18
        FilterOutputStream	§22.19
            BufferedOutputStream	§22.20
            DataOutputStream	§22.21
            PrintStream	§22.22
    RandomAccessFile	§22.23
    File	§22.24
    interface FileNameFilter	§22.25
    FileDescriptor	§22.26
    Throwable	§20.22
        Exception
            IOException	§22.27
                EOFException	§22.28
                FileNotFoundException	§22.29
                InterruptedIOException	§22.30
                UTFDataFormatException	§22.31


22.1 The Interface java.io.DataInput

The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types. There is also a facility for reconstructing a String from data in Java modified UTF-8 format.

The DataOutput interface (§22.2) supports the creation of binary output data suitable for reading back in through the DataInput interface.

The DataInput interface is implemented by classes DataInputStream (§22.11) and RandomAccessFile (§22.23).

public interface DataInput {
    public void readFully(byte[] b)
        throws IOException, NullPointerException;
    public void readFully(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public int skipBytes(int n) throws IOException;
    public boolean readBoolean() throws IOException;
    public byte readByte() throws IOException;
    public int readUnsignedByte() throws IOException;
    public short readShort() throws IOException;
    public int readUnsignedShort() throws IOException;
    public char readChar() throws IOException;
    public int readInt() throws IOException;
    public long readLong() throws IOException;
    public float readFloat() throws IOException;
    public double readDouble() throws IOException;
    public String readLine() throws IOException;
    public String readUTF() throws IOException;
    public final static String readUTF(DataInput in)
        throws IOException;
}

It is generally true of all the reading routines in this interface that if end of file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown. If any byte cannot be read for any reason other than end of file, an IOException other than EOFException is thrown. In particular, an IOException may be thrown if the input stream has been closed (§22.3.6).

22.1.1 public void readFully(byte[] b)
throws IOException, NullPointerException;

The general contract of readFully(b) is that it reads some bytes from an input stream and stores them into the buffer array b. The number of bytes read is equal to the length of b.

This method blocks until one of the following conditions occurs:

  • b.length bytes of input data are available, in which case a normal return is made.
  • End of file is detected, in which case an EOFException is thrown.
  • An I/O error occurs, in which case an IOException other than EOFException is thrown.

If b is null, a NullPointerException is thrown.

If b.length is zero, then no bytes are read. Otherwise, the first byte read is stored into element b[0], the next one into b[1], and so on.

If an exception is thrown from this method, then it may be that some but not all bytes of b have been updated with data from the input stream.

22.1.2 public void readFully(byte[] b, int off, int len)
throws IOException, NullPointerException,
IndexOutOfBoundsException

The general contract of readFully(b, off, len) is that it reads len bytes from an input stream.

This method blocks until one of the following conditions occurs:

  • len bytes of input data are available, in which case a normal return is made.
  • End of file is detected, in which case an EOFException is thrown.
  • An I/O error occurs, in which case an IOException other than EOFException is thrown.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If len is zero, then no bytes are read. Otherwise, the first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len.

If an exception is thrown from this method, then it may be that some but not all bytes of b in positions off through off+len-1 have been updated with data from the input stream.

22.1.3 public int skipBytes(int n) throws IOException

The general contract of skipBytes is that it makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. This method never throws an EOFException. The actual number of bytes skipped is returned.

22.1.4 public boolean readBoolean() throws IOException;

The general contract of readBoolean is that it reads one input byte and returns true if that byte is nonzero, false if that byte is zero.

This method is suitable for reading the byte written by the writeBoolean method of interface DataOutput (§22.2.4).

22.1.5 public byte readByte() throws IOException

The general contract of readByte is that it reads and returns one input byte. The byte is treated as a signed value in the range -128 through 127, inclusive.

This method is suitable for reading the byte written by the writeByte method of interface DataOutput (§22.2.5).

22.1.6 public int readUnsignedByte() throws IOException

The general contract of readUnsignedByte is that it reads one input byte, zero- extends it to type int, and returns the result, which is therefore in the range 0 through 255.

This method is suitable for reading the byte written by the writeByte method of interface DataOutput (§22.2.5) if the argument to writeByte was intended to be a value in the range 0 through 255.

22.1.7 public short readShort() throws IOException

The general contract of readShort is that it reads two input bytes and returns a short value. Let a be the first byte read and b be the second byte. The value returned is:

(short)((a << 8) | (b & 0xff))

This method is suitable for reading the bytes written by the writeShort method of interface DataOutput (§22.2.6).

22.1.8 public int readUnsignedShort() throws IOException

The general contract of readUnsignedShort is that it reads two input bytes and returns an int value in the range 0 through 65535. Let a be the first byte read and b be the second byte. The value returned is:

(((a & 0xff) << 8) | (b & 0xff))

This method is suitable for reading the bytes written by the writeShort method of interface DataOutput (§22.2.6) if the argument to writeShort was intended to be a value in the range 0 through 65535.

22.1.9 public char readChar() throws IOException

The general contract of readChar is that it reads two input bytes and returns a char value. Let a be the first byte read and b be the second byte. The value returned is:

(char)((a << 8) | (b & 0xff))

This method is suitable for reading bytes written by the writeChar method of interface DataOutput (§22.2.7).

22.1.10 public int readInt() throws IOException

The general contract of readInt is that it reads four input bytes and returns an int value. Let a be the first byte read, b be the second byte, c be the third byte, and d be the fourth byte. The value returned is:

(((a & 0xff) << 24) | ((b & 0xff) << 16) |
  ((c & 0xff) <<    8) | (d & 0xff))

This method is suitable for reading bytes written by the writeInt method of interface DataOutput (§22.2.8).

22.1.11 public long readLong() throws IOException

The general contract of readLong is that it reads eight input bytes and returns a long value. Let a be the first byte read, b be the second byte, c be the third byte, d be the fourth byte, e be the fifth byte, f be the sixth byte, g be the seventh byte, and h be the eighth byte. The value returned is:

(((long)(a & 0xff) << 56) |
  ((long)(b & 0xff) << 48) |
  ((long)(c & 0xff) <<  40) |
  ((long)(d & 0xff) << 32) |
  ((long)(e & 0xff) <<  24) |
  ((long)(f & 0xff) << 16) |
  ((long)(g & 0xff) <<    8) |
  ((long)(h & 0xff)))

This method is suitable for reading bytes written by the writeLong method of interface DataOutput (§22.2.9).

22.1.12 public float readFloat() throws IOException

The general contract of readFloat is that it reads four input bytes and returns a float value. It does this by first constructing an int value in exactly the manner of the readInt method (§22.1.10), then converting this int value to a float in exactly the manner of the method Float.intBitsToFloat (§20.9.23).

This method is suitable for reading bytes written by the writeFloat method of interface DataOutput (§22.2.10).

22.1.13 public double readDouble() throws IOException

The general contract of readDouble is that it reads eight input bytes and returns a double value. It does this by first constructing a long value in exactly the manner of the readlong method (§22.1.11), then converting this long value to a double in exactly the manner of the method Double.longBitsToDouble (§20.10.22).

This method is suitable for reading bytes written by the writeDouble method of interface DataOutput (§22.2.11).

22.1.14 public String readLine() throws IOException

The general contract of readLine is that it reads successive bytes, converting each byte separately into a character, until it encounters a line terminator or end of file; the characters read are then returned as a String. Note that because this method processes bytes, it does not support input of the full Unicode character set.

If end of file is encountered before even one byte can be read, then null is returned. Otherwise, each byte that is read is converted to type char by zero-extension. If the character '\n' is encountered, it is discarded and reading ceases. If the character '\r' is encountered, it is discarded and, if the following byte converts to the character '\n', then that is discarded also; reading then ceases. If end of file is encountered before either of the characters '\n' and '\r' is encountered, reading ceases. Once reading has ceased, a String is returned that contains all the characters read and not discarded, taken in order. Note that every character in this string will have a value less than \u0100, that is, (char)256.

22.1.15 public String readUTF() throws IOException

The general contract of readUTF is that it reads a representation of a Unicode character string encoded in Java modified UTF-8 format; this string of characters is then returned as a String.

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method (§22.1.8). This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

If the first byte of a group matches the bit pattern 0xxxxxxx (where x means "may be 0 or 1"), then the group consists of just that byte. The byte is zero-extended to form a character.

If the first byte of a group matches the bit pattern 110xxxxx, then the group consists of that byte a and a second byte b. If there is no byte b (because byte a was the last of the bytes to be read), or if byte b does not match the bit pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character:

(char)(((a & 0x1F) << 6) | (b & 0x3F))

If the first byte of a group matches the bit pattern 1110xxxx, then the group consists of that byte a and two more bytes b and c. If there is no byte c (because byte a was one of the last two of the bytes to be read), or either byte b or byte c does not match the bit pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character:

(char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))

If the first byte of a group matches the pattern 1111xxxx or the pattern 10xxxxxx, then a UTFDataFormatException is thrown.

If end of file is encountered at any time during this entire process, then an EOFException is thrown.

After every group has been converted to a character by this process, the characters are gathered, in the same order in which their corresponding groups were read from the input stream, to form a String, which is returned.

The writeUTF method of interface DataOutput (§22.2.14) may be used to write data that is suitable for reading by this method.


22.2 The Interface java.io.DataOutput

The DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream. There is also a facility for converting a String into Java modified UTF-8 format and writing the resulting series of bytes.

The DataInput interface (§22.1) can be used to read in and reconstruct Java data from the binary output data produced by the DataOutput interface.

The DataOutput interface is implemented by classes DataOutputStream (§22.21) and RandomAccessFile (§22.23).

public interface DataOutput {
    public void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void writeBoolean(boolean v) throws IOException;
    public void writeByte(int v) throws IOException;
    public void writeShort(int v) throws IOException;
    public void writeChar(int v) throws IOException;
    public void writeInt(int v) throws IOException;
    public void writeLong(long v) throws IOException;
    public void writeFloat(float v) throws IOException;
    public void writeDouble(double v) throws IOException;
    public void writeBytes(String s)
        throws IOException, NullPointerException;
    public void writeChars(String s)
        throws IOException, NullPointerException;
    public void writeUTF(String s)
        throws IOException, NullPointerException;
}

For all the methods in this interface that write bytes, it is generally true that if a byte cannot be written for any reason, an IOException is thrown.

22.2.1 public void write(int b) throws IOException

The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

22.2.2 public void write(byte[] b)
throws IOException, NullPointerException

The general contract for write is that all the bytes in array b are written, in order, to the output stream.

If b is null, a NullPointerException is thrown.

If b.length is zero, then no bytes are written. Otherwise, the byte b[0] is written first, then b[1], and so on; the last byte written is b[b.length-1].

22.2.3 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

The general contract for write is that len bytes from array b are written, in order, to the output stream.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If len is zero, then no bytes are written. Otherwise, the byte b[off] is written first, then b[off+1], and so on; the last byte written is b[off+len-1].

22.2.4 public void writeBoolean(boolean v) throws IOException

The general contract for writeBoolean is that one byte is written to the output stream. If the argument v is true, the value (byte)1 is written; if v is false, the value (byte)0 is written.

The byte written by this method may be read by the readBoolean method of interface DataInput (§22.1.4), which will then return a boolean equal to v.

22.2.5 public void writeByte(int v) throws IOException

The general contract for writeByte is that one byte is written to the output stream to represent the value of the argument. The byte to be written is the eight low- order bits of the argument b. The 24 high-order bits of b are ignored. (This means that writeByte does exactly the same thing as write for an integer argument.)

The byte written by this method may be read by the readByte method of interface DataInput (§22.1.5), which will then return a byte equal to (byte)v.

22.2.6 public void writeShort(int v) throws IOException

The general contract for writeShort is that two bytes are written to the output stream to represent the value of the argument. The byte values to be written, in the order shown, are:

(byte)(0xff & (v >> 8))
(byte)(0xff & v)

The bytes written by this method may be read by the readShort method of interface DataInput (§22.1.7), which will then return a short equal to (short)v.

22.2.7 public void writeChar(int v) throws IOException

The general contract for writeChar is that two bytes are written to the output stream to represent the value of the argument. The byte values to be written, in the order shown, are:

(byte)(0xff & (v >> 8))
(byte)(0xff & v)

The bytes written by this method may be read by the readChar method of interface DataInput (§22.1.9), which will then return a char equal to (char)v.

22.2.8 public void writeInt(int v) throws IOException

The general contract for writeInt is that four bytes are written to the output stream to represent the value of the argument. The byte values to be written, in the order shown, are:

(byte)(0xff & (v >> 24))
(byte)(0xff & (v >> 16))
(byte)(0xff & (v >>    8))
(byte)(0xff & v)

The bytes written by this method may be read by the readInt method of interface DataInput (§22.1.10), which will then return an int equal to v.

22.2.9 public void writeLong(long v) throws IOException

The general contract for writeLong is that four bytes are written to the output stream to represent the value of the argument. The byte values to be written, in the order shown, are:

(byte)(0xff & (v >> 56))
(byte)(0xff & (v >> 48))
(byte)(0xff & (v >> 40))
(byte)(0xff & (v >> 32))
(byte)(0xff & (v >> 24))
(byte)(0xff & (v >> 16))
(byte)(0xff & (v >>    8))
(byte)(0xff & v)

The bytes written by this method may be read by the readLong method of interface DataInput (§22.1.11), which will then return a long equal to v.

22.2.10 public void writeFloat(float v) throws IOException

The general contract for writeFloat is that four bytes are written to the output stream to represent the value of the argument. It does this as if it first converts this float value to an int in exactly the manner of the Float.floatToIntBits method (§20.9.22) and then writes the int value in exactly the manner of the writeInt method (§22.2.8).

The bytes written by this method may be read by the readFloat method of interface DataInput (§22.1.12), which will then return a float equal to v.

22.2.11 public void writeDouble(double v) throws IOException

The general contract for writeDouble is that eight bytes are written to the output stream to represent the value of the argument. It does this as if it first converts this double value to a long in exactly the manner of the Double.doubleToLongBits method (§20.10.21) and then writes the long value in exactly the manner of the writeLong method (§22.2.9).

The bytes written by this method may be read by the readDouble method of interface DataInput (§22.1.13), which will then return a double equal to v.

22.2.12 public void writeBytes(String s)
throws IOException, NullPointerException

The general contract for writeBytes is that for every character in the string s, taken in order, one byte is written to the output stream.

If s is null, a NullPointerException is thrown.

If s.length is zero, then no bytes are written. Otherwise, the character s[0] is written first, then s[1], and so on; the last character written is s[s.length-1]. For each character, one byte is written, the low-order byte, in exactly the manner of the writeByte method (§22.2.5). The high-order eight bits of each character in the string are ignored.

22.2.13 public void writeChars(String s)
throws IOException, NullPointerException

The general contract for writeChars is that every character in the string s is written, in order, to the output stream, two bytes per character.

If s is null, a NullPointerException is thrown.

If s.length is zero, then no characters are written. Otherwise, the character s[0] is written first, then s[1], and so on; the last character written is s[s.length-1]. For each character, two bytes are actually written, high-order byte first, in exactly the manner of the writeChar method (§22.2.7).

22.2.14 public void writeUTF(String s)
throws IOException, NullPointerException

The general contract for writeUTF is that two bytes of length information are written to the output stream, followed by the Java modified UTF representation of every character in the string s.

If s is null, a NullPointerException is thrown.

Each character in the string s is converted to a group of one, two, or three bytes, depending on the value of the character.

If a character c is in the range '\u0001' through '\u007f', it is represented by one byte:

(byte)c

If a character c is '\u0000' or is in the range '\u0080' through '\u07ff', then it is represented by two bytes, to be written in the order shown:

(byte)(0xc0 | (0x1f & (c >> 6)))
(byte)(0x80 | (0x3f & c))

If a character c is in the range '\u0800' through '\uffff', then it is represented by three bytes, to be written in the order shown:

(byte)(0xc0 | (0x0f & (c >> 12)))
(byte)(0x80 | (0x3f & (c >>    6)))
(byte)(0x80 | (0x3f & c))

First, the total number of bytes needed to represent all the characters of s is calculated. If this number is larger than 65535, then a UTFDataFormatError is thrown. Otherwise, this length is written to the output stream in exactly the manner of the writeShort method (§22.2.6); after this, the one-, two-, or three-byte representation of each character in the string s is written.

The bytes written by this method may be read by the readUTF method of interface DataInput (§22.1.15), which will then return a String equal to s.


22.3 The Class java.io.InputStream

An input stream makes input bytes available from some source.

public abstract class InputStream {
    public abstract int read() throws IOException;
    public int read(byte[] b)
    throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public long skip(long n) throws IOException;
    public int available() throws IOException;
    public void close() throws IOException;
    public void mark(int readlimit);
    public void reset() throws IOException;
    public boolean markSupported();
}

22.3.1 public abstract int read() throws IOException

The general contract of read is that it reads one byte from the input stream. The byte is returned as an integer in the range 0 to 255 (0x00-0xff). If no byte is available because the stream is at end of file, the value -1 is returned.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the byte cannot be read for any reason other than end of file, an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed (§22.3.6).

22.3.2 public int read(byte[] b)
throws IOException, NullPointerException

The general contract of read(b) is that it reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown.

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed (§22.15.5).

The read(b) method for class InputStream has the same effect as:

read(b, 0, b.length)

22.3.3 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException,
IndexOutOfBoundsException

The general contract of read(b, off, len) is that it reads some number of bytes from the input stream and stores them into the buffer array b. An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed (§22.15.5).

The read(b, off, len) method for class InputStream simple calls the method read() repeatedly. If the first such call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of file; the bytes read up to that point are stored into b and the number of bytes read before the exception occurred is returned.

22.3.4 public long skip(long n) throws IOException

The general contract of skip is that it makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. The actual number of bytes skipped is returned.

22.3.5 public int available() throws IOException

The general contract of available is that it returns an integer k; the next caller of a method for this input stream, which might be the same thread or another thread, can then expect to be able to read or skip up to k bytes without blocking (waiting for input data to arrive).

The available method for class InputStream always returns 0.

22.3.6 public int close() throws IOException

The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and cannot be reopened.

The close method for class InputStream does nothing and simply returns.

22.3.7 public void mark(int readlimit)

The general contract of mark is that, if the method markSupported returns true, the stream somehow remembers all the bytes read after the call to mark and stands ready to supply those same bytes again if and whenever the method reset is called. However, the stream is not required to remember any data at all if more than readlimit bytes are read from the stream before reset is called.

The mark method for class InputStream does nothing.

22.3.8 public void reset() throws IOException

The general contract of reset is:

  • If the method markSupported returns true, then:
    • If the method mark has not been called since the stream was created, or the number of bytes read from the stream since mark was last called is larger than the argument to mark at that last call, then an IOException might be thrown.
    • If such an IOException is not thrown, then the stream is reset to a state such that all the bytes read since the most recent call to mark (or since the start of the file, if mark has not been called) will be resupplied to subsequent callers of the read method, followed by any bytes that otherwise would have been the next input data as of the time of the call to reset.
  • If the method markSupported returns false, then:
    • The call to reset may throw an IOException.
    • If an IOException is not thrown, then the stream is reset to a fixed state that depends on the particular type of the input stream and how it was created. The bytes that will be supplied to subsequent callers of the read method depend on the particular type of the input stream.

The method reset for class InputStream always throws an IOException.

22.3.9 public boolean markSupported()

The general contract of markSupported is that if it returns true, then the stream supports the mark (§22.3.7) and reset (§22.3.8) operations. For any given instance of InputStream, this method should consistently return the same truth value whenever it is called.

The markSupported method for class InputStream returns false.


22.4 The Class java.io.FileInputStream

A file input stream obtains input bytes from a file in a file system. What files are available depends on the host environment.

public class FileInputStream extends InputStream  {
    public FileInputStream(String path)
        throws SecurityException, FileNotFoundException;
    public FileInputStream(File file)
        throws SecurityException, FileNotFoundException;
    public FileInputStream(FileDescriptor fdObj)
        throws SecurityException;
    public native int read() throws IOException;
    public int read(byte[] b)
        throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public native long skip(long n) throws IOException;
    public native int available() throws IOException;
    public native void close() throws IOException;
    public final FileDescriptor getFD() throws IOException;
    protected void finalize() throws IOException;
}

22.4.1 public FileInputStream(String path)
throws SecurityException, FileNotFoundException

This constructor initializes a newly created FileInputStream by opening a connection to an actual file, the file named by the path name path in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path argument as its argument.

If the actual file cannot be opened, a FileNotFoundException is thrown.

22.4.2 public FileInputStream(File file)
throws SecurityException, FileNotFoundException

This constructor initializes a newly created FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by the file argument as its argument.

If the actual file cannot be opened, a FileNotFoundException is thrown.

22.4.3 public FileInputStream(FileDescriptor fdObj)
throws SecurityException

This constructor initializes a newly created FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

First, if there is a security manager, its checkRead method (§20.17.18) is called with the file descriptor fdObj as its argument.

22.4.4 public final FileDescriptor getFD() throws IOException

This method returns the FileDescriptor object (§22.26) that represents the connection to the actual file in the file system being used by this FileInputStream.

22.4.5 public int read() throws IOException;

The byte for this operation is read from the actual file with which this file input stream is connected.

Implements the read method of InputStream (§22.3.1).

22.4.6 public int read(byte[] b)
throws IOException, NullPointerException

Bytes for this operation are read from the actual file with which this file input stream is connected.

Overrides the read method of InputStream (§22.3.2).

22.4.7 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

Bytes for this operation are read from the actual file with which this file input stream is connected.

Overrides the read method of InputStream (§22.3.3).

22.4.8 public long skip(long n) throws IOException

Bytes for this operation are read from the actual file with which this file input stream is connected.

Overrides the skip method of InputStream (§22.3.4).

22.4.9 public int available() throws IOException

Overrides the available method of InputStream (§22.3.5).

22.4.10 public void close() throws IOException

This file input stream is closed and may no longer be used for reading bytes.

Overrides the close method of InputStream (§22.3.6).

22.4.11 protected void finalize() throws IOException

A FileInputStream uses finalization to clean up the connection to the actual file.


22.5 The Class java.io.PipedInputStream

A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream. Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream (§22.17) by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread. The piped input stream contains a buffer, decoupling read operations from write operations, within limits.

public class PipedInputStream extends InputStream {
    public PipedInputStream (PipedOutputStream src)
        throws IOException;
    public PipedInputStream ();
    public void connect(PipedOutputStream src)
        throws IOException;
    public int read()  throws IOException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void close() throws IOException;
}

22.5.1 public PipedInputStream(PipedOutputStream src)
throws IOException

This constructor initializes a newly created PipedInputStream so that it is connected to the piped output stream src. Data bytes written to src will then be available as input from this stream.

22.5.2 public PipedInputStream()

This constructor initializes a newly created PipedInputStream so that it is not yet connected. It must be connected to a PipedOutputStream before being used.

22.5.3 public void connect(PipedOutputStream src)
throws IOException

The connect method causes this piped input stream to be connected to the piped output stream src. If this object is already connected to some other piped output stream, an IOException is thrown.

If src is an unconnected piped output stream and snk is an unconnected piped input stream, they may be connected by either the call:

snk.connect(src)

or the call:

src.connect(snk)

The two calls have the same effect.

22.5.4 public int read() throws IOException

If a thread was providing data bytes to the connected piped output stream, but the thread is no longer alive, then an IOException is thrown.

Implements the read method of InputStream (§22.3.1).

22.5.5 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

If a thread was providing data bytes to the connected piped output stream, but the thread is no longer alive, then an IOException is thrown.

Overrides the read method of InputStream (§22.3.3).

22.5.6 public void close() throws IOException

This piped input stream is closed and may no longer be used for reading bytes.

Overrides the close method of InputStream (§22.3.6).


22.6 The Class java.io.ByteArrayInputStream

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. See also StringBufferInputStream (§22.7).

public class ByteArrayInputStream extends InputStream {
    protected byte[] buf;
    protected int pos;
    protected int count;
    public ByteArrayInputStream(byte[] buf);
    public ByteArrayInputStream(byte[] buf,
            int offset, int length);
    public int read()
        throws NullPointerException, IndexOutOfBoundsException;
    public int read(byte[] b, int off, int len)
        throws NullPointerException, IndexOutOfBoundsException;
    public long skip(long n);
    public int available();
    public void reset();
}

22.6.1 protected byte[] buf;

An array of bytes that was provided by the creator of the stream. Elements buf[0] through buf[count-1] are the only bytes that can ever be read from the stream; element buf[pos] is the next byte to be read.

22.6.2 protected int pos;

This value should always be nonnegative and not larger than the value of count. The next byte to be read from this stream will be buf[pos].

22.6.3 protected int count;

This value should always be nonnegative and not larger than the length of buf. It is one greater than the position of the last byte within buf that can ever be read from this stream.

22.6.4 public ByteArrayInputStream(byte[] buf)

This constructor initializes a newly created ByteArrayInputStream so that it uses buf as its buffer array. The initial value of pos is 0 and the initial value of count is the length of buf.

22.6.5 public ByteArrayInputStream(byte[] buf,
int offset, int length)

This constructor initializes a newly created ByteArrayInputStream so that it uses buf as its buffer array. The initial value of pos is offset and the initial value of count is offset+len.

Note that if bytes are simply read from the resulting input stream, elements buf[pos] through buf[pos+len-1] will be read; however, if a reset operation (§22.6.10) is performed, then bytes buf[0] through buf[pos-1] will then become available for input.

22.6.6 public int read()
throws NullPointerException, IndexOutOfBoundsException

If pos equals count, then -1 is returned to indicate end of file. Otherwise, the value buf[pos]&0xff is returned; just before the return, pos is incremented by 1.

Implements the read method of InputStream (§22.3.1).

22.6.7 public int read(byte[] b, int off, int len)
throws NullPointerException, IndexOutOfBoundsException

If pos equals count, then -1 is returned to indicate end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos. If k is positive, then bytes buf[pos] through buf[pos+k-1] are copied into b[off] through b[off+k-1] in the manner performed by System.arraycopy (§20.18.16). The value k is added into pos and k is returned.

Overrides the read method of InputStream (§22.3.3).

22.6.8 public long skip(long n)

The actual number k of bytes to be skipped is equal to the smaller of n and count-pos. The value k is added into pos and k is returned.

Overrides the skip method of InputStream (§22.3.4).

22.6.9 public int available()

The quantity count-pos is returned.

Overrides the available method of InputStream (§22.3.5).

22.6.10 public void reset()

The value of pos is set to 0.

Overrides the reset method of InputStream (§22.3.8).


22.7 The Class java.io.StringBufferInputStream

A StringBufferInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. See also ByteArrayInputStream (§22.6).

public class StringBufferInputStream extends InputStream {
    protected String buffer;
    protected int pos;
    protected int count;
    public StringBufferInputStream(String s)
        throws NullPointerException;
    public int read();
    public int read(byte[] b, int off, int len)
        throws NullPointerException, IndexOutOfBoundsException;
    public long skip(long n);
    public int available();
    public void reset();
}

Note that bytes read from a StringBufferInputStream are the low-order eight bits of each character in the string; the high-order eight bits of each character are ignored.

22.7.1 protected String buffer;

A String that was provided by the creator of the stream. Elements buffer[0] through buffer[count-1] are the only bytes that can ever be read from this stream; element buffer[pos] is the next byte to be read.

22.7.2 protected int pos;

This value should always be nonnegative and not larger than the value of count. The next byte to be read from this stream will be buffer[pos].

22.7.3 protected int count;

This value equals the length of buffer. It is the number of bytes of data in buffer that can ever be read from this stream.

22.7.4 public StringBufferInputStream(String s)
throws NullPointerException

This constructor initializes a newly created StringBufferInputStream so that it uses s as its buffer array. The initial value of pos is 0 and the initial value of count is the length of buffer.

22.7.5 public int read()

If pos equals count, then -1 is returned to indicate end of file. Otherwise, the value buffer[pos]&0xff is returned; just before the return, 1 is added to pos.

Implements the read method of InputStream (§22.3.1).

22.7.6 public int read(byte[] b, int off, int len)
throws NullPointerException, IndexOutOfBoundsException

If pos equals count, then -1 is returned to indicate end of file. Otherwise, the number k of bytes read is equal to the smaller of len and count-pos. If k is positive, then bytes buffer[pos] through buffer[pos+k-1] are copied into b[off] through b[off+k-1] in the manner performed by System.arraycopy (§20.18.16). The value k is added into pos and k is returned.

Overrides the read method of InputStream (§22.3.3).

22.7.7 public long skip(long n)

The actual number k of bytes to be skipped is equal to the smaller of n and count-pos. The value k is added into pos and k is returned.

Overrides the skip method of InputStream (§22.3.4).

22.7.8 public int available()

The quantity count-pos is returned.

Overrides the available method of InputStream (§22.3.5).

22.7.9 public void reset()

The value of pos is set to 0.

Overrides the reset method of InputStream (§22.3.8).


22.8 The Class java.io.SequenceInputStream

A SequenceInputStream represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.

public class SequenceInputStream extends InputStream {
    public SequenceInputStream(Enumeration e);
    public SequenceInputStream(InputStream s1, InputStream s2);
    public int read() throws IOException;
    public int read(byte[] buf, int pos, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void close() throws IOException;
}

22.8.1 public SequenceInputStream(Enumeration e)

This constructor initializes a newly created SequenceInputStream by remembering the argument, which must be an Enumeration (§21.1) that produces objects whose run-time type is InputStream (§22.3). The input streams that are produced by the enumeration will be read, in order, to provide the bytes to be read from this SequenceInputStream. After each input stream from the enumeration is exhausted, it is closed by calling its close method.

22.8.2 public SequenceInputStream(InputStream s1,
InputStream s2)

This constructor initializes a newly created SequenceInputStream by remembering the two arguments, which will be read in order, first s1 and then s2, to provide the bytes to be read from this SequenceInputStream.

22.8.3 public int read() throws IOException

Implements the read method of InputStream (§22.3.1).

22.8.4 public int read(byte[] buf, int pos, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

Overrides the read method of InputStream (§22.3.3).

22.8.5 public void close() throws IOException

This SequenceInputStream is closed. A closed SequenceInputStream cannot perform input operations and cannot be reopened.

If this stream was created from an enumeration, all remaining elements are requested from the enumeration and closed before the close method returns.

Overrides the close method of InputStream (§22.3.6).


22.9 The Class java.io.FilterInputStream

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. The class FilterInputStream itself simply overrides all methods of InputStream with versions that pass all requests to the contained input stream. Subclasses of FilterInputStream may further override some of these methods and may also provide additional methods and fields.

public class FilterInputStream extends InputStream {
    protected InputStream in;
    protected FilterInputStream(InputStream in);
    public int read() throws IOException;
    public int read(byte[] b)
        throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public long skip(long n) throws IOException;
    public int available() throws IOException;
    public void close() throws IOException;
    public void mark(int readlimit);
    public void reset() throws IOException;
    public boolean markSupported();
}

22.9.1 protected InputStream in;

The input stream to be filtered.

22.9.2 protected FilterInputStream(InputStream in)

This constructor initializes a newly created FilterInputStream by assigning the argument in to the field this.in so as to remember it for later use.

22.9.3 public int read() throws IOException

This method simply performs in.read() and returns the result.

Implements the read method of InputStream (§22.3.1).

22.9.4 public int read(byte[] b)
throws IOException, NullPointerException

This method simply performs the call read(b, 0, b.length) and returns the result. It is important that it does not do in.read(b) instead; certain subclasses of FilterInputStream depend on the implementation strategy actually used.

Overrides the read method of InputStream (§22.3.2).

22.9.5 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

This method simply performs in.read(b, off, len) and returns the result.

Overrides the read method of InputStream (§22.3.3).

22.9.6 public long skip(long n) throws IOException

This method simply performs in.skip() and returns the result.

Overrides the skip method of InputStream (§22.3.4).

22.9.7 public int available() throws IOException

This method simply performs in.available() and returns the result.

Overrides the available method of InputStream (§22.3.5).

22.9.8 public void close() throws IOException

This method simply performs in.close().

Overrides the close method of InputStream (§22.3.6).

22.9.9 public void mark(int readlimit)

This method simply performs in.mark().

Overrides the mark method of InputStream (§22.3.7).

22.9.10 public void reset() throws IOException

This method simply performs in.reset().

Overrides the reset method of InputStream (§22.3.8).

22.9.11 public boolean markSupported()

This method simply performs in.markSupported() and returns whatever value is returned from that invocation.

Overrides the markSupported method of InputStream (§22.3.9).


22.10 The Class java.io.BufferedInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

public class BufferedInputStream extends FilterInputStream {
    protected byte[] buf;
    protected int count = 0;
    protected int pos = 0;
    protected int markpos = -1;
    protected int marklimit = 0;
    public BufferedInputStream(InputStream in);
    public BufferedInputStream(InputStream in, int size);
    public int read() throws IOException;
    public int read(byte[] b)
        throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public long skip(long n) throws IOException;
    public int available() throws IOException;
    public void mark(int readlimit);
    public void reset() throws IOException;
    public boolean markSupported();
}

22.10.1 protected byte[] buf;

The internal buffer array. When necessary, it may be replaced by another array of a different size.

22.10.2 protected int count = 0;

This value is always in the range 0 through buf.length; elements buf[0] through buf[count-1] contain buffered input data obtained from the underlying input stream.

22.10.3 protected int pos = 0;

This value is always in the range 0 through count. If it is less than count, then buf[pos] is the next byte to be supplied as input; if it is equal to count, then the next read or skip operation will require more bytes to be read from the contained input stream.

22.10.4 protected int markpos = -1;

This value is always in the range -1 through pos. If there is no marked position in the input stream, this field is -1. If there is a marked position in the input stream, then buf[markpos] is the first byte to be supplied as input after a reset operation. If markpos is not -1, then all bytes from positions buf[markpos] through buf[pos-1] must remain in the buffer array (though they may be moved to another place in the buffer array, with suitable adjustments to the values of count, pos, and markpos); they may not be discarded unless and until the difference between pos and markpos exceeds marklimit.

22.10.5 protected int marklimit;

Whenever the difference between pos and markpos exceeds marklimit, then the mark may be dropped by setting markpos to -1.

22.10.6 public BufferedInputStream(InputStream in)

This constructor initializes a newly created BufferedInputStream by saving its argument, the input stream in, for later use. An internal buffer array is created and stored in buf.

22.10.7 public BufferedInputStream(InputStream in, int size)

This constructor initializes a newly created BufferedInputStream by saving its argument, the input stream in, for later use. An internal buffer array of length size is created and stored in buf.

22.10.8 public int read() throws IOException

See the general contract of the read method of InputStream (§22.3.1).

Overrides the read method of FilterInputStream (§22.9.3).

22.10.9 public int read(byte[] b)
throws IOException, NullPointerException

See the general contract of the read method of InputStream (§22.3.2).

Overrides the read method of FilterInputStream (§22.9.4).

22.10.10 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the read method of InputStream (§22.3.3).

Overrides the read method of FilterInputStream (§22.9.5).

22.10.11 public long skip(long n) throws IOException

See the general contract of the skip method of InputStream (§22.3.4).

Overrides the skip method of FilterInputStream (§22.9.6).

22.10.12 public int available() throws IOException

See the general contract of the available method of InputStream (§22.3.5).

Overrides the available method of FilterInputStream (§22.9.7).

22.10.13 public void mark(int readlimit)

The field marklimit is set equal to the argument and markpos is set equal to pos

Overrides the mark method of FilterInputStream (§22.9.9).

22.10.14 public void reset() throws IOException

See the general contract of the reset method of InputStream (§22.3.8).

If markpos is -1 (no mark has been set or the mark has been invalidated), an IOException is thrown. Otherwise, pos is set equal to markpos.

Overrides the reset method of FilterInputStream (§22.9.10).

22.10.15 public boolean markSupported()

This method returns true (a BufferedInputStream always supports mark).

Overrides the markSupported method of FilterInputStream (§22.9.11).


22.11 The Class java.io.DataInputStream

A data input stream provides facilities for reading bytes from an input source and interpreting specific character sequences as representing data of diverse types.

public class DataInputStream extends FilterInputStream
        implements DataInput {
    public DataInputStream(InputStream in);
    public final void readFully(byte[] b)
        throws IOException, NullPointerException;
    public final void readFully(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public final int skipBytes(int n) throws IOException;
    public final boolean readBoolean() throws IOException;
    public final byte readByte() throws IOException;
    public final int readUnsignedByte() throws IOException;
    public final short readShort() throws IOException;
    public final int readUnsignedShort() throws IOException;
    public final char readChar() throws IOException;
    public final int readInt() throws IOException;
    public final long readLong() throws IOException;
    public final float readFloat() throws IOException;
    public final double readDouble() throws IOException;
    public final String readLine() throws IOException;
    public final String readUTF() throws IOException;
    public final static String readUTF(DataInput in)
        throws IOException;
}

22.11.1 public DataInputStream(InputStream in)

This constructor initializes a newly created DataInputStream by saving its argument, the input stream in, for later use.

22.11.2 public final void readFully(byte[] b)
throws IOException, NullPointerException

See the general contract of the readFully method of DataInput (§22.1.1).

Bytes for this operation are read from the contained input stream.

22.11.3 public final void readFully(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the readFully method of DataInput (§22.1.2).

Bytes for this operation are read from the contained input stream.

22.11.4 public final int skipBytes(int n) throws IOException

See the general contract of the skipBytes method of DataInput (§22.1.3).

Bytes for this operation are read from the contained input stream.

22.11.5 public final boolean readBoolean() throws IOException

See the general contract of the readBoolean method of DataInput (§22.1.4).

The byte for this operation is read from the contained input stream.

22.11.6 public final byte readByte() throws IOException

See the general contract of the readByte method of DataInput (§22.1.5).

The byte for this operation is read from the contained input stream.

22.11.7 public final int readUnsignedByte() throws IOException

See the general contract of the readUnsignedByte method of DataInput (§22.1.6).

The byte for this operation is read from the contained input stream.

22.11.8 public final short readShort() throws IOException

See the general contract of the readShort method of DataInput (§22.1.7).

Bytes for this operation are read from the contained input stream.

22.11.9 public final int readUnsignedShort() throws IOException

See the general contract of the readUnsignedShort method of DataInput (§22.1.8).

Bytes for this operation are read from the contained input stream.

22.11.10 public final char readChar() throws IOException

See the general contract of the readChar method of DataInput (§22.1.9).

Bytes for this operation are read from the contained input stream.

22.11.11 public final int readInt() throws IOException

See the general contract of the readInt method of DataInput (§22.1.10).

Bytes for this operation are read from the contained input stream.

22.11.12 public final long readLong() throws IOException

See the general contract of the readLong method of DataInput (§22.1.11).

Bytes for this operation are read from the contained input stream.

22.11.13 public final float readFloat() throws IOException

See the general contract of the readFloat method of DataInput (§22.1.12).

Bytes for this operation are read from the contained input stream.

22.11.14 public final double readDouble() throws IOException

See the general contract of the readDouble method of DataInput (§22.1.13).

Bytes for this operation are read from the contained input stream.

22.11.15 public final String readLine() throws IOException

See the general contract of the readLine method of DataInput (§22.1.14).

Bytes for this operation are read from the contained input stream.

22.11.16 public final String readUTF() throws IOException

See the general contract of the readUTF method of DataInput (§22.1.15).

Bytes for this operation are read from the contained input stream.

22.11.17 public final static String readUTF(DataInput in)
throws IOException

The readUTF method reads from the stream in a representation of a Unicode character string encoded in Java modified UTF-8 format; this string of characters is then returned as a String. The details of the modified UTF-8 representation are exactly the same as for the readUTF method of DataInput (§22.1.15).


22.12 The Class java.io.LineNumberInputStream

A LineNumberInputStream adds functionality to another input stream, namely the ability to count lines. When the LineNumberInputStream is created, the line number counter is set to zero. As bytes from the stream are read or skipped, the counter is incremented whenever a line terminator (\n, \r, or \r\n) is encountered. Such line terminators are also converted to a single '\n' character. The method getLineNumber returns the current value of the counter, and the method setLineNumber sets the counter to a given integer value. If the contained input stream supports the mark operation, then so does the LineNumberInputStream; the mark operation remembers the line number counter and the reset operation sets the counter to the value remembered by the mark operation.

public class LineNumberInputStream extends FilterInputStream {
    public LineNumberInputStream(InputStream in);
    public int read() throws IOException;
    public int read(byte[] b)
        throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)

        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public long skip(long n) throws IOException;
    public int available() throws IOException;
    public void mark(int readlimit);
    public void reset() throws IOException;
    public int getLineNumber();
    public void setLineNumber(int lineNumber);
}

22.12.1 public LineNumberInputStream(InputStream in)

This constructor initializes a newly created LineNumberInputStream by saving its argument, the input stream in, for later use.

22.12.2 public int read() throws IOException

See the general contract of the read method of InputStream (§22.3.1).

As bytes are read from the contained input stream, line terminators are recognized and counted. For each line terminator recognized in the contained input stream, a single character '\n' is returned.

Overrides the read method of FilterInputStream (§22.9.3).

22.12.3 public int read(byte[] b)
throws IOException, NullPointerException

See the general contract of the read method of InputStream (§22.3.2).

As bytes are read from the contained input stream, line terminators are recognized and counted. For each line terminator recognized in the contained input stream, a single character '\n' is returned.

Overrides the read method of FilterInputStream (§22.9.4).

22.12.4 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the read method of InputStream (§22.3.3).

As bytes are read from the contained input stream, line terminators are recognized and counted. For each line terminator recognized in the contained input stream, a single character '\n' is returned.

Overrides the read method of FilterInputStream (§22.9.5).

22.12.5 public long skip(long n) throws IOException

See the general contract of the skip method of InputStream (§22.3.4).

As bytes are read from the contained input stream, line terminators are recognized and counted. Each line terminator recognized in the contained input stream is considered to be a single byte skipped, even if it is the sequence \r\n.

Overrides the skip method of FilterInputStream (§22.9.6).

22.12.6 public int available() throws IOException

See the general contract of the available method of InputStream (§22.3.5).

Note that if the contained input stream is able to supply k input characters without blocking, the LineNumberInputStream can guarantee only to provide [image] characters without blocking, because the k characters from the contained input stream might consist of [image] \r\n pairs, which will be converted to just [image] '\n' characters.

Overrides the available method of FilterInputStream (§22.9.7).

22.12.7 public void mark(int readlimit)

See the general contract of the mark method of InputStream (§22.3.7).

Marking a point in the input stream remembers the current line number as it would be returned by getLineNumber (§22.12.9).

Overrides the mark method of FilterInputStream (§22.9.9).

22.12.8 public void reset() throws IOException

See the general contract of the reset method of InputStream (§22.3.8).

Resetting the input stream to a previous point also resets the line number to the value it had at the marked point.

Overrides the reset method of FilterInputStream (§22.9.10).

22.12.9 public int getLineNumber()

The current line number is returned. This quantity depends on k, the number of line terminators encountered since the most recent occurrence of one of the following three kinds of events:

  • If a call to the setLineNumber method was most recent, let n be the argument that was given to setLineNumber; then the current line number is [image].
  • If a call to the reset method was most recent, let m be the line number that had been remembered by mark; then the current line number is [image].
  • If creation of the LineNumberInputStream was most recent (that is, neither of the other kinds of event have occurred), then the current line number is k.

These rules imply that the current line number is 0 as the characters of the first line are read, and becomes 1 after the line terminator for the first line has been read.

22.12.10 public void setLineNumber(int lineNumber)

The current line number is set equal to the argument.


22.13 The Class java.io.PushbackInputStream

A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte. This is useful in situations where it is convenient for a fragment of code to read an indefinite number of data bytes that are delimited by a particular byte value; after reading the terminating byte, the code fragment can "unread" it, so that the next read operation on the input stream will reread the byte that was pushed back. For example, bytes representing the characters constituting an identifier might be terminated by a byte representing an operator character; a method whose job is to read just an identifier can read until it sees the operator and then push the operator back to be re-read.

public class PushbackInputStream extends FilterInputStream {
    protected int	 pushBack = -1;
    public PushbackInputStream(InputStream in);
    public int read() throws IOException;
    public int read(byte[] bytes, int offset, int length)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void unread(int ch) throws IOException;
    public int available() throws IOException;
    public boolean markSupported();
}

22.13.1 protected int pushBack = -1;

If this field has a nonnegative value, it is a byte that was pushed back. If this field is -1, there is currently no pushed-back byte.

22.13.2 public PushbackInputStream(InputStream in)

This constructor initializes a newly created PushbackInputStream by saving its argument, the input stream in, for later use. Initially, there is no pushed-back byte (the field pushBack is initialized to -1).

22.13.3 public int read() throws IOException

See the general contract of the read method of InputStream (§22.3.1).

If pushBack is not -1, the value of pushBack is returned and pushBack is set to -1. Otherwise, a byte is obtained from the contained input stream.

Overrides the read method of FilterInputStream (§22.9.3).

22.13.4 public int read(byte[] bytes, int offset, int length) throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the read method of InputStream (§22.3.3).

If pushBack is not -1, it is used as an input byte (and pushBack is set to -1) before any bytes are read from the contained input stream.

Overrides the read method of FilterInputStream (§22.9.5).

22.13.5 public void unread(int b) throws IOException

If pushBack is not -1, an IOException is thrown (it is not permitted to push back more than one byte). Otherwise, the byte value b is pushed back by assigning b to pushBack.

22.13.6 public int available() throws IOException

See the general contract of the available method of InputStream (§22.3.1).

This method first calls the available method of the contained input stream. If pushBack is -1, the result is returned; otherwise, the result plus 1 is returned.

Overrides the available method of FilterInputStream (§22.9.7).

22.13.7 public boolean markSupported()

This method returns false (a PushbackInputStream does not support mark).


22.14 The Class java.io.StreamTokenizer

A StreamTokenizer takes an input stream and parses it into "tokens," allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states, allowing recognition of identifiers, numbers, quoted strings, and comments in a standard style.

public class StreamTokenizer {
    public static final int TT_EOF = -1;
    public static final int TT_EOL = '\n';
    public static final int TT_NUMBER = -2;
    public static final int TT_WORD = -3;
    public int ttype;
    public String sval;
    public double nval;
    public StreamTokenizer (InputStream in);
    public void resetSyntax();
    public void wordChars(int low, int hi);
    public void whitespaceChars(int low, int hi);
    public void ordinaryChars(int low, int hi);
    public void ordinaryChar(int ch);
    public void commentChar(int ch);
    public void quoteChar(int ch);
    public void parseNumbers();
    public void eolIsSignificant(boolean flag);
    public void slashStarComments(boolean flag);
    public void slashSlashComments(boolean flag);
    public void lowerCaseMode(boolean flag);
    public int nextToken() throws IOException;
    public void pushBack();
    public int lineno();
    public String toString();
}

Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: whitespace, alphabetic, numeric, string quote, and comment character (a character may have more than one of these attributes, or none at all). In addition, there are three flags controlling whether line terminators are to be recognized as tokens, whether Java-style end-of-line comments that start with // should be recognized and skipped, and whether Java-style "traditional" comments delimited by /* and */ should be recognized and skipped. One more flag controls whether all the characters of identifiers are converted to lowercase.

Here is a simple example of the use of a StreamTokenizer. The following code merely reads all the tokens in the standard input stream and prints an identification of each one. Changes in the line number are also noted.

import java.io.StreamTokenizer;
import java.io.IOException;

class Tok {
    public static void main(String[] args) {
        StreamTokenizer st = new StreamTokenizer(System.in);
        st.ordinaryChar('/');
        int lineNum = -1;
        try {
            for (int tokenType = st.nextToken();
                    tokenType != StreamTokenizer.TT_EOF;
                    tokenType = st.nextToken()) {
                int newLineNum = st.lineno();
                if (newLineNum != lineNum) {
                    System.out.println("[line " + newLineNum
                                            + "]");
                    lineNum = newLineNum;
                }
                switch(tokenType) {
                case StreamTokenizer.TT_NUMBER:
                    System.out.println("the number " + st.nval);
                    break;
                case StreamTokenizer.TT_WORD:
                    System.out.println("identifier " + st.sval);
                    break;
                default:
                    System.out.println("  operator "
                                            + (char)tokenType);
                }
            }
        } catch (IOException e) {
            System.out.println("I/O failure");
        }
    }
}

If the input stream contains this data:

10 LET A = 4.5
20 LET B = A*A
30 PRINT A, B

then the resulting output is:

[line 1]
the number 10.0
identifier LET
identifier A
  operator =
the number 4.5
[line 2]
the number 20.0
identifier LET
identifier B
  operator =
identifier A
  operator *
identifier A
[line 3]
the number 30.0
identifier PRINT
identifier A
  operator ,
identifier B

22.14.1 public static final int TT_EOF = -1;

A constant that indicates end of file was reached.

22.14.2 public static final int TT_EOL = '\n';

A constant that indicates that a line terminator was recognized.

22.14.3 public static final int TT_NUMBER = -2;

A constant that indicates that a number was recognized.

22.14.4 public static final int TT_WORD = -3;

A constant that indicates that a word (identifier) was recognized.

22.14.5 public int ttype;

The type of the token that was last recognized by this StreamTokenizer. This will be TT_EOF, TT_EOL, TT_NUMBER, TT_WORD, or a nonnegative byte value that was the first byte of the token (for example, if the token is a string token, then ttype has the quote character that started the string).

22.14.6 public String sval;

If the value of ttype is TT_WORD or a string quote character, then the value of sval is a String that contains the characters of the identifier or of the string (without the delimiting string quotes). For all other types of tokens recognized, the value of sval is null.

22.14.7 public double nval;

If the value of ttype is TT_NUMBER, then the value of nval is the numerical value of the number.

22.14.8 public StreamTokenizer(InputStream in)

This constructor initializes a newly created StreamTokenizer by saving its argument, the input stream in, for later use. The StreamTokenizer is also initialized to the following default state:

  • All byte values 'A' through 'Z', 'a' through 'z', and 0xA0 through 0xFF are considered to be alphabetic.
  • All byte values 0x00 through 0x20 are considered to be whitespace.
  • '/' is a comment character.
  • Single quote '\'' and double quote '"' are string quote characters.
  • Numbers are parsed.
  • End of line is not significant.
  • // comments and /* comments are not recognized.

22.14.9 public void resetSyntax()

The syntax table for this StreamTokenizer is reset so that every byte value is "ordinary"; thus, no character is recognized as being a whitespace, alphabetic, numeric, string quote, or comment character. Calling this method is therefore equivalent to:

ordinaryChars(0x00, 0xff)

The three flags controlling recognition of line terminators, // comments, and /* comments are unaffected.

22.14.10 public void wordChars(int low, int hi)

The syntax table for this StreamTokenizer is modified so that every character in the range low through hi has the "alphabetic" attribute.

22.14.11 public void whitespaceChars(int low, int hi)

The syntax table for this StreamTokenizer is modified so that every character in the range low through hi has the "whitespace" attribute.

22.14.12 public void ordinaryChars(int low, int hi)

The syntax table for this StreamTokenizer is modified so that every character in the range low through hi has no attributes.

22.14.13 public void ordinaryChar(int ch)

The syntax table for this StreamTokenizer is modified so that the character ch has no attributes.

22.14.14 public void commentChar(int ch)

The syntax table for this StreamTokenizer is modified so that the character ch has the "comment character" attribute.

22.14.15 public void quoteChar(int ch)

The syntax table for this StreamTokenizer is modified so that the character ch has the "string quote" attribute.

22.14.16 public void parseNumbers()

The syntax table for this StreamTokenizer is modified so that each of the twelve characters

0 1 2 3 4 5 6 7 8 9 . -

has the "numeric" attribute.

22.14.17 public void eolIsSignificant(boolean flag)

This StreamTokenizer henceforth recognizes line terminators as tokens if and only if the flag argument is true.

22.14.18 public void slashStarComments(boolean flag)

This StreamTokenizer henceforth recognizes and skips Java-style "traditional" comments, which are delimited by /* and */ and do not nest, if and only if the flag argument is true.

22.14.19 public void slashSlashComments(boolean flag)

This StreamTokenizer henceforth recognizes and skips Java-style end-of-line comments that start with // if and only if the flag argument is true.

22.14.20 public void lowerCaseMode(boolean flag)

This StreamTokenizer henceforth converts all the characters in identifiers to lowercase if and only if the flag argument is true.

22.14.21 public int nextToken() throws IOException

If the previous token was pushed back (§22.14.22), then the value of ttype is returned, effectively causing that same token to be reread.

Otherwise, this method parses the next token in the contained input stream. The type of the token is returned; this same value is also made available in the ttype field, and related data may be made available in the sval and nval fields.

First, whitespace characters are skipped, except that if a line terminator is encountered and this StreamTokenizer is currently recognizing line terminators, then the type of the token is TT_EOL.

If a numeric character is encountered, then an attempt is made to recognize a number. If the first character is '-' and the next character is not numeric, then the '-' is considered to be an ordinary character and is recognized as a token in its own right. Otherwise, a number is parsed, stopping before the next occurrence of '-', the second occurrence of '.', the first nonnumeric character encountered, or end of file, whichever comes first. The type of the token is TT_NUMBER and its value is made available in the field nval.

If an alphabetic character is encountered, then an identifier is recognized, consisting of that character and all following characters up to, but not including, the first character that is neither alphabetic nor numeric, or up to end of file, whichever comes first. The characters of the identifier may be converted to lowercase if this StreamTokenizer is in lowercase mode.

If a comment character is encountered, then all subsequent characters are skipped and ignored, up to but not including the next line terminator or end of file. Then another attempt is made to recognize a token. If this StreamTokenizer is currently recognizing line terminators, then a line terminator that ends a comment will be recognized as a token in the same manner as any other line terminator in the contained input stream.

If a string quote character is encountered, then a string is recognized, consisting of all characters after (but not including) the string quote character, up to (but not including) the next occurrence of that same string quote character, or a line terminator, or end of file. The usual escape sequences (§3.10.6) such as \n and \t are recognized and converted to single characters as the string is parsed.

If // is encountered and this StreamTokenizer is currently recognizing // comments, then all subsequent characters are skipped and ignored, up to but not including the next line terminator or end of file. Then another attempt is made to recognize a token. (If this StreamTokenizer is currently recognizing line terminators, then a line terminator that ends a comment will be recognized as a token in the same manner as any other line terminator in the contained input stream.)

If /* is encountered and this StreamTokenizer is currently recognizing /* comments, then all subsequent characters are skipped and ignored, up to and including the next occurrence of */ or end of file. Then another attempt is made to recognize a token.

If none of the cases listed above applies, then the only other possibility is that the first non-whitespace character encountered is an ordinary character. That character is considered to be a token and is stored in the ttype field and returned.

22.14.22 public void pushBack()

Calling this method "pushes back" the current token; that is, it causes the next call to nextToken to return the same token that it just provided. Note that this method does not restore the line number to its previous value, so if the method lineno is called after a call to pushBack but before the next call to nextToken, an incorrect line number may be returned.

22.14.23 public int lineno()

The number of the line on which the current token appeared is returned. The first token in the input stream, if not a line terminator, is considered to appear on line 1. A line terminator token is considered to appear on the line that it precedes, not on the line it terminates; thus, the first line terminator in the input stream is considered to be on line 2.

22.14.24 public String toString()

The current token and the current line number are converted to a string of the form:

"Token[x], line m"

where m is the current line number in decimal form and x depends on the type of the current token:

  • If the token type is TT_EOF, then x is "EOF".
  • If the token type is TT_EOL, then x is "EOL".
  • If the token type is TT_WORD, then x is the current value of sval (§22.14.6).
  • If the token type is TT_NUMBER, then x is "n=" followed by the result of converting the current value of nval (§22.14.7) to a string (§20.10.15).

Overrides the toString method of Object (§20.1.2).


22.15 The Class java.io.OutputStream

An output stream accepts output bytes and sends them to some sink.

public abstract class OutputStream {
    public abstract void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void flush() throws IOException;
    public void close() throws IOException;
}

22.15.1 public abstract void write(int b) throws IOException

The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

If the byte cannot be written for any reason, an IOException is thrown. In particular, an IOException may be thrown if the output stream has been closed (§22.15.5).

22.15.2 public void write(byte[] b)
throws IOException, NullPointerException

The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length) (§22.15.3).

The write(b) method for class OutputStream in fact makes such a call.

22.15.3 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

The general contract for write(b, off, len) is that some of the bytes in the array b are written to the output stream as if one at a time, in order; element b[off] is the first byte written and b[off+len-1] is the last byte written by this operation.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If the byte cannot be written for any reason, an IOException is thrown. In particular, an IOException is thrown if the output stream has been closed (§22.15.5).

The write(b, off, len) method for class OutputStream simply calls the method write (§22.15.1) repeatedly, once for each byte in b to be written.

22.15.4 public void flush() throws IOException

The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The flush method for class OutputStream does nothing and simply returns.

22.15.5 public void close() throws IOException

The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

The close method for class OutputStream does nothing and simply returns.


22.16 The Class java.io.FileOutputStream

A file output stream writes output bytes to a file in a file system. What files are available or may be created depends on the host environment.

public class FileOutputStream extends OutputStream {
    public FileOutputStream(String path)
        throws SecurityException, FileNotFoundException;
    public FileOutputStream(File file)
        throws SecurityException, FileNotFoundException;
    public FileOutputStream(FileDescriptor fdObj)
        throws SecurityException;
    public void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void close() throws IOException;
    public final FileDescriptor getFD() throws IOException;
    protected void finalize() throws IOException;
}

22.16.1 public FileOutputStream(String path)
throws SecurityException, FileNotFoundException

This constructor initializes a newly created FileOutputStream by opening a connection to an actual file, the file named by the path name path in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkWrite method (§20.17.21) is called with the path argument as its argument.

If the actual file cannot be opened, a FileNotFoundException is thrown.

22.16.2 public FileOutputStream(File file)
throws SecurityException, FileNotFoundException

This constructor initializes a newly created FileOutputStream by opening a connection to an actual file, the file named by file in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkWrite method (§20.17.21) is called with the path represented by the file argument as its argument.

If the actual file cannot be opened, a FileNotFoundException is thrown.

22.16.3 public FileOutputStream(FileDescriptor fdObj)
throws SecurityException

This constructor initializes a newly created FileOutputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

First, if there is a security manager, its checkWrite method (§20.17.20) is called with the file descriptor fdObj argument as its argument.

22.16.4 public final FileDescriptor getFD() throws IOException

This method returns the FileDescriptor object (§22.26) that represents the connection to the actual file in the file system being used by this FileOutputStream.

22.16.5 public void write(int b) throws IOException

The byte for this operation is written to the actual file to which this file output stream is connected.

Implements the write method of OutputStream (§22.15.1).

22.16.6 public void write(byte[] b)
throws IOException, NullPointerException

Bytes for this operation are written to the actual file to which this file output stream is connected.

Overrides the write method of OutputStream (§22.15.2).

22.16.7 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

Bytes for this operation are written to the actual file to which this file output stream is connected.

Overrides the write method of OutputStream (§22.15.3).

22.16.8 public void close() throws IOException

This file output stream is closed and may no longer be used for writing bytes.

Overrides the close method of OutputStream (§22.15.5).

22.16.9 protected void finalize() throws IOException

A FileOutputStream uses finalization to clean up the connection to the actual file.


22.17 The Class java.io.PipedOutputStream

A piped output stream should be connected to a piped input stream; the piped input stream then provides whatever data bytes are written to the piped output stream. Typically, data is written to a PipeOutputStream object by one thread and data is read from the corresponding PipedInputStream (§22.5) by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread.

public class PipedOutputStream extends OutputStream {
    public PipedOutputStream(PipedInputStream snk)
        throws IOException;
    public PipedOutputStream();
    public void connect(PipedInputStream snk)
        throws IOException;
    public void write(int b) throws IOException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void close() throws IOException;
}

22.17.1 public PipedOutputStream(PipedInputStream snk)
throws IOException

This constructor initializes a newly created PipedOutputStream so that it is connected to the piped input stream snk. Data bytes written to this stream will then be available as input from snk.

22.17.2 public PipedOutputStream()

This constructor initializes a newly created PipedOutputStream so that it is not yet connected. It must be connected to a PipedInputStream before being used.

22.17.3 public void connect(PipedInputStream snk)
throws IOException

The connect method causes this piped output stream to be connected to the piped input stream snk. If this object is already connected to some other piped input stream, an IOException is thrown.

If snk is an unconnected piped input stream and src is an unconnected piped output stream, they may be connected by either the call:

src.connect(snk)

or the call:

snk.connect(src)

The two calls have the same effect.

22.17.4 public void write(int b) throws IOException

If a thread was reading data bytes from the connected piped input stream, but the thread is no longer alive, then an IOException is thrown.

Implements the write method of OutputStream (§22.15.1).

22.17.5 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

If a thread was reading data bytes from the connected piped input stream, but the thread is no longer alive, then an IOException is thrown.

Overrides the write method of OutputStream (§22.15.3).

22.17.6 public void close() throws IOException

This piped output stream is closed and may no longer be used for writing bytes.

Overrides the close method of OutputStream (§22.15.5).


22.18 The Class java.io.ByteArrayOutputStream

A ByteArrayOutputStream contains an internal buffer that accumulates all the bytes written to the stream since its creation or the most recent call to the reset method. At any point, the bytes written to the stream so far may be retrieved in the form of an array of bytes or a String. The bytes written so far may also be copied to some other output stream. The size method returns the number of characters written so far.

public class ByteArrayOutputStream extends OutputStream {
    protected byte[] buf;
    protected int count;
    public ByteArrayOutputStream();
    public ByteArrayOutputStream(int size);
    public void write(int b);
    public void write(byte[] b, int off, int len)
        throws NullPointerException, IndexOutOfBoundsException;
    public int size();
    public void reset();
    public byte[] toByteArray();
    public String toString();
    public String toString(int hibyte);
    public void writeTo(OutputStream out) throws IOException;
}

22.18.1 protected byte[] buf;

An internal array of bytes. Elements buf[0] through buf[count-1] are the bytes that have been written to the stream since its creation or the last reset (§22.18.8) operation.

22.18.2 protected int count;

This value should always be nonnegative. It is the number of bytes that have been written to the stream since its creation or the last reset (§22.18.8) operation.

22.18.3 public ByteArrayOutputStream()

This constructor initializes a newly created ByteArrayOutputStream so that its internal buffer array has length 32.

22.18.4 public ByteArrayOutputStream(int size)

This constructor initializes a newly created ByteArrayOutputStream so that its internal buffer array has length size. This matters only for reasons of efficiency; the buffer array is replaced by a larger one whenever necessary to accommodate additional bytes written to the stream.

22.18.5 public void write(int b)

One byte is added on the internal buffer. The byte to be added is the eight low- order bits of the argument n. The 24 high-order bits of n are ignored.

Implements the write method of OutputStream (§22.15.1).

22.18.6 public void write(byte[] b, int off, int len)
throws NullPointerException, IndexOutOfBoundsException

Elements b[off] through b[off+len-1] are appended to the internal buffer.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

Overrides the write method of OutputStream (§22.15.3).

22.18.7 public int size()

The current value of count is returned.

22.18.8 public void reset()

The internal variable count is reset to zero, thereby logically discarding all bytes written to the stream so far. However, the internal buffer array, which may be quite large, remains as it is.

22.18.9 public byte[] toByteArray()

A new array of bytes is created and returned. Its length is equal to the current value of count. Its initial contents are copies of the bytes written to the stream so far-that is, elements 0 through count-1 of buf.

22.18.10 public String toString()

A new String is created and returned. Its length is equal to the current value of count. Its initial contents are copies of the bytes written to the stream so far-that is, elements 0 through count-1 of buf, zero-extended to produce characters. Thus, tostring() has the same effect as toString(0) (§22.18.11).

Overrides the toString method of Object (§20.1.2).

22.18.11 public String toString(int hibyte)

A new array of bytes is created and returned. Its length is equal to the current value of count. Its initial contents are copies of the bytes written to the stream so far-that is, elements 0 through count-1 of buf-with hibyte supplying the high-order eight bits of each character. Thus, character k of the result is equal to:

((hibyte & 0xff) << 8) | (buf[k] & 0xff)

See the String constructor that accepts a hibyte argument (§20.12.6).

22.18.12 public void writeTo(OutputStream out) throws IOException

The current contents of the internal buffer are written to the output stream out by the call:

out.write(buf, 0, count)

Note that if out is the same as this, the effect is simply to append to the buffer a copy of its current contents, thereby doubling the number of buffered bytes. This may not be a particularly useful effect; the point is merely that the operation does terminate, having had a sensible effect, rather than running off into an endless loop.


22.19 The Class java.io.FilterOutputStream

A FilterOutputStream contains some other output stream, which it uses as its basic sink of data, possibly transforming the data along the way or providing additional functionality. The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the contained output stream. Subclasses of FilterOutputStream may further override some of these methods and may also provide additional methods and fields.

public class FilterOutputStream extends OutputStream {
    protected OutputStream out;
    public FilterOutputStream(OutputStream out);
    public void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)

        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void flush() throws IOException;
    public void close() throws IOException;
}

22.19.1 protected OutputStream out;

The output stream to be filtered.

22.19.2 public FilterOutputStream(OutputStream out)

This constructor initializes a newly created FilterInputStream by assigning the argument out to the field this.out so as to remember it for later use.

22.19.3 public void write(int b) throws IOException

This method simply performs out.write(b).

Implements the abstract write method of OutputStream (§22.15.1).

22.19.4 public void write(byte[] b)
throws IOException, NullPointerException

This method simply performs out.write(b).

Overrides the write method of OutputStream (§22.15.2).

22.19.5 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

This method simply performs out.write(b, off, len).

Overrides the write method of OutputStream (§22.15.3).

22.19.6 public void flush() throws IOException

This method simply performs out.flush().

Overrides the flush method of OutputStream (§22.15.4).

22.19.7 public void close() throws IOException

This method simply performs out.close().

Overrides the close method of OutputStream (§22.15.5).


22.20 The Class java.io.BufferedOutputStream

A BufferedOutputStream adds functionality to another output stream, namely the ability to buffer the output. When the BufferedOutputStream is created, an internal buffer array is created. As bytes are written to the stream, they are stored in the internal buffer, which is flushed as necessary, thereby performing output to the contained output stream in large blocks rather than a byte at a time.

public class BufferedOutputStream extends FilterOutputStream {
    protected byte[] buf;
    protected int count;
    public BufferedOutputStream(OutputStream out);
    public BufferedOutputStream(OutputStream out, int size);
    public void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void flush() throws IOException;
}

22.20.1 protected byte[] buf;

The internal buffer array.

22.20.2 protected int count;

This value is always in the range 0 through buf.length; elements buf[0] through buf[count-1] contain valid byte data.

22.20.3 public BufferedOutputStream(OutputStream out)

This constructor initializes a newly created BufferedOutputStream by saving its argument, the input stream out, for later use. An internal buffer array is created and stored in buf.

22.20.4 public BufferedOutputStream(OutputStream out, int size)

This constructor initializes a newly created BufferedOutputStream by saving its argument, the input stream out, for later use. An internal buffer array of length size is created and stored in buf.

22.20.5 public void write(int b) throws IOException

See the general contract of the write method of OutputStream (§22.15.1).

Overrides the write method of FilterOutputStream (§22.19.3).

22.20.6 public void write(byte[] b)
throws IOException, NullPointerException

See the general contract of the write method of OutputStream (§22.15.2).

Overrides the write method of FilterOutputStream (§22.19.4).

22.20.7 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the write method of OutputStream (§22.15.3).

Overrides the write method of FilterOutputStream (§22.19.5).

22.20.8 public void flush() throws IOException

See the general contract of the flush method of OutputStream (§22.15.4).

Overrides the flush method of FilterOutputStream (§22.19.6).


22.21 The Class java.io.DataOutputStream

A data output stream provides facilities for converting data of diverse types into character sequence of specific formats that are then sent to some output stream.

public class DataOutputStream extends FilterOutputStream
        implements DataOutput {
    protected int written;
    public DataOutputStream(OutputStream out);
    public void write(int b) throws IOException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public void flush() throws IOException;
    public final void writeBoolean(boolean v) throws IOException;
    public final void writeByte(int v) throws IOException;
    public final void writeShort(int v) throws IOException;
    public final void writeChar(int v) throws IOException;
    public final void writeInt(int v) throws IOException;
    public final void writeLong(long v) throws IOException;
    public final void writeFloat(float v) throws IOException;
    public final void writeDouble(double v) throws IOException;
    public final void writeBytes(String s)
        throws IOException, NullPointerException;
    public final void writeChars(String s)
        throws IOException, NullPointerException;
    public final void writeUTF(String str)
        throws IOException, NullPointerException;
    public final int size();
}

22.21.1 protected int written;

This field contains the number of bytes written to the stream so far.

22.21.2 public DataOutputStream(OutputStream out)

This constructor initializes a newly created DataOutputStream by saving its argument, the output stream out, for later use. The counter written is set to zero.

22.21.3 public void write(int b) throws IOException

The byte for this operation (the low eight bits of the argument b) is written to the contained output stream. If no exception is thrown, the counter written is incremented by 1.

Implements the write method of OutputStream (§22.15.1).

22.21.4 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by len.

Overrides the write method of OutputStream (§22.15.3).

22.21.5 public void flush() throws IOException

The contained output stream is flushed.

Overrides the flush method of OutputStream (§22.15.4).

22.21.6 public final void writeBoolean(boolean v)
throws IOException

See the general contract of the writeBoolean method of DataOutput (§22.2.4).

The byte for this operation is written to the contained output stream. If no exception is thrown, the counter written is incremented by 1.

22.21.7 public final void writeByte(int v) throws IOException

See the general contract of the writeByte method of DataOutput (§22.2.5).

The byte for this operation is written to the contained output stream. If no exception is thrown, the counter written is incremented by 1.

22.21.8 public final void writeShort(int v) throws IOException

See the general contract of the writeShort method of DataOutput (§22.2.6).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 2.

22.21.9 public final void writeChar(int v) throws IOException

See the general contract of the writeChar method of DataOutput (§22.2.7).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 2.

22.21.10 public final void writeInt(int v) throws IOException

See the general contract of the writeInt method of DataOutput (§22.2.8).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 4.

22.21.11 public final void writeLong(long v) throws IOException

See the general contract of the writeLong method of DataOutput (§22.2.9).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 8.

22.21.12 public final void writeFloat(float v) throws IOException

See the general contract of the writeFloat method of DataOutput (§22.2.10).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 4.

22.21.13 public final void writeDouble(double v) throws IOException

See the general contract of the writeDouble method of DataOutput (§22.2.11).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by 8.

22.21.14 public final void writeBytes(String s)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the writeBytes method of DataOutput (§22.2.12).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by the length of s.

22.21.15 public final void writeChars(String s)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the writeChars method of DataOutput (§22.2.13).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by twice the length of s.

22.21.16 public final void writeUTF(String str)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the writeUTF method of DataOutput (§22.2.14).

Bytes for this operation are written to the contained output stream. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of s, and at most two plus thrice the length of s.

22.21.17 public final int size()

The size method returns the current value of the counter written, the number of bytes written to the stream so far.


22.22 The Class java.io.PrintStream

A PrintStream adds functionality to another output stream-namely, the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested by the checkError method. Optionally, a PrintStream can be created so as to "autoflush"; this means that after an array of bytes is written, or after a single byte equal to '\n' is written, the flush method is automatically invoked.

public class PrintStream extends FilterOutputStream {
    public PrintStream(OutputStream out);
    public PrintStream(OutputStream out, boolean autoflush);
    public void write(int b);
    public void write(byte[] b, int off, int len)
        throws NullPointerException, IndexOutOfBoundsException;
    public void flush();
    public void close();
    public boolean checkError();
    public void print(Object obj);
    public void print(String s);
    public void print(char[] s) throws NullPointerException;
    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(boolean b);
    public void println();
    public void println(Object obj);
    public void println(String s);
    public void println(char[] s) throws NullPointerException;
    public void println(char c);
    public void println(int i);
    public void println(long l);
    public void println(float f);
    public void println(double d);
    public void println(boolean b);
}

22.22.1 public PrintStream(OutputStream out)

This constructor initializes a newly created PrintStream by saving its argument, the output stream out, for later use. This stream will not autoflush.

22.22.2 public PrintStream(OutputStream out, boolean autoflush)

This constructor initializes a newly created PrintStream by saving its argument, the output stream out, for later use. This stream will autoflush if and only if autoflush is true.

22.22.3 public void write(int b)

See the general contract of the write method of OutputStream (§22.15.1).

Overrides the write method of FilterOutputStream (§22.19.3).

22.22.4 public void write(byte[] b, int off, int len)
throws NullPointerException, IndexOutOfBoundsException

See the general contract of the write method of OutputStream (§22.15.3).

Overrides the write method of FilterOutputStream (§22.19.5).

22.22.5 public void flush()

See the general contract of the flush method of OutputStream (§22.15.4).

Overrides the flush method of FilterOutputStream (§22.19.6).

22.22.6 public void close()

See the general contract of the close method of OutputStream (§22.15.5).

Overrides the close method of FilterOutputStream (§22.19.7).

22.22.7 public boolean checkError()

The result is true if and only if this output stream has ever encountered any kind of trouble-that is, if any operation on the contained output stream has ever resulted in an IOException other than an InterruptedIOException. If an operation on the contained output stream throws an InterruptedIOException, then the PrintStream class converts the exception back to an interrupt by doing:

Thread.currentThread().interrupt();

or the equivalent.

22.22.8 public void print(Object obj)

The low-order bytes of the characters in the String that would be produced by String.valueOf(obj) (§20.12.38) are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.9 public void print(String s)

The low-order bytes of the characters in the string s are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3). If s is null, then the low-order bytes of the four characters n, u, l, l are written to the contained output stream.

22.22.10 public void print(char[] s) throws NullPointerException

The low-order bytes of the characters in the character array s are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

If s is null, a NullPointerException is thrown.

22.22.11 public void print(boolean b)

The low-order bytes of the characters in the String that would be produced by String.valueOf(b) (§20.12.41) as a string are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.12 public void print(char c)

The low-order byte of the character c is written to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.13 public void print(int i)

The low-order bytes of the characters in the String that would be produced by String.valueOf(i) (§20.12.43) as a string are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.14 public void print(long l)

The low-order bytes of the characters in the String that would be produced by String.valueOf(l) (§20.12.44) as a string are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.15 public void print(float f)

The low-order bytes of the characters in the String that would be produced by String.valueOf(f) (§20.12.45) as a string are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.16 public void print(double d)

The low-order bytes of the characters in the String that would be produced by String.valueOf(d) (§20.12.46) as a string are written, in order, to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.17 public void println()

The low-order byte of the newline character '\n' is written to the contained output stream in exactly the manner of the write method (§22.22.3).

22.22.18 public void println(Object obj)

This is exactly the same as print(obj) (§22.22.8) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.19 public void println(String s)

This is exactly the same as print(s) (§22.22.9) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.20 public void println(char[] s) throws NullPointerException

This is exactly the same as print(s) (§22.22.10) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

If s is null, a NullPointerException is thrown.

22.22.21 public void println(boolean b)

This is exactly the same as print(b) (§22.22.11) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.22 public void println(char c)

This is exactly the same as print(c) (§22.22.12) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.23 public void println(int i)

This is exactly the same as print(i) (§22.22.13) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.24 public void println(long l)

This is exactly the same as print(l) (§22.22.14) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.25 public void println(float f)

This is exactly the same as print(f) (§22.22.15) followed by writing the low- order byte of the newline character '\n' to the contained output stream.

22.22.26 public void println(double d)

This is exactly the same as print(d) (§22.22.16) followed by writing the low- order byte of the newline character '\n' to the contained output stream.


22.23 The Class java.io.RandomAccessFile

A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended. The file pointer can be read by the getFilePointer method and set by the seek method.

public class RandomAccessFile implements DataOutput, DataInput {
    public RandomAccessFile(String path, String mode)
        throws SecurityException, IOException,
            IllegalArgumentException;
    public RandomAccessFile(File file, String mode)
        throws SecurityException, IOException,
            IllegalArgumentException;
    public final FileDescriptor getFD() throws IOException;
    public native long getFilePointer() throws IOException;
    public native void seek(long pos) throws IOException;
    public native long length() throws IOException;
    public native void close() throws IOException;
    public native int read() throws IOException;
    public int read(byte[] b)
        throws IOException, NullPointerException;
    public int read(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    // The methods that implement interface DataInput:
    public final void readFully(byte[] b)
        throws IOException, NullPointerException;
    public final void readFully(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public int skipBytes(int n) throws IOException;
    public final boolean readBoolean() throws IOException;
    public final byte readByte() throws IOException;
    public final int readUnsignedByte() throws IOException;
    public final short readShort() throws IOException;
    public final int readUnsignedShort() throws IOException;
    public final char readChar() throws IOException;
    public final int readInt() throws IOException;
    public final long readLong() throws IOException;
    public final float readFloat() throws IOException;
    public final double readDouble() throws IOException;
    public final String readLine() throws IOException;
    public final String readUTF() throws IOException;
    // The methods that implement interface DataOutput:
    public native void write(int b) throws IOException;
    public void write(byte[] b)
        throws IOException, NullPointerException;
    public void write(byte[] b, int off, int len)
        throws IOException, NullPointerException,
            IndexOutOfBoundsException;
    public final void writeBoolean(boolean v) throws IOException;
    public final void writeByte(int v) throws IOException;
    public final void writeShort(int v) throws IOException;
    public final void writeChar(int v) throws IOException;
    public final void writeInt(int v) throws IOException;
    public final void writeLong(long v) throws IOException;
    public final void writeFloat(float v) throws IOException;
    public final void writeDouble(double v) throws IOException;
    public final void writeBytes(String s) throws IOException;
    public final void writeChars(String s) throws IOException;
    public final void writeUTF(String str) throws IOException;
}

It is generally true of all the reading routines in this class that if end of file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown. If any byte cannot be read for any reason other than end of file, an IOException other than EOFException is thrown. In particular, an IOException may be thrown if the stream has been closed (§22.23.7).

22.23.1 public RandomAccessFile(String path, String mode)
throws SecurityException, IOException, IllegalArgumentException

This constructor initializes a newly created RandomAccessFile by opening a connection to an actual file, the file named by the path name path in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path argument as its argument.

Next, if mode is "rw" and there is a security manager, its checkWrite method (§20.17.21) is called with the path argument as its argument.

If mode is "rw", then the file may be both read and written. If mode is "r", then the file may be read but may not be written (every write method for this object will simply throw an IOException). If mode is not "r" or "rw", then this constructor throws an IllegalArgumentException.

22.23.2 public RandomAccessFile(File file, String mode)
throws SecurityException, IOException, IllegalArgumentException

This constructor initializes a newly created RandomAccessFile by opening a connection to an actual file, the file named by file in the file system. A new FileDescriptor object is created to represent this file connection.

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by the file argument as its argument.

Next, if mode is "rw" and there is a security manager, its checkWrite method (§20.17.21) is called with the path represented by the file argument as its argument.

If mode is "rw", then the file may be both read and written. If mode is "r", then the file may be read but may not be written (every write method for this object will simply throw an IOException). If mode is not "r" or "rw", then this constructor throws an IllegalArgumentException.

22.23.3 public final FileDescriptor getFD() throws IOException

This method returns the FileDescriptor object (§22.26) that represents the connection to the actual file in the file system being used by this RandomAccessFile.

22.23.4 public long getFilePointer() throws IOException

The current file pointer for this random access file is returned. An IOException is thrown if the file pointer cannot be read for any reason.

22.23.5 public void seek(long pos) throws IOException

The file pointer for this random access file is set to pos, which is a position within the file, measured in bytes. Position 0 is the start of the file. An IOException is thrown if pos is less than zero or greater than the length of the file, or if the file pointer cannot be set for any other reason.

22.23.6 public long length() throws IOException

The length of this random access file, measured in bytes, is returned.

An IOException is thrown if the length cannot be read for any reason.

22.23.7 public void close() throws IOException

This random access file is closed. A closed random access file cannot perform input or output operations and cannot be reopened.

22.23.8 public int read() throws IOException

This method reads one byte from the random access file. The byte is returned as an integer in the range 0 to 255 (0x00-0xff). If no byte is available because the file pointer is at end of file, the value -1 is returned.

If the byte cannot be read for any reason other than end of file, an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed (§22.23.7).

Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the read method of InputStream (§22.3.1).

22.23.9 public int read(byte[] b)
throws IOException, NullPointerException

Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the read method of InputStream (§22.3.2).

22.23.10 public int read(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

Although RandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the read method of InputStream (§22.3.3).

22.23.11 public final void readFully(byte[] b)
throws IOException, NullPointerException

See the general contract of the readFully method of DataInput (§22.1.1).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.12 public final void readFully(byte[] b, int off, int len) throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the readFully method of DataInput (§22.1.2).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.13 public int skipBytes(int n) throws IOException

See the general contract of the skipBytes method of DataInput (§22.1.3).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.14 public final boolean readBoolean() throws IOException

See the general contract of the readBoolean method of DataInput (§22.1.4).

The byte for this operation is read from the random access file, starting at the current file pointer.

22.23.15 public final byte readByte() throws IOException

See the general contract of the readByte method of DataInput (§22.1.5).

The byte for this operation is read from the random access file, starting at the current file pointer.

22.23.16 public final int readUnsignedByte() throws IOException

See the general contract of the readUnsignedByte method of DataInput (§22.1.6).

The byte for this operation is read from the random access file, starting at the current file pointer.

22.23.17 public final short readShort() throws IOException

See the general contract of the readShort method of DataInput (§22.1.7).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.18 public final int readUnsignedShort() throws IOException

See the general contract of the readUnsignedShort method of DataInput (§22.1.8).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.19 public final char readChar() throws IOException

See the general contract of the readChar method of DataInput (§22.1.9).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.20 public final int readInt() throws IOException

See the general contract of the readInt method of DataInput (§22.1.10).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.21 public final long readLong() throws IOException

See the general contract of the readLong method of DataInput (§22.1.11).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.22 public final float readFloat() throws IOException

See the general contract of the readFloat method of DataInput (§22.1.12).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.23 public final double readDouble() throws IOException

See the general contract of the readDouble method of DataInput (§22.1.13).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.24 public final String readLine() throws IOException

See the general contract of the readLine method of DataInput (§22.1.14).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.25 public final String readUTF() throws IOException

See the general contract of the readUTF method of DataInput (§22.1.15).

Bytes for this operation are read from the random access file, starting at the current file pointer.

22.23.26 public void write(int b) throws IOException;

See the general contract of the write method of DataOutput (§22.2.1).

The byte for this operation is written to the random access file, starting at the current file pointer.

22.23.27 public void write(byte[] b)
throws IOException, NullPointerException

See the general contract of the write method of DataOutput (§22.2.2).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.28 public void write(byte[] b, int off, int len)
throws IOException, NullPointerException, IndexOutOfBoundsException

See the general contract of the write method of DataOutput (§22.2.3).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.29 public final void writeBoolean(boolean v)
throws IOException

See the general contract of the writeBoolean method of DataOutput (§22.2.4).

The byte for this operation is written to the random access file, starting at the current file pointer.

22.23.30 public final void writeByte(int v) throws IOException

See the general contract of the writeByte method of DataOutput (§22.2.5).

The byte for this operation is written to the random access file, starting at the current file pointer.

22.23.31 public final void writeShort(int v) throws IOException

See the general contract of the writeShort method of DataOutput (§22.2.6).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.32 public final void writeChar(int v) throws IOException

See the general contract of the writeChar method of DataOutput (§22.2.7).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.33 public final void writeInt(int v) throws IOException

See the general contract of the writeInt method of DataOutput (§22.2.8).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.34 public final void writeLong(long v) throws IOException

See the general contract of the writeLong method of DataOutput (§22.2.9).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.35 public final void writeFloat(float v) throws IOException

See the general contract of the writeFloat method of DataOutput (§22.2.10).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.36 public final void writeDouble(double v)
throws IOException

See the general contract of the writeDouble method of DataOutput (§22.2.11).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.37 public final void writeBytes(String s) throws IOException

See the general contract of the writeBytes method of DataOutput (§22.2.12).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.38 public final void writeChars(String s) throws IOException

See the general contract of the writeChars method of DataOutput (§22.2.13).

Bytes for this operation are written to the random access file, starting at the current file pointer.

22.23.39 public final void writeUTF(String str) throws IOException

See the general contract of the writeUTF method of DataOutput (§22.2.14).

Bytes for this operation are written to the random access file, starting at the current file pointer.


22.24 The Class java.io.File

A File object contains a path, which is a character string that can be used to identify a file within a file system. A path is assumed to consist of two parts, the directory and the file name, separated by the last occurrence within the path of a particular character known as the separator character. Some methods provide access to parts of the path string; other methods operate on the file that is identified by the path string. The details of such operations on files are to some extent dependent on the implementation of the host file system. The File class is designed to provide a set of abstract operations that are reasonably portable across otherwise incompatible file systems.

public class File {
    public static final String separator =
        System.getProperty("file.separator");
    public static final char separatorChar =
        separator.charAt(0);
    public static final String pathSeparator =
        System.getProperty("path.separator");
    public static final char pathSeparatorChar =
        pathSeparator.charAt(0);
    public File(String path) throws NullPointerException;
    public File(String dirname, String name)
        throws NullPointerException
    public File(File dir, String name)
        throws NullPointerException
    public String toString();
    public boolean equals(Object obj);
    public int hashCode();
    public String getName();
    public String getPath();
    public String getAbsolutePath();
    public String getParent();
    public native boolean isAbsolute();
    public boolean exists() throws SecurityException;
    public boolean canRead() throws SecurityException;
    public boolean canWrite() throws SecurityException;
    public boolean isFile() throws SecurityException;
    public boolean isDirectory() throws SecurityException;
    public long lastModified() throws SecurityException;
    public long length() throws SecurityException;
    public boolean mkdir() throws SecurityException;
    public boolean mkdirs() throws SecurityException;
    public String[] list() throws SecurityException;
    public String[] list(FilenameFilter filter)
        throws SecurityException;
    public boolean delete() throws SecurityException;
    public boolean renameTo(File dest) throws SecurityException;
}

22.24.1 public static final String separator = System.getProperty("file.separator");

This string should consist of a single character, whose value is also available in the field separatorChar; the string is provided merely for convenience.

22.24.2 public static final char separatorChar = separator.charAt(0);

The last occurrence of this character in a path string is assumed to separate the directory part of the path from the file name part of the path. On UNIX systems this character is typically '/'.

22.24.3 public static final String pathSeparator = System.getProperty("path.separator");

This string should consist of a single character, whose value is also available in the field pathSeparatorChar; the string is provided merely for convenience.

22.24.4 public static final char pathSeparatorChar = pathSeparator.charAt(0);

The first occurrence of this character in a string is sometimes assumed to separate a host name from a path name. On UNIX systems this character is typically ':'.

22.24.5 public File(String path) throws NullPointerException

This constructor initializes a newly created File so that it represents the path indicated by the argument path.

If the path is null, a NullPointerException is thrown.

22.24.6 public File(String dirname, String name)
throws NullPointerException

This constructor initializes a newly created File so that it represents the path whose directory part is specified by the argument dirname and whose file name part is specified by the argument name. If the dirname argument is null, the name is used as the path; otherwise the concatenation of dirname, the separatorChar (§22.24.2), and the name is used as the path.

If the name is null, a NullPointerException is thrown.

22.24.7 public File(File dir, String name)
throws NullPointerException

This constructor initializes a newly created File so that it represents the path whose directory part is specified by the File object dir and whose file name part is specified by the argument name.

If the name is null, a NullPointerException is thrown.

22.24.8 public String toString()

The result is a String equal to the path represented by this File object.

Overrides the toString method of Object (§20.1.2).

22.24.9 public boolean equals(Object obj)

The result is true if and only if the argument is not null and is a File object that represents the same path as this File object. In other words, two File objects are equal if and only if the strings returned by the getPath method (§22.24.12) are equal.

Overrides the equals method of Object (§20.1.3).

22.24.10 public int hashCode()

The hash code of this File object is equal to the exclusive OR of the hash code of its path string and the decimal value 1234321:

this.getPath().hashcode() ^ 1234321

Overrides the hashCode method of Object (§20.1.4).

22.24.11 public String getName()

If the path string contains the separatorChar character (§22.24.2), this method returns the substring of the path that follows the last occurrence of the separator character; otherwise, the entire path string is returned.

22.24.12 public String getPath()

The result is a String equal to the path represented by this File object.

22.24.13 public String getAbsolutePath()

The result is a String equal to the result of converting to "absolute form" the path represented by this File object.

22.24.14 public String getParent()

If the path has a parent directory, a String representing the path of that parent directory is returned; otherwise, null is returned.

22.24.15 public boolean isAbsolute()

The result is true if and only if the path represented by the File object is in absolute form, indicating a complete name that starts from the root of the directory hierarchy, rather than a name relative to some implied directory.

22.24.16 public boolean exists() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

The result is true if and only if the file system actually contains a file that is specified by the path of the File object.

22.24.17 public boolean canRead() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

The result is true if and only if both of the following are true:

  • The file system actually contains a file specified by the path of the File object.
  • The file so specified can be read.

22.24.18 public boolean canWrite() throws SecurityException

First, if there is a security manager, its checkWrite method (§20.17.21) is called with the path represented by this File object as its argument.

The result is true if and only if both of the following are true:

  • The file system actually contains a file specified by the path of the File object.
  • The file so specified can be written.

22.24.19 public boolean isFile() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

The result is true if and only if both of the following are true:

  • The file system actually contains a file specified by the path of the File object.
  • The file so specified is a data file rather than a directory.

22.24.20 public boolean isDirectory() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

The result is true if and only if both of the following are true:

  • The file system actually contains a file specified by the path of the File object.
  • The file so specified is a directory rather than a data file.

22.24.21 public long lastModified() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

An abstract modification time is returned. If two values returned by this method are compared, whether for the same file or for two different files, the smaller value represents an earlier modification time. Abstract modification times do not necessarily bear any relationship, even monotonicity, to times returned by the method System.currentTimeMillis (§20.18.6).

22.24.22 public long length() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

The length of the file, measured in bytes, is returned.

22.24.23 public boolean mkdir() throws SecurityException

First, if there is a security manager, its checkWrite method (§20.17.21) is called with the path represented by this File object as its argument.

An attempt is made to create the directory specified by the path represented by this File object; the result is true if and only if the creation operation succeeds.

22.24.24 public boolean mkdirs() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

If the directory name represented by this File object has a parent directory name (§22.24.14), an attempt is first made to create the parent directory; if this attempt fails, the result is false. Otherwise, once the parent directory has been determined to exist, or if the path has no parent, an attempt is made to create the directory specified by this File object. The result is true if and only if the creation operation succeeds.

22.24.25 public String[] list() throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

If the path represented by this File object does not correspond to a directory in the file system, then null is returned. Otherwise, an array of strings is returned, one for each file in the directory (on UNIX systems, the names "." and ".." are not included). Each string is a file name, not a complete path. There is no guarantee that the strings will appear in any particular order within the array; for example, they are not guaranteed to appear in alphabetical order.

22.24.26 public String[] list(FilenameFilter filter)
throws SecurityException

First, if there is a security manager, its checkRead method (§20.17.19) is called with the path represented by this File object as its argument.

If the path represented by this File object does not correspond to a directory in the file system, then null is returned. Otherwise, an array of strings is returned, one for each file in the directory (on UNIX systems, the names "." and ".." are not included) whose name satisfies the given filter. Each string is a file name, not a complete path. There is no guarantee that the strings will appear in any particular order within the array; for example, they are not guaranteed to appear in alphabetical order. A file name satisfies the filter if and only if the value true results when the accept method (§22.25.1) of the filter is called with this File object and the name as arguments.

22.24.27 public boolean renameTo(File dest)
throws SecurityException

First, if there is a security manager, its checkWrite method (§20.17.21) is called twice, first with the path represented by this File object as its argument and again with the path of dest as its argument.

An attempt is made to rename the file specified by the path represented by this File object to the name specified by dest; the result is true if and only if the renaming operation succeeds.

22.24.28 public boolean delete() throws SecurityException

First, if there is a security manager, its checkDelete method (§20.17.22) is called with the path represented by this File object as its argument.

An attempt is made to delete the file specified by the path represented by this File object; the result is true if and only if the deletion operation succeeds.


22.25 The Interface java.io.FilenameFilter

The list method (§22.24.26) of class File requires, as an argument, an object that implements the FilenameFilter interface. The only purpose of such an object is to provide a method accept that decides which files should appear in the generated directory listing.

public interface FilenameFilter {
    public boolean accept(File dir, String name);
}

22.25.1 public boolean accept(File dir, String name)

This method should return true if and only if the given file named name in the directory dir is to appear in the final list of files generated by the list method (§22.24.26) of class File.


22.26 The Class java.io.FileDescriptor

A FileDescriptor is an opaque representation of a connection to an actual file in a file system, or to a network socket, or to another source or sink of bytes. The main practical use for a file descriptor is to create a FileInputStream (§22.4.3) or FileOutputStream (§22.16.3) to contain it.

public final class FileDescriptor {
    public static final FileDescriptor in = ...;
    public static final FileDescriptor out = ...;
    public static final FileDescriptor err = ...;
    public boolean valid();
}

22.26.1 public static final FileDescriptor in = ...

A file descriptor for the standard input stream. Usually, this file descriptor is not used directly, but rather the input stream known as System.in (§20.18.1).

22.26.2 public static final FileDescriptor out = ...

A file descriptor for the standard output stream. Usually, this file descriptor is not used directly, but rather the output stream known as System.out (§20.18.2).

22.26.3 public static final FileDescriptor err = ...

A file descriptor for the standard error output stream. Usually, this file descriptor is not used directly, but rather the output stream known as System.err (§20.18.3).

22.26.4 public boolean valid()

If this FileDescriptor is valid (represents an active connection to a file or other active I/O connection), then the result is true. Otherwise, the result is false.


22.27 The Class java.io.IOException

The class IOException is the general class of exceptions produced by failed or interrupted input/output operations. Subclasses of IOException include:

EOFException
FileNotFoundException
InterruptedIOException
UTFDataFormatException
public class IOException extends Exception {
    public IOException();
    public IOException(String s);
}

22.27.1 public IOException()

This constructor initializes a newly created IOException with null as its error message string.

22.27.2 public IOException(String s)

This constructor initializes a newly created IOException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


22.28 The Class java.io.EOFException

An EOFException is thrown to indicate that an input operation has encountered end of file. Note that some Java input operations react to end of file by returning a distinguished value (such as -1) rather than by throwing an exception.

public class EOFException extends IOException {
    public EOFException();
    public EOFException(String s);
}

22.28.1 public EOFException()

This constructor initializes a newly created EOFException with null as its error message string.

22.28.2 public EOFException(String s)

This constructor initializes a newly created EOFException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


22.29 The Class java.io.FileNotFoundException

A FileNotFoundException is thrown to indicate that no actual file could be opened for a specified path name. See constructors FileInputStream (§22.4.1, §22.4.2) and FileOutputStream (§22.16.1, §22.16.2).

public class FileNotFoundException extends IOException {
    public FileNotFoundException();
    public FileNotFoundException(String s);
}

22.29.1 public FileNotFoundException()

This constructor initializes a newly created FileNotFoundException with null as its error message string.

22.29.2 public FileNotFoundException(String s)

This constructor initializes a newly created FileNotFoundException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


22.30 The Class java.io.InterruptedIOException

An InterruptedIOException is thrown to indicate that an input or output transfer has been terminated because the thread performing it was interrupted. The field bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred.

public class InterruptedIOException extends IOException {
    public int bytesTransferred = 0;
    public InterruptedIOException();
    public InterruptedIOException(String s);
}

22.30.1 public int bytesTransferred = 0;

The number of bytes that had been transferred by the I/O operation before the operation was interrupted.

22.30.2 public InterruptedIOException()

This constructor initializes a newly created InterruptedIOException with null as its error message string.

22.30.3 public InterruptedIOException(String s)

This constructor initializes a newly created InterruptedIOException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


22.31 The Class java.io.UTFDataFormatException

A UTFDataFormatException is thrown to indicate that a problem occurred in converting data from Java modified UTF-8 format. See method readUTF of DataInput (§22.1.15).

public class UTFDataFormatException extends IOException {
    public UTFDataFormatException();
    public UTFDataFormatException(String s);
}

22.31.1 public UTFDataFormatException()

This constructor initializes a newly created UTFDataFormatException with null as its error message string.

22.31.2 public UTFDataFormatException(String s)

This constructor initializes a newly created UTFDataFormatException by saving a reference to the error message string s for later retrieval by the getMessage method (§20.22.3).


Copyright © 1997 Sun Microsystems, Inc. "Java" is a trademark of Sun Microsystems, Inc. This document is covered by the full copyright and trademark declarations in The Java Language Specification. This document is excerpted from the fourth printing of The Java Programming Language by Ken Arnold and James Gosling, Addison-Wesley, 1996, ISBN 0-201-63455-4.

Appendix D

Changes for Java 1.1

No unmet needs exist and...current unmet needs that are being met will continue to be met.

-- Transportation Commission on Unmet Transit Needs, California

A newer version of Java has arrived since the original publication of this book. Called the Java 1.1 Platform (hereafter simply "Java 1.1"), it adds some language features, a few packages, and many classes to existing packages. The goals of Java 1.1 are to support internationalization better, fix the incongruities of the original abstract window toolkit package (java.awt, or just "AWT" for short), complete functionality that was missing or impoverished, and add several useful packages. This book does not cover AWT, so we do not cover it in this appendix.

This appendix does summarizes the other changes. For extensive changes, especially those having to do with new classes and packages, you will have to use the reference documentation shipped with your Java 1.1 system to supplement this appendix. The section titles in this appendix correspond to the chapters of this book where the new features would appear.

D.1 Classes

D.1.1 Inner Classes

 Classes and interfaces can be nested inside other classes. Such classes, called inner classes, should be ones that exist only to support the work of the class in which they nest. For example, the sole purpose of the SortMetrics class on page 75 is to return multiple values from the metrics method of the SortDouble class. It is a good candidate to be an inner class:

    abstract class SortDouble {
    static final class SortMetrics implements Cloneable {
        // ... the rest of SortMetrics (see page 75)
    }
    // ... the rest of SortDouble (see page 73)
    }

An inner class name is qualified by its enclosing class. In this case, the proper name of SortMetrics is SortDouble.SortMetrics, and so its declaration in SimpleSortDouble on page 76 would be

    SortDouble.SortMetrics metrics = bsort.sort(testData);
Inner classes and interfaces can use the same access modifiers as other members of a class. A class that was used only in internal data structures might be marked private; one intended only for use by subclasses would be protected. Inner classes can also be public or package accessible.

The example above declares SortMetrics as static. An inner class that is not static has an implicit reference to its enclosing object, which is the object that created the inner class object. This reference is useful because many inner classes are strongly tied to particular objects, and need to access their fields. For example, the class EnumerateWhichChars on page 222 is used to implement the Enumeration interface for the WhichChars class, and could be nicely rewritten to look like this:

    public class WhichChars {
    private BitSet used = new BitSet();     // in original
    private class Enumerate implements Enumeration {
        private int pos = 0;
        private int setSize = used.size();

        public boolean hasMoreElements() {
        while (pos < setSize && !used.get(pos))
            pos++;
        return (pos < setSize);
        }

        public Object nextElement()
        throws NoSuchElementException
        {
        if (hasMoreElements())
            return new Character((char)pos++);
        else
            throw new NoSuchElementException();
        }
    }

    public Enumeration characters() {       // from page 223
        return new Enumerate();
    }
    }

We use the shorter class name Enumerate because the class is already nested inside WhichChars, so EnumerateWhichChars would be redundant. The class is private so that even other classes in the package can't use the type directly-it is purely an implementation detail of the WhichChars class.

In the original code on page 222, used was passed as a parameter to the class's constructor, which stored the reference in a field of its own called bits. Here the code for Enumerate directly accesses the field used of its enclosing object. When resolving identifiers, the inner class's enclosing object (also called its enclosing instance) is searched for fields and methods after the class's own this. Because Enumerate does not have a field named used, the identifier used in the inner class refers to the enclosing object's field of that name. The enclosing object for an inner class is the this reference of the method that created the inner class object. In our example above, when an Enumerate object is created inside a particular WhichChar object, the Enumerate object's enclosing object is set to be the this reference of the WhichChar method that created it. This means you cannot create an instance of a non-static inner class in a static context (inside a static method, a static block, or as an initializer for a static field).

You can get a reference to an enclosing object using its class name. For example, code in an Enumerator object could get a reference to its enclosing object using WhichChar.this.

D.1.2 New Uses for final

Method parameters and local variables can be declared final. If you do not expect to change the value of a parameter or variable inside the method, you can declare it final to let the compiler enforce that. The compiler can also optimize uses of a final parameter or variable since it knows the value will never change.

The final-ness of a parameter is not part of the method signature-it is simply a detail of the implementation. A subclass can override a method and add or drop any final parameter modifiers you wish. You can also add or drop final modifiers in a method's parameters without causing any harm to existing compiled code that uses that method. The final declaration does not show up in the documentation generated from doc comments.

You can defer initialization of a final field or variable, as long as you initialize it before it is used and assign a value to it exactly once. The compiler will check for proper assignment, as will the verifier before code is executed. Deferred initialization can be useful when the proper value can only be calculated by a loop or other code that is hard or impossible to encode in a variable initializer, such as code that throws exceptions that must be caught and handled.

D.1.3 Object Initializers

You can have arbitrary blocks of code that are executed after the superclass constructor is executed, but before the class's own constructor body is executed. Such blocks are analogous to static blocks described on page 44, except the keyword static is left off.

D.2 Extending Classes

D.2.1 Anonymous Classes

 When you are writing simple subclasses or implementations of interfaces, creating a bunch of classes for each trivial class can be awkward. Anonymous classes are a convenient short form of inner classes that have no name, only an implementation that is specified right along with the new. Suppose you want to create a simple Observer object (see page 233) that keeps a history of the events stored in a field of your object. The following would do this directly and simply:

    private Vector history = new Vector();

    public void watch(Observable o) {
    o.addObserver(new Observer() {
        public void update(Observable o, Object arg) {
        history.addElement(arg);
        }
    });
    }

The addObserver has an embedded new of an anonymous class that implements the Observer interface, implicitly extending Object. This anonymous class implements update by adding an element to the enclosing object's history vector. The compiler creates an unnamed (hence "anonymous") class that overrides update as specified. The end of the anonymous class declaration is the end of the allocation expression started by the new. Here we simply close off the call to addObserver with a closing parenthesis.

An anonymous class can extend a class instead of implementing an interface, in which case it is an unnamed subtype of that class. Such a new can invoke any superclass constructor. Anonymous classes cannot have their own constructors.

Anonymous classes are a quick, terse subclassing tool that is useful in certain situations, such as creating several types of AWT buttons, each with its own small action, or creating simple Runnable objects. Unfortunately, they share a common failing of many terseness features-it is trivial to write code that is torture to read. You should use of anonymous classes only for tiny classes that override one, or at most two, methods, with a total of four lines of code or fewer. Otherwise people who read your code can become confused trying to keep track of what piece of which class's method's code they are reading, and what the outer context is. Use this tool sparingly. When it's good, it's very, very good. When it's not, it's awful.

D.2.2 New Hashing Method

The default implementation of Object.hashCode is to return keys that are likely to be different for different objects. As described on page 64, many classes override both hashCode and equals to provide different notions of equality. However, sometimes you need the original notion of equality, in which all objects are different, even for an object that usually is used with a broader notion. You can use == to test if two objects are the same, but you will need to use System.identityHashCode to hash the objects, since it preserves the default implementation of hashCode in which all objects are considered different.

D.3 Tokens, Operators, and Expressions

Documentation comments ("doc comments") contain @ tags (such as @author and @see) that are not documented in this book. The new @deprecated tag has particular meaning-it marks a class, interface, field, or method as not recommended for continued use. Existing code that uses the deprecated entity will still compile and run, but the compiler will generate a warning, suggesting that you update your code to avoid that entity. You should follow that recommendation.

To have this effect on a type or a member of a type, the @deprecated tag must be at the beginning of a doc comment line (ignoring white space and any * character). This is the only place in the entire Java language where the contents of a comment affect the generated code. The @deprecated tag should always refer readers to the preferred replacement(s). For example

    /**
      * @deprecated	This call has been replaced with dwishm
      * @see dwishm
      */
    public void dwim() { /*...*/ }
The transient keyword, marked as "unused" on page 93, now has defined meaning; see Section D.5.2.

You can initialize the contents of an array when you new it. For example, the following would be a flexible way to create an array of strings:

    String[] martians = new String[] {
                "Gidney", "Cloyd"
            };

D.4 Threads

 The interruption mechanism briefly described on pages 173-174 as future functionality has been implemented in Java 1.1. See those pages for more details.

D.5 I/O

D.5.1 Internationalization

 Many new I/O classes have been added to handle full internationalized character issues. The original classes really worked only with ISO-Latin-1 8-bit characters (notice that InputStream.read, for example, returned eight bits, not sixteen, in its int). The most specific change is that PrintStream is now a deprecated class, since it thinks only in terms of ISO-Latin-1. The new class is called PrintWriter, and provides all the methods of PrintStream except those for writing raw bytes. Existing code that uses the print and println methods of PrintStream will have the output translated to the local character set. (To prevent a massive outpouring of deprecation warnings, only the constructors of PrintStream are deprecated.)

The autoflushing of PrintStream described on page 199 has been cleaned up. If autoflush is turned on, any newline anywhere in the output causes a flush, as does any write of a byte array. If autoflush is off, no automatic flushing is done.

PrintWriter is a subclass of the abstract Writer class, which is the parallel to OutputStream for classes that understand internationalization. The Reader abstract class is the parallel to InputStream. There are several new Reader and Writer classes for internationalized I/O.

The fields System.in, System.out, and System.err are final in Java 1.1 for security reasons, so code that modifies these fields (like that shown on page 197) will not work.

The new package java.text includes many classes useful for parsing and producing internationalized text. It includes classes for date and number formatting, comparing and sorting strings in a locale-sensitive way, splitting up native language text, and other locale-related I/O.

D.5.2 Object Serialization

The streams ObjectInputStream and ObjectOutputStream help you read and write entire objects and object graphs. Objects written to an ObjectOutputStream using writeObject generate a stream of bytes that, when read by an ObjectInputStream with readObject, create a full copy of the original objects. The process of creating such a stream of bytes is called serialization. Serialized copies are deep-you can serialize an entire graph of objects, and when you deserialize the generated bytes, you will get a full copy of the original graph. If two or more objects refer to a particular object in the original graph, a deserialized copy will have copies of those two or more objects that refer to a copy of that same particular object.

The byte stream encodes the state of the serialized object, including private fields. Therefore any serializable object can have the values of its private fields examined by someone who serializes the object and reads the generated bytes. Some programmers view private fields as secret, and would not be pleased to have values exposed in this way. For this reason, objects are not serializable unless they implement the Serializable interface. Serializable is an empty interface that simply marks the object as one that can be serialized. The default serialization mechanism just writes the non-static, non-transient fields of an object. You can override this by providing readObject and writeObject methods.

A class that instead implements the interface Externalizable-a subinterface of Serializable-is serializable but must provide custom readExternal and writeExternal methods; the default serialization will not be used.

D.6 Utilities

D.6.1 Resource Localization

 Several new utilities have been added for localization. A new Locale class describes particular locales to define a user's preferred language and other properties. A ResourceBundle superclass is provided to customize a set of resources (such as messages that might be displayed to the user) based on the user's preferred locale. Some subtypes of ResourceBundle are provided: ListResourceBundle, an abstract class that provides a simple implementation of ResourceBundle to which you must simply provide the list of resources and keys for each resource, and PropertyResourceBundle, which uses files that contain the keyed resources.

D.6.2 Dates and Times

The functionality of the Date class has been split up into a richer system that can cope with varying reckonings of time. A Date object now only represents a particular moment in time with millisecond granularity. Its other constructors and methods previously performed two other duties: formatting strings and viewing a moment in time as year, month, day, hour, minute, and second values. All these methods are deprecated in favor of:

  • an abstract Calendar class for handling various ways of marking time
  • an abstract TimeZone class that represents time zone offsets and other adjustments, such as daylight savings time
  • an abstract java.text.DateFormat class that defines how one can parse and format date strings

These abstract classes allow flexibility, but almost everyone will need to work with Gregorian dates that are used in most of the world and in international commerce, so Java 1.1 also provides:

  • a GregorianCalendar class
  • a SimpleTimeZone class for use with GregorianCalendar
  • a java.text.SimpleDateFormat class that parses and formats Gregorian dates For example, the following program uses a GregorianCalendar to print out the current year:

    class CurrentYear {
    public static void main(String[] args) {
        GregorianCalendar now = new GregorianCalendar();
        int year = now.get(Calendar.YEAR);
        System.out.println("The year is " + year);
    }
    }

D.7 Programming with Types

D.7.1 Reflection

 The package java.lang.reflect provides a reflection mechanism for Java. This is a tool for examining classes fully. A Class object can now return a list of all the public methods and fields of the related class. You can use the Method objects returned to invoke methods, and the Field objects to get and set field values. A Class object can also return a list of all members, including non-public ones, but security restrictions usually prevent doing this.

You should avoid the temptation to use reflection when other tools more natural to the language would suffice. If you are accustomed to using function pointers in another language, for example, you might think that using Method objects are a natural replacement, but usually an object-oriented tool-such as an interface that is implemented by objects that perform the needed action-is better. Reflection is intended for use by language tools such as debuggers and class browsers.

D.7.2 Wrapper Classes

Two new wrapper classes have been added: Short and Byte. These are subtypes of Number. A new Void class has also been added for completeness, and is used by the reflection methods to represent void return types.

D.7.3 Getting the Class Object for a Named Class

You can get the Class object for a given type with a new use of the class keyword:

    Class threadClass = Thread.class;
    Class intClass = int.class;
    Class voidClass = void.class;

D.8 Native Methods

 The API for writing C implementations of Java methods is now completely different. The mapping has been regularized, and is less tied to a particular implementation of the Java Virtual Machine. The general comments about native method mappings in Appendix A are still valid, but the specific details described, while still supported, are strongly deprecated. The new Java Native Interface (JNI) is much easier to learn and to use.

D.9 New Packages

Java 1.1 has several new packages:

  • java.beans-Java Beans are software components that allow unrelated developers to write and ship Java components that can be composed together by end-user tools.
  • java.math-This package provides tools for mathematical manipulations. Currently a BigInteger class provides arbitrary-precision integer arithmetic, and BigDecimal provides arbitrary-precision decimal arithmetic.
  • java.rmi-Remote Method Invocation (RMI) allows you to create objects whose methods can be invoked by objects running in other Virtual Machines, including Virtual Machines running on other hosts. Because Java code can be downloaded and run securely, RMI lets you pass subtypes of the declared method parameters, and return subtypes of the declared type of the remote method. This allows you to pass object behavior as well as simple values. RMI provides remote procedure calls with a Java flavor and benefits.
  • java.security-This package and its subpackages provide some basic interfaces and classes for security-related operations, such as authentication, authorization, signed data, and encryption.
  • java.sql-This package provides tools for using relational databases.
  • java.text-This package provides text internationalization tools, such as date parsing and number formatting.
  • java.util.zip-You can use these classes for handling ZIP files.


Reserved Words (A-L)

 | default | float
boolean | delegate | for
break | do | if
byte | double | implements
case | else | import
catch | extends | instanceof
char | false | int
class | final | interface
continue | finally | long


abstract

The abstract keyword can be used in the declaration of classes and methods. Use of the keyword in a class declaration typically means that one or more of the methods within the class body are declared as abstract. If the keyword is left off the class declaration, and a method within the body of the class is declared using the abstract keyword, then the class is implicitly defined to be abstract. In other words, the keyword abstract need not be provided as part of the class declaration in this circumstance, and the code will compile successfully. (For readability it is recommended that abstract class declarations include the keyword to make the class intention clear.)

Classes declared to be abstract cannot be instantiated. Instead, abstract classes force the programmer to provide a body for each abstract method within a new derived class. The following example shows a simple abstract class and a class derived from it:

public abstract class FruitClass
{

    public boolean isPeelable( );

    .
    .
    .
}

public class BananaClass extends FruitClass
{

    private boolean bPeel;

    public boolean isPeelable( ) {
        .
        .
        .
        return bPeel;
    }

}

The derived class (BananaClass) may be instantiated, and any non-abstract methods of the abstract class (FruitClass) will be inherited unless they are overridden.

Note that a class declaration cannot use abstract and final.

The abstract keyword can also be used to define methods. As already shown above, a class containing abstract methods is then also (either implicitly or explicitly) defined as abstract and must be subclassed in order to be instantiated. An abstract method cannot have the implementation defined within the abstract class. Rather, it is declared with arguments and a return type as usual, but the body that is enclosed in curly braces is replaced with a semicolon.

Consider the following example declaration of an abstract method:

abstract public int someMethod( int arg1, int arg2);

Note that a method declared with the keyword abstract cannot be declared with the keywords static, private, or final.


boolean

The boolean keyword is used to declare a primitive Java data type containing a truth value. The two possible values of a boolean variable are true and false. Note that true and false are defined as keywords in the Java language, but they are actually literal values. Hence, the keywords true and false can be used as return values, in conditional tests, and in assignments and comparisons to other boolean variables.

The contents of boolean variables cannot be cast to or from other types; the current value of a boolean variable can be converted to a string however.

The following code demonstrates declaration and assignment for a boolean variable:

private boolean isRunning;

isRunning = true;


break

The break keyword is used to define a break statement which, without a label, transfers control out of the innermost enclosing while, do, for, or switch statement. If the break statement includes a label and the statement is executed, control will be transferred out of the enclosing statement to the line immediately following the label declaration. (In this case, the break target need not be a while, do, for or switch statement.)

The break statement also transfers control outside of try/catch blocks. Note that if the break statement with a label is executed within a try or catch block, and an associated finally block is defined for the try/catch block, then the contents of the finally block will first be executed. After the entire finally block has executed, control will once again transfer to the first statement immediately following the label declaration.

The following example demonstrates a break statement used with a label:

block1:

   recordsRemain = getUpdateStatus( );

while (recordsRemain)
{
    if (isRunning)
        System.out.println("Update another record");
    else
        break block1;
}


byte

The byte keyword is used to declare a primitive Java data type containing an integer value in the range of negative 128 to positive 127. A byte is defined as 8 bits in length, regardless of the platform the Java bytecode executes on.

Note that byte variables can be cast to and from other numeric types.

The following example demonstrates declaration and assignment for a byte variable:

private byte stripThis;

stripThis = 64;


case

The case keyword can only be used within a switch statement block. It is used repeatedly to provide any number of unique constants (or numeric labels) for comparison within a switch statement block. If the case constant equals the value of the expression at the top of the switch statement, then control is passed to the statement immediately following the case statement. If, on the other hand, the expression at the top of the switch statement block and the case label do not match, control is passed to the next case for comparison.

In the event that no case constants match the value of the expression given at the top of the switch statement, often a default case is provided.

For an example of how the case keyword can be used, see the keyword switch.


catch

The catch keyword is used to introduce an exception-handling block of code. The keyword is followed by an exception type, an argument name in parentheses, and a block of code to execute should the specified exception actually occur. A try statement and its corresponding block of code always precede a catch statement. When an exception is thrown within the corresponding try statement block, the catch statement's exception type is evaluated to determine whether it is capable of handling the exceptional condition. If the exception type can be handled, the argument is assigned to the specified type and the code within the catch block is executed.

For an example of how the catch keyword can be used, see the keyword try.


char

The char keyword is used to declare a primitive Java data type containing a single 16-bit Unicode character in the range \u0000 to \uffff. Unicode characters are used to represent a majority of known written languages throughout the world. (ASCII characters make up a very small part of the Unicode character set.)

Note that values stored by char may be cast to and from other numeric types. However, because character data is implicitly unsigned, casts of char to byte or short can result in a negative number.

The following example demonstrates declaration and assignment for a char variable:

private char hitChar;

hitChar = 'a';


class

The class keyword is used in the declaration of a new class. A class declaration defines a new reference type (or object) and describes its implementation through the use of constructors, methods, and fields. These implementation details can be inherited from superclasses, or uniquely defined as part of the class declaration.


continue

The continue keyword is used in nested loops to define a continue statement, which, without a label, transfers control to the end of the innermost enclosing while, do, or for loop. Once control is passed, the current loop iteration ends and a new one begins. If the continue statement includes a label and is executed, control is transferred to the last statement of the outer loop. In this case, the continue target label must point to a while, do, or for loop. (Contrast this with the labeled break statement, where the target need not be a loop, or iteration, statement.)

Note that if the continue statement with a label is executed within a try or catch block, and an associated finally block is defined for the try/catch block, then the contents of the finally block will be executed first. After the entire finally block has executed, control will once again transfer to the last statement of the loop immediately following the label declaration.

The following code demonstrates the continue keyword used with and without a label:

block1:
for ( int i = 0; i < 10; i++ )
{
    while ( statusOkay )
    {
        if ( someNum < 0 )
        {
            someNum++;
            System.out.println("Do it again");
            continue;
        }

        if (string1[i] == null)
        {
            System.out.println("null string here");
            continue block1;
        }
        else
        {
            string2[i] = string1[i];
        }
    // continue statement without label points here
    }
// continue statement with label points here
}


default

The default keyword can only be used within a switch statement block. It can be used only once, and is typically located at the end of the switch statement block. The default keyword is used to label statements that are to be executed by default. That is, the default statement block is only executed when the result value of the switch expression does not match any of the case labels within a switch statement block.

For an example of how the default keyword is used, see the keyword switch.


delegate

The delegate keyword is used as part of a class declaration to create method pointers. This keyword is an extension to the Java language, provided by Microsoft.

Thanks for using this version of Visual J++ Technology Preview 1.


do

The do keyword is used as part of a do/while loop. Unlike the other, more commonly used loop constructs, a do/while loop expression is evaluated only after the block of code within its body has been executed. Thus, you are ensured that the code within the loop body is executed at least once, even if the expression tested causes the loop to end.

Note Don't forget that a semicolon is required after the condition in a do/while loop.

The following code shows a typical do/while loop construct:

int i = getValue( );

do
{
    System.out.println("Printing at least once");
    .
    .
    .
} while ( i <= 10 );


double

The double keyword is used to declare a primitive Java data type containing a 64-bit floating-point number in IEEE 754 format. Variables of type double store values in the range negative 1.7E308 to positive 1.7E308 within approximately 14 significant digits of accuracy. When you want a floating-point literal value to be treated as a double, append the letters 'd' or 'D' to the end of the value.

Note that double variables may be cast to and from other numeric types. However, doubles cannot be cast to or from values of type boolean.

The following example demonstrates declaration and assignment for a double variable:

private double dCalcSet;

dCalcSet = 1.23d;
dCalcSet = 3e2;
dCalcSet = .25;


else

The else keyword is used to provide an alternative clause to an if statement. If the expression defined by the if statement evaluates to false, then control transfers to the first statement following the else keyword. If the expression defined by the if statement evaluates to true, then control transfers to the first statement following the if keyword.

Note that if/else conditional testing is a frequent source of program bugs. Consider the following example of a poorly formatted if/else condition:

if ( numPrints < 1000 )
    if ( paperFeed == fullTray )
    {
        printPaperCopy( );
        showStatus( );
        paperFeed--;
    }
else
    suspendPrintJob( ) // Bad indenting!;

In the example shown above, the beginning of the else statement block is formatted to fall into the same column as the outermost if statement, even though it's proper association is with the closest if statement. Problems of this nature can be easily overlooked unfortunately, and it is up to the programmer to use good formatting to illustrate the logical intent of the code.


extends

The extends keyword is used in a class declaration to specify the direct superclass of the class being declared. The superclass can be thought of as the class from whose implementation the implementation of the current class is derived. The class being declared is said to be the direct subclass of the class it extends. If no class is explicitly defined as the superclass with the extends keyword, then that class has the class java.lang.Object as its implicitly declared superclass.

When a class is extended, the class being declared has access to all the public and protected variables and methods of it's superclass. Note that classes declared with the keyword final cannot be subclassed.

The following example shows typical use of the keyword extends:

public class TransactionApplet extends Applet
{
    .
    .
    .
}


false

The false keyword can be used as one of the two possible boolean values. Strictly speaking, false is not a keyword of the Java language; rather, it is a literal value to be assigned to a variable of type boolean.

For an example of how the false keyword can be used, see the keyword boolean.


final

The final keyword is used as a modifier for classes, methods, and variables.

When the final keyword appears in a class declaration, it means that the class may never be subclassed or overridden. This prevents over-specialization of a particular class. In some sense, the person who created the class considered any further changes to be tangential to its primary purpose.

When the final keyword appears in a method declaration, it means that the method may never be overridden. (Note that methods declared with the keywords static or private are implicitly final.)

When the final keyword appears in a variable declaration, it means that the variable has an assigned value that can never be changed.


finally

The finally keyword is used to define a block of code following a try/catch exception block. The finally block is optional, and appears after the try block and after any catch blocks. The code in a finally block is always executed once, regardless of how the code in a try block executes. In normal execution, control reaches the end of the try block and then proceeds to the finally block, which typically performs any necessary cleanup.

Note that if control leaves the try block because of a return, continue, or break statement, the contents of the finally block are still executed before control transfers out of the try block.

If an exception occurs in the try block, and there is an associated catch block to handle the exception within the method, 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 moves up the series of prior method calls until the exception can be handled.


float

The float keyword is used to declare a primitive Java data type containing a 32-bit floating-point number represented in IEEE 754 format. Variables of type double store values in the range positive 3.40282347E+38 to negative 1.40239846E-45. When you want a floating-point literal value to be treated as a float, append the letters 'f' or 'F' to the end of the value.

The following example demonstrates declaration and assignment for a float variable:

float fCalcSet;

fCalcSet = 1.23f;
fCalcSet = 3e2f;
fCalcSet = .25f;


for

The for keyword is used to create a loop construct. An initialization section, an expression section, and an update section immediately follow the keyword. A semicolon separates each section, and all appear together within at least one set of parentheses.

The initialization section allows the programmer to declare one or more local loop variables. Once the loop ends, these variables are no longer valid.

The expression section contains an expression that is evaluated to determine whether the loop should continue. A true result allows the loop to continue; a false result allows control to transfer to the statement following the loop body.

The update section allows the programmer to increment loop counters or perform other updates. Typically, the update section is used to increment or decrement whatever loop counters the programmer defines.

The following example shows a typical for loop construct:

for ( int i = 0; i < 10; i++ )


if

The if keyword is used to execute a statement or block of statements when it's associated expression evaluates to true. An if statement may also have an alternative else clause. If the expression defined by the if statement evaluates to false, then control transfers to the statement (or block of statements) following the else keyword. If the expression defined by the if statement evaluates to true, then control transfers to the first statement following the if keyword.

Note that if/else conditional testing is a frequent source of program errors. Consider the following example of a poorly formatted if/else condition:

if ( numPrints < 1000 )
    if ( paperFeed == fullTray )
    {
        printPaperCopy( );
        showStatus( );
        paperFeed--;
    }
else
    suspendPrintJob( );  // Bad indenting!

In the example shown above, the beginning of the else statement block is formatted to fall into the same column as the outermost if statement, even though it's proper logical association is with the if statement closest to it. Problems of this nature can be easily overlooked, unfortunately and it is up to the programmer to use good formatting techniques to illustrate the logical intent of the code.


implements

The implements keyword is used in a class declaration to indicate that the class provides an implementation for one or more interfaces. If more than one interface is implemented within the class, the interface names must be separated by commas in the declaration. The implements keyword must also follow the extends clause in the class declaration.

The following example demonstrates use of the keyword implements in a class declaration:

public class PotatoHead implements InterchangeableParts
{

}


import

The import keyword is used by Java to make classes available to the current file using an abbreviated name. Any number of import statements may appear in a Java program, but they must appear after the optional package statement at the top of the file, and before the first class or interface definition in the file.

The following examples demonstrate use of the keyword import:

import my.package.*;   // all classes in my.package are imported
import my.package.cool; // only the cool class is imported from my.package


instanceof

The instanceof keyword is used as an operator that returns true if an object on its left side is an instance of the class specified on its right side. The instanceof operator will also return true when comparison is done with an object implementing an interface. The instanceof operator returns false if the object is not an instance of the specified class or does not implement the specified interface. It also returns false if the specified object is null.


int

The int keyword is used to declare a primitive Java data type that contains an integer value in the range of negative 2147483648 to positive 2147483647. An int is defined as 32 bits in length, regardless of what platform the Java bytecode executes on.

The contents of int variables can be cast to or from other numeric types.

The following example demonstrates declaration and assignment for an int variable:

private int iValueK;

iValueK = 1024;


interface

The interface keyword is used in the declaration of an interface. An interface can be thought of as a template for a class that you may need to implement, but you don't have to do all the design work yourself.

Interfaces differ from classes in the following ways:

  • Interfaces cannot implement other interfaces. (They may extend other interfaces.)

  • Interfaces cannot contain constructors, instance variables, class methods, or static class initializers.

  • All methods declared within an interface are implicitly declared to be public and abstract. Methods within an interface cannot be declared as final, native, static, or synchronized.

  • All variables declared within an interface are implicitly declared to be static and final, and thus, must be assigned a constant value. Variables are also implicitly public, and cannot be declared as either transient or volatile.


long

The long keyword is used to declare a primitive Java data type containing a value in the range negative 9223372036854775808 to positive 9223372036854775807. A long is defined as 64 bits in length, regardless of what platform the Java bytecode executes on.

The contents of long variables can be cast to or from other numeric types.

The following example demonstrates declaration and assignment for a long variable:

private long iLedgerBalance;

iLedgerBalance = 1234567890;


Reserved Words (M-Z)

native | short | transient
new | static | true
null | super | try
package | switch | void
private | synchronized | volatile
protected | this | while
public | throw |
return | throws |


native

The native keyword is a modifier used in the declaration of a method to indicate that the method is implemented in another programming language. Because a native method is implemented outside of a Java program, the method declaration ends with a semicolon rather than a method body.

Note that native methods cannot be declared with the keyword abstract. For easy access to the Windows API, see Writing Windows-Based Applications with J/Direct.


new

The new keyword is used as an operator for creating a new object or array.

When new is used to create an object, it first creates an instance of the specified class, then initializes all of the instance variables to their default values, and last invokes the appropriate constructor for the class, depending on the arguments provided in the argument list.

Using the new keyword to create a class object typically looks like this:

Button b = new Button("OK");

The new operator can also be used to allocate dimensional arrays for any numeric or object type. Once an array has adequate space allocated, all the elements of the array are initialized to a default value, and it is then up to the programmer to supply values other than the defaults.

Using the new keyword to create an array typically looks like this:

int array[] = new int[ 10 ];


null

The null keyword represents a special value that indicates a variable does not refer to any object. The value null may be assigned to any class or interface variable to aid garbage collection. (Assigning the value null to any of the items above indicates to the garbage collection system that the object or variable is no longer in use.) It cannot be cast to any other type, and should not be considered to have a known numeric value.


package

The package keyword is used by Java to specify which package the code in the file is located in. Java code that is part of a particular package has access to all classes in the package, and all non-private methods and variables in those classes.

The package statement must come before anything else (except comments and conditional compilation directives) in a Java file. If the package statement is omitted from a Java file, the code in that file becomes part of an unnamed default package.


private

The private keyword is a modifier that can be used in the declaration of methods or variables. (Note that the private keyword cannot be used in the declaration of local variables.) Using the private modifier in the declaration for either of these types hides the methods and variables so they cannot be directly referenced outside of the class they're declared in. One exception to this rule is that private methods or variables declared within a class can also be used by inner classes.


protected

The protected keyword is a modifier that can be used in the declaration of methods or variables. (Note that the protected keyword cannot be used in the declaration of local variables.) A protected variable or method is only visible within its class, within its subclasses, or within the class package. Note that the subclasses may reside within different packages, however.


public

The public keyword is a modifier that can be used in the declaration of classes and interfaces. (Note that the public keyword cannot be used in the declaration of local variables.) The public keyword can also be used as a modifier in the declaration of methods and variables. Classes or interfaces declared as public are visible everywhere. Methods and variables declared as public are visible everywhere their corresponding classes are visible.

Note that public classes must have a class name that exactly matches the name of the .java file in which they appear.


return

The return keyword returns control to the invoker of a method or constructor. A return statement used in a method can either return a value, or simply return to the invoker without specifying a value. If a return value from a method is not needed, the return keyword is followed immediately by a semicolon (rather than a value) and the method's declaration must specify a return type of void. If a return value from a method is needed, the method's declaration must specify a return type that matches the type of value being returned.

Note that in constructors, return statements cannot return values.


short

The short keyword is used to declare a primitive Java data type containing a value in the range negative 32768 to positive 32767. A short is defined as 16 bits in length, regardless of what platform the Java bytecode resides on.

The contents of short variables can be cast to or from other numeric types.

The following example demonstrates declaration and assignment for a short variable:

private short squareFeet;

squareFeet = 4600;


static

The static keyword is used as a modifier for methods and variables. The keyword can also be used to define static initializing blocks.

When the static keyword appears in a method or variable declaration, it means that there will be only one copy of the method or variable that each class object may reference, regardless of the number of instances of the containing class that are created.

The static keyword can also be used to create a static initializing block of code that runs only once, when the class object is first loaded into memory.


super

The super keyword is typically used to access hidden variables or overridden methods in a superclass. This keyword can also be used, along with an optional list of arguments, as the first line in a constructor body to call a superclass constructor.


switch

The switch keyword is used along with the keyword case, and sometimes the keyword default, to create a conditional statement. In a switch statement, the switch keyword is followed by an expression within parentheses whose value must evaluate to a primitive Java data type. Once the expression has been evaluated, its value is compared against the label following each case statement within the switch statement body. When a label has the same value, the lines following that case statement are executed. An optional default label is included within the body of a switch statement when there is no guarantee that the labels provided by each case statement are the only values the switch expression may evaluate to.

The following example shows a typical switch statement construct:

switch ( someExpression )
{
    case 1:
        {
        doCase1( );
        break;
        }
    case 2:
        {
        doCase2( );
        break;
        }
    case 3:
        {
        doCase3A( );
        doCase3B( );
        }
    default:
        doDefault( );
}

The break keyword is also, at times, used within the body of a switch statement. Once the lines following a case statement have executed, the break statement is included to jump over the remaining body of the switch condition. Without a break statement, subsequent case statements would continue being evaluated, and eventually the default statement, if one were included, would execute.


synchronized

The synchronized keyword can be used as a modifier to specify thread-safe methods, and as a statement to specify critical sections of code. Used as a method modifier, synchronized indicates that the method should only be available to one thread at a time. Used as a statement, synchronized is followed by an expression in parentheses and a block of statements. If the expression within parentheses evaluates to an object type or array, the program obtains a lock on the item before executing the statement block.


this

The this keyword is used with instance methods and constructors to refer to the current object. Use of the keyword this in the very first statement in the body of a constructor means that another constructor in the same class is being called to assist in creation of the object. For example:

public class MyClass
{

    private long birthday;
    private String name;

    // first constructor
    MyClass( String bDay )
    {
        birthday = formatBirthday( bDay );

    }

    // second constructor
    MyClass(String nm, String bDay )
    {   this ( bDay );

        name = new String(nm);

    }
}

Note The keyword this must appear as the first statement in the body of a constructor, otherwise your code will not compile.

Use of the keyword this in an instance method is helpful when a variable using the same name appears within the method body. For example, when you refer to a class scope variable in a method containing the variable name x, the class scope variable would be known as this.x.


throw

The throw keyword is typically used within a try block to indicate that an exceptional condition has occurred. The throw keyword is followed by an exception object, derived from the class Throwable, indicating the type of exception being thrown. A throw statement causes a program to immediately stop and resume at the nearest catch statement that can handle the specified exception object. Hence, throw statements may also be outside a try block, if the exception will be caught elsewhere within the program.

The following example shows use of the throw keyword:

public void someMethod( int div ) throws Exception1
{
    try
    {
        if ( div == 0 )
            throw new Exception1( );
    }
    catch(Exception1 e1)
    {
        // Exception can be handled in this catch
        // block
        .
        .
        .
    }
}


throws

The throws keyword is used in a method declaration to list any exceptions not derived from Error or RuntimeException that a method can throw. (Exceptions derived from type RuntimeException are typically avoidable. Exceptions derived from type Error are usually related to serious system problems; thus, little can be done about them.)

The following example shows a typical method declaration using the throws keyword:

public int someMethod( int argument ) throws Exception1, Exception2
{
    // This method may contain a try/catch block
    // for detecting and possibly handling any caught
    // exceptions.

}


transient

The transient keyword is a modifier used in the declaration of variables. Use of this keyword specifies that the current value of the variable need not be serialized (or saved) along with other data stored in a class object.

The following example shows the declaration of a variable with the transient modifier:

private transient int currentTime;


true

The true keyword can be used as one of the two possible boolean values. Strictly speaking, true is not a keyword of the Java language; rather, it is a literal value that is assigned to a variable of type boolean.

For an example of how the true keyword can be used, see the keyword boolean.


try

The try keyword is used to indicate a block of code in which an exception might occur. For each try statement, there must be at least one corresponding catch clause. If the exception occurs, the catch clause parameter is evaluated to determine whether it is capable of handling the exceptional condition. If the exceptional condition cannot be handled by any of the catch clauses corresponding to the try statement, then control is transferred up the chain of method calls and all the previous exception types are evaluated until one capable of handling the condition is found.

Note that if the try statement has a corresponding finally clause, then the body of the finally clause will be executed no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

The following example shows a typical try/catch/finally construct:

try
{
    // code within this block may cause an exception.
    .
    .
    .
}
catch( Exception1 e1 )
{
    // code within this block is executed only
    // when an exception of type Exception1 occurs,
    // otherwise it is skipped over.
    .
    .
    .
}
catch( Exception2 e2 )
{
    // code within this block is executed only
    // when an exception of type Exception2 occurs,
    // otherwise it too is skipped over.
    .
    .
    .
}
finally
{

    // code within this block is always executed,
    // regardless whether an exception within the
    // try block occurs or not. This block is
    // typically used for cleaning up.
    .
    .
    .
}


void

The void keyword is used in the declaration of a method to indicate that the method returns no value.

Note that Java provides only this very limited use of the void keyword. Unlike in the C language, the void keyword cannot be used to declare the absence of method parameters, void pointers, and so on.


volatile

The volatile keyword is a modifier used in the declaration of variables. Use of this keyword specifies that the value the variable contains may change asynchronously, and, therefore, the compiler should not attempt to perform optimizations with it.


while

The while keyword is used to create a loop construct. In a while loop, the expression in parentheses immediately following the keyword is evaluated, and if the boolean result is true, the statements appearing within the loop body are executed. If multiple statements make up the body of the loop, they must be enclosed with curly braces. Once the loop body has executed, control transfers back to the top of the loop where the test is performed again, and the execution of the loop body is repeated until the value of the expression evaluates to false.

The following example shows a typical while loop construct:

while ( i < 10 )
{
    // statements here execute if above expression is true
    .
    .
    .
}


Compiler Error J0001

INTERNAL COMPILER ERROR:

The compiler was unable to recover after detecting an error. Please consult your technical support help file, available from the Help menu, for instructions on how to search the Microsoft Knowledge Base for the latest information on this problem. Also, try to simplify the code where the compiler reported this error and compile again.


Compiler Error J0002

Out of memory

The compiler attempted to allocate some additional memory during processing, but was unable to do so. Check the location, size, and validity of your system swap file. Also, ensure that there is sufficient growth space available on the drive on which your swap file resides.


Compiler Error J0004

Cannot open class file 'filename' for reading

The compiler could not open the program source file for reading. This error usually occurs when another program has an exclusive lock on the source file. Close other processes that may be accessing the source file and compile again.


Compiler Error J0005

Cannot open class file 'filename' for writing

The compiler failed to generate the output .class file. This error usually occurs when the compiler cannot get write or create permission for the file. Ensure the file does not have its read-only attribute set, and that it is not currently in use by another process. This error can also occur when you are running or debugging the program that contains the specified .class file. Close all instances of the program and compile again.


Compiler Error J0006

Cannot read class file 'filename'

The compiler failed to read the specified .class file. This error usually occurs when the compiler encounters an error reading the storage device, or when the compiler cannot otherwise get read permission for the file. Ensure that the file is not in use by another process. Also, ensure the validity of the storage device you are attempting to use by using a disk scanning utility.


Compiler Error J0007

Cannot write class file 'filename'

The compiler failed while attempting to write the contents of a buffer to the specified .class file. This error usually occurs when space is exhausted on the targeted storage device. Free up any available space on the storage device and compile again.


Compiler Error J0010

Syntax error

The compiler could not determine the meaning of an expression or statement within the source program. This error usually occurs when the line, indicated in the error message, is syntactically invalid. This error typically accompanies a more descriptive error. Correct any accompanying errors and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {
      int i =; // error: missing assignment value
   }
}


Compiler Error J0011

Expected ':'

The compiler expected to find a colon following a case label or in a conditional expression that makes use of the ternary operator. This error usually occurs when a colon is accidentally omitted. Many times this error is caused on the line previous to the line the compiler has reported the error on. Ensure that the lines that require a colon are correct and compile again.

The following example illustrates this error:

public class Simple {

   private int i;
   private static int x = 1;

   public void method1(int arg1) {

      switch (arg1) {
         case 1 // error: ':' omitted after 'case'
      }

      i = ( arg1 < x) ? arg1  x; // error: ':' omitted after 'arg1'
   }
}


Compiler Error J0012

Expected ';'

The compiler expected to find a semicolon in the position indicated by the error message. This error usually occurs when the semicolon is accidentally omitted from the end of a statement. It can also occur when a conditional expression is not syntactically correct. This error is often caused on the line previous to the line the compiler has reported the error on. Ensure that semicolons are used properly and compile again.

The following example illustrates this error:

public class Simple {

   private static int x = 10 // error: ';' omitted

   public void method1(int arg1) {

      for (int i = 1; i < x i++) {
         // error: ';' omitted
      }
   }
}


Compiler Error J0013

Expected '('

The compiler expected to find a left parenthesis in the position indicated by the error message. This error usually occurs when the left parenthesis is accidentally omitted in any of the following situations:

  • Type initializations

  • catch statements

  • Parenthesized expressions

  • while loops

  • for loops

  • if/else statements

The following example illustrates this error:

public class Simple {

   private int i;

   public void method1(int arg1, int arg2) {

      if arg1 < arg2) // error: '(' omitted
         i = arg1;
      else
         i = arg2;

   }
}


Compiler Error J0014

Expected ')'

The compiler expected to find a right parenthesis in the position indicated by the error message. This error usually occurs when the right parenthesis is accidentally omitted in any of the following situations:

  • Type initializations

  • Type casts

  • catch statements

  • Parenthesized expressions

  • while loops

  • for loops

  • if/else statements

The following example illustrates this error:

public class Simple {

   private int i;

   public void method1(int arg1, int arg2) {

      i = (arg1 < arg2 ? arg1 : arg2;
      // error: ')' omitted
   }
}


Compiler Error J0015

Expected ']'

The compiler expected to find a right square bracket in the position indicated by the error message. This error usually occurs when the right square bracket is accidentally omitted from an array declaration. This error is often caused on the line previous to the line the compiler has reported the error on. Ensure that all brackets match and compile again.

The following example illustrates this error:

public class Simple {

   private int x[ = new int[500]; // error: ']' omitted

}


Compiler Error J0016

Expected '{'

The compiler expected to find a left brace in the position indicated by the error message. This error usually occurs when the left brace is accidentally omitted from the beginning of a class declaration or method code block. This error is often caused on the line previous to the line the compiler has reported the error on. Ensure that all braces match and compile again.

The following example illustrates this error:

public class Simple // error: '{' omitted

   public void method1() {
      // do something meaningful
   }
}


Compiler Error J0017

Expected '}'

The compiler expected to find a right brace in the position indicated by the error message. This error usually occurs when a class or method’s closing brace is not found. This error is often caused on the line previous to the line the compiler has reported the error on. Ensure that all braces match and compile again.

The following example illustrates this error:

public class Simple {
{
   int x,y;
   //error: no matching brace found for class


Compiler Error J0018

Expected 'while'

The compiler expected to find the keyword while in the position indicated by the error message. This error usually occurs when a do/while loop is not syntactically correct.

The following error illustrates this error:

public class Simple{
   public void method1(){
      do{
          // do something useful here
      }; //error: missing 'while' statement
}

The following code illustrates the correct form of a do/while loop:

public class Simple{
   public static void method1(){
      int x = 10;
      do{
        System.out.println(x);
        x--;
      }while(x != 0); //this is correct form for do/while loop
   }
   public static void main(String args[]){Simple.method1();}
}


Compiler Error J0019

Expected identifier

The compiler expected to find an identifier before the name of a class, interface, variable, or method declaration. This error usually occurs when the type is accidentally omitted in a declaration.

The following example illustrates this error:

public class Simple {

   private i;  // error: type omitted

}


Compiler Error J0020

Expected 'class' or 'interface'

The compiler expected to find either class or interface used within the corresponding declaration. This error usually occurs when the keywords are accidentally omitted from a class or interface declaration. Another possible cause of this error is unbalanced scoping braces.

The following example illustrates this error:

public Simple{ //error: missing the 'class' keyword
   //Do something here
}

This example illustrates this error caused by unbalanced scoping braces:

public class Simple {

   // do something meaningful

}}   // error: additional '}' not needed


Compiler Error J0021

Expected type specifier

The compiler expected to find a type specifier in the position indicated by the error message. This error usually occurs when a typographical error exists in an object instantiation or variable declaration.

The following example illustrates this error:

public class Simple {

   public Object o =new; //error: missing 'Object' type specifier
}


Compiler Error J0022

Expected end of file

The compiler expected to encounter an end-of-file character, but did not. This error usually occurs when the source file has been damaged in some way. Visually check the source file for obvious corruption, save any changes, and compile again.


Compiler Error J0023

Expected 'catch' or 'finally'

The compiler expected to find a catch or finally block immediately following a corresponding try block.

The following example illustrates this error:

public class Simple {
   public void method1(){
      try {
         // do something meaningful
      }
   } // error: 'catch' or 'finally' not found
}

The following example illustrates the correct syntax for using a try/catch block:

public clas Simple{
   public void method1(){
      try{
        //Do something here. Possibly throw an exception type
      }
      catch(Exception e){
         /*Handle any errors here and use the 'Exception' object to
         determine the type of error that occurred */
      }
   }
}


Compiler Error J0024

Expected method body

The compiler expected to find a method body immediately following a method declaration. This error usually occurs when the braces surrounding the method body are missing. This error can also occur when the method was intended to be abstract or native, but the abstract or native keyword was mistakenly omitted from the method declaration.

The following example illustrates this error:

public abstract class Simple {

   public void method1();
   // error: 'abstract' omitted
   // This error would also exist if the class is not declared 'abstract'

}


Compiler Error J0025

Expected statement

The compiler expected to find a statement before the end of the current scope. This error usually occurs when the left brace, designating the beginning of the current scope, or both left and right braces are missing. Ensure that the braces for the current scope are balanced.

The following example illustrates this error:

public class Simple {

   void method1(int arg1) {

      if (arg1==1)
      // error: missing the left brace for the if statement
   }
}


Compiler Error J0026

Expected Unicode escape sequence

The compiler expected to find a valid Unicode escape sequence. This error usually occurs when a backslash is not followed by the letter "u" to signify a Unicode escape sequence. Check the syntax of your Unicode escape sequence and compile again.

The following example illustrates this error:

public class Simple {

   int i = \\u0032;
   // error: '\\' not invalid

}


Compiler Error J0027

Identifier too long

The compiler detected an identifier name with a length greater than 1024 characters. Shorten the identifier name and compile again.


Compiler Error J0028

Invalid number

The compiler detected a numeric value that the Java language is not capable of supporting. This error usually occurs when the number specified is an amount that is outside of the range of any of Java's primitive data types. This error usually occurs when a numerical value is too large to be stored in the specified data type.

The following example illustrates this error:

public class Simple {

   long i = 12345678901234567890;
   // error: value out of range for 'long'

}


Compiler Error J0029

Invalid character

The compiler detected an ASCII character that could not be used in an identifier. This error usually occurs when a class, interface, method, or variable identifier includes an invalid character.

The following example illustrates this error:

public class Simple {

   private int c#;
   // error: '#' not supported

}


Compiler Error J0030

Invalid character constant

The compiler detected an attempt to assign an invalid character or character escape sequence to a variable of type char.

The following example illustrates this error:

public class Simple {

   char c = '\';
   // error: invalid escape character
   char x = '\\'; \* correct assignment of the backslash to the char
                     variable */
}


Compiler Error J0031

Invalid escape character

The compiler detected the use of an invalid escape character. This error usually occurs when a syntactical error is found in a Unicode escape sequence. The error can also occur if you use a "\" character in a string assignment.

The following example illustrates this error:

public class Simple {

   int i = \u032;
   // error: Unicode uses 4 hex digits
   int x = \u0032;
   //correct assignment of a Unicode escape sequence

}

The following example illustrates the error being caused by assigning the "\" character improperly to a string:

public class Simple{

   public String str = "C:\Windows\Desktop";
   //error: invalid assignment of the '\' character to a string
   //To assign it correctly use the '\\' character assignment
}


Compiler Error J0032

Unterminated string constant

The compiler did not detect a terminating double-quote character at the end of a string constant. This error usually occurs when the string terminator is accidentally omitted, or when the string constant is mistakenly divided onto multiple lines.

The following example illustrates this error:

public class Simple {

   String str = "Hello;
   // error: closing quote omitted

}


Compiler Error J0033

Unterminated comment

The compiler detected the beginning of a block comment, but did not detect a valid ending. This error usually occurs when the comment terminator is accidentally omitted.

The following example illustrates this error:

public class Simple {

   /* This comment block
    * does not have a valid
    * terminator

}


Compiler Error J0035

Initializer block cannot have modifiers except 'static'

The compiler detected a modifier other than static associated with an initializer. Use only the static keyword to specify the initializer as a static initializer or no modifier to signify that the initializer is an instance initializer. Remove the modifier from the initializer specified in the error message or add the static modifier to the initializer and compile again.

The following example illustrates this error:

public class Simple {
   protected{   // error: 'protected' is invalid here
      //do something here
   }
}


Compiler Error J0036

A data member cannot be 'native', 'abstract', or 'synchronized'

The compiler detected one of the modifiers shown above used in the declaration of a variable. The modifiers synchronized and native can only be applied to method declarations. The abstract modifier can be applied to methods, classes, and interfaces.

The following example illustrates this error:

public class Simple{

   native int myvar1;
   abstract int myvar2;
   synchronized int myvar3;
   //error: the vars above have invalid modifiers

}


Compiler Error J0037

A method cannot be 'transient' or ‘volatile’

The compiler detected one of the modifiers shown above used in the declaration of a method. The modifiers transient and volatile can only be applied to field declarations.

The following example illustrates this error:

public class Simple{

   transient void Method1(){};
   volatile void Method2(){};
   //error: the methods above have invalid modifiers

}


Compiler Error J0038

'final' member ‘identifier’ must be initialized when declared in an interface

The compiler detected an uninitialized final variable in an interface definition. Variables declared as final in an interface definition must have their value set at declaration. Once set, the value cannot be programmatically changed.

The following example illustrates this error:

interface ISimple {

   final int COOL_RAD;
   // error: must have value set

}


Compiler Error J0040

Cannot define a method body for abstract/native methods

The compiler detected a method body defined immediately following the corresponding declaration of an abstract or native method. An abstract method must have it's implementation code defined in a subclass. Native methods are implemented using code from a native language such as C++.

The following example illustrates this error:

public abstract class Simple{
   abstract void method1(){
      //Do something here
   }//error: abstract methods are implemented in subclasses
}

Methods declared within an interface are implicitly abstract. As such, this error can also occur when you attempt to define a method body in an interface. The following code illustrates this scenario:

public interface Simple {

   public void method1() {
      // error: must define this method body
      // in a class that implements the
      // 'Simple' interface
   }
}


Compiler Error J0041

Duplicate modifier

The compiler detected a modifier used twice in a declaration. This error usually occurs when the same modifier is mistakenly used more than once within a declaration.

The following example illustrates this error:

public class Simple {

   public public void method1() { // error: 'public' used twice
      // do something meaningful
   }
}


Compiler Error J0042

Only classes can implement interfaces

The compiler detected an interface declaration using the implements keyword. Interfaces cannot implement other interfaces. Interfaces can only be implemented by classes. This error usually occurs when an interface is mistakenly implemented instead of extending another interface using the extends keyword.

The following example illustrates this error:

public interface Simple implements color{
   // error: 'Simple' cannot implement the
   // 'color' interface

}
interface color {
   // do something meaningful
}

interface pattern extends color{
   //extending an interface is OK here
}


Compiler Error J0043

Redeclaration of member 'identifier'

The compiler detected the same identifier name being declared more than once within the same scope. This error usually occurs when a variable or method is mistakenly declared more than once. Ensure that you have not declared a method or variable more than once in the same class. Methods can have the same name but must differ in method parameters in order to be different.

The following example illustrates this error:

public class Simple {
   private int i;
   public void method1(){
      //do something here
   }

   //Other declarations for the class go here

   private int i; // error: 'i' declared twice
   public void method1(){
      //error: method declared twice
   }
}


Compiler Error J0044

Cannot find definition for class 'identifier'

The compiler could not locate the definition for the specified class. This error is usually caused by a typographical error. It can also occur when the package containing the specified class cannot be found.

The following example illustrates this error:

class NotSimple{
   //do something here
}

public class Simple {

   NotSimple smp = new NotSmple();
   // error: 'NotSmple' not a valid class name

}


Compiler Error J0045

'identifier' is not a class name

The compiler detected one of the following conditions:

  • A class name provided as part of an import statement could not be found.

  • The import statement was not syntactically valid.

  • The class attempted to extend an interface. Only classes can be used with the extends statement.

  • Ensure that that the package exists and that any classes you import exist in the package specified in the import statement and compile again.

The following example illustrates this error:

package non.existent;
import non.existent; /* error: the package is not existant and cannot be
                        imported */

public class Simple {

   // do something meaningful

}


Compiler Error J0046

'identifier' is not an interface name

The compiler detected that the identifier referred to by the keyword implements is not an interface. This error usually occurs when a class is used instead of an interface in an implements statement.

The following example illustrates this error:

class Simple2 {

   // do something meaningful

}

public class Simple implements Simple2 {

   // error: cannot implement class ‘Simple2’

}


Compiler Error J0048

Cannot extend final class 'identifier'

The compiler detected an attempt to subclass a class declared with the keyword final. Classes declared as final cannot be subclassed.

The following example illustrates this error:

final class Simple2 {

   // do something meaningful

}

public class Simple extends Simple2 {

   // error: cannot extend ‘Simple2’

}


Compiler Error J0049

Undefined name 'identifer'

The compiler detected a reference to a class, method, or variable that does not exist. Examples of when this error can occur include:

  • A variable is referenced that does not exist or is mistyped.

  • The object used with a method call does not exist or is mistyped.

  • A class is imported that does not exist in the package specified or is mistyped.

Ensure that the reference to the class, method, or variable displayed in the error message is correct and compile again.

The following example illustrates this error:

import java.io.bogus; // error: unknown class name

public class Simple {

   public int method1(){
      return novar1;
      //error: 'novar1' does not exist
   }
   public void method2(){
      NotSimple nt = new NotSimple();
      np.methodx();
      //error: the object reference 'np' should be 'nt'
}

class NotSimple{
   public void methodx(){
      //do something meaningful here
   }
}


Compiler Error J0051

Undefined package 'identifier'

The compiler detected a package name declaration, but was unable to locate the package definition. This error usually occurs when a syntactical error exists in an import statement. This error may also occur when the package cannot be found or does not exist.

The following example illustrates this error:

import java.lang.bogus.*;
// error: ‘bogus’ not a valid package name

public class Simple {

   // do something meaningful

}


Compiler Error J0053

Ambiguous name: 'identifier' and 'identifier'

The compiler could not resolve an ambiguity between the two identifiers shown. This error usually occurs when the same class name appears in two packages that are both imported into a source file using the "*" class import specifier. Ensure that you do not have two classes with the same name in the packages you are importing into your source file and compile again.


Compiler Error J0056

Missing return type specification

The compiler detected a method declaration without a return type specified. All method declarations must specify a return type. If the method is not meant to return a value, use the void keyword.

The following example illustrates this error:

public class Simple {

   public method1() { // error: no return type

      // do something meaningful
   }
}


Compiler Error J0057

Class file 'identifier' should not contain class 'identifier'

This compiler did not detect the class specified in the error in the specified class file. This error usually occurs when a class is compiled into a class file that later is renamed. Because the class file has a different name than the class contained inside of it, attempting to use the name of the class file as a class will fail. To avoid this situation you will need to change the class definition to have the correct name or rename the file back to the original class name.


Compiler Error J0058

Cannot have a variable of type 'void'

The compiler detected a variable declared as type void. The keyword void is not allowed in variable declarations. Rather, void can only be used as a method return type, noting that the method does not actually return a value.

The following example illustrates this error:

public interface Simple {

   public final static void i = 1;
   // error: 'void' not valid
}


Compiler Error J0059

Cannot reference member 'identifier' without an object

The compiler detected an attempt to reference a variable without a known object association. This error usually occurs when an instance field or method (a field or method declared without the keyword static) is referenced from within a static method without a valid instance. Static methods cannot use instance fields and methods without a valid instance of the class.

The following example illustrates this error:

public class Simple {

   private int x;
   public void method1(){
      //Do something here
   }
   public static void main(String args[]) {

      x = 0; /* error: 'x' must be static or referenced using class
                instance */
      method1(); /* error: 'method1' must be static or referenced with
                           a class instance */
   }
}

The following example illustrates the correct method to refer to a non-static member field or method:

public class Simple{

   private int x; //access level of member does not matter
   public void method1(){
      //Do something here
   }
   public static void main(String args[]){
      //Create an instance of the 'Simple' class
      Simple smp = new Simple();
      smp.x = 0; //valid reference to field
      smp.method1(); //valid call to method
   }
}


Compiler Error J0060

Invalid forward reference to member 'identifier'

The compiler detected an attempt to initialize a variable with another variable that had not yet been defined. To avoid this situation, reverse the field declarations order so that a variable that is referenced by another is defined first.

The following example illustrates this error:

public class Simple {
   private static int i = j;
   // error: 'j' not yet defined
   private static int j = 0;
}

The following shows the correct way to initialize a field using another field in the same class:

public class Simple{
   private static int j = 0; //field is instantiated and populated
   private static int i = j; //with 'j' properly set, 'i' can be set
}


Compiler Error J0061

The members 'identifier' and 'identifier' differ in return type only

The compiler detected a subclass method attempting to overload a base class method, but the methods differed only in return type. In Java, overloaded methods must be distinguished by unique signatures. A unique signature consists of the method name, the number, type and positions of its parameters, and the return type.

The following example illustrates this error:

public class Simple extends Simple2 {

   public void method1() {
      // error: only return type differs
   }
}

class Simple2 {

   public int method1() {

      return 1;
   }
}


Compiler Error J0062

Attempt to reduce access level of member 'identifier'

The compiler detected an overridden method in the class being compiled that reduces the access level of its base class method. The base class access modifier for a method must be maintained by all derived classes that wish to overload the method.

The following example illustrates this error:

public class Simple{
   public void method1(){
      //Do something here
   }
}

class Simple2 extends Simple{
   private void method1(){
      /*error: cannot change access level of a method
      when overriding a base class's method. */
   }
}


Compiler Error J0063

Declare the class abstract, or implement abstract member ‘identifier’

The compiler detected an abstract method defined in a class, a superclass, or an implemented interface but the method was never implemented. This error usually occurs when a class implements an interface or extends a class that contains an abstract method definition, but the class never implements the abstract method. This error can also occur if a class defines an abstract method but the class does not have the abstract modifier defined. Ensure that your class has implemented any abstract methods and compile again.

The following example illustrates this error:

interface ITest{
   public abstract void method1();
}

public class Simple implements ITest{
   //Do something meaningful here
   //error: the abstract method defined in 'ITest' is never implemented
}


Compiler Error J0065

Cannot assign to this expression

The compiler detected an expression in the position normally held by an lvalue for assignment. This error usually occurs when an expression is being assigned a value but the expression is not capable of accepting the assignment.

The following example illustrates this error:

public class Simple {

   public void method1() {

      int x = 0;
      int y = 1;

      x++ = y; //error: '++' not valid
   }
}


Compiler Error J0066

'this' can only be used in non-static methods

The compiler detected use of the keyword this within a class (or static) method. Class methods are not passed implicit this references. As such, they cannot reference instance (non-static) variables or methods.

The following example illustrates this error:

public class Simple {

   int x;

   public static void method1() {

      this.x = 12; // error: 'this' instance specific
   }
}


Compiler Error J0067

Cannot convert 'type' to 'type'

The compiler detected a variable type used out of its correct context. As such, the compiler could not implicitly convert the result to anything meaningful. Convert the value you are attempting to use to something the method or field definition requires and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {

      int i = 10;

      if (i--) {
         // error: conditional needs expression
         // or boolean field
      }
   }
}


Compiler Error J0068

Cannot implicitly convert 'type' to 'type'

The compiler could not convert the specified variable without an explicit typecast. This error usually occurs when a numerical field is assigned to a data type that is not numerical. Use a typecast to convert the data type to the appropriate data type and compile again.

The following example illustrates this error:

public class Simple {

   int i = 10;

   public void method1() {
      char c = i; // error: expected type char
      char c = (char)i; // this is the correct assignment statement
   }
}


Compiler Error J0069

Cannot apply '.' operator to an operand of type 'identifier'

The compiler detected the '.' operator applied to an invalid type. This error usually occurs when an invalid method call is made on an intrinsic data type. Ensure that your method call is using the correct object and compile again.

The following example illustrates this error:

public class Simple {

   int i = 123;
   int j = i.length; // error: 'i' not an array

}


Compiler Error J0072

'identifier' is not a member of class 'identifier'

The compiler detected a method call, but the method is undefined. This error usually occurs when the method name is either misspelled or cannot be found within the proper scope. This error can also occur when the method does not exist. Ensure that the member you are trying to reference exists in the specified class and compile again.

The following example illustrates this error:

public class Simple {

   public static void main(String args[]) {

      System.out.printline("Hello");
      // error: 'printline' should be 'println'
   }
}


Compiler Error J0074

Operator cannot be applied to 'identifier' and 'identifier' values

The compiler detected an operator that cannot be correctly applied to the identifiers shown in the error message. This error usually occurs when two fields are non-numerical and operators used for numbers are applied to the fields.

The following example illustrates this error:

public class Simple {

   public void method1() {

      String s1 = "one";
      String s2 = "two";
      String result;

      result = s1 * s2; // error: invalid operands
   }
}


Compiler Error J0075

Invalid call

The compiler detected syntax for a method call, but the identifier does not represent a valid method name. This error usually occurs when a method name is misspelled or contains characters that are not recognized as valid in the Java language naming conventions.

The following example illustrates this error:

class Simple {
   int x = 1();
   //error: '1()' is not a valid method name
}


Compiler Error J0076

Too many arguments for method 'identifier'

The compiler detected a known method call, but the call contained more arguments than needed. Check the number of arguments for the method you are attempting to call and remove any additional arguments from the call.

The following example illustrates this error:

public class Simple {

   public void method1(int arg1) {

      // do something meaningful
   }

   public void method2() {

      method1(1, 2); // error: Too many arguments
   }

}


Compiler Error J0077

Not enough arguments for method 'identifier'

The compiler detected a known method call, but the call contained fewer arguments than needed. This error usually occurs when one or more arguments are accidentally omitted from the call.

The following example illustrates this error:

public class Simple {

   public void method1(int arg1) {
      // do something meaningful
   }

   public void method2() {

      method1(); // error: Too few arguments
   }
}


Compiler Error J0078

Class 'identifier' doesn’t have a method that matches 'identifier'

The compiler identified a call to a known overloaded method within another class, but was unable to detect a matching method with the correct number of arguments. Ensure that the overloaded method call has the correct number and type of arguments and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {
      // do something meaningful
   }

   public void method1(int arg1) {
      // do something meaningful
   }
}

class Simple2 {

   public void method1() {

      Simple s = new Simple();
      s.method1(1, 2, 3); // error: too many arguments
   }
}


Compiler Error J0079

Ambiguity between 'identifier' and 'identifier'

The compiler could not distinguish the correct method to execute. This error usually occurs when two overloaded methods have related argument lists and the method call cannot be differentiated between the two methods. Ensure your method call is not using a parameter that conflicts with another overloaded method. Another way to avoid this error is to change the argument lists of the two overloaded methods so that they have a different number of arguments or more uniquely defined parameter data types.

The following example illustrates this error:

public class Simple {

   static void method1(Simple2 s2, Simple3 s3) {
      // do something meaningful
   }

   static void method1(Simple3 s3, Simple2 s2) {
      // do something meaningful
   }

   public static void main(String args[]) {

      Simple2 s2 = new Simple2();
      method1(s2, s2);
      // error: Ambiguity between Simple2 and Simple3
   }
}

class Simple2 extends Simple3 {
   // do something meaningful
}

class Simple3 {
   // do something meaningful
}


Compiler Error J0080

Value for argument 'identifier' cannot be converted from 'identifier' in call to 'identifier'

The compiler detected a method argument that does not match the parameters specified in the method declaration. This error usually occurs when a numerical field is passed as an argument to a method but the method requires a different numerical type. To pass different numerical types to arguments of a method, typecast the field being passed to the method.

The following example illustrates this error:

public class Simple {

   public void method1(int arg1) {
      // do something meaningful
   }

   public void method2() {

      float f = 1.0f;
      method1(f); // error: mismatched call types
   }
}

The following example illustrates how to avoid this error:

public class Simple{
   public void method1(int arg1){
      //do something meaningful
   }

   public void method2(){
      float f = 1.0f;
      method1((int)f); //typecast the 'float' to be treated as an 'int'
   }
}


Compiler Error J0081

Value for argument 'identifier' cannot be converted from 'identifier' in call to 'identifier'

The compiler detected a call to a method in a class located in a different class file, but was unable to convert one of the arguments from the supplied type to the type shown in the method declaration. This error usually occurs when a method is called with the arguments in the wrong order or the wrong method was called. Check the argument number that caused the error in the error message and ensure you passed the correct type of argument.


Compiler Error J0082

Class 'identifier' doesn't have a constructor that matches 'identifier'

The compiler did not detect a constructor matching the call identified in the error. This error usually occurs when a constructor is called with the wrong number of arguments. Ensure that the class has a constructor that matches the one you are attempting to call and compile again.

The following example illustrates this error:

public class Simple {

   Simple(int arg1) {
      // do something meaningful
   }

   public static void main (String args[]) {

      Simple s = new Simple(12, 13);
      // error: too many arguments
   }
}


Compiler Error J0083

'super()' or ‘this()’ may only be called within a constructor

The compiler detected use of either the super() or this() keyword outside of a constructor. The super() keyword is used to call a superclass constructor, while the this() keyword is used to call one constructor from another. To reference methods in a base class you must use the super. keyword.

The following example illustrates this error:

public class Simple {

   public void method1 () {

      super(); // error: 'super' cannot be called
   }
}

The following example illustrates using the super. keyword to reference a method in a base class:

class NotSimple{
   public class method1(){
      //do something here
   }
}

public class Simple{
   public method2(){
      super.method1(); //correct way to call a method of a superclass
   }
}


Compiler Error J0084

Cannot return a value from a 'void' method

The compiler detected an attempt to return a value from a method declared with a return type of void.

The following example illustrates this error:

public class Simple {

   public void method1() {
      return 1; // error: cannot return a value
   }
}


Compiler Error J0085

Expected return value of type 'identifier'

The compiler detected the keyword return within the body of a method which was declared to return a specific type, but the return had no associated value. The return statement with no associated value will not return a default value and thus must be assigned a valid return value.

The following example illustrates this error:

public class Simple {

   public int method1() {
      return; // error: must return int value
   }
}


Compiler Error J0086

'[]' cannot be applied to a value of type 'identifier'

The compiler detected array brackets used with a non-array type. Change the field to be a valid array declaration if you want to use the field as an array and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {
      int i = 0;
      int j, x;

      x = j[i]; // error: ‘j’ not declared as array
   }
}


Compiler Error J0087

'goto' statement is not currently supported by Java

The keyword goto, while defined as a keyword, has not yet been implemented in the Java language.


Compiler Error J0089

The case 'identifier' has already been defined in switch statement

The compiler identified two or more case statements with the same identifier or value occurring within the same switch statement.

The following example illustrates this error:

public class Simple {

   public int method1(int arg1) {

      switch (arg1) {
         case 1:
            return (int) 1;
         case 2:
            return (int) 2;
         case 2: // error: duplicate of above
            return (int) 3;
         default:
            return (int) 0;
      }
   }
}


Compiler Error J0090

'default' has already been defined in switch statement

The compiler identified two or more instances of the keyword default occurring within the same switch statement.

The following example illustrates this error:

public class Simple {

   public int method1(int arg1) {

      switch (arg1) {
         case 1:
            return (int) 1;
         case 2:
            return (int) 2;
         default:
            return (int) 3;
         default: // error: duplicate of above
            return (int) 0;
      }
   }
}


Compiler Error J0091

'case' outside of switch statement

The compiler identified the keyword case used outside the scope of a switch statement.

The following example illustrates this error:

public class Simple {

   public int method1() {
      case 1: // error: no switch statement
         return 1;
   }
}


Compiler Error J0092

Constant expression expected

The compiler detected an expression that used a non-constant value when a constant value was required. This error usually occurs when a variable is used in a case statement. Check the expression to be sure that a constant value is being used and compile again.

The following example illustrates this error:

public class Simple{
   int var1 = 10;
   int var2 = 20;
   public void method1(){
      switch(var1){
        case var2:
        //error: cannot use variable with case
      }
   }
}


Compiler Error J0093

'break' only allowed in loops and switch statements

The compiler detected the keyword break occurring outside the scope of a loop or switch statement.

The following example illustrates this error:

public class Simple{
   public void method1(){
      if (true)
         break;
         //error: break allowed in loops only
   }
}


Compiler Error J0094

Label 'identifier' not found

The compiler detected a label name associated with one of the keywords continue or break, but could not find the label. This error usually occurs when a label does not exist, yet it is being referenced by a break or continue statement. This error can also occur if the label is placed outside the break or continue statement's scope. A break or continue statement must reference a label that precedes an enclosing loop or block. Ensure that the break or continue statement can access a valid label and compile again.

The following example illustrates this error:

public class Simple{
   public int method1(){
      int y;
      for (int x = 0; x < 10; x++){
         y = x *2;
         if (x == 5)
            break test; //error 'test' is not defined as a label
      }
      return y;
   }
}

The following example illustrates the correct usage of a label when used with the break or continue statements:

public class Simple{
   public int method1(int arg1){
      int x,y = 0;
      test: //label precedes the loop.
      if (arg1 = 0)
         return y;
      for (x=1; x < 10; x++){
         y = x * arg1;
         if (y <= arg1){
            y = -1;
            break test;
         }
      }
      return y;
   }
}


Compiler Error J0095

'continue' only allowed in loop

The compiler detected attempted use of the keyword continue outside the scope of a loop. This error usually occurs when a loop is removed and continue statements are left in the code. Remove any continue statements that are outside of a loop and compile again.

The following error illustrates this error:

public class Simple{
   public void method1(int arg1){
      if (arg1 ==1)
         continue;
         //error: continue only allowed in loops. Remove 'continue;'.
   }
}


Compiler Error J0096

Class value expected

The compiler detected a synchronization block, but the synchronized statement was applied to an invalid type. This error usually occurs when an identifier other than a class object instance is used with the synchronized statement.

The following example illustrates this error:

public class Simple {

   public void method1() {
      int i;
      synchronized (i){ //error 'i' must resolve to an object reference
         // Do something here
      }
   }
}


Compiler Error J0097

'instanceof' operator expected class or array

The compiler detected the instanceof operator applied to a type that did not resolve to a class or array. The instanceof operator is used to determine if identifier is an instance of a specific class or array. Ensure the lvalue used with the instanceof operator references a class instance or array and the rvalue references a valid class name or array and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {

      Simple2 obj = new Simple2();

      if (obj instanceof int) // error: 'int' is not a class name
          // do something meaningful
   }
}

class Simple2 {
   // do something meaningful
}


Compiler Error J0098

Attempt to access non-existent member of 'identifier'

The compiler detected an array member specified, but could not identify it. This error usually occurs when an attempt to reference the length method of an array is mistyped. This error can also occur when an attempt is made to call a method in an array of objects but the call does not reference an element of the array.

The following example illustrates this error:

public class Simple {

   public void method1() {
      String j[] = new String[10];
      //intialize the array elements here
      String str = j.toUpperCase();
      //error: missing array brackets '[]'
   }
}


Compiler Error J0100

Cannot throw 'identifier' — the type does not inherit from 'Throwable'

The compiler detected an object in a throw statement that was not derived from the class Throwable. This error usually occurs when a throw statement uses a class that does not inherit from the Throwable class. Ensure that the exception class you are throwing is a valid exception class.

The following example illustrates this error:

class BogusException{
   //Do something useful here
}

public class Simple{

   public void method1(int arg1){
       //Do something meaningful
       if (arg1 == 0){
          throw new BogusException();
          //error: BogusException is not a valid exception class
       }
   }
}


Compiler Error J0101

The type 'identifier' does not inherit from 'Throwable'

The compiler detected an invalid class argument used as an argument in a catch statement. When using a catch statement to handle exceptions, you must define it with a class derived from Throwable as a parameter. Ensure that the class you defined for the catch statement is derived from Throwable and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {

      try {
         // do something meaningful
      } catch (String s) {
         // error: 'String' not a subclass
         // of 'Throwable'
      }
   }
}

The following example illustrates the correct way to use the catch statement to trap exceptions:

public class Simple{
   public void method1(int arg1){
      try{
        //do something here
        if (arg1 == 0)
           throw new myException(); //throw a valid exception object
      }
      catch(myException c){ //this is a valid exception object to catch
         //handle exception here
      }
   }
}
class myException extends Throwable{
   //class definition goes here
}


Compiler Error J0102

Handler for 'identifier' hidden by earlier handler for 'identifier'

The compiler detected an exception handler that will never be executed because an earlier handler would have already caught the exception. This error usually occurs when catch statements are written in the wrong order.

The following example illustrates this error:

class Simple {

   static
   {
      try
      {
      }
      catch (Exception e)
      {
      }
      catch (ArithmeticException e)
      {
      }
      // error: any exceptions this block
      // could have caught are already caught
      // by the first catch statement
   }
}


Compiler Error J0103

Cannot override final method 'identifier'

The compiler detected a class method attempting to override one of its base class methods, but the base class method was declared with the keyword final. Methods defined with the final modifier cannot be overridden by a derived class.

The following example illustrates this error:

public class Simple extends Simple2 {

   public void method1() {
      // error: ‘method1’ final in superclass
   }
}

class Simple2 {

   public final void method1() {
      // do something meaningful
   }
}


Compiler Error J0104

Unreachable statement or declaration

The compiler detected a statement or declaration that cannot be reached under any circumstances. This error usually occurs when a return statement is called from a method, and code is placed below the return statement. This error can also occur if a break statement is used in a loop without any flow control to allow code below it to be run.

The following example illustrates this error:

class Simple {
   public int method1(int arg1){
      for (int y = 10; y < 10;y++){
         break;
         int z = y +10; //error: break causes this line to never be run
      }
      //do something here
      return arg1;
      int x = arg1 /2;
      /*error: this line of code cannot be reached because of return
               statement */
   }
}


Compiler Error J0105

Method 'identifier' must return a value

The compiler detected a method declaration that included a return type other than void, but the keyword return was not found in the method body. This error usually occurs when a method that returns a value is missing a valid return statement. This error can also occur if a return statement is called within a flow control block and cannot always be accessed due to the logic of the method.

The following example illustrates this error:

public class Simple {

   public int method1(int arg1) {
      if (arg1==0)
         return arg1 + 2;
   } // error: flow control prohibits a value from always being returned
}


Compiler Error J0106

Class 'identifier' has a circular dependency

The compiler detected two or more classes directly or indirectly attempting to subclass each other. This error usually occurs when two classes extend each other. One class should act as the base class of the other.

The following example illustrates this error:

public class Simple extends Simple2 {

   // error: extending ‘Simple2’
}

class Simple2 extends Simple {

   // error: also extending ‘Simple’
}


Compiler Error J0107

Missing array dimension

The compiler detected the initialization of an array, but failed to detect a valid array dimension. This error usually occurs when an array is defined but one of the dimensions of the array is not defined. In order to use an array, all dimensions must be defined.

The following example illustrates this error:

public class Simple {

   public void method1() {

      int [][] i = new int[][12];
      // error: missing first array dimension
   }
}


Compiler Error J0108

Cannot 'new' an instance of type 'identifier'

The compiler detected an attempt to instantiate a data type that does not require the use of the keyword new. This error usually occurs when an attempt is made to use the new keyword with an intrinsic data type and the declaration is not an array. Ensure your member declaration does not use the new keyword unless it is a class object or array declaration.

The following example illustrates this error:

public class Simple {

   public void method1() {
      String myString = new String(); /*usage OK since it is a class
                                        object*/
      int x[] = new int[10]; //usage of new here is OK
      int i = new int(5);
      // error: cannot use 'new' on 'int' types
   }
}


Compiler Error J0109

Cannot 'new' an instance of abstract class 'identifier'

The compiler detected an attempt to instantiate a class object declared as abstract. A class declared as abstract cannot be instantiated and exists only as a base class for other classes to derive from.

The following example illustrates this error:

abstract class Simple2 {
   // do something meaningful
}

public class Simple {

   public void method1() {

      Simple2 s2Object = new Simple2();
      // error: class ‘Simple2’ declared as abstract
   }
}


Compiler Error J0110

Cannot 'new' an interface 'identifier'

The compiler detected an attempt to instantiate an interface object declared as abstract. Interfaces can only be implemented by a class, and thus cannot be instantiated in the way a class can.

Note Interfaces are abstract by default, regardless of whether or not the keyword abstract is used in their declaration.

The following example illustrates this error:

interface Simple2 {
   // do something meaningful
}

public class Simple {

   public void method1() {

      Simple2 s2Object = new Simple2();
      // error: interface Simple2 is abstract
   }
}


Compiler Error J0111

Invalid use of array initializer

The compiler detected an attempt to initialize an array, but the initialization statement was not syntactically correct. Arrays can be initialized at declaration with an initial set of values. This error usually occurs when trying to initialize an array of arrays with the incorrect number or positioning of braces and commas. Ensure that the syntax of your array initialization is correct and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      int[]i = {{1,2,3}, {4,5,6}};
      //error: 'i' delcared for only one dimension
   }
}

The following example illustrates the proper syntax for array initialization:

public class Simple{
   public void method1(){
      int[]i = (1,2,3,4,5,6}; //single dimension initialization
      int [][]x = {{1,2,3},{4,5,6}};//multi-dimension initialization
   }
}


Compiler Error J0112

Cannot assign final variable 'identifier'

The compiler detected an attempt to change the value of a field declared as final. A field declared as final cannot be assigned a value once it has been initialized with a value either at declaration, in an instance initializer, or constructor.

The following example illustrates this error:

public class Simple {
   private final int i = 3;

   public void method1(int arg1) {
      i = arg1;
      // error: variable 'i' declared final
   }
}


Compiler Error J0113

Call to constructor must be first statement in constructor

The compiler detected a constructor called from within the body of a second constructor, but the constructor call was not placed at the beginning of the second constructor body. In a constructor, calls to another constructor must be the first line of code in the constructor's body. Ensure that the constructor call is the first line of code in the constructor body and compile again.

The following example illustrates this error:

public class Simple {

   int i, j;
   Simple () {

      i = 0;
   }

   Simple(int arg1) {

      j = arg1;
      this(); // error: call to Simple() must be first
   }
}


Compiler Error J0114

Cannot reference 'this' in constructor call

The compiler detected an improper reference to this in a constructor. The this statement is usually used in a constructor to access methods and fields of the constructor's class. Usage of this(this) or super(this) in a constructor will cause this error to occur because the instance of the class has not yet been created and thus cannot be passed to another constructor.

The following example illustrates this error:

class SuperSimple {
   SuperSimple(){}
   SuperSimple(Object o) { }
}

public class Simple extends SuperSimple {
   int x;
   public Simple()
   {
      this(10); //this is OK; calls another constructor
      super(this);
      //error: cannot pass this to a super constructor
      this.x = 1; //this is OK
      this.method1(); //this is OK too
   }
   public Simple(int arg1){
      this.x = arg1; //this is OK
   }
   public void method1(){}
}


Compiler Error J0115

Cannot call constructor recursively (directly or indirectly)

The compiler detected a recursive constructor call. This error usually occurs when a constructor has a call to the same constructor. This error can also occur if one constructor calls a second constructor and the second constructor has a call back to the first constructor.

The following example illustrates this error:

public class Simple {

   Simple (int arg1) {

      this(1);
      // error: constructor calling itself
   }
}


Compiler Error J0116

Variable 'identifier' may be used before initialization

The compiler detected an attempt to use a variable before it was properly initialized. In order to use a variable in an assignment or expression, you need to assign it a value. Initialize the variable in a constructor or field initializer and compile again.

The following example illustrates this error:

public class Simple {

   static
   {
      int i;
      int j = i;
      // error: 'i' not yet initialized

   }
}


Compiler Error J0117

Cannot declare an interface or outer class to be 'private'

The compiler detected use of the modifier private in an outer class or interface declaration. This modifier may only be used with fields, methods, and inner class declarations.

The following example illustrates this error:

private class Simple {

   // error: a class cannot be 'private'

}


Compiler Error J0120

Divide or mod by zero

The compiler detected a division by zero error.

The following example illustrates this error:

public class Simple {

   final int x = 0;
   int y = 1 % x;
   //error: x cannot be 0

}


Compiler Error J0121

Unable to recover from previous error(s)

The compiler encountered a serious error and could not continue processing the file reliably. Fix whatever errors are already flagged and compile again.


Compiler Error J0122

Exception 'identifier' not caught or declared by 'identifier'

The compiler detected an exception that was thrown but never caught within the exception class. This error usually occurs when a method calls another method that is declared to throw an exception. In order for a method to call another method that throws an exception, the method must either be declared to throw the exception or handle the error using a try/catch combination.

The following example illustrates this error:

class SimpleException extends Exception {
   // do something meaningful
}

class Simple {

   void method1() throws SimpleException { }
   void method2() { method1(); }
   // error: exception not declared for method2
}

The following examples illustrates how to call a method that is declared to throw an exception:

/*This example illustrates handling by declaring the other method as
throwing an exception duplicate to the method it is calling.*/
class SimpleException extends Exception{
   //do something here
}

public class Simple{
   void method1() throws SimpleException{
      //do something here
   }
   void method2() throws SimpleException{
      method1(); //caller of method2 now is forced to handle exception
   }
}

/*This example illustrates handling the exception using a try/catch
  combination.*/
class SimpleException extends Exception{
   //do something here
}

public class Simple{
   void method1() throws SimpleException{
      //do something here
   }
   void method2(){
      try{
        method1();
      }
      catch(SimpleException e){
         //handle exception here
      }
   }
}


Compiler Error J0123

Multiple inheritance of classes is not supported

The compiler detected a class attempting to apply the keyword extends to more than one base class. This is defined as multiple inheritance in other languages and is not supported in Java.

The following example illustrates this error:

public class Simple extends BaseClass1, BaseClass2 {
   // error: multiple inheritance not supported in Java
}

class BaseClass1 {

   // do something meaningful
}

class BaseClass2 {

   // do something meaningful
}


Compiler Error J0124

Operator cannot be applied to 'identifier' values

The compiler detected an operator being applied to a type it cannot be used with. Ensure that the operator you are attempting to use is valid for that type of variable or object and compile again.

The following example illustrates this error:

public class Simple {

   void method1(boolean b) {

      b++;
      /* error: post increment operator cannot
         be applied to boolean variables */
   }
}


Compiler Error J0125

'finally' block used without 'try' statement

The compiler detected a finally block but did not find a corresponding try statement. A finally block is used to execute code after a try statement, regardless of the results of the try statement.

The following example illustrates this error:

public class Simple {

   public void method1() {

      finally {
         // error: missing corresponding try statement
      }
   }
}

The following example illustrates the correct usage of the finally block:

public class Simple{

   public int method1(int arg1){
      try{
         arg1/10;
      }
      catch(Exception e){
         //handle exception here; must come before 'finally'
      }
      finally{
        //do something here; this section is run regardless of 'try'
      }
   }
}


Compiler Error J0126

'catch' block used without 'try' statement

The compiler detected a catch statement but did not find a corresponding try statement. In order to use a catch statement you must have a try statement preceding it. Ensure that you have a valid try statement preceding your catch statement and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {

      catch {
         // error: missing corresponding try statement
      }
   }
}

The following example illustrates the proper usage of the catch block:

public class Simple {

   public void method1() {
      try{
         //do something here
      }
      catch (Exception e){
         //handle exceptions from try statement here
      }
   }
}


Compiler Error J0127

'else' keyword used without 'if' statement

The compiler detected the keyword else but did not find a corresponding if statement. This error usually occurs when there are scoping issues regarding the placement of an else statement. It can also occur if an else statement's corresponding if statement is missing.

The following example illustrates this error:

public class Simple {

   public void method1(int arg1) {
      if (arg1 == 0){
        //Do something here
        else{}
           //error 'else' is inside of the 'if' block instead of outside
      }
   }
}


Compiler Error J0128

Cannot declare an interface to be 'final'

The compiler detected an interface declared with the keyword final. Interfaces cannot be defined as final and thus cannot use the final modifier. Remove the final keyword from the interface declaration and compile again.

The following example illustrates this error:

final interface Simple {

   /*error: 'final' only applies to
      classes, methods,or variables*/

}


Compiler Error J0129

Cannot declare a class to be 'identifier' and 'identifier'

The compiler detected a class declared with modifiers that cannot be combined. Ensure that the modifiers you have applied to the class do not conflict with each other and compile again.

The following example illustrates this error:

public abstract final class Simple {

   /*error: 'abstract' and 'final' cannot
     be used together in a class declaration*/

}


Compiler Error J0130

Cannot declare an interface method to be 'native', 'static', 'synchronized' or 'final'

The compiler detected one of the keywords shown in the error message used in the declaration of an interface method. Because an interface method does not have implementation code, it cannot be declared as native, static, synchronized, or final.

The following example illustrates this error:

interface Simple {

   public final void method1();
   /*error: ‘method1’ cannot be declared
      as final in an interface*/
}


Compiler Error J0131

Cannot declare a method to be 'identifier' and 'identifier'

The compiler detected the use of two or more incompatible modifiers in the declaration of a method. This error usually occurs when a method has been defined with two access modifiers such as public and private. Ensure that the modifiers for the method do not conflict with each other and compile again.

The following example illustrates this error:

public class Simple {

   public private void method1() {

      // error: modifiers 'public' and 'private'
      // cannot be combined in a declaration
   }
}


Compiler Error J0132

Cannot declare a field to be 'identifier' and 'identifier'

The compiler detected the use of two or more incompatible modifiers in the declaration of a variable. This error usually occurs when a field has been defined with two access modifiers such as public and private. Ensure that the modifiers for the field do not conflict with each other and compile again.

The following example illustrates this error:

public class Simple {

   public private int i;
   // error: modifiers 'public' and 'private'
   // cannot be combined in a declaration
}


Compiler Error J0133

Constructors cannot be declared 'native', 'abstract', 'static', 'synchronized', or 'final'

The compiler detected the use of one of the modifiers shown above in the declaration of a constructor. Ensure that the constructor is not defined with any of the modifiers mentioned in the error message and compile again.

The following example illustrates this error:

public class Simple {

   final Simple() {}
   // error: constructors cannot be 'final'

}


Compiler Error J0134

Interfaces cannot have constructors

The compiler detected an interface containing a constructor declaration. Because an interface cannot be instantiated, constructors cannot be defined for an interface. If you are defining a method with the same name as the interface, ensure that it has the appropriate modifiers to differentiate it from a constructor declaration.

The following example illustrates this error:

interface Simple {

   Simple();
   // error: interfaces cannot
   // declare constructors

}


Compiler Error J0135

Interface data members cannot be declared 'transient', 'volatile', 'private', or 'protected'

The compiler detected one of the modifiers shown above used in the declaration of an interface member variable. Because interfaces are public and cannot be instantiated, these modifiers are not applicable and should be used with classes only.

The following example illustrates this error:

interface Simple {

   volatile int i = 1;
   // error: 'volatile'cannot be used

}


Compiler Error J0136

Public class 'identifier' should not be defined in 'identifier'

The compiler detected more than one class declared with the modifier public in a source file. Remove the public access modifier from other classes and ensure that the class that will be exposed through the class file is declared as public. You can also move classes that need to remain declared as public to their own source file. This error can also occur if a source file has a different name than the public class defined within it, or the public class and the source file do not match in case. Rename the source file or the name of the public class defined within it so that they are the same and compile again.

The following example illustrates this error:

public class Simple {

   // do something meaningful

}

public class Errorclass {

   // error: only one class may be defined as
   // 'public' within the same source file

}


Compiler Error J0138

Interface cannot have static or instance initializer

The compiler detected a static initializer or instance initializer within an interface. Because an interface does not get instantiated, initializers cannot be defined in an interface. To set the values of interface fields, initialize them at the time of declaration.

The following example illustrates this error:

interface Simple {
   int x = 10; //This is OK
   {
      // error: initializers cannot
      // be used in interfaces
   }
}


Compiler Error J0139

Invalid label

The compiler detected an invalid label. Labels must start with a non-numeric character. Change the label and compile again.

The following example illustrates this error:

public class Simple {

   public int method1(int arg1) {
      123:
         //error: label cannot begin with a number.
         return arg1 * 2;
   }
}


Compiler Error J0140

Cannot override static method 'identifier' with non-static method ‘identifier’

The compiler detected an attempt to override a static method from within a subclass. A method that has been declared as static cannot be overridden.

The following example illustrates this error:

public class Simple {

   static void method1() {}
}

class SimpleSubclass extends Simple {

   void method1() {}
   // error: cannot override
   // static method
}


Compiler Error J0141

Argument cannot have type 'void'

The compiler detected a method argument defined as type void. The void type can only be used for method return values to declare a method has no return value. Change the data type of the argument and compile again.

The following example illustrates this error:

public class Simple {

   public void method1(void i) {
      // error: type void can only
      // be used as a return value
   }
}


Compiler Error J0142

Cannot make static call to abstract method 'identifier'

The compiler detected an attempt to directly call an abstract method. Abstract methods are defined to provide a definition of a method to be implemented by subclasses; therefore, abstract methods do not have implementation code. Because of this lack of implementation in an abstract method, calling an abstract method using the super keyword is invalid.

The following example illustrates this error:

public abstract class Simple {

   abstract int method1();
}

class SimpleSubclass extends Simple {

   int method1() {

      return super.method1();
      // error: cannot call abstract method
   }
}


Compiler Error J0143

Cannot throw exception 'identifier' from static initializer

The compiler detected an attempt to throw an exception from within a static initializer. This error usually occurs when a throw statement is called or when an initialization of a static class instance occurs within a static initializer. To capture exceptions from static class instance intializations in a static initializer, use a try/catch block combination.

The following example illustrates this error:

public class Simple {

   static {
      ThrowClass TClass = new ThrowClass();
      // error: cannot throw exceptions
      // within static initializers
   }
}

class ThrowClass {

   ThrowClass() throws Exception{}

}

The following example illustrates how to use the try/catch block combination to capture potential errors when initializing static class instances in a static initializer:

public class Simple{
   static ThrowClass thr;
   static{
     try{
        ThrowClass thr = new ThrowClass();
     }
     catch (Exception e){
         //Handle errors here from initialization of 'ThrowClass'
     }
   }
}

class ThrowClass {
   ThrowClass() throws Exception(){
      // Do something here
   }
}


Compiler Error J0144

Cannot find definition for interface 'identifier'

The compiler could not locate a definition for the named interface. This error usually occurs when an implemented interface is either missing or misspelled. Verify the location and name of the interface you are implementing and compile again.

The following example illustrates this error:

public class Simple implements Bogus {
   // error: the interface 'Bogus' does not exist

}


Compiler Error J0145

Output directory or file too long: 'identifier'

The output directory or source file being saved exceeds 228 characters in length. Shorten the length of the output directory path or source file and compile again.


Compiler Error J0146

Cannot create output directory 'identifier'

The output directory could not be created. This error usually occurs when you do not have write permission on the specified drive.


Compiler Error J0147

Cannot access private member 'identifier' in class 'identifier' from class 'identifier'

The compiler detected an invalid attempt to access a private member contained within another class. Private class members are only accessible from within the member's class. A class’s private members are also available from its inner classes.

The following example illustrates this error:

class AccessClass {

   private int i = 0;

}

public class Simple {

   public void method1() {

      AccessClass ac = new AccessClass();

      ac.i = 1;
      // error: cannot access 'i'
   }
}


Compiler Error J0148

Cannot reference instance method 'identifier' before superclass constructor has been called

The compiler detected an attempt to reference an instance method before the superclass constructor was called. This error usually occurs when a base class method is called from within a subclass's constructor using the super() statement. This error can also occur if the subclass calls its own methods from the constructor using the this() statement. This error occurs because instances of the subclass and base class have not been instantiated at the time the constructor is called. To avoid this situation, use the super. statement to call a base class method, and use the this. statement to call a subclass method.

The following example illustrates this error:

abstract class Simple {

   Simple(int i) {}

   int method1() {

      return 0;
   }
}

class SimpleSubclass extends Simple {

   SimpleSubclass() {

      super(method1());
      // error: constructor must be called first
   }
}

Using the abstract class from the example above, the following example illustrates how to call the base class method from the constructor:

class SimpleSubclass extends Simple{

   SimpleSubclass(){
     super.method1();
   }
}


Compiler Error J0150

Cannot have repeated interface 'identifier'

The compiler detected an interface name being repeated within a class declaration. This error is usually caused when a class implements a large number of interfaces and one of the interfaces has a duplicate entry in the implements list. Ensure that you do not have a duplicate interface entry and compile again.

The following example illustrates this error:

interface SimpleI {
   // do something meaningful
}

class Simple implements SimpleI,IColor,IFont, SimpleI {
// error: 'SimpleI' repeated
}


Compiler Error J0151

Variable 'identifier' is already defined in this method

The compiler detected two variables with the same name that are defined twice within the same scope of a method. Ensure that a variable has not been defined twice in the same scope or that a variable has not been defined the same name as an argument passed to the method and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {

      int i = 1;
      int j = i;
      //more code here
      int i = 0;
      // error: 'i' defined twice within
      // the same scope

   }
}


Compiler Error J0152

Ambiguous reference to 'identifier' in interfaces 'identifier' and 'identifier'

The compiler detected an ambiguous reference to an identifier. The identifier may have been declared in two or more interfaces, and the compiler could not determine which reference to use. Ensure that you do not have two interfaces with the same field defined.

The following example illustrates this error:

interface Interface1 {
    final int i = 0;
}

interface Interface2 {
    final int i = 1;
}

public class Simple implements Interface1, Interface2 {

   int method1() {
      return i; //error: cannot determine which instance of 'i' to use
   }
}


Compiler Error J0158

Class 'identifier' already defined

The compiler detected two or more classes defined with the same name. Ensure that you do not have the class defined more than once (as an outer class) in the same source file or package. This error can also occur if a class is duplicated by an imported class. Rename one of the classes or remove the duplicate instance and compile again.

The following example illustrates this error:

public class Simple {
   // do something meaningful
}

class Simple {
   // error: class 'Simple' already defined
}


Compiler Error J0159

'@' must be followed by the response filename

The compiler detected the @ character on the JVC command line, but did not detect a valid response filename immediately following it. Supply the response filename and compile again.


Compiler Error J0160

Response file 'identifier' could not be opened

The compiler could not open the specified response file. This error usually occurs when the response file name is misspelled or the file does not exist. Check the location of the response file and compile again.


Compiler Error J0161

Cannot open source file: 'identifier'

The source file specified in the error message could not be opened. This error usually occurs when either the filename specified is misspelled or the file does not exist. Check the location of the specified source file and compile again.


Compiler Error J0162

Failed to initialize compiler

The compiler failed to properly initialize. This error most often occurs because the compiler and/or the Microsoft Virtual Machine for Java (VM) are not properly installed or are the incorrect version. Confirm the correct version and installation of the VM and compiler.


Compiler Error J0163

Array 'identifier' missing array index

The compiler detected access to an array type, but the index value was missing. To access an element of an array, you must provide a valid integer index for the array. Ensure that a valid integer is used to reference an index of the array and compile again.

The following example illustrates this error:

public class Simple {

   int j[] = {1, 2, 3};

   void method1() {
      j[] = 0;
      // error: 'j' missing index value
   }
}


Compiler Error J0164

Ambiguous import of class 'identifier' from more than one package

The compiler detected two or more import statements attempting to import identical class names from different packages. This error usually occurs when two packages contain duplicate classes and both packages are imported into the same source file. Check the packages imported into the source file for duplicate classes. Remove the duplicate class from one of the packages or remove one of the import statements from the source file.

The following example illustrates this error:

import Box.Test; //This package contains a class named 'Test'
import Carton.Test; //This package contains a class named 'Test' also
//error: which 'Test' class should be used by the compiler?

public class Simple{
   //Do something here
}


Compiler Error J0165

Cannot throw exception 'identifier' from method 'identifier' -- it is not a subclass of any exceptions thrown from overridden method 'identifier'

The compiler detected an overridden method attempting to throw more exceptions than the method it overrides. In Java, an override method cannot be declared to throw more exceptions than the overridden method. Either change the exception thrown to one that the base class throws, or change the base class declaration to throw the exception type that the subclass needs to throw.

The following example illustrates this error:

class ExceptionA extends Exception {
   // do something meaningful
}

class ExceptionB extends Exception {
   // do something meaningful
}

class AnotherClass {

   public void method1() throws ExceptionA {
      // do something meaningful
   }
}

public class Simple extends AnotherClass {

   public void method1() throws ExceptionA, ExceptionB {
      // error: cannot throw greater than
      // one exception here
   }
}


Compiler Error J0166

Cannot access member 'identifier' in class 'identifier' from 'identifier' -- it is in a different package

The compiler detected an invalid attempt to reference a member variable or method defined within a different package. This error usually occurs when an attempt is made to access a protected or default access member defined within another package. Protected or default access members of a class located in a different package are not accessible. Ensure that the member you are attempting to access in another package is not a protected or default access member.


Compiler Error J0167

Cannot override non-static method 'identifier' with static method 'identifier'

The compiler detected an attempt to override a superclass method with a subclass method declared with the modifier static. When a method is overridden in a subclass, the method cannot raise or lower the access level of the method or apply the static modifier. Remove the static modifier from the overridden method declaration and compile again.

The following example illustrates this error:

public class Simple {

   public void method1() {
      // do something meaningful
   }
}

class Simple2 extends Simple {

   static public void method1() {
      // error: overriding superclass 'method1'
      // with a static method is not valid
   }
}


Compiler Error J0168

The declaration of an abstract method must appear within an abstract class

The compiler detected a method declared with the modifier abstract within a class which was not defined as abstract. This error usually occurs when a class is intended to be abstract but is missing the abstract modifier in the class declaration. Either change the class so it is declared as abstract or remove the modifier from the methods defined in the class.

The following example illustrates this error:

public class Simple {

   abstract void method1();
      // error: class must also be abstract
}


Compiler Error J0169

Cannot access 'identifier' -- only public classes and interfaces in other packages can be accessed

The compiler detected an attempt to access a non-public class or interface contained within another package. Only classes or interfaces defined with the modifier public can be accessed in other packages. Check the access level of the class or interface you are accessing in the other package to ensure that it is public and compile again.

The following example illustrates this error:

//Source located in 'Boxes.Java' in the 'Box' package
package Box;
public class Box{
   TapeRoll tr = new TapeRoll();
   //Do meaningful stuff here
}
class TapeRoll{
   //Define the class here
}

//Source located in 'Simple.java'
import Box.TapeRoll;
public class Simple{
   public static void main(String args[]){
      Box.TapeRoll tr = new Box.TapeRoll();
      //error: cannot access a 'non-public' class in a different package
   }
}


Compiler Error J0170

Cannot load predefined class 'identifier'

The compiler attempted to load a predefined class, but was unable to find the appropriate file. This error usually occurs when the Java API class files cannot be found on the system or the correct version of the Microsoft Virtual Machine for Java (VM) is not properly installed. Ensure that your Java API class files and the VM have been installed properly on the system and compile again.


Compiler Error J0173

Found class 'identifier' in package 'identifier' rather than package 'identifier'

The compiler found the specified class, but the class was not defined as a member of the correct package. This error usually occurs when the class file is being imported from the wrong directory. Ensure that the class you are importing is located in the correct package directory and compile again.


Compiler Error J0175

Cannot invoke method on 'null' literal

The compiler detected an attempt to call a method from the null keyword. Null is not a class object and provides no methods. Remove the statement that attempted a method call from the null keyword and compile again.

The following example demonstrates this error:

public class Simple{
   public String methdo1(){
      //Do something meaningful here
      return null.toString();
      //error : cannot invoke a method from 'null'
   }
}


Compiler Error J0176

Duplicate label 'identifier' nested inside another label with same name

The compiler detected a nested label that was the same as another label. Rename the label to something different. Change all break and continue statements that reference the label and compile again.

The following example illustrates this error:

public class Simple{
   void method1(){
      outsideLoop:
      for (int i=0;i<10;i++)
      {
         outsideLoop:  //error: duplicate label
         for (int x=0;x<10;x++)
         {
            break outsideLoop;
         }
         break outsideLoop;
      }
   }
}


Compiler Error J0189

'return' not allowed in a static initializer or instance initializer

A return statement was found in a static or instance initializer. Initializers, like constructors, can not return a value. Remove the return statement and compile again.

The following example illustrates this error:

public class Simple{

   static int var1;

   static{
      var1 = 0;
      return;
      //error: return statement not allowed in static initializer
   }
}


Compiler Error J0191

Expected '.class'

The compiler detected usage of an intrinsic type name in an expression or assignment statement but did not find .class after the name. This error usually occurs when the .class keyword is omitted. Add the .class extension to the end of the intrinsic type and compile again.

The following example illustrates this error:

public class Simple{
   public static void main (String args[]){
      Class x = int;//error: missing '.class'
   }
}


Compiler Error J0192

'.class' on intrinsic type requires Java 1.1 compatible class libraries

The compiler detected usage of the .class keyword with an intrinsic data type, but either the Microsoft Virtual Machine (VM) for Java or the Java class libraries are based on Java 1.0. Ensure that your class libraries and Java VM are the Java 1.1 versions and compile again.


Compiler Error J0193

Cannot have an array of type 'void'

An attempt to define an array of type void was found by the compiler. The void data type is for use with methods to declare that the method has no return value and can not be used as an array.

public class Simple{

   void MyArray[]; //error: void arrays not supported

}


Compiler Error J0194

Class or interface cannot be declared 'volatile', 'native', 'transient', or 'synchronized'

The compiler detected that an inner class or interface was declared with one of the above mentioned modifiers. This error usually occurs when a method or field modifier is applied to an inner class or interface definition. Inner classes and interfaces can use the private, public, and protected access modifiers. Inner classes can also use modifiers such as abstract, static, and final.

The following example illustrates this error:

public class Simple{
   //Do something here
   volatile class InnerClass{
      /*error: like outer class, inner classes cannot be defined as
               volatile */
   }
}


Compiler Error J0195

Cannot declare 'identifier' as 'static' in inner class 'identifier'

The compiler detected an attempt to declare a variable or method as static from within an inner class. Unlike regular class declarations, inner classes do not support static members. Classes defined within another class, that are declared as static, can have static members but the class is considered an outer class. This error can also occur if an interface was defined within an inner class.

The following example illustrates this error:

public class Simple{

   //Do something meaningful here

   class InnerClass{

   static int var1; /* error: cannot declare static
                              members in inner class
   }
}

The following example illustrates how to define a class within a class that can contain static members:

public class Simple{

   //Do something meaningful here

   /*Because 'InnerClass' class is declared as static it is now treated
     as an outer class enclosed within the 'Simple' class*/
   static class InnerClass{
      static int var1 = 100; // This is OK as long as the class is static
   }
}


Compiler Error J0196

Nested class 'identifier' cannot have the same name as any of its enclosing classes

The specified inner class has the same name as one of the classes that it is nested under. Ensure that you have not duplicated the name of a class in which your inner class is nested within and compile again.

The following example illustrates this error:

public class Simple{

   // Do something meaningful here
   class InnerClass{
      //Do something meaningful here
        class Simple{
            //error: inner class has same name as a parent class
        }
   }
}


Compiler Error J0197

Cannot declare interface in inner class 'identifier'

The compiler detected an attempt to declare an interface inside an inner class. Inner class definitions do not support interfaces declared within them. Remove the interface declaration from within the inner class declaration and compile again.

The following example illustrates this error:

public class Simple{
   //Do something meaningful here
   class InnerClass{
   //Do something meaninful here
      interface MyInterface{
         /*error: interfaces cannot be declared
                  inside inner classes */
      }
   }
}


Compiler Error J0198

An enclosing instance of type 'identifier' is required

The compiler detected that an inner class definition tried to reference something outside of its scope. Examples of when this can occur are:

  • A class declared within another class as static referenced one of the parent class's non-static variables or methods. Since the inner class is declared static it cannot reference any members of the parent class without an instance of the parent class defined.

  • An inner class tried to reference a class that was not its outer class using the this keyword with the classes name preceding it. Since the referenced class is not the inner class's parent class, an instance cannot be implied.

The following examples illustrate this error:

//This example illustrates the first error situation
public class Simple{
   int x = 10;
   static class InnerClass{
      public void method1(){
         int y = x; /*error: instance variable needed
                             to reference parent
                             variables. */
      }
   }
}

//This example illustrates the second error situation
class A{
   int x;
}
class B{
   //Do something meaningful here
   class InnerClass{
      void method1(){
         int y = A.this.x;
         /*error: no instance of A defined. Cannot use
           the <classname.this.variable> syntax here.*/
      }
   }
}


Compiler Error J0199

Call of 'this()' cannot be qualified

The compiler detected that an inner class's constructor attempted to call it’s outer class constructor using the class name with the this() method. Inner classes cannot call their outer class's constructors. Remove the call to the outer class constructor from the inner class constructor and compile again.

The following example illustrates this error:

public class Simple{
   int x;
   Simple(int x){
      this.x = x;
   }
   class InnerClass{
      InnerClass(){
         Simple.this(10);
         //error: cannot call outer class constructor
      }
   }
}


Compiler Error J0200

'this' must be qualified with a class name

The compiler detected that an attempt was made in an inner class to reference an outer class member using the this keyword with a name other than an outer class's name. Only the name of the outer class can be used from an inner class to reference members of the outer class.

The following example illustrates this error:

public class Simple{
   int x;
   class InnerClass{
      void method1(){
         int j = x.this;
         /*error: only a class name can be used with
         this to reference outer class */
      }
   }
}

The following example illustrates the proper way to reference an outer class's members:

public class Simple{
   int x;
   int method2(int arg1){
     return arg1 * ;
   }
   class InnerClass{
      void method1(){
         int j = Simple.this.x; //This is OK!
         int z = Simple.this.method2(10);
      }
   }
}


Compiler Error J0201

'super' cannot be qualified except as a superclass constructor call

The compiler detected the usage of the super keyword with an instance of the superclass preceding it to access a field or method of the superclass. Using an instance of a superclass, along with the keyword super, is limited to referencing a superclass constructor when the superclass has inner classes defined within it.

The following example illustrates this error:

class Simple{
   int x;
}

class NotSimple extends Simple{
   NotSimple(Simple smp){
      smp.super.x = 100;
      /*error Cannot reference field with superclass
              name */
      super.x = 100;//This is OK!
   }
}


Compiler Error J0202

'super()' cannot be qualified; superclass 'identifier' is not an inner class

The compiler detected a call to a superclass constructor using an instance of the superclass but the superclass is not an inner class. The usage of an instance of a superclass combined with the super keyword is only used when a superclass is an inner class.

The following example illustrates this error:

class Simple{
   //Do something meaningful here
}

class NotSimple extends Simple
{
   NotSimple(Simple smp){
      smp.super();
      /*error: cannot call 'super' with instance when
        superclass does not contain inner classes*/
   }
}

The following example shows the usage of a superclass instance with the super keyword:

class Simple{
   //Do something here
   class InnerClass{
      int var1, var2;
   }
}

public class NotSimple extends Simple.InnerClass{
   NotSimple(Simple smp){
     smp .super();
     //This is OK!
   }
}


Compiler Error J0203

Cannot access protected member 'identifier' in class 'identifier' from class 'identifier'

The compiler detected an attempt to access a protected member from a class in a different package. A protected member of a class may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that class. Remove the call to the other package's protected member or make your class a subclass of the other package's class and compile again.

The following example illustrates this error:

/*(source located in a file called PublicClass.java in
   the the Boxes Package directory) */
package Boxes;

public class PublicClass{
   protected void method1(){
      //Do something here
   }
}

//(source located in a file called Simple.java)
import Boxes.PublicClass;

public class Simple extends PublicClass{
   public void method1(){
      PublicClass pub = new PublicClass();
      pub.method1();
      /*error: Cannot access protected method 'method1' because it
               is located in a different package.*/
   }
}


Compiler Error J0204

Cannot access protected member 'identifier' in class 'identifier' via a qualifier of type 'identifier'

The compiler detected that a class in one package, that is extending a class in another package, attempted to access a protected member of the base class using an instance of the base class. This error usually occurs when a class attempts to access members of its base class through an instance other than this, super, or an instance of the derived class. Ensure that the base class's protected member is accessed using the this or super keyword, or an instance of the derived class and compile again.

The following example illustrates this error:

/*(source located in a file called Point.java located in the Boxes package directory) */
package Boxes;

public class Point{
   protected int x, y;
   //Do other meaningful code here
}
//(source located in a file called simple.java)
import Boxes.Point;

public class Simple extends Point{
   public void method1(Point p){
      super.x = 0; //this is OK!
      p.x = 0; /*error: cannot use a protected member
                 for usage other than extending it. */
   }
}


Compiler Error J0205

Cannot use non-final local variable 'identifier' from a different method

The compiler detected that a local variable, which was not declared as final, was referenced in a method. This error can occur if an inner class is defined in a local block or method declaration and the inner class attempts to reference a parameter or local variable defined outside of its scope.

The following example illustrates this error:

public class Simple{
   void method1(int var1){
      class InnerClass{
         boolean getVar1(){
           return(var1 == 1);
           /*error cannot reference local variable of
                   method from within inner class. */
         }
      }
   }
}


Compiler Error J0206

Cannot assign a second value to blank final variable 'identifier'

The compiler detected an attempt to assign a value to a final variable more than once. This error usually occurs when a blank final variable is initialized more than once in a constructor or initializer. Check for duplicate initializations of the final variable mentioned in the error message and compile again.

The following example illustrates this error:

public class Simple{
   final int var1;

   {
      var1 = 10;
      //Do other initializations here
      var1 = 20; //error: duplicate assignment
   }
}


Compiler Error J0207

Cannot assign blank final variable 'identifier' in a loop

The compiler detected that a final variable was assigned a value from within the scope of a program control loop. A final variable can only be assigned a value once and thus cannot be initialized within a loop. Move the initialization of the final variable specified in the error message outside of the loop and ensure that it is initialized only once.

The following example illustrates this error:

public class Simple{
   final int x;

   public Simple(){
      for (int z=0;z<10;z++){
         x = z; /*error: cannot assign final variable
                  in loop */
      }
   }
}


Compiler Error J0208

Constructor or instance initializer must assign a value to blank final variable 'identifier'

The compiler detected that a final variable was declared but never assigned a value in either an initializer or constructor. In order for a variable to be properly declared final it must be assigned a value.

The following example illustrates this error:

public class Simple{
   final int x; //error: final variables must be assigned a value
   final int z = 10; //This is OK
}


Compiler Error J0209

Expected '='

The compiler detected that an equal sign was missing from a comment tag (for example @com, @security, @dll) attribute. This error usually occurs when an equal sign is missing from an attribute in a comment tag declaration. This error can also occur if another symbol or character obscures the equal sign from being evaluated by the compiler. Ensure that all comment tag attributes have proper equal signs applied and compile again.

The following example illustrates this error:

/**@com.interface(iid 31415926-5358-9793-2384-612345678901)*/
//error: missing equal sign in 'iid' parameter
interface Itest{
   //Do something meaningful here
}


Compiler Error J0210

Expected '.'

The compiler detected that the specified comment tag's declaration (for example @com, @dll) is missing a period after the comment tag (for example @com.method). This error can also occur if another symbol or character obscures the period symbol from being evaluated by the compiler. Ensure that your comment tag declaration contains a period after the comment tag and compile again.

The following example illustrates this error:

/**@com class*/
//error: missing '.' from @com statement

public class Simple{
   //Do something meaningful here
}


Compiler Error J0214

Invalid GUID specified

The compiler detected that an @com attribute that requires a GUID has an invalid GUID entry. This can be caused by a syntax error in entering the GUID. Check the syntax for the GUID and compile again.


Compiler Error J0215

Syntax error in @com declaration

A syntax error was found in the specified @com declaration. This is most often caused by incorrectly typing the declaration. Check the syntax of the @com declaration and compile again.

The following example illustrates this error:

/** @com.inteface (iid=31415926-5358-9793-2384-612345678910)
//error:  The word 'interface' is misspelled.
interface ITest{
   //Do something here
}


Compiler Error J0216

@com attribute 'identifier' on 'identifier' is illegal in this context

The compiler has detected that a value assigned to an attribute within an @com declaration is illegal. This error most often occurs when an attribute is specified but usage of the attribute requires that other specific attributes be specified. This error can also occur if an attribute is specified in the wrong location within an @com declaration.


Compiler Error J0217

@com attribute 'identifier' was not specified for 'identifier' but is required in this context

The compiler detected an attribute (for the @com declaration shown in the error) that is missing and that is required for this type of declaration. Each type of @com declaration has attributes that are required. See the documentation on @com for more details on what attributes are required for the @com declaration that is listed in the error message.

The following example illustrates this error:

/**@com.class() */
//error: must specify classid for @com.class
public class Simple{
   //Do something here
}


Compiler Error J0218

@com attribute 'identifier' on 'identifier' has an invalid value

The compiler detected that the value specified in the error message is either not the correct type for the attribute specified in the error or is outside the valid range for the attribute. Check the value assigned to the specified attribute and compile again.

The following example illustrates this error:

/** @com.class(classid=911CAED0-2957-11d1-A55E-00A0C90F26EE) */
class Simple{
   /** @com.parameters([type=CUSTOM, customMarshal="foo.bar",
       customMarshalFlags = 5] i) */
       //error: customMarshalFlags cannot be set higher than 3
   native void method1(Object i);
}


Compiler Error J0219

An @com attribute cannot be placed on member 'identifier' unless the containing class or interface also has an @com attribute

The compiler detected that an @com declaration was placed on a member of a class or interface, but the class or interface was not declared with an @com declaration. Ensure that the class or interface which contains the method specified in the error has a valid @com declaration defined and compile again.

The following example illustrates this error:

interface Simple{
   /**@com.method(dispid=777); */
   public void method1();
   /*error: interface does not have an @com comment tag
            assigned*/
}


Compiler Error J0220

An @com attribute cannot be placed on static member 'identifier'

The compiler detected that an @com declaration was placed on a static member of a class. Static members cannot be exposed through COM. Remove the static keyword from the method or field and compile again.

The following example illustrates this error:

/*@com.class(classid=31415926-5358-9793-2384-612345678910)
public class Simple{
   /**@com.method(dispid=777);*/
   static void method1(){}
   //error: cannot expose static method via COM
}


Compiler Error J0221

The @com attribute on member 'identifier' cannot be used in this type of class or interface

The compiler detected that an @com declaration was placed on a member of a class or method but because of the type of @com attribute used with the class or interface, it is not allowed. This error can occur in the following situations:

  • Using an @com.structmap declaration on a member of a class or interface that has the @com.class or @com.interface declaration applied.

  • Using an @com.method declaration on a member of a class that has the @com.struct declaration applied.

The following example illustrates this error:

/**@com.struct()*/
class Simple{
   /**@com.method(dispid=777)*/
   public native void method1();
   /*error: cannot use @com.method inside of
            @com.struct*/
}


Compiler Error J0222

@com attribute cannot be placed on method 'identifier'-- it must be declared 'native' or be in an interface

The compiler detected that a method was specified with an @com.method or @com.parameters attribute, but the method was not declared with the native modifier or declared in an interface definition. For methods to be exposed through a COM interface they must either be declared in an interface declaration or declared native from within a class declaration.

The following example illustrates this error:

public class Simple{

   /** @com.method(dispid=306); */
   public void method1(){}
   /*error: method must be declared 'native' or
            declared in an interface */
}


Compiler Error J0223

The @com.parameters declaration on member 'identifier' has the wrong number of parameters

The compiler detected that the @com.parameters attribute (specified in the error message) has a different number of parameters than the method it is exposing through COM. Ensure that both the method's declaration and the @com.parameters attribute have the correct number of parameters and compile again.

The following example illustrates this error:

/**@com.interface(iid=31415926-5358-9793-2384-612345678910)*/
interface Itest{
   /** @com.method(dispid=306);
       @com.parameters([type=BOOLEAN] var1, var2, var3)
   */
   public void method1(boolean var1, int var2);
   /*error: extra parameter added to com.parameters
            declaration */
}


Compiler Error J0224

'return' must be the last item in an @com.parameters declaration

When declaring @com.parameters for a method, the return parameter must be the last parameter in the list. The compiler detected the return parameter in a different position within the parameter list. Check the location of the return parameter in the @com.parameters attribute specified in the error message, make the appropriate changes, and compile again.

The following example illustrates this error:

/** @com.class(classid=911CAED0-2957-11d1-A55E-00A0C90F26EE) */
class Simple{
   /** @com.parameters([type=I4] return, [type=CUSTOM,
       customMarshal="foo.bar", customMarshalFlags = 3] i) */
       //error: 'return' cannot be defined as the first parameter
   native int method1(Object i);
}


Compiler Error J0225

An @com.'identifier' declaration is illegal for this type of item

The compiler detected that an @com declaration was defined for the wrong type of item. This error usually occurs as a result of a change to your code, but it is not due to the syntax or placement of an @com declaration. Ensure that the proper @com declaration is used on the specified item in your code.

The following example illustrates this error:

/**@com.interface(iid=31415926-5358-9793-2384-612345678901,dual)*/
interface Itest{
   /**@com.struct()*/
   public int method1();
   //error: wrong type of @com declaration applied
}


Compiler Error J0226

The @com declared type of 'identifier' is illegal for a dispatch or dual interface

The compiler detected that an @com interface declaration, declared as either a dual or dispatch interface, has a member that contains an @com.parameters declaration with an incorrect type. Certain @com.parameters types are not allowed when the interface they are defined in is declared as either a dual or a dispatch interface. The following list shows which values are invalid for type:

  • FIXEDARRAY

  • SYSFIXEDSTRING

  • I8

  • U8

  • STRUCT

  • CUSTOM, CUSTOMBYREF/CUSTOMBYVAL

  • PTR (except PTR to VARIANT)

  • Arrays of any of the above listed values

The following example illustrates this error:

/**@com.interface(iid=31415926-5358-9793-2384-612345678901,dual) */
interface Itest{
   /**@com.parameters([in,out] n , [type = I8] j); */
   /*error: cannot use 'I8' as a type in a dual
            interface */
   public void method1(int n, int j);
}


Compiler Error J0227

It is impossible for an expression of type 'identifier' to be an instance of 'identifier'

The compiler detected that a comparison of two classes using the instanceof operator could never be instances of each other. In order to use the instanceof operator correctly you must compare classes that have some common class lineage. Either change the expression containing the instanceof operator so that it uses a related class and instance for its comparison or remove the expression and compile again.

The following example illustrates this error:

class Simple1{
   //do something meaningful here
}

class Simple2{
   //do something meaningful here
}

class CompClasses{
   Simple1 x = new Simple1();
   public static void main(String args[]){

   if(smp.x instanceof Simple2){
      /*error: non related classes cannot be instances of each other*/
   }
}

The following example illustrates the correct usage of the instanceof operator to determine if a class instance is an instance of a specific class:

class Simple1 extends Simple2{
   //do something meaningful here
}

class Simple2{
   //do something meaningful here
}

class CompClasses{
   Simple1 x = new Simple1();
   public static void main(String args[]){

   if(smp.x instanceof Simple2){
      // This is OK since 'Simple1' is a subclass of 'Simple2'
   }
}


Compiler Error J0228

Syntax error in @dll declaration

The compiler detected a syntax error in an @dll comment tag. This error usually occurs when an @dll comment tag has been mistyped. Check the statement for syntactical errors and compile again.

The following example illustrates this error:

public class Simple{
   /**@dll.import(kernel32, ansi)*/
   /* error: missing quotes around 'kernel32' */

   public static native boolean GetComputerName(StringBuffer s, int[]cb);
}


Compiler Error J0229

Expected string constant

The compiler detected that a string constant parameter of a comment tag's declaration (for example @com, @dll, or @security) was either missing the string constant or the string constant was incorrectly entered. This error most often occurs when matching quotes are missing around a value passed to an attribute. Check your comment tag declaration's attributes and compile again.

The following example illustrates this error:

/**@com.interface(iid=31415926-5358-9793-2384-612345678901,dual)*/
interface ITest{
   /**@com.method(name=method1);*/
   //error: Missing quotes around 'method1'
   public void method1();
}


Compiler Error J0230

Class or interface name 'identifier' conflicts with import 'identifier'

The specified class or interface conflicts with a class that has been imported. This can be caused by declaring a class or interface that is already declared in the Java API, and you are trying to import that API class or interface into your source file.

The following example illustrates this error:

import java.lang.Cloneable;

class Cloneable{ /*error Cloneable has already been
                         imported */
   //class implementation
}


Compiler Error J0231

Expression statement must be assignment, method call, increment, decrement, or "new"

The compiler detected an invalid expression statement. An expression statement is a statement that can reside on its own line of source code. The following are some examples of valid expression statements:

m_cars.changeColor(); //Method calls
int x = y + z; //Assignment statements
j++; //Increment statement
m_tempVar1 += 3;
new Simple();

The following are examples of invalid expression statements:

1+2;  //error: No assignment statement
j+k-method1();  //A method call but not a valid assigment statement
var1 == var2;  /*Comparison statements should be contained in flow
                 control statements*/


Compiler Error J0232

Expected '{' or ';'

The compiler detected an error with a method declaration in a class or interface. This error usually occurs if an interface's method declaration is missing a semicolon at the end of the declaration or a class's declaration is missing its opening brace '{'. Check the specified class or interface method declaration and for a missing semicolon or opening brace and compile again.

The following example illustrates this error:

interface ISimple{
   public void method1()
   //error: missing semicolon to end declaration
}

public class Simple{
   public void method1()
   //error: missing opening brace
}


Compiler Error J0233

Catch clause is unreachable; exception 'identifier' is never thrown in the corresponding try block

The compiler detected that the specified catch clause will never be executed because the corresponding try statement block never throws the catch statement's exception type. Catch statements are required to catch exceptions or derivations of exceptions that the try statement block can throw. This error can be avoided by changing the catch statement so it does not catch a specific exception type, but instead, catches the base Exception class. Change the exception class your catch statement will trap and compile again.

The following example illustrates this error:

class Simple{
   void method1(){
      int I = 0;
      try{
         I = I + 1; //This try block has nothing to do with clones
      }
      catch (CloneNotSupportedException c){
         //error: The exception type can never be caused by try block
      }
   }
}

The following example illustrates how to avoid this error by using the base Exception class:

class Simple{
   void method1(){
      int I = 0;
      try{
         I = I + 1; //This try block has nothing to do with clones
      }
      catch (Exception e){
         //This is OK since all exceptions must derive from this class
      }
   }
}


Compiler Error J0234

'identifier' is not a field in class 'identifier'

The compiler detected a field reference but the field does not exist in the specified class. This error usually occurs when the field reference is mistyped or the field reference was meant to reference a field in a different class. Ensure that the field exists in the specified class, that your reference to the field is syntactically correct, and compile again.

The following example illustrates this error:

public class Simple{
   int var1;
   public Simple(){
       this.var = 10;
       //error: 'var' is not a field in this class
   }
}


Compiler Error J0235

'identifier' is not a method in class 'identifier'

The compiler detected a method call but the method does not exist in the specified class. This error usually occurs when the method call is called incorrectly or the method call was meant to reference a method in a different class. Ensure that the method exists in the specified class, that your method call is syntactically correct, and compile again.

The following example illustrates this error:

class Simple{
   public void method1(){
      //do something here
   }
}

class Simple2{
   public void method1(){
      Simple smp = new Simple();
      smp.method2();
      //error: 'method2' does not exist in the class 'Simple'
   }
}


Compiler Error J0236

'identifier' is not a nested class or interface in class 'identifier'

The compiler detected a reference to a nested class or interface but the nested class or interface does not exist in the specified class. This error usually occurs due to a syntactical error in referencing a nested class or interface. Check the reference to the inner class for syntax errors and ensure that the class or interface exists inside the specified class, and compile again.

The following example illustrates this error:

class NotSimple{
}

public class Simple{
   void method1(){
      NotSimple nt = new NotSimple();
      Object o = nt.new InnerClass();
      //error: 'InnerClass' is not an inner class of 'NotSimple'
   }
}


Compiler Error J0237

'identifier' is not a field or nested class in class 'identifier'

The compiler detected a reference to a nested class or field but the nested class or field does not exist in the specified class. This error usually occurs due to a syntactical error in referencing a nested class or field. This error can also occur if a reference to a field in an inner class is made but the field does not exist within the inner class definition. Ensure that the inner class or field exists and compile again.

The following example illustrates this error:

class Simple1{
   int var1;
}

class Simple2{
   static class InnerClass{
      int var1;
   }
   static Simple1 smp;
}

public class Simple{
   void method1(){
      int x, y;

      x = Simple2.innerclass.var1; /*error: 'innerclass' is not name of
                                  an inner class. 'InnerClass' is */
      y = Simple2.smt.var1; /*error: 'smt' is not the name of a field in
                         'Simple2'. Should be 'smp' */
   }
}


Compiler Error J0238

Cannot throw exception 'identifier' from field initializer

The compiler detected that an exception was thrown within a field initializer. This error usually occurs when an exception is throwable from a constructor of a class, and an instance of that class is declared and instantiated as a member of another class. To resolve this problem, have the class object that throws the exception instantiated inside a constructor so it can use a try/catch combination to trap any exceptions from the other class's constructor call.

The following example illustrates this error:

public class Simple{
   public int i;
   public Simple(boolean var1) throws Exception{
      if (var1 = true)
         i = 0;
      else
         throw new Exception();
   }
}
//This is the incorrect way to instantiate this class
class Simple2{
   Simple smp = new Simple(true);
   /* error: cannot call constructor that throws exception in field
            initializer*/
}

The following code replaces the 'Simple2' class code in the example above to show the correct way to instantiate the 'Simple' class instance:

//This is the correct way to instantiate Simple
class Simple2{
   Simple smp;
   public Simple2(){
      try{
         smp = new Simple(true);}
      catch(Exception e){}
   }
}


Compiler Error J0239

Static initializer must assign a value to blank final variable 'identifier'

The compiler detected that a static final variable was not initialized to a value using a static or field initializer. In order to declare a variable as static and final you must use a static or field initializer to set an initial value. This error can also occur if a field is declared as static and final and assigned a value in a constructor.

The following example illustrates this error:

public class Simple{
   static final int MAX_CONTROL;
} //error: static final variables must have value assigned


Compiler Error J0240

Syntax error in @security declaration

The compiler detected a syntax error in the specified @security comment tag. This error usually occurs when the comment tag is missing a closing parenthesis or the tag's attributes are incorrect. Ensure the syntax of the specified @security comment tag declaration is correct and compile again.

The following example illustrates this error:

/**@security()*/   //error: invalid @security syntax
public class Simple{
   //class members defined here
}


Compiler Error J0241

'@security' can only be specified on a class or interface

The compiler detected that the @security comment tag was applied to something other than a class or interface declaration. The @security comment tag is used to define the security settings for a class or interface definition and cannot be applied to methods or fields of a class or interface.

The following example illustrates this error:

public class Simple{
   /**@security(checkDllCalls=on)*/
   public void method1(){
   //error: cannot use @security tag on method
   }
}


Compiler Error J0242

Cannot make static call to non-static method 'identifier'

The compiler detected that a method was called by using the static method call syntax '<classname>.<method>', but the method is not a static method. Change the method call to use an instance of the class that contains the method instead of the class name itself and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      //do something here
   }
}

class NotSimple{
   public void methodx(){
      Simple.method1();
      //error: 'method1' is not a static method
   }
}


Compiler Error J0243

'identifier' is obsolete; use 'identifier' instead

The compiler detected a comment tag (for example @com, @dll, @security) that is using a format that is now considered obsolete. To avoid this error change the line of code that the error occurred on to the newer format specified in the error message and compile again.

The following example illustrates this error:

public class Simple{
   /**@dllimport("kernel32", ansi)*/
   /* error: 'dllimport' is no longer a supported format for
      @dll.import declarations */
   public static native boolean GetComputerName(StringBuffer s, int[]cb);
}


Compiler Error J0244

@conditional allowed only on void-returning methods

The compiler detected an @conditional comment tag for a method that has a non-void return value. The @conditional comment tag can only be used for methods without a return value. Change the method declaration to return void or remove the @conditional comment tag and compile again.

The following example illustrates this error:

public class Simple{
   /**@conditional(DEBUG)*/
   public int method1(int x){
      //error: conditional methods cannot return a value
   return x * 2;
   }
}


Compiler Error J0245

Warning treated as error

The compiler was run using the /wx switch, and a warning was found during compilation. The /wx compiler switch treats all warnings as errors. In order for the /wx compiler switch to display this error, the warning level switch (/w{0-4}) must be set high enough to display the warning. Determine the cause of the warning and compile again. You can also remove this switch from your compiler options and compile again.


Compiler Error J0246

Invalid token on a # directive

The compiler detected an invalid token for a conditional compilation expression. This error usually occurs when a token is mistyped or the token used is not a legal token. Ensure that the conditional compilation directive specified in the error is correct and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      #iff DEBUG //error: 'iff' is not a valid token
        System.out.println("Do something meaningful here");
      #endif
   }
}


Compiler Error J0247

#elif without matching #if

The compiler detected a #elif conditional compilation directive, but did not detect a matching #if directive. Ensure that you have a valid #if conditional compilation directive to match your #elif directive and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      //error: need to have '#if' before '#elif'
      #elif DEBUG
         System.out.println("Do something meaningful here");
      #endif
   }
}


Compiler Error J0248

#endif without matching #if

The compiler detected a #endif conditional compilation directive, but did not detect a matching #if directive. This error usually occurs because an extra #endif directive was supplied. This error can also occur when a #if conditional compilation directive was deleted or commented out but the matching #endif directive was not deleted. Ensure that you have matching directives and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      //#if SIMPLE
      //do something here
      #if DEBUG
          //do something here
          #if WIN95
             //do something here
          #endif
      #endif
      #endif //error: extra '#endif' directive not permitted
   }
}


Compiler Error J0249

#else without matching #if

The compiler detected a #else conditional compilation directive but, did not detect a matching #if directive. This error usually occurs because an extra #else directive was supplied. This error can also occur when a #if conditional compilation directive was deleted or commented out but a #else directive was not deleted. Ensure that you have matching directives and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      //do something here
      #else /*error: this '#else' directive has no matching '#if'
              directive */
   }
}


Compiler Error J0250

Already had an #else

The compiler detected a duplicate #else conditional compilation directive in a #if directive block. A #if directive can only have one #else directive. Ensure that you have only one #else conditional compilation directive for the #if directive in which the error occurred and compile again.

The following example illustrates this error:

public class Simple{
   #if A
     #if B
     void method1{
       //do something here
     }
   #else
     void method2{
       //do something here
   #else  //error: extra '#else' directive supplied
   #endif
}


Compiler Error J0251

Unexpected EOF while looking for #endif

The compiler detected a #if conditional compilation directive but did not find a matching #endif directive, and the symbol used by the #if directive was not defined. This error usually occurs when a #if conditional compilation directive is used but a matching #endif directive was not defined to close the conditional compilation block. Ensure that you have a matching #endif directive for the #if directive specified in the error and compile again.

The following example illustrates this error:

public class Simple{
   void method1(){
      #if DEBUG //debug has not been defined
         System.out.println("Do something here");
   //error: '#endif' not specified for the '#if' directive
   }
}


Compiler Error J0252

#if nested too deeply

The compiler detected nested #if conditional compilation blocks that were nested too deeply. Nesting of #if conditional compilation blocks is limited to 64 levels. Ensure that your nesting of #if blocks is within the limit and compile again.


Compiler Error J0253

Cannot have #define/#undef after source

The compiler detected a #define or #undef conditional compilation directive after other Java source code. The #define and #undef directives must be placed before other Java source code (except for other conditional compilation directives and source comments). Move the #define or #undef directive indicated by the error to the front of all Java source code in the file and compile again.

The following example illustrates this error:

package boxes;

#define DEBUG
//error: '#define' must occur before the 'package' statement

public class Simple{
}


Compiler Error J0254

Cannot change predefined symbol

The compiler detected an attempt to use the #define or #undef directive on a symbol already defined in Java. This error occurs when a symbol such as true or false, which are already defined for conditional compilation, is redefined using the #define or #undef conditional compilation directives. Remove or change the #define or #undef directives specified in the error and compile again.

The following example illustrates this error:

#undef false //error: cannot undefine the 'false' symbol
#define true //error: cannot define the predefined 'true' symbol

public class Simple{
   //do something here
}


Compiler Error J0255

Expected #endif

The compiler detected a #if conditional compilation directive but did not find a matching #endif directive; however, the symbol used by the #if directive was defined. This error usually occurs when a #if conditional compilation directive is used but a matching #endif directive in not defined to close the conditional compilation block, and the code is intended to be compiled. Ensure that you have a matching #endif directive for the #if directive specified in the error and compile again.

The following example illustrates this error:

#define DEBUG

public class Simple{
   void method1(){
      #if DEBUG
         System.out.println("Do something here");
   //error: '#endif' has not been specified for the '#if' directive
   }
}


Compiler Error J0256

Expected 'class', 'interface', or 'delegate'

The compiler expected to find the class, interface, or delegate keywords used within the corresponding declaration. This error usually occurs when the keywords are accidentally omitted from a class, interface, or delegate declaration. Another possible cause of this error is unbalanced scoping braces.

Note This error will only occur if the Microsoft Extensions are enabled in your project. Otherwise, compiler error J0020 will be displayed.

The following example illustrates this error:

public Simple{ //error: missing the 'class' keyword
   //Do something here
}

This example illustrates this error caused by unbalanced scoping braces:

public class Simple {

   // do something meaningful

}}   // error: additional '}' is not permitted


Compiler Error J0257

Delegate cannot be initialized with static method 'identifier'

The compiler detected a delegate instantiation but the method reference, passed as a parameter, was a static method. When instantiating a delegate, you must pass a non-static method as a parameter. Ensure that the method you are defining the delegate to use is a non-static method and compile again.

The following example illustrates this error:

delegate int MyDelegate (int var1, String var2)throws Exception;

public class Simple{

   public static int method1(int var1, String var2) throws Exception{
      //do something here
      return var1;
   }

   public static void main (String args[]){
      Simple smp = new Simple();
      MyDelegate md = new MyDelegate(smp.method1);
      /*error: the method passed as a parameter to the delegate is a
               static method */
   }
}


Compiler Error J0258

Cannot declare delegate in inner class 'identifier'

The compiler detected an attempt to declare a delegate inside an inner class. Inner class definitions do not support delegates declared within them. Remove the delegate declaration from within the inner class declaration and compile again.

The following example illustrates this error:

public class Simple{
   //Do something meaningful here
   class InnerClass{
   //Do something meaninful here
      delegate int MyDelegate (int var1, String var2);
         /*error: delegates cannot be declared
                  inside inner classes */
   }
}


Compiler Error J0259

Exception 'identifier' from method 'identifier' is not a subclass of any exceptions declared thrown by delegate 'identifier'

The compiler detected a delegate that was initialized with a method that throws an exception that is incompatible with the delegate's declared set of exceptions. Each exception thrown by the method must be the same class or a subclass of an exception that the delegate throws. Change the set of exceptions thrown by either the delegate or the method and compile again.

The following example illustrates this error:

delegate void SimpleDelegate(String var1) throws Exception;

public class Simple{
   public void method1(String var1) throws Throwable{
      //do something here
   }
   public static void main (String args[]){

      Simple smp = new Simple();
      SimpleDelegate del1 = new SimpleDelegate(smp.method1);
      /* error: the method reference argument throws an exception that is
             not the same or a subclass of the exception declared by the
             delegate */
   }
}


Compiler Error J0260

Cannot declare an interface method to be 'protected' or 'private'

The compiler detected an interface with a method declared as protected or private. Interface methods must be declared as either public or with no access modifier (default). Change the interface method declaration specified in the error so that it is not declared protected or private and compile again.

The following example illustrates this error:

interface ISimple{
   public void method1(); //this is OK!
   void method2(); //this is OK! Declared as "default" access
   protected void method3(); /*error: cannot declare interface method as
                                      protected */
   private void method4(); /*error: cannot declare interface method as
                                    private */
}


Compiler Error J0261

An explicit enclosing instance of class 'identifier' is needed to instantiate inner class 'identifier'

The compiler detected an attempt to create an instance of an inner class without specifying an instance of its enclosing class. This error usually occurs when an attempt is made, within a static method, to instantiate an inner class as you would an outer class. To create an instance of an inner class, you must use an existing instance of its outer class. Create an instance of the enclosing class and use it to instantiate the inner class and compile again.

The following example illustrates this error:

public class Simple{
   class InnerClass{
      //do something here
   }

   public static void main(String args[]){
      InnerClass inc = new InnerClass();
      /*error: an instance of the outer class is required to instantiate
               its inner class */
   }
}

The following example illustrates how to create an instance of an inner class using an instance of its outer class:

public class Simple{
   class InnerClass{
      //Do something here
   }
   public static void main(String args[]){
      Simple smp = new Simple();
      /*use the instance of 'Simple' to create an instance of its inner
        class*/
      InnerClass inc = smp.new InnerClass();
   }
}


Compiler Error J0262

An explicit enclosing instance of class 'identifier' is needed to call constructor of superclass 'identifier'

The compiler detected an attempt by a derived class to call its superclass constructor without an instance of the superclass. This error usually occurs because the superclass is also an inner class. When a derived class is instantiated, an instance of its superclass is also created (and the superclass constructor is invoked). In order to create an instance of an inner class you must instantiate the inner class using an instance of its outer class.

The following example illustrates this error:

class OuterClass{
   class InnerClass{
   //do something here
   }
}

public class Simple extends OuterClass.InnerClass{
   //do something here
}
/*error: superclass 'InnerClass' cannot be instantiated without its outer class 'OuterClass' being instantiated */

The following example illustrates how to instantiate a class that is derived from an inner class:

class OuterClass{
   class InnerClass{
   //do something here
   }
}

public class Simple extends OuterClass.InnerClass{
   Simple(){
      /*this line creates an instance of the outer class and calls
        the superclass (the inner class) constructor */
      new OuterClass().super();
   }
}


Compiler Error J0264

Array cannot have a dimension

The compiler detected an attempt to initialize an array dimension incorrectly. This error usually occurs when an array dimension size is specified before the instance is created. This error can also occur when an array is given a dimension in the proper place but an initialization list is also provided to set the values of the array (you cannot specify an array size for the dimension when using an initialization list). Correct the initialization of the array specified by the error and compile again.

The following example illustrates this error:

public class Simple{
   public void method1(){
      String[3] var1; /* error: cannot specify array size here since
                         array is not instantiated yet */
      String[] var2 = new String[3]; //this is OK!

      boolean var3 = new boolean[3]{true,false,true};
      /*error: cannot specify an array size for the dimension when using
               an initialization list */
      boolean var4 = new boolean[]{true, false,true}; //this is OK!
   }
}


Compiler Error J0265

@dll attribute cannot be placed on method 'identifier' — it must be declared 'native'

The compiler detected an @dll comment tag placed on a method that is not declared with the native modifier. This error usually occurs if an @dll comment tag is defined but the method it was applied to was removed or commented out, and other methods in the class can have the comment tag applied to them. Ensure that the method declared with the @dll comment tag is declared as native or remove the @dll comment tag and compile again.

The following example illustrates this error:

public class Simple{
   /** @dll.import("USER32") */
   //private native static int MessageBox(int hwndOwner, String text,
                                          String title, int fuStyle);

   /*error: the @dll comment tag cannot applied to 'method1' which is a
            non-native method instead of the intended native method*/
   public void method1(){
     //do something here
   }
}


Compiler Error J0266

Compilation canceled by user

The user canceled compilation. This error simply informs the user that the request to cancel compilation was successful.


Compiler Error J0267

A delegate cannot be 'identifier'

The compiler detected an attempt to declare a delegate with an invalid modifier. Only the public and final modifiers can be applied to a delegate declared outside of a class. A delegate declared within a class can have the public, final, protected, and private modifiers applied. Ensure that your delegate declaration is not using an invalid modifier and compile again.

Note Although you can use the final modifier in a delegate declaration, it is not needed as delegates are implicitly final.

The following example illustrates this error:

private delegate void Simple(int var1, int var2);
//error: cannot declare a delegate as 'private'


Compiler Error J0268

A delegate cannot be 'identifier' and 'identifier'

The compiler detected a delegate declaration, within a class, attempted to use a combination of access modifiers that are not allowed. This error usually occurs when a delegate is declared with two access modifiers applied. Remove the additional access modifier applied to the specified delegate declaration and compile again.

The following example illustrates this error:

public class Simple{
   public private delegate void SimpleDelegate();
   //error: cannot declare a delegate to be 'public' and 'private'
}


Compiler Error J0269

Ambiguous name: inherited 'identifier' and outer scope 'identifier' — an explicit 'this' qualifier is required

The compiler detected reference to a variable or method from within an inner class that is defined in both its outer class and its superclass. The compiler cannot determine which variable or method is to be used. You can reference the outer class variable or method by using class.this.name, where class is the name of the outer class whose variable or method you wish to reference and name is the variable or method name. To reference the superclass variable or method you can use the this super keyword before the reference.

The following example illustrates this error:

class NotSimple{
   int var1 = 20;
}

public class Simple{
   int var1 = 10;
   class InnerClass extends NotSimple{
      int var2 = var1;
      //error: cannot determine which 'var1' to use
   }
}

The following example illustrates how to resolve name ambiguity between the outer class and superclass variables:

class NotSimple{
   int var1 = 20;
}

public class Simple{
   int var1 = 10;
   class InnerClass extends NotSimple{
      int var2 = Simple.this.var1;
      //this is OK and references the outer class variable
      int var3 = super.var1;
      //this is OK and references the superclass variable
   }
}


Compiler Error J0270

The compiler detected an ambiguous reference to a field. This error usually occurs when a class's superclass and an interface the class implements have the same field declared. The compiler cannot determine which instance of the field to use. Ensure that you do not have a superclass and implemented interface that have the same field defined and compile again.

The following example illustrates this error:

public class Simple extends SuperClass implements SuperInterface{
   public static void main (String args[]){
      float x = var1; /*error: cannot determine which instance of 'var1'
                               to use */
   }
}

class SuperClass{
   float var1;
}

interface SuperInterface{
   float var1=6.0f;
}


Compiler Error J0271

Expected 'delegate'

The compiler detected the multicast modifier but did not detect the delegate keyword. The multicast modifier can only be used in conjunction with the delegate keyword to create multicast delegates. Ensure that you have the delegate keyword in the declaration specified by the error message and compile again.

The following example illustrates this error:

public multicast void SimpleDelegate(String x, int y);
//error: the 'delegate' keyword is missing after the 'multicast' modifier
public class Simple{
   //Do something here
}


Compiler Error J0272

A multicast delegate cannot return a value

The compiler detected a return type other than void for a multicast delegate declaration. Although delegates can return a value other than void, multicast delegates cannot return a value other than void. Ensure that the multicast delegate declaration specified by the error returns void and compile again.

The following example illustrates this error:

multicast delegate int SimpleDelegate(int x, int y);
//error: cannot declare multicast delegate with non-void return type
public class Simple{
   public int method1(int x, int y){
      //Do something here
   }

   public static void main (String args[]){
      Simple smp = new Simple;
      SimpleDelegate sd = new SimpleDelegate(smp.method1);
   }
}


Compiler Error J0273

The compiler detected an attempt to cast the return value of a method call to void. Casting a method call to void is not allowed in the Java language. Remove the void cast for the method call specified by the error and compile again.

The following examples illustrates this error:

public class Simple{
   public void method1(){
      //Do something meaningful here
   }
   public static void main (String args[]){
      Simple smp = new Simple();
      (void) method1();
      //error: cannot cast method's return value to 'void'.
   }
}


Compiler Error J0274

Expected 'identifier' within single comment preceding class 'identifier'

The compiler detected that the class, specified in the error message, was declared with either the @com.typeinfo or @com.transaction comment tag and a corresponding @com.register comment tag was not found within the same comment. This error can occur when an @com.register comment tag is declared but is within a separate comment. Ensure that an @com.register comment tag is defined within the same comment as the @com.typeinfo or @com.transaction comment tags defined for the class specified in the error message and compile again.

The following example illustrates this error:

/** @com.register ( clsid=AE032C46-E6A0-11d0-8C83-00C04FC2AAE7) */
/** @com.typeinfo(attrid=31415926-5358-9793-2384-612345678901,
value="Help") */
public class Simple{
   /error: the '@com.register' tag is ignored since it is in a separate
           comment */
}

/** @com.register ( clsid=AE032C46-E6A0-11d0-8C83-00C04FC2AAE7)
    @com.typeinfo(attrid=31415926-5358-9793-2384-612345678901,
value="Help")*/
public class Simple2{
   //This comment is OK. It combines both tags in a single comment.
}


Compiler Error J0275

Class or interface name 'identifier' conflicts with package 'identifier'

The specified class or interface name conflicts with a package name. This error can be caused by declaring a class or interface within a package with the same name as a subpackage. Rename either the subpackage or the class or interface that is causing the ambiguity and compile again.

The following example illustrates this error:

//located in a file called Plastic.java
package Boxes.Dishes;
public class Plastic{
   //do something here
}

//located in a file called Dishes.java
package Boxes;
public class Dishes{
   //error: the name 'Dishes' is also the name of the subpackage
}


Compiler Error J0500

#error 'user defined error'

This error message is generated when there is a #error conditional compilation directive in the program.

The following example illustrates this error:

#define DEBUG
public class Simple{
   public void method1(){
      #if DEBUG
         #error You should not be running in debug mode here!
         //error: displayed when 'DEBUG' is defined
      #endif
   }
}


Compiler Warning J5001

Local variable 'identifier' is initialized but never used

The compiler detected an initialized variable that was not referenced in any class code. This message occurs at warning level 3 or greater. Use the variable or remove its declaration.

The following example illustrates this warning:

public class Simple {

   public int method1() {

      int i = 1;
      return 1;
      // warning: 'i' is never used
   }
}


Compiler Warning J5002

Compiler option 'identifier' is not supported

The compiler detected that an unsupported command line option was specified. Check your compiler switch settings and compile again.


Compiler Warning J5003

Ignoring unknown compiler option 'identifier'

The compiler detected an unknown option specified on the JVC command line. This warning usually occurs when a typographical error exists. For example, specifying /W4 on the command line will cause this warning because the warning level option must use a lowercase 'w'.


Compiler Warning J5004

Missing argument for compiler option 'identifier'

The compiler detected a valid command line option, but the required argument was not specified. Check your compiler switch settings and compile again.


Compiler Warning J5005

Package 'identifier' was already implicitly imported

The compiler detected an import statement for a package that was already implicitly imported, such as java.lang. This message occurs at warning level 1 or greater.

The following example illustrates this warning:

import java.lang.*;
//warning: process is already imported in the first import statement
import java.lang.Process;

public class Simple{
   //Do something meaningful here
}


Compiler Warning J5006

'private protected' not supported, using 'protected'

The compiler detected use of the modifier combination private protected. This combination is now obsolete and has been replaced by protected. This message occurs at warning level 1 or greater.


Compiler Warning J5014

'identifier' has been deprecated by the author of 'identifier'

The method or class referenced has been marked as deprecated. Deprecated methods or classes are marked by the creator of the source code as outdated and subject to removal. To keep code stable, avoid calling functions that have been flagged as deprecated.


Compiler Warning J5015

The parameter 'identifier' in an @com.parameters declaration does not match the corresponding argument 'identifier'

An @com.parameters declaration does not match the method that implements the interface. This error could indicate data type inconsistencies or mismatched parameter locations. Ensure that your @com.parameters declaration has the same number of parameters, the correct types, and correct order with the method being declared and compile again.

The following example illustrates this warning:

/** @com.interface(iid=31415926-5358-9793-2384-612345678901, dual) */
interface ExampleInterface
{
/**
@com.method(dispid=306)
@com.parameters([type=BOOLEAN] when, on)
*/
//error: @com.parameters declaration has parameters in wrong location

public String Method1(boolean on, int when);
}


Compiler Warning J5016

This 'instanceof' operator will always be true

The compiler determined that the specified instanceof expression will always evaluate to true. This can occur when instanceof is used to determine if a subclass instance is a member of a base class or an implemented interface. Although it is not an error to use the instanceof operator in this fashion, it's not particularly useful since the expression will always evaluate to true.

The following example illustrates this warning:

interface I {}
class X {}
class Y extends X implements I {}

public class Simple{
   void f()
   {
      Y y = new Y();
      X x = new X();
      Object o;

      // These statements give J5016 warnings...
      if (y instanceof X){
         // y is of type Y, which extends X, so this is always true
      }
      if (y instanceof I){
         // type Y implements I, so this is always true.
      }
      if (x instanceof Object){
         // everything is of type Object
      }
   }
}


Compiler Warning J5018

Class, interface, or package name contains characters not in the ASCII character set

The compiler detected a character that is not in the ASCII character set used for a class, interface, or package name. Some computer systems may not support this character. To ensure that your class, interface, or package name can be interpreted by Virtual Machines (VM) on other computer systems, change the invalid character to a valid character from the ASCII character set and compile again.


Compiler Warning J5019

Public member of COM-exposed class or interface contains characters not in the ASCII character set

The compiler detected a character that is not in the ASCII character set used for a method or field that is accessible to other languages via COM. Other languages may not support this character. To ensure that your member name can be accessed from other languages, change the character to a valid character from the ASCII character set and compile again.


Compiler Warning J5020

Directive 'identifier' ignored -- extensions are turned off

The compiler detected a comment tag such as @com or @dll applied in your source code but Microsoft Language Extensions were disabled. In order to use comment tags and other Microsoft Language Extensions, the extensions option must be enabled.

! WARNING With the Microsoft Language Extensions option disabled, any code that utilizes Microsoft Language Extensions may not work correctly.

The following example illustrates this warning:

//Microsoft Language Extensions are 'disabled'
public class Simple{
   /**@dll.import("User32")*/
   public static native int MessageBox(int hWnd, String text, String
                                       caption, int type);
   //warning: the 'MessageBox' method may not work correctly


Compiler Warning J5021

Package 'identifier' should not be defined in directory 'identifier'

The compiler detected a package statement in your source file but the directory name where the source file resides does not match the package statement. Although the source code will compile, other source files will not be able to reference classes, interfaces, and delegates defined in this source file using the package name.

The following example illustrates this warning:

//source file resides in c:\files\simple
package boxes; //warning: package 'boxes' does not match directory name
'simple'
public class NotSimple{
  //warning: this class is not accessible using the current package name
}


Compiler Warning J5022

Referenced class file 'filename' may be older than 'filename'

The compiler detected a class file, which is referenced by the source file being compiled, that is out of date or not found. This warning usually occurs when automatic re-compilation of referenced classes has been disabled (using the ref- compiler option). If you are compiling within Visual J++, the ref- option is passed to the compiler by default. If any of your source files reference a class file that is not in your project and the file is out of date with its source, you will need to update the referenced class files. You can either recompile the external class files to make them up to date, add the external files to your project, or add the ref compiler option. You can add the ref compiler option by entering it in the Additional Compiler Options text box in the Compile tab of the Project Settings dialog box.


Compiler Warning J5023

File 'filename' has more than 65535 lines--debug information may be incorrect

The compiler attempted to place debugging information in a source file that contains more than 65535 lines of code. Your code may compile, however; not all the debugging code needed for your application will be contained in this file. Reduce the size of your source file so that the debugging information can be added and compile again.


Compiler Warning J5024

Package 'identifier' was already imported

The compiler detected a package imported more than once in the specified source file. Although this will not cause the compiler to fail, you should remove the extra import statement for the package specified in the warning message.


Compiler Warning J5500

#warning 'user defined warning

This warning message is generated when there is a #warning conditional compilation directive in the program.

The following example illustrates this error:

#define DEBUG
public class Simple{
   public void method1(){
      #if DEBUG
         #warning You are compiling for debug mode
         //warning: displayed when 'DEBUG' is defined
      #endif
   }
}


COM Registration Errors (Visual J++)

During registration of a COM class, you may be prompted with an error or warning message. The following is a list of the more common errors and warnings. Each error or warning includes information as to the possible reasons the error occurred and, where applicable, suggestions on how to resolve the error or warning.

No registration attribute in class file 'filename'

Registration of the class file referenced in the error message was attempted but the class file did not contain a @com.register comment tag. Ensure that the COM class in the class file you are attempting to register has a valid @com.register comment tag.

Cannot create instance of class 'identifier'

In order to create a type library and register your COM class, a class must be able to be instantiated and call the standard constructor (the constructor that does not contain any parameters). This error can occur if any dependent classes of your COM class cannot be located or if there is an error in the standard constructor for your class. Ensure that the dependent classes for your COM class can be accessed and that your class's standard constructor contains no errors.

Cannot open filename 'filename'

During the COM registration process, a temporary type library file is generated. This error occurs when the temporary filename cannot be copied and renamed to the final type library name.

Unable to create registry keys for class 'identifier'

While attempting to register your COM class, the COM registration process could not create a key in the system registry. This error can also occur if the COM registration process cannot open a specific key or write a value into the registry. Ensure that your system registry is not damaged.

Class file 'filename' does not have the extension '.class'

In order to register a COM class, the compiled class file must have the ".class" extension. This error can also occur if the file to be registered as a COM class is not a valid Java class file. Ensure that the class file you are attempting to register as a COM class contains the ".class" extension and that it is a valid Java class file.

The internal class name 'identifier' does not match the file or directory name of class file 'filename' -- it cannot be loaded

The COM class that is being registered has a different class name than the class file it is located in, or the class file is located in a directory that conflicts with the class's defined package. Ensure that the COM class name and its defined package match the location and name of the class file.

Classes contain more than one type library id. Only one type library can be created at a time

Only one type library can be specified in your Visual J++ project at a time. This error usually occurs when a COM class's @com.register comment tag has a different typelib GUID than the other COM classes in your project. All COM classes in a project must have the same typelib GUID specified. You can resolve this conflict by clearing the check box next to the class in the COM Classes tab of the Project Properties dialog box, apply the changes, and then recheck the check box for the class. This will reassign the class as a COM class and specify the same typelib GUID.


Windows EXE/COM DLL Packaging Errors (Visual J++)

During the creation of a Windows EXE or COM DLL, you may be receive an error message. The following is a list of the error messages that might occur. Each error includes information as to the possible reasons the error message occurred and, where applicable, suggestions on how to resolve the error message.

Path too long: 'path'

The path and filename of a Windows EXE or COM DLL is larger than 256 characters. Reduce the size of the path and filename and rebuild your project.

No main class file specified

An attempt was made to create a Windows EXE but a main class (a class with a main method defined) was not specified. In order for a Windows EXE to be created, you must specify a main class in the Launch tab of the Project Properties dialog box.

No class files found

An attempt was made to create a Windows EXE or COM DLL but no class files were found or specified to create the EXE or DLL. Ensure that your project contains at least one class file and that a class file is specified in the Output Format tab of the Project Properties dialog box.

Unable to open output file: 'filename'

The file specified in the error message could not be opened. Ensure that the specified file is not read-only or in use by another program. This error can also occur if the specified file is located in a directory in which you do not have write permission.

Unable to update resources in file: 'filename'

An attempt was made to write resource information to the resource file specified in the error message, but was unable to update the resource file. Ensure that you have enough available free disk space on your computer.

Badly formatted class file: 'filename'

The class file specified in the error message is in an invalid format. This error usually occurs when a class file is damaged or is a file with the class extension, but is not a valid Java class file. Delete the class file specified in the error message and rebuild your project.

File not found: 'filename'

The file specified in the error message was not found. Ensure that the proper location of the file is specified in the Output Format tab of the Project Properties dialog box and rebuild your project.

Unable to load resources from file 'filename'

The resource file specified in the error message could not be opened. Ensure that the resource file is a valid Windows resource file and that the resource file is not in use by another program.

Unable to read typelib file 'filename'

The type library file specified in the error message could not be opened. Ensure that the type library file is a valid type library file and that the file is not in use by another program.

Corrupt registration attribute in class 'identifier'

A COM registration attribute for the class specified in the error message is corrupted. This error usually occurs when the class file for the specified class is damaged or in an invalid file format. Delete the class file for the specified class and rebuild your project.

Class 'identifier' does not have a method of the form 'static public void main (String[])'

A class was specified as the main class of a Windows EXE, but the class did not contain a main method. The main method provides a starting point for the Windows EXE and must be specified. Add a main method to the class specified in the error message or choose a different main class in the Launch tab of the Project Properties dialog box and rebuild your project.

Main class name 'identifier' is too long

The main class name specified in the error message is larger than 256 characters. Reduce the size of the class name and rebuild your project.

Specified main class 'identifier' not found

While creating a Windows EXE file, the class specified as the main class for the Windows EXE was not found. This error usually occurs when a main class was specified in the Launch tab of the Project Properties dialog box, but the main class has been removed or renamed from the class file. Specify a new main class in the Launch tab of the Project Properties dialog box and rebuild your project.

Unable to read from file 'filename'

The file specified in the error message could not be opened for reading. Ensure that the specified file is not in use by another program.

Cannot create a DLL with no COM classes

An attempt was made to create a COM DLL, but the project does not contain any COM classes. You can create a COM class by selecting a class from the list of classes in the COM Classes tab of the Project Properties dialog box. If you do not wish to expose any of your classes as COM classes, change the type of package you want to create in the Output Format tab of the Project Properties dialog box and rebuild your project.

Failure during auto-registration of 'filename'

A COM DLL failed to auto-register after being created. This error usually occurs when the system registry is damaged.

Out of memory

Insufficient memory was available when creating a Windows EXE or COM DLL. Close other programs that are currently running to provide more available memory and rebuild your project.


Class Outline

Class Outline provides a graphical tool for navigating and manipulating the interfaces, delegates, classes, and class members of the individual Java source files in your project. It provides the ability to quickly gain access to elements in your classes and other files that are related to your classes.

With Class Outline you can:

  • Double-click a class, interface, delegate, method, or field name to take you to the section of the source file where the selected element is defined.

  • Double-click a package class, imported class, superclass, implemented interface, or inherited member to take you to its source code, if available, or to its entry in the Object Browser.

  • Use the shortcut menus to set breakpoints on class members.

  • Use the shortcut menus to override superclass members inherited by your class.

  • Use the shortcut menus to cut, copy, paste or delete classes, delegates, interfaces and their members from the source file.

  • Use the shortcut menus to display the Class Builder for adding classes and members to the source file.

Elements

The Class Outline is displayed when a Java source file is opened for editing. The Class Outline tree contains nodes for each class, delegate, and interface found in the source file. The following is a list of the nodes and items that can be found in the Class Outline, depending on the code in your source file.

Package Node

The first node in the tree is the Package node. It is labeled as Default Package (when the source is not in a specific package) or it has the name of the package as defined by the package declaration in your source code. If the source file is a member of a specific package, the node expands to display all the class names in the package. Otherwise, the package node displays all the classes in the project directory.

Imports Node

The Imports node displays all the classes that are imported using the import keyword in the source file. This node is not visible if the source file does not import other classes.

Class and Interface Nodes

Each class, delegate, and interface that are defined in the current source file is listed as a node in the Class Outline tree. Expanding a class, delegate, or interface node displays the methods and fields that are defined in the class, delegate, or interface definition. An icon is associated with each member to identify its access level and member type. See Class Outline Icons for a list of the icons and their meanings.

Superclasses

The Superclasses node is displayed under each class and lists all the classes that the current class extends, explicitly or not.

Inherited Members

The Inherited members node is displayed under each class and provides a list of all the methods that the class has inherited from its superclasses.

Implemented Interfaces

The Implemented Interfaces folder is added if a class implements any interfaces. The names of the interfaces that the class implements are displayed in this folder.

Nested and Member Classes

The Nested or Member Classes node is added if a class has any nested classes or interfaces defined in its implementation. When a nested class or interface node is expanded, it displays the same information that an outer class or interface displays.

Note Nested classes and interfaces that are defined within a method are not displayed, since they are local to the method.

Initializers

The Initializers folder is displayed if a class declaration includes any initializer blocks. This folder contains a list of the static and instance initializers in the selected class. Each initializer item displays the intializer's type and a section of the initializer code.

Javadoc Pane

If a class is selected that contains Javadoc comments, the Javadoc pane (located below the Class Outline tree) displays the first sentence of the comment.

Class Outline Icons

Icons are used throughout Class Outline to help identify elements of the source file. The following table identifies each icon and its meaning in the Class Outline.

Icon | Meaning
 | Package
 | Imported Package
 | Imported Class
 | Class
 | Interface
 | Superclass
 | Delegate
 | Inherited Method
 | Inherited Variable
 | Member Class
 | Initializer
 | Variable
 | Method
 | Protected Access
 | Private Access
 | Package Access
 | Error (This icon is displayed when a superclass or implemented interface could not be found)
 | Circular Reference (This icon is displayed when a class is its own superclass)


Project Explorer (Visual J++)

Project Explorer is a graphical navigation tool for accessing the different files in your Visual J++ project.

Project Explorer allows you to view the files that make up your project. Because Visual J++ projects are directory based, Project Explorer is dynamic. Files that are added to your Visual J++ project directory are automatically added to Project Explorer. When directories are added to a Visual J++ project, Project Explorer treats the directory as a package where groups of source files and other project support files can be added and maintained.

When a Visual J++ project is selected in Project Explorer you can:

  • Open a source file in either the source editor or the graphical editor (if the source file supports graphical editing).

  • Use the shortcut menus to add a package to a project.

  • Display all files in your project directory or only those that are considered part of your project.

  • Display a project in one of two views, Directory View or Package View.

  • Use the shortcut menus to add, remove, or delete items from a project.

  • Use the shortcut menus to set configuration options for a project.

Views

Two views are available in Project Explorer when a Java project is selected: Package View and Directory View. The views are designed to make finding elements of a project easier. You can change the view to Directory View by clicking the Directory View button in Project Explorer or by clicking Directory View on the Project menu. You can change the view to Package View by clicking the Package View button in Project Explorer or by clicking Package View on the Project menu.

Directory View

The default view for Project Explorer is Directory View. It displays the editable files and directories that make up your Visual J++ project structure. Files that are not directly editable in Visual J++ are filtered out by default. You can view all the files that are in your project directory structure, including files that are filtered out, by selecting the Show All Files button or clicking Show All Files from the Project menu. Files can be removed from the project, but kept in the project's directory structure. To remove a file from the project right-click on the file you wish to remove and click Remove From Project on the shortcut menu. When a file is removed from a project, its icon is shaded and cannot be opened for editing in Visual J++. If you want to add a file that is not currently in your project but is located in your project directory, click the Show All Files button to display all files in your project directory structure. Right-click on the file that you want to add to your project, and then click Add To Project on the shortcut menu. The file is now added to your project.

Package View

Package View displays all the packages in your project and their source files. Unlike Directory View, packages located under the project directory are not displayed as sub-items of the project, but instead are displayed as items directly under the project name. Each package is displayed using the package's declared name (for example PackageA.PackageB) instead of just the directory name in which the package's source files are located. Package View allows you to view the project as another Java program would view your project — as a group of packages. Also, unlike Directory View, Package View only displays Java source files. Non-Java source files are filtered out in Package View. If a non-Java source file is added while in Package View, the file will only be displayed until your Project Explorer view is changed. Since only Java source files are displayed in Package View, the Show All Files button is disabled.

Note If a directory within your project directory structure does not contain a Java source file, it will not be displayed in Package View. Only directories that contain at least one Java source file are displayed in Package View.


Launch Tab (Project Properties Dialog Box)

The Launch tab allows you to choose a class file, HTML page, or external program to use when your project is run inside Visual J++.

From the Launch tab you can:

  • Choose the class file or HTML page that will be used as a starting point when your project is run from within Visual J++.

  • Determine whether Java applications will run using a console window or the Visual J++ Output window for program output.

  • Start a separate program (instead of Internet Explorer, JVIEW, or WJVIEW) when your project is run from inside Visual J++.

Options

Configuration

This option contains a list from which you can select your build type. This setting is global to all the tabs in this dialog box.

Your choices are:

  • Debug – This is the version of your application that includes information to assist in debugging.

  • Release – This is the version of your application that will be distributed to your users.

  • All Configurations – This option is used to make setting changes global to all build types.

Default Section

This option allows you to choose a class file (which is the compiled output of your Visual J++ project source files) or an HTML page to run, as well as the application it will run inside.

Project File to Run List

This list provides the names of the class files and HTML pages that can be run from within Visual J++. You can select a class file that contains a class with a properly defined main method (such as an application project), a class file that contains a class that extends the java.applet.Applet class (such as an Applet project), or an HTML file.

Program

Displays the program that will host the selected file from your project when it is run. This could be JVIEW (for applications and applets), Microsoft Internet Explorer (for HTML files) or WJVIEW (for Java applications displaying windows). This text box cannot be modified.

Arguments

Lists the arguments that are passed to the program specified in the Program text box. This text box cannot be modified.

Launch as a Console Application

Allows you to determine whether your application will display its output in a standard console window or in the Visual J++ environment. When this option is checked, all output is displayed in a console window. When this option is not checked, the Java program runs in the Visual J++ environment and all output is sent to the Visual J++ Output window. This option is only enabled when a Java class file is selected from the Executing File List. The default value for this option is unchecked.

Other Executable Section

Allows you to run a completely different executable program when your Java program starts.

Program

The path and name of the executable to be started.

Arguments

The arguments that are passed to the program when it starts.


Compile Tab (Project Properties Dialog Box)

The Compile tab allows you to make changes to the compiler settings.

From the Compile tab you can:

  • Make general compiler settings.

  • Disable Microsoft extensions from being compiled.

  • Set conditional compilation identifiers with which you want to compile.

  • Specify the root directory where class files will be generated.

Options

Configuration

This option contains a list from which you can select your build type. This setting is global to all the tabs in this dialog box.

Your choices are:

  • Debug – This is the version of your application that includes information to assist in debugging.

  • Release – This is the version of your application that will be distributed to your users.

  • All Configurations – This option is used to make setting changes global to all build types.

Warning Level

Use this option to choose warning levels for your project. The levels range from no warning to warning level 4. The higher the level, the more sensitive the compiler will be. The following is a list of the different warning levels and their meaning.

Warning level | Description
None | Turns off all warning messages.
Level 1 | Displays only severe warning messages.
Level 2 | Displays warning messages less severe than Level 1. (Default)
Level 3 | Displays warning messages less severe than Level 2. For example, not initializing a local variable or specifying an invalid compiler setting.
Level 4 | Displays all warning messages.

Disable Microsoft Language Extensions

When selected, this option directs the compiler to disallow Java language extensions defined by Microsoft. Language features such as conditional compilation will be treated as syntax errors if encountered in your source files.

Note Disabling Microsoft language extensions from your projects may not result in syntax errors with comment-based extensions like J/Direct. However, your program will not run correctly.

Generate Debugging Information

When selected, this option directs the compiler to include full debugging information, such as line number references, in the compiled Java class files. Adding debugging information to your compiled files allows you to debug your application from within the Visual J++ environment. Including debugging information in your compiled code may decrease code execution speed and increase the size of your compiled code.

Optimize Compiled Code

When selected, this option informs the compiler to perform a fully optimized compilation of the source files in the project. Selecting this option will allow the compiler to tune your Java class files so they can execute faster.

Recompile Only Changed Files

When selected, this option informs the compiler to only compile files that have been changed. You can use this option to optimize compile time by.

Treat All Warnings As Errors

When selected, this option informs the compiler that all warnings are to be treated as errors. Using this option requires all warnings be eliminated from the source code before compilation can succeed.

Output Directory

A text box that allows you to specify an alternate output directory to use when your project is compiled. You can use this directory to differentiate between the different builds of your project.

Conditional Compilation Symbols

This text box allows you to enter a space, tab, semicolon, or comma-delimited list of strings that represent the conditional identifiers used within any conditional compilation code.

Additional Compiler Options

This text box allows you to pass compiler options, that are not available in this dialog box, to the compiler. Any items entered in this text box are passed as command line settings to the compiler after all other options have been passed to the compiler.


Classpath Tab (Project Properties Dialog Box)

The Classpath tab allows you to specify the location of packages required by your project to run within Visual J++. If your source code requires classes located in packages that are not installed on your system or are not part of your project, this list allows you to define the path to the package. Also displayed in this dialog box is a list of packages that are already installed on your system and are available to your project.

In the Classpath tab you can:

  • View the list of packages that are already installed on your system.

  • Add or remove package paths that are specific to your project.

  • Change the search order of project-specific packages.

Options

Configuration

This option contains a list from which you can select your build type. This setting is global to all the tabs in this dialog box.

Your choices are:

  • Debug – This is the version of your application that includes information to assist in debugging.

  • Release – This is the version of your application that will be distributed to your users.

  • All Configurations – This option is used to make setting changes global to all build types.

Default Path

Displays the current project path. Because the project path is the most frequently accessed path, it is automatically displayed as the top item in the project-specific packages list. The project path is not editable in this display.

Project-Specific Classpath List

This list displays the location of packages required by your project to run within Visual J++. You may have classes in various locations throughout your local or network path. With this list, you can see at a glance what search paths exist for your project's required class files. You can also add new search paths to the list. The list is displayed in the search order that the VM and compiler use to find classes; therefore, paths located at the top of the list are found first. If you double click an item in the list, the Extend Classpath dialog box is displayed. This dialog box allows you to modify the path entry.

Merge All Project-Specific Classpaths In Solution

When selected, this option will merge all of the project paths in a solution. Use this option if a project path in your solution is needed by another project.

New

Displays the Extend Classpath dialog box for adding a new path to the project's class path entries.

Delete

Deletes the selected path entry from the list.

Up

Moves the selected path up in the search order.

Down

Moves the selected path down in the search order.

Package Manager Class Store (JPM) List

Displays a list of the packages that have already been installed on your system. Packages listed here are global to all Java programs and can be used from your project without adding them to the Project Specific Packages list. The Installed Packages list is not editable from this display.


COM Classes Tab (Project Properties Dialog Box)

The COM Classes tab allows you to expose classes in your project as Component Object Model (COM) objects.

Note Settings made in this tab are defined for all builds of the project, regardless of the Configuration list setting in this dialog box.

From the COM Classes tab you can:

  • Create classes that can be called from other applications using COM.

  • Create or use external type libraries with your project.

Options

Classes with COM Extensions

This list displays all the Java class definitions in your project that are capable of being exposed through COM. Selecting a check box next to a class in the list marks the class as a COM class. Visual J++ places code at the top of the class definition in the form of a comment tag, when the OK or Apply button for the dialog box is clicked. This code notifies Visual J++ to register the class as a COM object.

Automatically Generate Type Library

When this option is selected, a type library is automatically generated each time you build your project. Visual J++ generates a type library for all the classes that are checked in the Classes with COM Extensions list.

Options

Displays the Type Library Options dialog box for setting options for the automatically created type library.

Use Existing Type Library

This option allows you to specify an existing type library file. If you choose this option and select a valid type library file or a file that contains an embedded type library, such as an OCX, DLL, or EXE file, Visual J++ creates class templates for them in your project.

Select

This option displays the COM Templates dialog box for selecting the pre-existing type library you want to use in your project. The type library may be a stand-alone file, or it could be embedded in a COM executable (such as an OCX, DLL, or EXE file).


Java Exceptions Dialog Box

The Java Exceptions dialog box defines exception handling settings for Java exceptions that occur during debugging sessions.

Options

Exceptions List

This is a tree view list that displays the entire Java exceptions hierarchy. Each exception listed in the tree displays an icon that shows the current breakpoint setting. A red icon indicates that the exception will cause Visual J++ to break on the line of code that caused the exception. A large gray icon signifies that the exception will not cause a break into the debugger if there’s an exception handler; otherwise, a break will occur. A small gray icon signifies that the exception will use its superclass' current setting. The default setting for all exceptions is to not break into the debugger when an exception occurs and a handler is present.

Exception Settings

This group of option buttons is used to set the break status for the currently selected exception from the Exceptions List. The options are:

Break into debugger This displays a message box when the selected exception type occurs. This message box provides the ability to view the code (if available) that caused the exception. A large red icon is displayed when this setting is chosen.

Continue and break only if the exception is not handled If the selected exception occurs, Visual J++ stops only if the exception is not handled by exception handling code. This is the default setting for all exceptions. A large gray icon is displayed when this setting is chosen.

Use setting from superclass Uses the break setting for the currently selected exception's superclass. Depending on the exception's superclass setting, a small red or gray icon is displayed when this setting is chosen.

Find

Displays the Find dialog box that allows you to enter a string of text to search for a specific exception within the Exceptions List.

Find Next

Used with the Find button, this button displays the next exception that contains the text entered in the Find dialog box.

Clear All

Clears all exception handling settings that have been made and returns them to the default settings.


J/Direct Call Builder

J/Direct Call Builder is a graphical tool for automating the process of calling the Win32 API from within Java programs.

With the J/Direct Call Builder you can:

  • View a list of methods, structures, and constants from the Win32 API to add to your project.

  • Choose the target class in which to add the API usage code.

  • Add the code necessary to use a specific API method, structure, or constant to a class in your project.

Options

Source

This dialog box allows you to select the API text file that you wish to use with the J/Direct Call Builder. The default option is the WIN32.TXT file, which allows you to import Win32 API methods, structures, and constants.

Note The J/Direct Call Builder only provides API listings for the GDI32, Kernel32, User32, Shell32, Advapi32, Spoolss and Winmm Win32 API Libraries.

Target

A non-editable text box that displays the class that the J/Direct Call Builder will add code to. The default value for the text box is a class called Win32. If this class does not exist when you select an API to import, you will be prompted to create the class in a Java source file called Win32.java. To choose a different class in which to add your API imports, click the button located next to the Target text box. This displays the Select Class dialog box, which allows you to select a class from your project or the Clipboard. Choosing the Clipboard as the target for class imports allows you to paste the import into any class you choose. Since structures are defined as classes in Java, when a structure is selected from the API Elements list, the structure's class is created as a nested class of the class selected in the Target text box.

API Elements List

This contains a list of the Win32 API elements found in the text file specified in the Source text box. This list can be filtered using the Method, Structs, or Constants check boxes located at the top of the window. You can get help on any Win32 API element by right-clicking on the API element and choosing the Display API Help menu item from the shortcut menu. To add a selected API element to your project you can either select the element in the list and then click the Copy to Target button, or double-click the element in the list. This will add the necessary code to the class file specified in the Target text box. The Find text box located above the list allows you to type a string of text to search for a specific element in the list. Multiple API elements can be selected from the list by holding down the CTRL key and clicking on the list items that you want to add. A display area below the list shows the code that will be added for the currently selected API elements. You can determine the type of API element based on the associated icon. The list below illustrates each icon that can be displayed in the list and its meaning.

Icon | Description
 | Method
 | Constant
 | Struct (Structure)

Methods

When this option is selected, any methods contained in the currently selected API are displayed in the API Elements list. The default value for this option is true.

Structs

When this option is selected, any structures contained in the currently selected API are displayed in the API Elements list. The default value for this option is true.

Constants

When this option is selected, any constants contained in the currently selected API are displayed in the API Elements list. The default value for this option is true.

Copy to Target

This copies the specified API elements to the class specified in the Target text box.


J/Direct Call Builder Options Dialog Box

The J/Direct Call Builder Options dialog box allows you to specify options for the J/Direct Call Builder.

With the J/Direct Call Builder Options dialog box you can:

  • Determine whether the J/Direct Call Builder will display the source after an API import.

  • Enable or disable the addition of security checks for API calls.

Options

Show Target Window When Copy To Target

When this option is selected, the J/Direct Call Builder displays the Text editor with the class that has been selected as the target class for API imports when an API import is added to the target class.

Disable Stack Crawl Security Check

When this option is selected, the J/Direct Call Builder inserts a comment tag before the API import statement that disables the security check normally performed when an API function is called. With this option enabled, your API calls have better performance but could potentially be exposed to others when used in Internet applications.

Note Once added, clearing this option will not remove the disable security check comment in your target class.


COM Wrappers Dialog Box

The COM Wrappers dialog box allows you to create Java source code wrappers in your project for accessing COM components.

A COM wrapper is Java source code that allows you to gain access to a specific COM component on your system. If you have a COM component (such as an ActiveX control) that you wish to use in your project, you can select the registered type library (in the case of a DCOM component) or COM component from the list and Visual J++ will create Java classes to access the COM component or type library.

With the COM Wrappers dialog box you can:

  • Select the components you wish to create a Java source file for from a list of COM components that are registered on your system.

  • Browse your computer for TLB, OLB, OCX, DLL, or EXE files that you wish to create COM wrappers for.

  • View location, language, and version information on COM components highlighted in the Installed COM Components list.

Options

Installed COM Components List

This is a list of all COM components registered on your system. You can select a COM component from the list by clicking the check box next to the name. When the OK button is selected, the environment will create a package, source files, and code for each of the COM classes and interfaces found in the component and adds them to your project. The code that is created allows you to access the COM component from within your Java project.

Browse

Displays a dialog that allows you to browse your computer system for a DLL, EXE, OCX, TLB or OLB file that you wish to access in Java. Use this feature only if the COM component you want to use is not currently registered on your system.

Component Information

Below the Installed COM Components list is a section that displays information for the currently highlighted COM component.

Location The location of the selected COM component on the computer.

Language Displays the name of the human language that the COM component is designed for.

Version Displays the version number of the selected COM component.


COM Templates Dialog Box

The COM Templates dialog box allows you to create Java class templates for registered type libraries and COM components on your system.

A COM template allows you to use Java source code to implement COM components that are described in type libraries and existing COM components. If you have a type library or existing COM component that you wish to implement using Java, you can select a registered type library or COM component from the list and Visual J++ will build the template code in your project. You can then implement each of the methods templates provided and compile to create a COM component.

With the COM Templates dialog box you can:

  • Select the components you wish to create Java class templates for from a list of COM components and type libraries that are registered on your system.

  • Browse your computer for OCX, DLL, EXE, TLB, or OLB files that you wish to create class templates for.

  • View location, language, and version information on COM components and type libraries highlighted in the Installed COM Components list.

Options

Installed COM Components List

This is a list of all COM components and type libraries registered on your system. You can select a COM component or type library from the list by clicking the check box next to the name. When the OK button is selected, the environment creates a package, source files, and class templates for each of the classes found in the COM component or type library and adds them to your project.

Browse

Displays a dialog box that allows you to browse your computer for a DLL, EXE, TLB, OLB, or OCX file that you wish to create Java class templates for. Use this feature only if the COM component or type library you want to use is not currently registered on your system.

Component Information

Below the Installed COM Components list is a section that displays information for the currently highlighted COM component or type library.

Location The location of the selected COM component or type library on the computer.

Language Displays the name of the human language that the COM component or type library is designed for.

Version Displays the version number of the selected COM component or type library.


Type Library Options Dialog Box

The Type Library Options dialog box allows you to change type library settings for the type library that is automatically generated for COM classes in your project.

When you select classes to be registered as COM classes in the COM Classes tab of the Project Properties dialog box, a type library is automatically generated. This dialog box allows you change the settings for the type library file.

Options

File Name

A text box that allows you to specify the name of the type library that is generated. The default is the name of your project.

Library Name

A text box that allows you to specify the name of the library. This name is displayed when a user is importing the type library into their project. The default name for the library is the name of your project.

Description

A text box that allows you to enter a short description for the library. This information is viewable (depending on the tool) when a user imports your type library into their project. The default description is the name of your project.

Help File Name

A text box that allows you to specify the help file that will be used to provide help on members of your COM classes.

Help Context ID

A text box that allows you to specify a help context ID. This ID can be used by your COM classes to select a specific help topic from the help file specified in the Help File Name text box.


The Designer

The Designer allows you to visually design the windows, dialog boxes, and components in your application.

With the Designer you can:

  • Resize the form to the size needed for normal display.

  • Add components to the form.

  • Lock components so that they cannot be moved within the designer.

  • Double-click on a component or the form to create an event handler for the form's or component's default event.

  • Set properties on the form to change its display position, size, caption buttons, and MDI client state.

  • Align and size components based on the form or other components on the form.

  • Create menus for the form.


Properties Window (Visual J++)

The Properties window allows you to view and modify the properties (design-time only) and events of Java forms and components in your project.

With a Java object selected, you can use the Properties window to:

  • View and modify the properties of forms and WFC components.

  • Create event handlers for forms and components that are on a form.

Views

When the Form Designer is displayed, the Properties window provides two different views, the standard Properties View and Event View. You can switch between these views by selecting either the Properties button or the Events button from the Properties window.

Properties View

Properties View displays all of the properties for the selected form or component. This is the default view for all objects in Visual J++.

Event View

Event View displays all of the events and any event handlers for the specified form or component. You can add an event handler by either double-clicking the event name to create a default handler (the name of the event handler method will be in the nameOfObject_eventName format) or by entering your own event handler name next to the event you wish to handle. Either method will display the Text editor at the location that the event handler is created.


General Tab (Class Builder)

The General tab allows you to make changes to general class attributes.

With the General tab of the Class Builder you can:

  • Change the modifiers of the class.

  • Change your Javadoc comments for the class.

  • Include a ClassInfo class with your class for component support.

  • Implement the selected class as a COM class.

  • Add transaction support to the class.

  • Add a new class to your project.

  • Select a class to use the builder with.

Options

Class Name

A read-only text box that displays the name of the class that is currently being used in the Class Builder. You can change the class being used by clicking the Select Class button. This will display the Select Class dialog box where you can choose a class from your project.

Select Class

Displays the Select Class dialog box to select a class from your project to work with in the Class Builder.

Add Class

Displays the Add Class dialog box for adding a new class to your project.

Access

A list that defines the access modifier for the class. Non-nested classes can be declared either as public or default (package). Nested classes can be declared as default, public, protected, or private.

Abstract

When selected, applies the abstract modifier to the currently selected class. This option is disabled if the final modifier is already applied to the class.

Final

When selected, applies the final modifier to the currently selected class. This option is disabled if the abstract modifier is already applied to the class.

Static

When selected, applies the static modifier to the currently selected class. This option is disabled if the class is not a nested class.

Include ClassInfo

When selected, the Class Builder adds a nested ClassInfo class to the currently selected class. ClassInfo classes are used if your class is going to be exposed as a component. This option is disabled if the currently selected class is a nested class.

Javadoc Comment

A text box that allows you to view and modify the Javadoc comments for the currently selected class. Only the first sentence of the Javadoc comment is displayed in this text box.

COM Class

When selected, a comment tag is added above the current class declaration to register the class as a COM class. Selecting this option allows your class to be exposed as a COM object and be accessible to other languages that support COM. If this option is not selected, any COM registration code added above the class declaration is removed. This option is selected if the class is selected in the COM Classes tab of the Project Properties dialog box or MTS support is specified. This option is disabled if the currently selected class is a nested class.

MTS Support

When the Enabled option is selected, Microsoft Transaction Server support is added to the current class declaration. Because transaction support is only valid for COM classes, when this option is selected, the COM Class option will automatically be selected. The Class Wizard adds the @com.register and @com.transaction comment tags, as well as the com.ms.mtx.IObjectControl interface to the class's implemented interfaces list. The list provided next to the Enabled option allows you to define the parameter of the @com.transation comment tag. The parameter allows you to define the behavior of the transaction object.


Extends Tab (Class Builder)

The Extends tab allows you to select a superclass and overloaded methods for your classes.

With the Extends tab you can:

  • Change the superclass for a class.

  • View the list of inherited methods for a class.

  • Override inherited methods for a class.

Options

Superclass Name

A read-only text box that displays the superclass of the class you are currently modifying. You can change the superclass by clicking the Select Superclass button. This displays the Select Superclass dialog box which allows you to either type in a name or choose a valid name from the list provided.

Select Superclass

Displays the Select Superclass dialog box for selecting the superclass of the class you are modifying.

Inherited Methods

A list of all the inherited methods that are available for the currently selected superclass. When a method is moved from the Inherited Methods list to the Local Overrides list (by using the left and right arrows located between the lists), an override method is added to your class. If the current class's superclass is declared as final, the buttons for selecting methods to override are disabled.

Note The Inherited Methods list is only populated with method names if the superclass specified is a valid superclass.

Local Overrides

A list of the methods that are currently overloaded for the selected superclass. When a method is moved from the Local Overrides list to the Inherited Methods list (by using the left and right arrows located between the lists), the override method is removed from the currently selected class.


Implements Tab (Class Builder)

The Implements tab allows you to manage implemented interfaces and required interface methods for your classes.

The Implements tab allows you to add interfaces to your class's list of implemented interfaces. When interfaces are added to the list of implemented interfaces, method templates are automatically created in your class for each interface's list of required methods to implement.

With the Implements tab you can:

  • Add or remove interfaces to be implemented by your class.

  • Create method templates for required interface methods.

Options

Implemented Interfaces

A list of the implemented interfaces for the currently selected class. When an interface is selected from the list, the Interface Methods list is filled with the names of methods that must be implemented.

Add

Displays the Select Interface dialog box for adding an interface to the list of implemented interfaces for the class. When an interface is added to the list, the Interface Methods list is updated to reflect the methods required to be implemented by the class, and method templates are created in your class for each method in the list.

Remove

Removes the currently selected interface from the list of implemented interfaces for the currently selected class.

Interface Methods

A list of all the methods for the selected implemented interface.


Member Variables Tab (Class Builder)

The Member Variables tab allows you to create and modify member variables in your class.

With the Member Variables tab you can:

  • Define new member variables for your class.

  • Create member variables based on other member variables that are defined in your class.

  • Modify member variables that you have defined.

  • Remove member variables from your class.

Options

Member Variables

A list of all the member variables currently specified in the class you are modifying.

Add

Displays the Add Member Variable dialog box for defining a new member variable in your class.

Modify

Displays the Modify Member Variable dialog box for modifying the currently selected member variable in the Member Variables list. This button is enabled only if a member variable is selected from the Data Members list.

Clone

Displays the Clone Member Variable dialog box for creating a member variable based on the currently selected member variable in the Member Variables list. This button is enabled only if a member variable is selected from the Data Members list.

Delete

Deletes the currently selected member variable in the Member Variables list. This button is enabled only if a member variable is selected from the Data Members list.


Methods Tab (Class Builder)

The Methods tab allows you to create and modify methods in your class.

With the Methods tab you can:

  • Define new methods for your class.

  • Create methods based on other methods that are defined in your class.

  • Modify methods that you have defined.

  • Remove methods from your class.

Options

Methods

A list of all the methods currently specified in the class you are modifying. If you have any methods that are exposed in your class's ClassInfo class, an icon is displayed next to the name of the method.

Add

Displays the Add Method dialog box for defining a new method in your class.

Modify

Displays the Modify Method dialog box for modifying the currently selected method in the Methods list. This button is enabled only if a method is selected from the Methods list.

Clone

Displays the Clone Method dialog box for creating a method based on the currently selected method in the Methods list. This button is enabled only if a method is selected from the Methods list.

Delete

Deletes the currently selected method in the Methods list. This button is enabled only if a method is selected from the Methods list.


Properties Tab (Class Builder)

The Properties tab allows you to create and modify properties in your classes.

With the Properties tab you can:

  • Define new properties for your class.

  • Create properties based on other properties that are defined in your class.

  • Modify properties that you have defined.

  • Remove properties from your class.

Options

WFC Properties

A list of all the properties currently specified in the class you are modifying.

Add

Displays the Add Property dialog box for defining a new property in your class.

Modify

Displays the Modify Property dialog box for modifying the currently selected property in the WFC Properties list. This button is enabled only if a property is selected from the WFC Properties list.

Clone

Displays the Clone Property dialog box for creating a property based on the currently selected property in the WFC Properties list. This button is enabled only if a property is selected from the WFC Properties list.

Delete

Deletes the currently selected property in the WFC Properties list. This button is enabled only if a property is selected from the WFC Properties list.


Events Tab (Class Builder)

The Events tab allows you to create and modify events in your classes.

With the Events tab you can:

  • Define new events for your class.

  • Create events based on other events that are defined in your class.

  • Modify events that you have defined.

  • Remove events from your class.

Options

WFC Events

A list of all the events currently specified in the class you are modifying.

Add

Displays the Add Event dialog box for defining a new event in your class.

Modify

Displays the Modify Event dialog box for modifying the currently selected event in the WFC Events list. This button is enabled only if an event is selected from the WFC Events list.

Clone

Displays the Clone Event dialog box for creating an event based on the currently selected event in the WFC Events list. This button is enabled only if an event is selected from the WFC Events list.

Delete

Deletes the currently selected event in the WFC Events list. This button is enabled only if an event is selected from the WFC Events list.


Class Builder Options Dialog Box

Allows you to define the options for the Class Builder.

With the Class Builder Options dialog box you can:

  • Specify whether list boxes in the Class Builder will be filtered based on previous selections.

  • Specify whether calls to the superclass method are made when overriding a method.

  • Determine if TODO comments are added to methods that are created by the wizard.

  • Determine if interface methods are automatically created for abstract classes.

  • Determine if removing an interface from the list of implemented interfaces removes the interface methods from the class.

  • Specify whether changes in a class's superclass automatically change the class's ClassInfo class.

Options

Filter Listbox Entries

When this option is selected, all list boxes in the Class Builder filter out items that have already been selected. For example, if a method is selected to be overridden in the Extends tab of the Class Builder, the method name is removed from the list of available methods to override. This option is selected by default.

Include Call To Superclass In Overrides

When this option is selected, the Class Builder provides a call to the superclass method when creating an overridden method. Select this option if the superclass method performs actions that you wish to occur in addition to your overridden method's code. This option is selected by default.

Include TODO Comments In New Methods

When this option is selected, the Class Builder generates TODO comments in methods it creates. TODO comments allow you to view tasks that need to be completed in your method's code. The TODO tasks can be viewed in the Task List window. This option is selected by default.

Add Interface Methods In Abstract Classes

When this option is selected, the Class Builder automatically adds interface methods for classes declared as abstract. An abstract class is a class that is intended to be used as a superclass of another class and cannot be instantiated. Because an abstract class does not require that all interface methods be implemented, you may want to have this option cleared to prevent all interface methods from automatically being added to your abstract class. This option is selected by default.

Remove Interface Methods When Removing An Interface

When this option is selected, the Class Builder removes interface method code that is added to a class when an interface is removed from the list of implemented interfaces for the class. With this option not selected, you can leave method code that the Class Builder added to your class even though the interface is no longer implemented by the class. This option is not selected by default.

Automatically Update ClassInfo When Superclass Changes

When this option is selected, the Class Builder automatically updates the nested ClassInfo class added to your class when the superclass is changed to another class. For example, if you create a class in the Class Builder that extends the ListBox class, the Class Builder adds a nested ClassInfo class into your class that is based on the ListBox's ClassInfo class. If later on you change your class to extend the ComboBox class, when this option is selected, the Class Builder will automatically change your nested ClassInfo class to be based on the ComboBox's ClassInfo class. This option is selected by default.


Introduction (Class Wizard)

The Class Wizard provides a step-by-step way to create a class for your project. Various features can be selected during the course of the wizard, which can add additional capabilities to the class the wizard generates. Once the wizard is complete, you can modify the class that the wizard produces by using the Class Builder tool.


General Class Information (Class Wizard)

Allows you to specify general class attributes for the class you are creating in the Class Wizard.

With the General Class Information step of the Class Wizard you can:

  • Add a new class to your project.

  • Specify the modifiers of the class.

Options

Class Name

A read-only text box that displays the name of the class that is being created in the Class Wizard.

Access

A list that defines the access modifier for the class you are creating. Classes can be declared as either public or default (package).

Abstract

When selected, applies the abstract modifier to the class you are creating. This option is disabled if the final modifier is already applied to the class. A class that is declared as abstract cannot be instantiated and is used as a superclass for another class.

Final

When selected, applies the final modifier to the class you are creating. This option is disabled if the abstract modifier is already applied to the class. When a class is defined as final the class cannot be a superclass for another class.


Superclass and Server Support (Class Wizard)

Allows you to add COM and Microsoft Transaction Server support to the class you are creating in the Class Wizard. In this step you can also define the superclass and Javadoc comments for the class.

With the Superclass and Server Support step of the Class Wizard you can:

  • Include a ClassInfo class with your class for component support.

  • Add Javadoc comments for the class.

  • Implement the class you are creating as a COM class.

  • Add MTS support to the class you are creating.

Options

Superclass Name

A read-only text box that shows the superclass for the class you are creating. You can change the superclass by clicking the Select Superclass button. This displays the Select Superclass dialog box which allows you to type in a name or choose a valid name from the list provided.

Select Superclass

Displays the Select Superclass dialog box for selecting the superclass for the class you are creating.

Javadoc Comment

A text box that allows you to add Javadoc comments for the class you are creating.

COM Class

When selected, a comment tag is added above the class declaration to register the class as a COM class. Selecting this option allows the class you are creating to be exposed as a COM object and be accessible to other languages that support COM.

MTS Support

When the Enabled option is selected, Microsoft Transaction Server support is added to the current class declaration. Because transaction support is only valid for COM classes, when this option is selected, the COM Class option is automatically selected. The Class Wizard adds the @com.register and @com.transaction comment tags, as well as the com.ms.mtx.IObjectControl interface to the class's implemented interfaces list. The list provided next to the Enabled option allows you to define the parameter of the @com.transation comment tag. The parameter allows you to define the behavior of the transaction object.


Local Method Overrides (Class Wizard)

Allows you to create overloaded methods for your classes.

With the Local Method Overrides step of the Class Wizard you can:

  • View the inherited methods for a class.

  • Override inherited methods for a class.

Options

Inherited Methods

This is a list of all the inherited methods that are available for the currently selected superclass. When a method is moved from the Inherited Methods list to the Local Overrides list (by using the right arrow located between the lists), an override method is added to your class.

Note The Inherited Methods list is only populated with method names if the superclass is a valid superclass.

Local Overrides

A list of the methods that are currently overloaded for the currently selected superclass. When a method is moved from the Local Overrides list to the Inherited Methods list (by using the left arrow located between the lists), the override method is removed from the class you are creating.


Implemented Interface Information (Class Wizard)

Allows you to manage implemented interfaces and required interface methods for the class you are creating.

The Implemented Interfaces step of the Class Wizard allows you to add interfaces to your class's list of implemented interfaces. When interfaces are added to the list of implemented interfaces, method templates are automatically created in your class for each interface's list of required methods to implement.

With the Implemented Interfaces step of the Class Wizard you can:

  • Add or remove interfaces to be implemented by your class.

  • Create method templates for required interface methods.

Options

Implemented Interfaces

A list of the implemented interfaces for the class you are creating.

Add

Displays the Select Interface dialog box for adding an interface to the list of implemented interfaces for the class you are creating. When an interface is added to the list, the Interface Methods list is updated to reflect the methods required to be implemented by the class, and method templates are created in the class for each method in the list.

Remove

Removes the currently selected interface from the list of implemented interfaces for the class you are creating.

Interface Methods

A list of all the methods for the selected implemented interface.


Member Variables (Class Wizard)

Allows you to create member variables in the class you are creating in the Class Wizard.

With the Member Variables step of the Class Wizard you can:

  • Define new member variables for your class.

  • Create member variables based on other member variables that are already defined in your new class.

  • Modify member variables that you have defined in the Class Wizard.

  • Remove member variables that you have defined for your new class.

Options

Member Variables

A list of all the member variables currently specified in the class you are creating.

Add

Displays the Add Member Variable dialog box for defining a new member variable in your class.

Modify

Displays the Modify Member Variable dialog box for modifying the currently selected member variable in the Member Variables list.

Clone

Displays the Clone Member Variable dialog box for creating a member variable based on the currently selected member variable in the Member Variables list.

Delete

Deletes the currently selected member variable in the Member Variables list.


Methods (Class Wizard)

Allows you to create and modify methods in the class you are creating with the Class Wizard.

With the Methods step of the Class Wizard you can:

  • Define new methods for your class.

  • Create methods based on other methods that are already defined in your new class.

  • Modify methods that you have defined in the Class Wizard.

  • Remove methods that you have defined for your new class.

Options

Member Methods

A list of all the methods currently specified in the class you are creating.

Add

Displays the Add Method dialog box for defining a new method in your class.

Modify

Displays the Modify Method dialog box for modifying the currently selected method in the Methods list.

Clone

Displays the Clone Method dialog box for creating a method based on the currently selected method in the Methods list.

Delete

Deletes the currently selected method in the Methods list.


Properties (Class Wizard)

Allows you to create and modify properties in the class you are creating with the Class Wizard.

With the Properties step of the Class Wizard you can:

  • Define new properties for your class.

  • Create properties based on other properties that are already defined in your new class.

  • Modify properties that you have defined in the Class Wizard.

  • Remove properties that you have defined for your new class.

Options

WFC Properties

A list of all the properties currently specified in the class you are creating.

Add

Displays the Add Property dialog box for defining a new property in your class.

Modify

Displays the Modify Property dialog box for modifying the currently selected property in the WFC Properties list.

Clone

Displays the Clone Property dialog box for creating a property based on the currently selected property in the WFC Properties list.

Delete

Deletes the currently selected property in the WFC Properties list.


Events (Class Wizard)

Allows you to create and modify events in the class you are creating with the Class Wizard.

With the Events step of the Class Wizard you can:

  • Define new events for your class.

  • Create events based on other events that are already defined in your new class.

  • Modify events that you have defined in the Class Wizard.

  • Remove events that you have defined for your new class.

Options

WFC Events

A list of all the events currently specified in the class you are creating.

Add

Displays the Add Event dialog box for defining a new event in your class.

Modify

Displays the Modify Event dialog box for modifying the currently selected event in the WFC Events list.

Clone

Displays the Clone Event dialog box for creating an event based on the currently selected event in the WFC Events list.

Delete

Deletes the currently selected event in the WFC Events list.


Summary (Class Wizard)

Allows you to view a report of the Class Wizard settings.

Options

View Report

This button displays a dialog box that allows you to review a report that contains the settings you made while running the Class Wizard. You can save the report as an HTML file to your hard disk for reading later.


Select Class Dialog Box

The Select Class dialog box allows you to select a class from the classes in your project.

With the Select Class dialog box you can:

  • Select a class from the tree that you wish to use.

  • View your projects in either Class View or Project View.

Options

Project View

This option allows you to view your project's classes in a way similar to the Project Explorer. Project View displays the projects and class files that make up your project. You can select a class file and any of the classes that are defined inside the class file. To select a class you can either double-click the name of the class or click the class name and then click the OK button.

Class View

This option allows you to view your project's classes in a way similar to the Class Outline. Class View displays a simple list of each available class in the currently selected project. To select a class you can either double-click the name of the class or click the class name and then click the OK button.

Note When the Select Class dialog box is displayed from the J/Direct Call Builder, two additional objects are available for selection. These objects are the Windows Clipboard and a predefined class called Win32.


Select Interface Dialog Box

The Select Interface dialog box allows you to select an interface to implement for the class you are modifying in the Class Builder or Class Wizard.

Options

Interface to Implement

This dialog box allows you to either enter the name of an interface you wish to implement for your class or select the name from a predefined list of interfaces.

Note Interfaces that you enter in the dialog box are not added to the list.


Select Superclass Dialog Box

The Select Superclass dialog box allows you to select the superclass of the class you are modifying in Class Builder.

Options

Superclass

This dialog box allows you to either enter the name of the class you wish to derive your class from or it allows you select the name from a predefined list of classes.

Note Classes that you enter in the dialog box are not added to the list.


Add Class Dialog Box

The Add Class dialog box allows you to define a new class for your project.

With the Add Class dialog box you can:

  • Specify the name of the class you wish to create.

  • Specify modifiers for the class.

  • Specify whether the class is a nested class.

  • Provide Javadoc comments for the class.

  • Specify whether or not you want to display the class in Class Builder after it is created.

Options

Class Name

A text box that allows you to specify the name of the class you are creating.

Create a Nested Class

When selected, this option defines the class as a nested class. The class becomes a nested class of the currently selected class. A nested class is a class that is defined within another class.

Access

A list that defines the access modifier for the class. Non-nested classes can be declared either as public or default (package). Nested classes can be declared as default (package), public, protected, or private.

Abstract

When selected, applies the abstract modifier to the class. This option is disabled if the final modifier is already applied to the class.

Final

When selected, applies the final modifier to the class. This option is disabled if the abstract modifier is already applied to the class.

Static

When selected, applies the static modifier to the class. This option is only available for nested classes.

Javadoc Comment

A text box that allows you to create Javadoc comments for the class.

Display New Class In Class Builder

When selected, the class that you create is displayed in the Class Builder. Select this option if you want to use this class in Class Builder to add fields, methods, properties, or events.


Add Method Dialog Box

Allows you to define a new method in your class.

With the Add Method dialog box you can:

  • Specify the name of your method.

  • Assign an access modifier to your method.

  • Identify the return type and value for your method.

  • Specify your method's parameters.

  • Define whether your method is abstract, static, final, synchronized, or native.

  • Create Javadoc comments for your method.

Options

Method Name

A text box that allows you to enter the name of the method.

Return Type

A dialog box that allows you to specify the return type for the method. You can select from a list of standard return type values or enter your own return type in the edit portion of the dialog box.

Return Value

A text box that allows you to specify an initial return value. This return value should be of the same data type as the return type specified for the method or errors will occur during compilation.

Parameters

A grid that allows you to specify the parameter names and types for your method.

Access

A list that allows you to select an access modifier for the method. You can choose from default (package), public, private, or protected.

Abstract

When this option is selected, the abstract modifier is applied to the method declaration. An abstract method must be defined in an abstract class. Also, an abstract method does not contain any implementation code.

Static

When this option is selected, the static modifier is applied to the method declaration. The static modifier allows a method to be called without an instance of the method's class.

Final

When this option is selected, the final modifier is applied to the method declaration. The final modifier prevents the method from being overridden by a subclass class.

Synchronized

When this option is selected, the synchronized modifier is applied to the method declaration. The synchronized modifier locks the method's object from being modified until after the method has completed.

Native

When this option is selected, the native modifier is applied to the method declaration. The native modifier identifies a method as being implemented in another language such as C or C++.

Javadoc Comment

A text box that allows you to create Javadoc comments for the method. The Javadoc comment allows you to document the method and any related information about the method.


Modify Method Dialog Box

Allows you to modify a method in your class.

With the Modify Method dialog box you can:

  • Modify the name of your method.

  • Assign an access modifier to your method.

  • Modify the return type and value for your method.

  • Modify your method's parameters.

  • Select or deselect modifiers that are applied to your method.

  • Modify the Javadoc comments for your method.

Options

Method Name

A text box that allows you to change the name of the currently selected method.

Return Type

A dialog box that allows you to modify the return type for the method. You can select from a list of standard return type values or enter your own return type in the edit portion of the dialog box.

Return Value

A text box that allows you to modify the initial return value. This return value should be of the same data type as the return type specified for the method or errors will occur during compilation.

Parameters

A grid that allows you to modify the parameter names and types for your method.

Access

A list that allows you to select an access modifier for the method. You can choose from default (package), public, private, or protected.

Abstract

When this option is selected, the abstract modifier is applied to the method declaration. An abstract method must be defined in an abstract class. Also, an abstract method does not contain any implementation code.

Static

When selected, applies the static modifier to the method. The static modifier allows a method to be called without an instance of the method's class.

Final

When selected, applies the final modifier to the method. The final modifier prevents the method from being overridden by a class.

Synchronized

When selected, applies the synchronized modifier to the method. The synchronized modifier locks the method's object from being modified until after the method has completed.

Native

When selected, applies the native modifier to the method. The native modifier identifies a method as being implemented in another language such as C or C++.

Javadoc Comment

A text box that allows you to modify the Javadoc comments for the method. The Javadoc comment allows you to document the method and any related information about the method.


Clone Method Dialog Box

Allows you to create a new method for your class based on a previously defined method.

With the Clone Method dialog box you can:

  • Specify the name of your method.

  • Assign an access modifier to your method.

  • Identify the return type and value for your method.

  • Specify your method's parameters.

  • Define whether your method is static, final, synchronized, or native.

  • Create Javadoc comments for your method.

Options

Method Name

A text box that allows you to enter the name of the method.

Return Type

A dialog box that allows you to specify the return type for the method. You can select from a list of standard return type values or enter your own return type in the edit portion of the dialog box.

Return Value

A text box that allows you to specify an initial return value. This return value should be of the same data type as the return type specified for the method or errors will occur during compilation.

Parameters

A grid that allows you to specify the parameter names and types for your method.

Access

A list that allows you to select an access modifier for the method. You can choose from default (package), public, private, or protected.

Abstract

When this option is selected, the abstract modifier is applied to the method declaration. An abstract method must be defined in an abstract class. Also, an abstract method does not contain any implementation code.

Static

When selected, applies the static modifier to the method. The static modifier allows a method to be called without an instance of the method's class.

Final

When selected, applies the final modifier to the method. The final modifier prevents the method from being overridden by a class.

Synchronized

When selected, applies the synchronized modifier to the method. The synchronized modifier locks the method's object from being modified until after the method has completed.

Native

When selected, applies the native modifier to the method. The native modifier identifies a method as being implemented in another language such as C or C++.

Javadoc Comment

A text box that allows you to create Javadoc comments for the method. The Javadoc comment allows you to document the method and any related information about the method.


Add Member Variable Dialog Box

Allows you to create a new member variable in your class.

With the Add Member Variable dialog box you can:

  • Specify the name of the member variable you wish to create.

  • Define the data type of the member variable.

  • Apply an access modifier to the member variable.

  • Assign the static, transient, final, or volatile modifiers to the member variable.

  • Specify an initial value for the member variable.

  • Create Javadoc comments for the member variable definition.

Options

Member Variable Name

A text box that allows you to specify the name of the member variable. The member variable name must be a valid Java identifier.

Data Type

A dialog box that allows you to specify the data type for the member variable. A list of standard data types is provided to select from. You can enter a valid data type that is not specified in the list by entering it into the edit portion of the dialog box. User defined types that are entered in the dialog box are not added to the list.

Access

A list that allows you to apply an access modifier to the member variable. You can choose from the default (package), public, protected, and private access modifiers.

Static

When selected, applies the static modifier to the member variable declaration. A static member variable may be accessed without using an instance of the class the member variable is defined in. Static member variables retain their value through the life of the application.

Transient

When selected, applies the transient modifier to the member variable declaration. A member variable defined with the transient modifier will not store its state in a class object's persistent storage.

Final

When selected, applies the final modifier to the member variable declaration. A member variable defined with the final modifier cannot be modified – its value stays constant. When you declare a member variable as final, you must specify a value in the Initial Value text box of the dialog.

Volatile

When selected, applies the volatile modifier to the member variable declaration. A volatile member variable is not optimized by the compiler. This allows the member variable to be modified by external processes.

Initial Value

A text box that allows you to specify the initial value for the member variable. The value should be in a data type that matches the member variable's data type or errors will occur during compilation.

Javadoc Comment

A text box that allows you to create Javadoc comments for the member variable. The Javadoc comment allows you to document the member variable and any related information about the member variable.


Modify Member Variable Dialog Box

Allows you to modify a member variable in your class.

With the Modify Member Variable dialog box you can:

  • Modify the name of the member variable.

  • Modify the data type of the member variable.

  • Apply an access modifier to the member variable.

  • Assign the static, transient, final, or volatile modifiers to the member variable.

  • Modify the initial value for the member variable.

  • Modify the Javadoc comments for the member variable definition.

Options

Member Variable Name

A text box that allows you to modify the name of the member variable. The member variable name must a valid Java identifier.

Data Type

A dialog box that allows you to modify the data type for the member variable. A list of standard data types is provided to select from. You can enter a valid data type that is not specified in the list by entering it into the edit portion of the dialog box. User defined types that are entered in the dialog box are not added to the list.

Access

A list that allows you to apply an access modifier to the member variable. You can choose from the default (package), public, protected, and private access modifiers.

Static

When selected, applies the static modifier to the member variable declaration. A static member variable may be accessed without using an instance of the class the member variable is defined in. Static member variables retain their value through the life of the application.

Transient

When selected, applies the transient modifier to the member variable declaration. A member variable defined with the transient modifier will not store its state in a class object's persistent storage.

Final

When selected, applies the final modifier to the member variable declaration. A member variable defined with the final modifier cannot be modified — its value stays constant. When you declare a member variable as final, you must specify a value in the Initial Value text box of the dialog.

Volatile

When selected, applies the volatile modifier to the member variable declaration. A volatile member variable is not optimized by the compiler. This allows the member variable to be modified by external processes.

Initial Value

A text box that allows you to modify the initial value for the member variable. The value should be in a data type that matches the member variable's data type or errors will occur during compilation.

Javadoc Comment

A text box that allows you to modify the Javadoc comments for the member variable. The Javadoc comment allows you to document the member variable and any related information about the member variable.


Clone Member Variable Dialog Box

Allows you to create a new member variable based on a member variable that is already defined in your class.

With the Clone Member Variable dialog box you can:

  • Specify the name of the member variable you wish to create.

  • Define the data type of the member variable.

  • Apply an access modifier to the member variable.

  • Assign the static, transient, final, or volatile modifiers to the member variable.

  • Specify an initial value for the member variable.

  • Create Javadoc comments for the member variable definition.

Options

Member Variable Name

A text box that allows you to specify the name of the member variable. The name must be a valid Java identifier.

Data Type

A dialog box that allows you to specify the data type for the member variable. A list of standard data types is provided to select from. You can enter a valid data type that is not specified in the list by entering it into the edit portion of the dialog box. User defined types that are entered in the dialog box are not added to the list.

Access

A list that allows you to apply an access modifier to the member variable. You can choose from the default (package), public, protected, and private access modifiers.

Static

When selected, applies the static modifier to the member variable declaration. A static member variable may be accessed without using an instance of the class the member variable is defined in. Static member variables retain their value through the life of the application.

Transient

When selected, applies the transient modifier to the member variable declaration. A member variable defined with the transient modifier will not store its state in a class object's persistent storage.

Final

When selected, applies the final modifier to the member variable declaration. A member variable defined with the final modifier cannot be modified - its value stays constant. When you declare a member variable as final, you must specify a value in the Initial Value text box of the dialog.

Volatile

When selected, applies the volatile modifier to the member variable declaration. A volatile member variable is not optimized by the compiler. This allows the member variable to be modified by external processes.

Initial Value

A text box that allows you to specify the initial value for the member variable. The value should be in a data type that matches the member variable's data type or errors will occur during compilation.

Javadoc Comment

A text box that allows you to create Javadoc comments for the member variable. The Javadoc comment allows you to document the member variable and any related information about the member variable.


Add Property Dialog Box

Allows you to create a new property in your class.

With the Add Property dialog box you can:

  • Specify the name of the property you wish to create.

  • Specify the data type of the property you wish to create.

  • Choose a category for the property.

  • Specify an initial value for the property.

  • Specify a description of the property for display in property browsers.

  • Specify an associated member variable to store the property's data.

Options

Property Name

A text box that allows you to specify the name of your property. Property names usually start with a capital letter and must follow standard Java naming conventions.

Data Type

A dialog box that defines the data type for the property. You can enter a data type in the edit portion of the dialog box or select a predefined data type from the list.

Category

A dialog box that allows you to specify a category for your property. You can select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display properties in categories to make finding related properties easier.

Default Value

A text box that allows you to specify a default value to assign to the property. Any values assigned to the property should match the data type assigned for the property or errors will occur during compilation.

Description

A text box that allows you to enter a description for the property. The description of the property allows the user of the property to view descriptive information about the property. Visual J++ displays the description of the property in the description pane of the Properties window.

Associated Member Variable

A text box that allows you to enter the name of the member variable that will be associated with the property. The associated member variable is a private member used to store the property's data.


Modify Property Dialog Box

Allows you to modify a property in your class.

With the Modify Property dialog box you can:

  • Modify the name of the property.

  • Modify the data type of the property you wish to create.

  • Change the category for the property.

  • Change the initial value for the property.

  • Modify the description of the property.

Options

Property Name

A text box that allows you to change the name of the property. Property names usually start with a capital letter and must follow standard Java naming conventions.

Data Type

A dialog box that defines the data type for the property. You can enter a data type in the edit portion of the dialog box or select a predefined data type from the list.

Category

A dialog box that allows you to modify the category for the property. You can select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display properties in categories to make finding related properties easier.

Default Value

A text box that allows you to modify the default value to assign to the property. Any values assigned to the property should match the data type assigned for the property or errors will occur during compilation.

Description

A text box that allows you to modify the description of the property. The description of the property allows the user of the property to view descriptive information about the property. Visual J++ displays the description of the property in the description pane of the Properties window.


Clone Property Dialog Box

Allows you to create a new property based on a property defined in your class.

With the Modify Property dialog box you can:

  • Specify the name of the property you wish to create.

  • Specify the data type of the property you wish to create.

  • Choose a category for the property.

  • Specify an initial value for the property

  • Specify a description of the property for display in property browsers.

  • Specify an associated member variable to store the property's data.

Options

Property Name

A text box that allows you to specify the name of the property. Property names usually start with a capital letter and must follow standard Java naming conventions.

Data Type

A dialog box that defines the data type for the property. You can enter a data type in the edit portion of the dialog box or select a predefined data type from the list.

Category

A dialog box that allows you to specify a category for your property. select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display properties in categories to make finding related properties easier.

Default Value

A text box that allows you to specify a default value to assign to the property. Any values assigned to the property should match the data type assigned for the property or errors will occur during compilation.

Description

A text box that allows you to enter a description for the property. The description of the property allows the user of the property to view descriptive information about the property. Visual J++ displays the description of the property in the description pane of the Properties window.

Associated Member Variable

A text box that allows you to enter the name of the member variable that will be associated with the property. The associated member variable is a private member used to store the property's data.


Add Event Dialog Box

Allows you to create an event source for your class.

With the Add Event dialog box you can:

  • Specify the name of the event you wish to create.

  • Specify the type of the event you wish to create.

  • Choose a category for the event.

  • Specify a description of the event for display in property browsers.

Options

Name

A text box that allows you to specify the name of your event. Event names usually start with a capital letter and must follow standard Java naming conventions.

Type

A dialog box that defines the event type. You can enter a type in the edit portion of the dialog box or select a predefined type from the list.

Category

A dialog box that allows you to specify a category for your event. You can select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display events in categories to make finding related events easier.

Description

A text box that allows you to enter a description for the event. The description of the event allows the user of the event to view descriptive information about the event. Visual J++ displays the description of the event in the description pane of the Properties window.


Modify Event Dialog Box

Allows you to modify an event source in your class.

With the Modify Event dialog box you can:

  • Change the name of the event.

  • Modify the type of the event.

  • Modify the category for the event.

  • Change the description of the event for display in property browsers.

Options

Name

A text box that allows you to modify the name of the event. Event names usually start with a capital letter and must follow standard Java naming conventions.

Type

A dialog box that defines the event type. You can enter a type in the edit portion of the dialog box or select a predefined type from the list.

Category

A dialog box that allows you to modify the category for your event. You can select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display events in categories to make finding related events easier.

Description

A text box that allows you to modify the description for the event. The description of the event allows the user of the event to view descriptive information about the event. Visual J++ displays the description of the event in the description pane of the Properties window.


Clone Event Dialog Box

Allows you to create an event source based on an exiting event in your class.

With the Clone Event dialog box you can:

  • Choose between using a predefined event or creating a new event.

  • Specify the name of the event you wish to create.

  • Specify the type of the event you wish to create.

  • Choose a category for the event.

  • Specify a description of the event for display in property browsers.

Options

Name

A text box that allows you to specify the name of the event. Event names usually start with a capital letter and must follow standard Java naming conventions.

Type

A dialog box that defines the event type. You can enter a type in the edit portion of the dialog box or select a predefined type from the list.

Category

A dialog box that allows you to specify a category for your event. You can select a predefined category from the list. Categories allow you to group related properties. The Visual J++ Properties window allows you to display events in categories to make finding related events easier.

Description

A text box that allows you to enter a description for the event. The description of the event allows the user of the event to view descriptive information about the event. Visual J++ displays the description of the event in the description pane of the Properties window.


Introduction (Data Form Wizard)

The Data Form Wizard is designed to automatically generate WFC forms that contain individual bound controls and methods used to manage information derived from local or remote data sources. You can use the Data Form Wizard to create single recordset forms to manage the data from a single table or query.

This step of the wizard allows you to choose a profile to retrieve settings from a previous Data Form Wizard session.

Options

Profile Selection

A list that allows you to select a profile. A profile is a file that stores your settings from a previous wizard session. The ellipsis button, located next to the list, allows you to choose a profile other than those provided in the list.


Database Type (Data Form Wizard)

Allows you to select the type of database you want to use as a data source for this form.

Options

Database Formats List

Lists the database formats available to Visual J++. The available database formats are:

  • Access Any version of the Microsoft Access .MDB database.

  • Remote (ODBC) Any ODBC compliant database driver. You should select this option to connect with any ISAM database (dBase, FoxPro, Paradox) or remote data source (SQL Server, Oracle). Although you can use the Microsoft Access ODBC driver, it is recommended that you select the Access option to gain better performance.


Access Database (Data Form Wizard)

Allows you to select a Microsoft Access database file to use for your data form.

Options

Database Name

Allows you to enter the name and location of the Microsoft Access database file you want to use, or it displays the name of the database file you chose when you used the Browse button.

Browse

Displays an Open dialog box so you can search for the database file you want to use.

Record Sources

Allows you to choose which type of data source you want to use. Your options are:

  • Tables Allows you to select from tables in the database.

  • Queries Allows you to select query definitions from the database.


Connect Information (Data Form Wizard)

Collects the necessary information to connect to an ODBC data source. This step only appears if you chose Remote (ODBC) for the database type in the Database Type step of the wizard.

Options

DSN (Data Source Name)

Displays a list of DSNs currently installed on your computer to which you can connect. Use the 32-bit ODBC icon in the Control Panel to install new DSNs.

UID (User ID)

Allows you to type the User ID required to connect to this data source. If the data source does not require a User ID, leave this blank.

PWD (Password)

Allows you to type the password required to connect to the data source. If the data source does not require a password, leave this blank.

Database

Allows you to type the name of the database to which you want to connect.

Driver

Displays a list of drivers currently available on your computer that you can use to create a connection to a Remote data source. This option is not available if you select a DSN.

Server

Allows you to type the name of the server where the database resides. This option is not available if you select a DSN.


Form Type (Data Form Wizard)

Allows you to select the name and type of form you want to create.

Options

Form Name

Allows you to specify the name of the form. This name is also used to name the form's source file. The name of the data source (without its extension) is used as the default name.

Form Layout

Single record Specifies a form that displays one record at a time. This is the default.


Record Source (Data Form Wizard)

Allows you to choose the record source and fields within the record source to place on the form.

Options

Record Source

Lists available record sources in the database you chose. Depending on the data source, this could be tables, queries, or both.

Available Fields

Lists the available fields in the selected record source.

Selected Fields

Lists the fields to include in your form.

Selection and Order Buttons

Buttons are provided to move items between the Selected Fields list and the Available Fields list as well to change the order of the fields on the form. The following shows each button and its meaning:

Button | Description
 | Moves the selected field in the Available Fields list to the Selected Fields list.
 | Moves all of the fields in the Available Fields list to the Selected Fields list.
 | Moves the selected field in the Selected Fields list to the Available Fields list.
 | Moves all of the fields in the Selected Fields list to the Available Fields list.
 | Changes the order of the fields on your form. Each time you click the button, the selected field in the Selected Fields list moves up one position.
 | Changes the order of the fields on your form. Each time you click the button, the selected field in the Selected Fields list moves down one position.

Column to Sort By

Specifies the field you want to use for sorting. This can be any field in the selected record source and is not limited to the fields selected for display.


Control Selection (Data Form Wizard)

Allows you to choose the controls you want to appear on the form and enables the wizard to create the associated code for each control.

Options

Add Button

When selected, this option places an Add button on the form with the associated code to add new records to the database.

Delete Button

When selected, this option places a Delete button on the form with the associated code to delete records from the database.

Refresh Button

When selected, this option places a Refresh button on the form with the associated code to refresh data from the database.

Close Button

When selected, this option places a Close button with the associated code to close your form.

Show Data Navigator

When selected, this option places a Data Navigator control on your form for navigating the records of the form's recordset.


Summary (Data Form Wizard)

Allows you to specify a profile to save your wizard settings for reuse when using the wizard.

Options

Profile Name

A list that allows you to specify an existing profile to store your wizard settings. A profile file stores the settings of the wizard so they can be reselected the next time you use the Data Form wizard. A button located next to the list displays a dialog box in which you can create a new profile name and specify its location. The default setting is "(None)" which does not save your settings in a profile.

View Report

This button displays a dialog box that allows you to review the settings that you made while running the Data Form wizard. You can save the report as an HTML file to your hard disk for reading later.


Custom Tab (Project Properties Dialog Box)

The Custom Tab allows you to define commands that will be applied before and after building your project. When you build, Visual J++ creates a batch file that contains the commands specified in this dialog box. Visual J++ then executes the pre-build rules, if any, before building your project. After your project has successfully been built, the post-build rules are executed, if any are defined. All output from the pre- and post-build commands is displayed in the Visual J++ Output Window.

Options

Configuration

This option contains a list from which you can select your build type. This setting is global to all the tabs in this dialog box.

Your choices are:

  • Debug – This is the version of your application that includes information to assist in debugging.

  • Release – This is the version of your application that will be distributed to your users.

  • All Configurations – This option is used to make setting changes global to all build types.

Pre-Build Commands

A multi-line text box that defines the commands to execute before building the currently specified project. The pre-build commands can be any batch command or program you wish to execute. Clearing the text box prevents any pre-build commands from occurring.

Post-Build Commands

A multi-line text box that defines the commands to execute after building the currently specified project. The post-build commands can be any batch command or program you wish to execute. Clearing the text box removes any post-build commands.


WFC Controls Tab (Customize Toolbox Dialog Box)

Allows you to add or remove WFC components from the toolbox.

With the WFC Tab you can:

  • View a list of the installed WFC components on your system.

  • Add or remove WFC components from the toolbox.

Options

Installed Components List

A check box list of the WFC components currently installed on your system. A check mark in the check box next to the component name indicates that the component is currently displayed in your toolbox. The list also displays the package where the component is located.

Note To have a component displayed in the list of installed components, the path to the component must be defined in either the Classpath or the Java Package Manager.


Introduction (Application Wizard)

The Application Wizard provides a step-by-step way to create a Windows application. Various features can be selected during the course of the wizard, which can add additional capabilities to the application the wizard generates. The wizard generates all code and forms needed to produce a working "Notepad" style application. Once the wizard is complete, you can modify the application to fit the needs of your project. When the wizard has completed its process, a report can be displayed that provides helpful suggestions on features you can add or change in the wizard's output project.

Options

Profile Selection

A list that allows you to select a profile. A profile is a file that stores your settings from a previous wizard session. A button is provided next to the list to choose a profile file from your computer to use instead of those listed in the list.


Application Type (Application Wizard)

Allows you to determine the type of application the wizard will generate.

Options

Form Based Application

When selected, the Application wizard generates a form-based application. The application developed by the wizard is a simple "Notepad" type application.

Form Based Application with Data

When selected, the Application Wizard starts the Data Form wizard to step you through the process of creating a single form application based on a database.

Note This step of the Application wizard is only available in the Visual J++ Professional edition and the Enterprise edition of Visual Studio.


Application Features (Application Wizard)

Allows you to specify features to add to your application's form.

Options

Features List

A list of features that you can add to the application generated by the wizard. A check box next to each feature in the list indicates if the wizard will add it to your form. The following is a list of available features to add to your form:

Feature | Description
Menu | When selected, the wizard adds a pre-defined menu to the form it generates.
Edit | When selected, the wizard adds an edit control to the form that fills the contents of the window. By selecting the edit box option the wizard uses the edit control to create a "Notepad" style application.
Toolbar | When selected, the wizard adds a toolbar and pre-defined buttons to the form it generates.
Status Bar | When selected, the wizard adds a status bar to the form it generates.


Commenting Style (Application Wizard)

Allows you to specify the how much and what type of comments you want the wizard to generate for your application.

Options

Doc Comment

When this option is selected, the wizard adds Javadoc comments to all classes and their members. Javadoc comments make documenting your code easier. The comments generated by the wizard provide useful information on the code that the Application wizard generates.

TODO Comments

When this option is selected, the wizard adds TODO comments in sections of the code that the wizard generates which can be modified or where code should be added to enhance the application. You can view TODO comments in the Task List window.

Sample Functionality Comments

When this option is selected, the wizard adds comments for any sample functionality code generated by the wizard. Sample functionality comments provide information on what the code added by the wizard is intended to do, and it can assist you in determining what code was automatically generated for your application.


Summary (Application Wizard)

Allows you to specify a profile to save your wizard settings for reuse when using the wizard.

Options

Profile Name

A list that allows you to specify an existing profile to store your wizard settings. A profile file stores the settings of the wizard so they can be reselected the next time you use the Application wizard. A button located next to the list displays a dialog box where you can create a new profile name and specify its location. The default setting is "(None)" which does not save your settings in a profile.

View Report

This button displays a dialog box that allows you to review a report that contains the settings you made while running the Application wizard. The report also displays suggestions for things to consider or do with the application generated by the wizard. You can save the report as an HTML file to your hard disk for reading later.


WFC (Form Designers - Options Dialog Box)

Provides options for configuring the Visual J++ Forms designer.

With the WFC section of the Form options you can:

  • Determine if a grid is displayed on the Form designer to aid in placing controls.

  • Configure the height and width of grid cells on the Form designer.

  • Determine if controls will be automatically aligned with the grid.

Options

Show Grid

When selected, the form designer displays a grid. This grid allows you to position and align controls easier. This option is selected by default.

Vertical Spacing

A text box that allows you to define the width, in pixels, between each column in the Form designer grid. Assigning a smaller number assigns a smaller distance between grid columns. This text box is disabled if the Show Grid option is not selected.

Horizontal Spacing

A text box that allows you to define the height, in pixels, between each row in the Form designer grid. Assigning a smaller number assigns a smaller distance between grid rows. This text box is disabled if the Show Grid option is not selected.

Snap To Grid

When selected, controls added to a form or moved on a form are automatically aligned to the rows and columns of the Designer's grid. You can finely govern where controls are placed on a form, after they have been aligned on the grid, by changing the control's positioning properties. This option is not available if the Show Grid option is not selected. This option is selected by default.


Java Format (Text Editor - Options Dialog Box)

Provides options for Java source code formatting.

With the Java Format section of the Text editor options you can:

  • Determine if indenting will occur in the editor.

  • Specify the format style for code braces.

  • Specify how various code elements will be indented and aligned.

Options

Indenting

A group of options for determining the type of indentation support for the Text editor. The following is a list of the options available for indentation:

Indentation mode | Description
None | The Text editor does not automatically add indentation while you are entering code. Text goes to the beginning of the line when a return is entered.
Block | The text editor adds indentation but keeps the code on the same indentation level until you change it.
Smart | This is the default setting. The Text editor adds indentation and uses the context of the indentation to determine the level automatically.

Separate Smart Indent Actions In Undo List

When this option is selected, Undo commands (accessed by clicking the Undo menu item from the Edit menu or by pressing CTRL+Z on the keyboard) separates the automatic indentation caused by Smart indenting from other keystrokes. This allows you to undo Smart indentation actions without undoing the command that caused the indentation to occur. If the Smart indentation option is not selected, this option is disabled.

Indent Braces With Contained Code

When this option is selected, a brace is indented to be in-line with code that follows the brace. This option is not selected by default.

Format Open Brace

When this option is selected, open brace entries are formatted for you. A list is provided next to this option to allow you to select the style of open brace formatting. The following contains a list of the options for open brace formatting:

Open brace format | Description
On separate line | When this format is selected, an open brace is automatically positioned on a separate line from the method or code block that the open brace belongs to.
At end of line | When this format is selected, an open brace is automatically positioned on the same line as the method or code block that the open brace belongs to.

This option is not selected by default.

Indent Case Labels

When this option is selected, case labels are indented within the case's switch block. This option is not selected by default.

Align Operands In Multi-Line Expressions

When this option is selected, the operands in a multi-line expression are aligned one below the other. For example:

      int total += var1 + var2
                        + var3
                        + var4;

When not selected, continuation lines are indented by one additional tab stop. This option is selected by default.

Align Parameters

When this option is selected, the parameters in a multi-line method declaration or call are aligned with the first parameter in each line of the declaration or call. For example:

      public native void method1 (String arg1, String arg2
                                  String arg3,
                                  String arg4);

When not selected, continuation lines are indented by one additional tab stop. This option is selected by default


Java Tasks (Text Editor - Options Dialog Box)

Provides settings for determining how the Task List works with your code.

With the Java Tasks section of the Text editor options you can:

  • Determine if comment tasks will appear in the Task List.

  • Determine if Visual J++ will perform syntax checking of your code while you are typing.

  • Determine if code errors will be reported in both the Task List and the Text editor.

Options

Detect Comment Tasks

When this option is selected, the Task List displays comment tasks entered in code. You can add or modify the strings that you want to be detected as comment tasks in the Environment section of the Options dialog box. This option is selected by default.

Check Syntax As You Type

When this option is selected, Visual J++ checks the syntax of your code as you enter it in the Text editor. Syntax errors detected are displayed in the Task List. This option is selected by default.

Include Statement-Level Errors

When this option is selected, Visual J++ performs a more detailed check for syntax errors while you are typing. This option is not available if the Check Syntax As You Type option is not selected. This option is selected by default.

Underline Syntax Errors As You Type

When this option is selected, Visual J++ displays a red "squiggly" line under any code that contains a syntax error. This option is not available if the Check Syntax As You Type option is not selected. This option is selected by default.

Underline Java Compilation Errors

When this option is selected, the Visual J++ compiler displays a blue "squiggly" line under any code that produced an error during compilation. Descriptions of any errors that are found during compilation are displayed in the Task List. This option is selected by default.


EXE/DLL Options Tab (Advanced Properties Dialog Box)

Defines the options for COM DLL and Windows EXE packages.

With the EXE/DLL Options Tab of the Advanced Properties dialog box you can:

  • Specify the version of the COM DLL or Windows EXE package you are creating.

  • Specify the base DLL address for COM DLLs.

  • Enter product, company, and file information that can be viewed by a user.

Options

Version Number

Allows you to define the version information for the Windows EXE or COM DLL you are creating. Three text boxes are provided for defining the Major, Minor, and Revision numbers of the version. This information can be viewed from within Windows by the user to determine the version of the Windows EXE or COM DLL they are currently running.

Preview

A preview of what the version information will look like based on the numbers entered in the Major, Minor, and Revision text boxes.

DLL Base Address

A text box that allows you to specify the base memory address where the COM DLL will be loaded. This text box is only displayed when you are creating a COM DLL package. Specifying a base address for your COM DLL is not required. By specifying a base address, you can avoid using the same memory location as other DLL's in memory. This will cause the load time of your COM DLL to be faster.

Type

A list box that allows you to select the type of information to add or modify for the Windows EXE or COM DLL you are creating. The Value text box allows you to define a string value for each selected item in the list.

Value

A multi-line text box that allows you to specify a string value for the currently selected information type in the Type list box.


Packaging Options (Application Wizard)

Define the type of package to create for the application you are creating with the wizard.

Options

Class Files

When this option is selected, the Application wizard will not package the project into package file of any type. Use this option if you want to use some other method for distributing your application. This option is selected by default.

EXE File

When this option is selected, an EXE file will be created when your project is compiled and built. Use this option if you want to create a file that a user can use to run your application.

Cabinet File

When this option is selected, a cabinet file (CAB) will be created when your project is compiled and built. A CAB file is a compressed file that contains all of the important information for your project. Use this option if you plan to distribute your project through the Internet.

Deploy to (URL)

When this option is selected, you can define a URL to deploy your application to. The text box located below this option allows you to specify a URL to deploy your application to.


Samples

Visual J++ Samples

Thanks for using this version of Visual J++ Technology Preview 1.

The following samples are included in this technology preview:

  • ChatServer

  • dataBinder

  • Desk Manager

  • Executive Decision Maker

  • SamisLaw

  • TextFX

  • Wink Control

For last moment documentation updates, please review the Visual J++ readme file.


ChatServer Sample

Thanks for using this version of Visual J++ Technology Preview 1.

Click here to extract the sample.


dataBinder Sample

Thanks for using this version of Visual J++ Technology Preview 1.

Click here to extract the sample.


Desk Manager Sample

Desk Manager is a Desktop Icon Manager that allows you to change the otherwise unchangeable aspects of the icons on your Win95/NT4 desktop. Desk Manager uses a TrayIcon class that is a custom WFC Control class.

When running, the Desk Manager icon appears in the system tray. Right-clicking this icon will bring up a menu that allows you to change the style of the desktop, setting it to large icons, small icons, or details. It also allows you to make the icon labels transparent.

The Desk Manager sample demonstrates use of:

  • Win32 TrayIcon Feature

  • WFC control authoring

Click here to extract the sample.


Executive Decision Maker Sample

Thanks for using this version of Visual J++ Technology Preview 1.

Click here to extract the sample.


SamisLaw Sample

Thanks for using this version of Visual J++ Technology Preview 1.

Click here to extract the sample.


TextFX Sample

TextFX shows text, rendered between two arbitrary lines -- the effect is difficult to explain, yet easy to see. When started, random lines are drawn, and new random lines can be drawn using a menu option (or an accelerator). You may also click and drag the mouse to draw the lines. Once the second line is drawn, TextFX will render the text between the lines. You may change the text, change the font, and change other appearance options as well.

TextFX illustrates the following Win32 techniques:

  • Changing the class style.

  • Menus and Accelerators

  • Capturing the mouse input.

  • Creating a PeekMessage loop to temporarily trap all input.

  • Creating a Callback class to use with an API that wants a function pointer (LineDDA)

  • The Font selection common dialog.

  • Detailed GDI rendering, using paths, polylines, etc.

Click here to extract the sample.


Wink Control Sample

The Wink Control demonstrates creation of a Windows Foundation Class control. Moving the mouse pointer around the screen causes the eyes on this form-based control to follow the mouse movement.

The Wink Control illustrates use of:

  • WFC control authoring classes

Click here to extract the sample.


Extracting Visual J++ Samples

All Visual J++ samples are located in a single, self-extracting executable file. To extract and run these samples:

  • Insert CD1 of MSDN.

  • Navigate to the \\SAMPLES\VJ98 directory.

  • Double-click the file VJ6SAMPL.EXE


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Associating Data with a Callback

Frequently, it is necessary to pass some data from the caller of the function to the callback. This explains why EnumWindows takes an extra lparam argument. Most Win32 functions that take callbacks accept one extra 32-bit parameter that is passed to the callback without interpretation. With the Callback mechanism, it is not necessary to pass data using the lparam argument. Because the callback method is non-static, you can store your data as fields in the EnumWindowsProc object.


Casting to a Reference to an @dll.struct Class

One way to read and write data through a raw pointer is to cast the raw pointer to a reference to an @dll.struct class. Once this is done, you can read and write the data using normal field access syntax. For instance, suppose you have a raw pointer that you wish to access as a RECT. You can use the system method DllLib.ptrToStruct as follows:

/** @dll.struct() */
  class RECT {
    int left;
    int top;
    int right;
    int bottom;
  }

  import com.ms.dll.*;

  int  rawptr = ...;
  RECT rect = (RECT)DllLib.ptrToStruct(RECT.class, rawptr);
  rect.left = 0;
  rect.top = 0;
  rect.right = 10;
  rect.bottom = 10;

The ptrToStruct method wraps the raw pointer in a RECT instance. Unlike instances created by the new operator, this RECT instance will not attempt to free the raw pointer upon reclamation by the garbage collector because the RECT object has no way of knowing how the pointer was allocated. In addition, because the native memory was already constructed at the time ptrToStruct was called, the RECT class constructor is not called.


Comparison Between the Two Methods

In most cases, overloading is the preferred approach because it offers superior run time performance as well as better type checking. In addition, overloading avoids the need to wrap integer arguments inside an Integer object.

However, declaring the parameter as type Object can be useful in cases where there is more than one polymorphic parameter. You might also choose this method when you want to access a service that acts generically on a wide variety of types, such as a function that can accept any object declared with the @dll.struct directive.


Correspondence Between Types Inside Structures

The following table describes how scalar types map inside structures.

Java | Native
byte | BYTE
char | TCHAR (CHAR or WCHAR depending on @dll.struct definition)
short | SHORT
int | LONG
long | __int64
float | float
double | double
boolean | BOOL (32-bit boolean)

Reference types (Java objects and classes) normally map to embedded structures and arrays. Each supported mapping is described in the following table.

Java | Native
String | Pointer to a string, or an embedded fixed-string string
Class marked with @dll.struct | Nested structure
char[] | Nested array of TCHAR (CHAR/WCHAR)
byte[] | Nested array of BYTE
short[] | Nested array of SHORT
int[] | Nested array of LONG
long[] | Nested array of __int64
float[] | Nested array of floats
double[] | Nested array of doubles

There is no direct support for pointers inside structures, due to the large number of possible ways referenced objects could be allocated and disposed of. To represent a structure with an embedded pointer, declare the pointer field as type int. You will need to make explicit DLL calls to the appropriate allocation functions and initialize the memory blocks yourself. (You could use DllLib.ptrToStruct to map the blocks onto @dll.struct classes.)


Declaring a Method that Takes a Callback

To represent a callback parameter in Java, declare the Java type to be either type com.ms.dll.Callback or a class that derives from it. For example, the Microsoft Win32 EnumWindows function is prototyped as follows:

BOOL EnumWindows(WNDENUMPROC wndenumproc, LPARAM lparam);

The corresponding Java prototype is:

import com.ms.dll.Callback;
  /** @dll.import("USER32") */
  static native boolean EnumWindows(Callback wndenumproc,
                                    int lparam);


Declaring the Parameter as Type Object

The following shows how to declare WinHelp by declaring dwData as type Object:

  /** @dll.import("USER32") */
  static native boolean WinHelp(int hwnd, String szHelpFile,
                                int cmd, Object dwData);

When WinHelp is invoked, J/Direct will use the runtime type to determine how to translate dwData. The following table describes how the types are translated.

Type | Translated as
java.lang.Integer | 4-byte integer
java.lang.Boolean | 4-byte BOOL
java.lang.Char | CHAR (or WCHAR if the unicode or ole modifiers are in effect)
java.lang.Short | 2-byte SHORT
java.lang.Float | 4-byte FLOAT
java.lang.String | LPCSTR (or LPCWSTR if the unicode or ole modifier is in effect)
java.lang.StringBuffer | LPSTR (or LPWSTR if the unicode or ole modifier is in effect)
byte[] | BYTE*
char[] | CHAR* (or WCHAR* if the unicode or ole modifier is in effect)
short[] | SHORT*
int[] | INT*
long[] | __int64
float[] | float*
double[] | double*
@dll.struct | pointer to structure


Embedding a Callback Inside a Structure

To embed a callback inside a structure, you can first call the com.ms.dll.Root.alloc method to wrap the Callback in a root handle. Then pass the root handle to the DllLib.addrOf method to obtain the actual (native) address of the callback. Then, store this address as an integer.

For example, the WNDCLASS structure can be declared in Java as:

/** @dll.struct() */
  class WNDCLASS {
    int style;
    int   lpfnWndProc; // CALLBACK
    ... /* <other fields deleted for brevity> */
  }

Let's assume you have extended Callback as follows:

class WNDPROC extends Callback
  {
    public int callback(int hwnd, int msg, int wparam, int lparam)
    {
   ...
    }
  }

To store a pointer to the callback inside the WNDCLASS object, use the following sequence:

import com.ms.dll.*;
  WNDCLASS wc = new WNDCLASS();
  int callbackroot = Root.alloc(new WNDPROC());
  wc.lpfnWndProc = DllLib.addrOf(callbackroot);


Fixed-size Scalar Arrays Embedded within Structures

Fixed-size arrays of scalars embedded in structures can be specified using the @dll.structmap directive. The following is a C language structure that contains fixed-size scalar arrays:

struct EmbeddedArrays
{
  BYTE     b[4];
  CHAR     c[4];
  SHORT    s[4];
  INT      i[4];
  __int64  l[4];
  float    f[4];
  doubl    d[4];
};

You can specify the EmbeddedArrays structure by using @dll.structmap in the following way:

/** @dll.struct() */
class EmbeddedArrays
{
    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    byte b[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    char c[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    short s[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    int i[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    long l[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    float f[];

    /** @dll.structmap([type=FIXEDARRAY, size=4]) */
    double d[];

}


Fixed-size Strings Embedded within Structures

Some structures have fixed size strings embedded in them. The LOGFONT structure is defined as follows:

typedef struct {
     LONG lfHeight;
     LONG lfWidth;
     /* <many other fields deleted for brevity> */
     TCHAR lfFaceName[32];
   } LOGFONT;

This structure can be expressed in Java using an extension syntax to specify the size:

/** @dll.struct() */
   class LOGFONT {
     int lfHeight;
     int lfWidth;
     /* <many other fields deleted for brevity> */
     /** @dll.structmap([type=TCHAR[32]]) */
     String   lfFaceName;
   }

The @dll.structmap directive indicates the size of the fixed string as measured in characters (including space for the null terminator).

For more information, see:

  • Fixed-size Scalar Arrays Embedded within Structures


Invoking a Function that Takes a Callback

To invoke a function that takes a callback, you need to define a class that extends Callback. The derived class must expose one non-static method whose name is callback (all lowercase). The C language definition of WNDENUMPROC is:

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lparam);

To author an EnumWindowsProc in Java, you declare a class that extends Callback as follows:

class EnumWindowsProc extends Callback
  {
    public boolean callback(int hwnd, int lparam)
    {
      StringBuffer text = new StringBuffer(50);
      GetWindowText(hwnd, text, text.capacity()+1);

      if (text.length() != 0) {
        System.out.println("hwnd = " + Integer.toHexString(hwnd) +
                           "h: Text = " + text);
      }
      return true;  // return TRUE to continue enumeration.
    }

  /** @dll.import("USER32") */
  private static native int GetWindowText(int hwnd, StringBuffer text,
                                          int cch);
  }

You can invoke EnumWindows with this Callback in the following way:

boolean result = EnumWindows(new EnumWindowsProc(), 0);


Nested Structures

A structure can embed another structure simply by naming the other structure as the field type. For example, the Windows MSG structure embeds a POINT structure as follows:

   typedef struct {
      LONG x;
      LONG y;
   } POINT;

   typedef struct {
      int hwnd;
      int message;
      int wParam;
      int lParam;
      int time;
      POINT pt;
   } MSG;

This translates directly into Java as follows:

   /** @dll.struct() */
   class POINT {
      int x;
      int y;
   }
   /** @dll.struct() */
   class MSG {
      public int hwnd;
      public int message;
      public int wParam;
      public int lParam;
      public int time;
      public POINT pt;
   }

Tip Although embedding structures is handy, the fact remains that Java does not truly support embedded objects – only embedded references to objects. The Microsoft VM must translate between these two formats each time a nested structure is passed. Therefore, in a critical code path, you can improve performance by nesting structures manually (by copying the fields of the nested structure into the containing structure). For example, the pt field in the MSG structure could easily be declared as two integer fields, pt_x and pt_y.


Overloading the Function

Another way to declare the WinHelp function is to overload the function for each possible type:

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, int dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, String dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, MULTIKEYHELP dwData);

/** @dll.import("USER32") */
static native boolean WinHelp(int hwnd, String szHelpFile,
                              int cmd, HELPWININFO dwData);

You cannot handle a polymorphic return value using overloading because Java methods cannot be overloaded on return value only. Therefore, you need to give each variant of the function a different Java name and use the entrypoint modifier to link them all to the same DLL method. See Aliasing (Method Renaming) to learn more about renaming DLL methods.


Passing a String to a DLL Function

To pass a standard null-terminated string to a DLL function, just pass a Java String.

For example, to change the current directory, you can access the Kernel32 function CopyFile as follows:

class ShowCopyFile
{
  public static void main(String args[])
  {
    CopyFile("old.txt", "new.txt", true);
  }
  /** @dll.import("KERNEL32") */
  private native static boolean CopyFile(String existingFile,
                                  String newFile, boolean f);
}

Strings are read-only in Java, so the Microsoft VM will only convert the String object as an input. To allow virtual machine implementations to marshal Strings without copying the characters, String object parameters should not be passed to DLL functions that can modify the string. If the DLL function might modify the string, pass a StringBuffer object.

Strings are converted to ANSI unless the unicode or ole modifier is used, in which case the string is passed in Unicode format.

Strings cannot be declared as return types of a DLL function except in ole mode, where the native return type is assumed to be a LPWSTR allocated using the CoTaskMemAlloc function.


Raw Pointers

A pointer to an unknown or particularly difficult structure can be stored in a plain Java integer. If your application only needs to store the pointer and not dereference it, this is the simplest and most efficient approach. You might want to use this technique to store a pointer that has been returned by a DLL function that allocates a memory block. In fact, you can use this technique to store a pointer returned by any DLL function. Needless to say, using raw pointers eliminates many of the safety advantages of Java. An alternative approach should be used whenever possible. However, there are situations when you might choose to use raw pointers. With that in mind, there are two ways to read and write data from raw pointers.

For more information, see:

  • Casting to a Reference to an @dll.struct Class

  • Using the DllLib Copy Methods


Receiving a String from a DLL Function

There are two common ways of passing a string back from a function: either the caller allocates a buffer that is filled in by the function, or the function allocates the string and returns it to the caller. Most Win32 functions use the first method, but OLE functions use the second method. (See Invoking OLE API Functions to learn about the special support that J/Direct provides for calling OLE functions.) One function that uses the first method is the Kernel32 function GetTempPath, which has the following prototype:

DWORD GetTempPath(DWORD sizeofbuffer, LPTSTR buffer);

This function simply returns the path of the system tempfile directory (such as "c:\tmp\"). The buffer argument points to a caller-allocated buffer that receives the path, and sizeofbuffer indicates the number of characters that can be written to the buffer. (This is different from the number of bytes in the Unicode version.) In Java, strings are read-only, so you cannot pass a String object as the buffer. Instead, you can use Java's StringBuffer class to create a writable StringBuffer object. The following is an example that invokes the GetTempPath function:

class ShowGetTempPath
{
  static final int MAX_PATH = 260;
  public static void main(String args[])
  {
    StringBuffer temppath = new StringBuffer(MAX_PATH);
    GetTempPath(temppath.capacity(), temppath);
    System.out.println("Temppath = " + temppath);
  }

  /** @dll.import("KERNEL32") */
  private static native int GetTempPath(int sizeofbuffer,
                                        StringBuffer buffer);
}

To understand this example, it is important to distinguish between a StringBuffer's length and its capacity. The length is the number of characters logically in the string currently stored in the StringBuffer. The capacity is the actual amount of storage currently allocated to that StringBuffer. After the following statement executes:

StringBuffer sb = new StringBuffer(259);

the value of sb.length is zero, and the value of sb.capacity is 259. When you invoke a DLL method passing a StringBuffer, the Microsoft VM examines the capacity of the StringBuffer, adds one for the null terminator, multiplies by 2 if Unicode is the default character size, and then allocates that many bytes of memory for the buffer that is passed to the DLL function. In other words, you use the capacity, not the length, to set the size of the buffer. Be careful not to make the following mistake:

StringBuffer sb = new StringBuffer();  //Wrong!
  GetTempPath(MAX_PATH, sb);

Invoking the StringBuffer constructor with no arguments creates a StringBuffer object with a capacity of 16, which is probably too small. MAX_PATH was passed to the GetTempPath method, indicating that there was enough room in the buffer to hold 260 characters. Thus, GetTempPath will probably overrun the buffer. If you were planning to use GetTempPath extensively, you should wrap it in a Java-friendly wrapper in the following manner:

public static String GetTempPath()
{
  StringBuffer temppath = new StringBuffer(MAX_PATH-1);
  int res = GetTempPath(MAX_PATH, temppath);
  if (res == 0 || res > MAX_PATH) {
    throw new RuntimeException("GetTempPath error!");
  }
  return temppath.toString(); // can't return a StringBuffer
}

This method offers both convenience and safety, and it maps the error return value of the function to a Java exception. Notice that you cannot return StringBuffer objects.


Restrictions on Types Accepted by the Callback Method

The return type of the callback method must be void, int, boolean, char, or short. The only parameter type currently allowed is the int type. Fortunately, this is not as restrictive as it sounds. You can use the DllLib methods ptrToStringAnsi, ptrToStringUni, and ptrToString to treat a parameter as an LPTSTR. You can use the ptrToStruct method to treat a parameter as a pointer to an @dll.struct class.


Return Value Pointers

Win32 functions that have multiple return values typically handle them by having the caller pass a pointer to a variable to be updated. For example, the GetDiskFreeSpace function has the following prototype:

BOOL GetDiskFreeSpace(LPCTSTR szRootPathName,
                         DWORD  *lpSectorsPerCluster,
                         DWORD  *lpBytesPerCluster,
                         DWORD  *lpFreeClusters,
                         DWORD  *lpClusters);

GetDiskFreeSpace is typically called as follows:

DWORD sectorsPerCluster, bytesPerCluster, freeClusters, clusters;
GetDiskFreeSpace(rootname, &sectorsPerCluster,
                 &bytesPerCluster, &freeClusters, &clusters);

In Java, this is just a special case of passing scalar arrays where the array size is one element. The following example shows how to call the GetDiskFreeSpace function:

class ShowGetDiskFreeSpace
{
  public static void main(String args[])
  {
    int sectorsPerCluster[] = {0};
    int bytesPerCluster[] = {0};
    int freeClusters[] = {0};
    int clusters[] = {0};
    GetDiskFreeSpace("c:\\", sectorsPerCluster, bytesPerCluster,
                     freeClusters, clusters);
    System.out.println("sectors/cluster  = " + sectorsPerCluster[0]);
    System.out.println("bytes/cluster = " + bytesPerCluster[0]);
    System.out.println("free clusters = " + freeClusters[0]);
    System.out.println("clusters = " + clusters[0]);
  }

  /** @dll.import("KERNEL32") */
  private native static boolean GetDiskFreeSpace(String rootname,
                   int pSectorsPerCluster[], int pBytesPerCluster[],
                   int pFreeClusters[], int pClusters[]);
}


Security Checks at Link Time

Linking is what occurs when one Java class invokes or accesses (using the Reflection API) a member of another class. At link time, the Microsoft VM checks to see whether the class being referenced is accessible and whether the arguments being passed are of the correct type and number. The class is considered accessible if it is in the same package or if it is declared public.

With the standard Java language, you are limited to a choice of two options for class accessibility: you can either declare a class public (so that anyone can link to it) or you can declare class without the public modifier (so that only classes in the same package can link to it). However, with Microsoft Internet Explorer 4.0, there is now a third option. You can declare the class as "public for fully trusted callers only." You can declare any class with this type of accessibility, even if the class does not use J/Direct. To declare the class, place the following directive at the beginning of the class.

/** @security(checkClassLinking=on) */

It is important to notice that this security check only prevents untrusted callers from directly calling the "protected" class. It does not prevent indirect calls. A third (fully trusted) class can forward a call from an untrusted caller to the "protected" class. However, there is a safeguard. The intermediate class must either be installed on the target computer's CLASSPATH, or it must be digitally signed for maximum trust and installed using the browser.


Security Checks Upon Every Invocation

This is the most stringent check available. On every call, the entire call stack is examined. If even one caller that is not fully-trusted is discovered on the call stack, a SecurityException is thrown. By default, all J/Direct methods perform this check. RNI methods do not perform this check due to backward compatibility requirements. RNI was designed to allow easy porting from the original JDK 1.0 native interface, which did not offer this security check.

Although this security check offers maximum safety, Microsoft offers a way to disable it. The mechanism for disabling is provided because this stringent security check has two important side effects:

Possible Performance Degradation | This security check requires a scan of the entire call stack each time a J/Direct method is called. The performance degradation is most noticeable on trusted applets, which generally run with a security manager present. Applications, on the other hand, usually do not see a significant performance drop. This is due to the fact that J/Direct omits the call stack scan for applications that run without a security manager.
Inflexibility | This security mechanism forces the use of maximum permissions, even in cases where only one specific permission is required. For example, consider a trusted library that uses J/Direct to expose a single permission to untrusted applets in a safe way. It would be appropriate for this library to turn off the call time security check and perform its own security check for the specific permission.

The @security directive disables the per-invocation security check. The syntax for this directive is:

/** @security(checkDllCalls=off) */

The @security directive applies to the entire class. Individual methods within a class cannot be tagged. The following example shows the placement of the @security directive:

/** @security(checkDllCalls=off) */
  class FastJDirectMethods{
    /** @dll.import(...) */
    static native void func();
  }

Be aware of the fact that disabling this security check transfers responsibility for security from the Microsoft VM to you. Remember that even with this security check disabled, you will still have to digitally sign the class for maximum trust. If you decide to use this directive, be sure to take the following precautions:

  • All J/Direct methods should be declared private.

  • Any publicly accessible methods should never blindly pass caller arguments to J/Direct. You must take responsibility for ensuring that only valid arguments are passed to native code.

  • Your class should expose no more capability than is required, and it should guard all access to these capabilities with the appropriate security checks.

Important Calls from within an applet's init, start, stop, or destroy methods may trigger a SecurityExceptionEx even if the applet is trusted. To avoid this situation, you should assert permissions by executing the following code:

  import com.ms.security.*;
    ...
  PolicyEngine.assertPermission(PermissionID.SYSTEM);


Security Checks Upon First Invocation

The first invocation of a method is the first time the method is invoked from any caller. At this time, for each method marked with the native keyword, the Microsoft VM determines whether the method is a member of a fully trusted class. If it is not, a SecurityException is thrown that includes the message, "Only fully trusted classes can have native methods as members." Because this security check does not depend on the calling context, it only needs to be performed once. If it passes, the check does not take place on future invocations. There is no way to disable this security check.


Structure Packing

Structure fields are padded and aligned according to ANSI C draft 3.5.2.1. The packing size can be set using the pack modifier:

/** @dll.struct(pack=n) */

where n can be 1, 2, 4 or 8. The default is 8. For users of the Microsoft Visual C++ compilers, "pack=n" is equivalent to "#pragma pack(n)".


The Lifetime of a Callback

Some care is required to ensure that the Callback is not reclaimed by garbage collection before the native function is finished with it. If the callback is short-term (only callable for the duration of one function call), no special action is required because a Callback passed to a DLL function is guaranteed not to be reclaimed by garbage collection while the call is in progress.

If a callback is long-term (used across function calls), you will need to protect the Callback from being reclaimed, typically by storing a reference to it in a Java data structure. You can also store references to Callbacks within native data structures by using the com.ms.dll.Root class to wrap the Callback inside a root handle. The root handle is a 32-bit handle that prevents the Callback from being reclaimed until the handle is explicitly freed. For example, a root handle to a WndProc can be stored in the application data area of an HWND structure, and then explicitly freed on the WM_NCDESTROY message.


Understanding the Relationship Between @dll.struct and @com.struct

The @dll.struct directive is very similar to the @com.struct directive emitted by the jactivex tool and implicitly by the javatlb tool. (The javatlb tool, documented in previous versions of Microsoft Visual J++, has been replaced by jactivex.) The main difference is that the default type mappings are suited for Microsoft Windows function calling instead of COM object calling. Given this information, it follows that you can also generate @dll.struct classes by describing the structure in a type library and using the jactivex tool to generate the Java class. However, it's usually faster to generate the classes manually.


Using the DllLib Copy Methods

Another method for reading and writing data through a raw pointer is to use the overloaded copy methods in DllLib. These methods copy data between Java arrays of various types and raw pointers. If you need to treat a raw pointer as a pointer to a string (LPTSTR), you can use one of the DllLib methods ptrToStringAnsi, ptrToStringUni, or ptrToString to parse the string and convert it into a java.lang.String object.

import com.ms.dll.*;

  int rawptr = ...;
  String s = DllLib.ptrToStringAnsi(rawptr);

! WARNING All Java objects are subject to movement in memory or reclamation by the garbage collector. Therefore, you should not attempt to obtain a pointer to a Java array by calling a DLL function that does generic casting. The following example shows you an incorrect way to obtain the pointer:

// Do not do this!
  /** @dll.import("MYDLL") */
  private native static int Cast(int javaarray[]);

  // Inside MYDLL.DLL
  LPVOID Cast(LPVOID ptr)
  {
    // Do not do this!
    return ptr; // comes in as a Java array; goes out as a Java int
  }

The value of ptr is guaranteed to be valid only for the duration of the call to the Cast function. This is because VM implementations are allowed to implement passing of arrays by copying and because garbage collection may cause the physical location of the array to be different after the call to the Cast function returns.


Adding Items to Class Outline from the Text Editor

Although Visual J++ provides Class Outline and Class Builder to help you add methods, member variables, and classes to a project, you can also add these to your project by typing the code directly into your .java file from the Text editor. When you add the code for new classes and class members to a .java file, IntelliSense immediately displays the appropriate icon for the new class or class member in your project's Class Outline.

The following procedure demonstrates the dynamic updating of Class Outline when a new class and method is added to a source file from the Text editor.

Note The code examples in this and the following topic, Adding Javadoc Comments to Source Files, were created with a Visual J++ Console Application project. You may use any existing Visual J++ project to reproduce the results of these scenarios. If you want to create a Console Application project for the following procedures, see Using the Console Application Template and follow the steps to create and open the project before proceeding.

To add a new class to Class Outline from the Text editor

  1. In Project Explorer, click the plus ("+") sign to the left of your project's name to expand your project.

  2. Double-click the filename or icon of the .java file containing your project's main() method (Class1 .java by default).

    Visual J++ opens the Text editor and loads your .java file. The file is now ready for editing.

  3. On the View menu, click Other Windows and select Document Outline from the cascading menu.

    Class Outline appears with a collapsed tree view of your file.

  4. From within the Text editor, after the closing brace of the class definition for Class1, add the following code to your .java source file:
    class Greeting
{
}
  5. In Class Outline, notice that a new class icon has been added to the tree view of your project's file for the Greeting class you've just created.

Note When you use the Text editor to move the insertion point in the source file, Class Outline does not indicate which definition has been navigated to. To synchronize Class Outline with the source file, right-click the declaration in the Text editor and click Sync Class Outline on the shortcut menu.

To add a new method to Class Outline from the Text editor

  1. In Class Outline, expand the Greeting class to display the icons for Superclasses and Inherited Members.

  2. From within the Text editor, add the following code after the opening brace of the Greeting class:
    public static String hello()
{
String strGreet = new String("Hello World!");
return strGreet;
}
  3. In Class Outline, notice a new method icon has been added to your project for the hello() method you've just created.

Note When you use the Text editor to move the insertion point in the source file, Class Outline does not indicate which definition has been navigated to. To synchronize Class Outline with the source file, right-click the declaration in the Text editor and click Sync Class Outline on the shortcut menu.

  3. To test the hello() method of the Greeting class, add the following code to your application's main() method:
    System.out.println(Greeting.hello());
return;
  4. Build the program.

  5. In the Text editor, place the cursor on "return" (the last statement of this program's code). Click the right mouse button and select Run To Cursor from the shortcut menu.

  6. View the following results in JVIEW's console window:
    Hello World!

To add a Javadoc comment to the new hello() method, see Adding Javadoc Comments to Source Files.


Adding Javadoc Comments to Source Files

Below your file's tree view in Class Outline is a Javadoc pane. If a class, method, or member variable has Javadoc comments , the comments appear in this pane. When you add a Javadoc comment to your code, IntelliSense displays the first sentence of the comment in the Javadoc pane whenever you highlight a class, method, or member variable name in Class Outline.

The following procedure explains how to add a Javadoc comment to a method; however, you follow the same steps to add Javadoc comments to classes and member variables.

Note This procedure uses a Console Application project and adds to the code created in the scenario that updates items in Class Outline. If you have not completed the steps that add a Greeting class and hello() method to a basic Console Application, take a few minutes and follow the steps in Adding Items to Class Outline from the Text Editor before continuing.

To add a Javadoc comment to a method

  1. In Project Explorer, click the plus ("+") sign to the left of your project's name to expand your project.

  2. Double-click the filename or icon of the .java file containing your project's main() method (Class1 .java by default).

    Visual J++ opens the Text editor and loads your .java file. The file is now ready for editing.

  3. On the View menu, click Other Windows and select Document Outline from the cascading menu.

    Class Outline appears with a collapsed tree view of your project.

  4. In Class Outline, expand the Greeting class to display the icons for Superclasses, Inherited Members, and the hello() method.

  5. From within the Text editor, type the opening characters for a Javadoc comment, /**, above the hello() method declaration in your source file.

    IntelliSense creates a Javadoc comment block by inserting the closing characters for a Javadoc comment, */, into your code.

  6. After the opening characters of the Javadoc comment block, type the following:
    /** The hello() method is a static method that takes
 * no arguments and returns a String object to the
 * calling method. The value returned will always
 * be "Hello World!".
 */
  7. In Class Outline, highlight the hello() method.

    Notice that the first sentence of the comment you've just added appears in the Javadoc pane.

When you are creating Javadoc comments for your classes, methods, and member variables, you may want or need to add one or more Javadoc fields to a comment. IntelliSense displays a list of Javadoc fields available in Visual J++. The following procedure adds an author field to the Javadoc comment created above.

To add an Javadoc field to a Javadoc comment

  1. In Project Explorer, click the plus ("+") sign to the left of your project's name to expand your project.

  2. Double-click the filename or icon of the .java file containing your project's main() method (Class1 .java by default).

    Visual J++ opens the Text editor and loads your .java file. The file is now ready for editing.

  3. In the hello() method's Javadoc comment, after the last sentence but before the closing Javadoc characters, */, type an @ sign.

    IntelliSense displays a list box of valid Javadoc comment fields.

  4. Double-click "author" in the list box.

    The word "author" is inserted into your Javadoc comment after the @ sign.

  5. Type your name after @author.

    Your finished Javadoc comment should look like this:

    /** The hello() method is a static method that takes
 * no arguments and returns a String object to the
 * calling method. The value returned will always
 * be "Hello World!".
 * @author Mary Doe
 */


Building an Argument List with Parameter Info

This example uses Statement Completion's Parameter Info feature to display information for a method's argument.

Note If you have completed the steps of Creating Statements with Word Completion, Selecting an Overloaded Method, and Selecting Methods from a Member List, continue with the following procedure. If not, take a few minutes and work through those procedures before selecting a method for the String class.

Before proceeding, make sure you have loaded a .java file into the Text editor that contains the following code:

String myStr = new String("Hello World!");
if(myStr.equalsIgnoreCase

To select build an argument list with Parameter Info

  1. Continuing to build the if statement, type an opening parenthesis, "(", immediately after "myStr.equalsIgnoreCase".

    Parameter Info displays the method's declaration with the single parameter (String p1) in a bold-type font.

    Note In this case, the method has only one parameter (String p1). If you select a method that takes more than one argument, IntelliSense displays argument types and positions within the method declaration. When you type the opening parenthesis after the method's name, IntelliSense bolds the first argument. As you add commas between the arguments, IntelliSense bolds the type and position information for the next argument that's needed to complete the method's call.

    Tip If you do not get a pop-up window with parameter information after you type the opening parenthesis, select Parameter Info from the Edit menu or use the keyboard shortcut, CTRL+SHIFT+I. If this continues to happen, make sure you've enabled the Statement Completion feature.

  2. After the opening parenthesis, complete the statement by typing:
    "hello world!"))

    The completed if statement should look like the following:

    if(myStr.equalsIgnoreCase("hello world!"))
  3. Using the Statement Completion's Word Completion, Member List, and Parameter Info options, complete this example by adding the following code after the closing parenthesis of the if statement:
       {
System.out.println("The strings are the same.");
}
else
   {
System.out.println("The strings are different.");
}
return;
  4. Build the program.

  5. In the Text editor, place the cursor on "return" (the last statement of this program's code). Click the right mouse button and select Run To Cursor from the shortcut menu.

  6. View the following results in JVIEW's console window:
    The strings are the same.


Coffee and Tea Source Code

The following code snippet supports the creation of the Multithreaded Beverages Application. The following Coffee and Tea classes extend the Thread class which allows them to run on separate threads.

class Coffee extends Thread
{
   public void run()
   {
      for(int i = 0; i < 10; i++)
      {
         System.out.println("I Like Coffee" + “ “ + i);
         yield();
      }
   }
}

class Tea extends Thread
{
   public void run()
   {
      for(int i = 0; i < 10; i++)
      {
         System.out.println("I Like Tea" + “ “ + i);
         yield();
      }
   }
}


Creating Statements with Word Completion

For the examples in this topic, Word Completion provides visual clues when you're typing the name of String and System classes, and creating a new String object. Word Completion is available for any Visual J++ project.

Note The code examples in the following scenario were created with a Visual J++ Console Application project. If you would like to create a Console Application project to complete this scenario, see Using the Console Application Template and follow the steps to create and open the project before proceeding.

To select an item from a list provided by the Word Completion feature

  1. On the View menu, click Project Explorer") to open Project Explorer.

  2. In Project Explorer click the plus ("+") sign to the left of your project's name to expand your project.

  3. Highlight the .java file containing your project's main() method (Class1.java by default) and select View Code from the shortcut menu.

    Visual J++ opens the Text editor and loads your .java file. The file is now ready for editing.

  4. To get Word Completion assistance for the String class, type an "S" between the braces of the application's main() method and leave the cursor to the right of this letter.

    Tip Notice the red squiggly line drawn under the letter. Since an "S" has no significance within the context of this program, IntelliSense gives a visual clue for the syntax error. For more information about visual editing clues, see Finding Errors with Dynamic Syntax Checking.

  5. On the Edit menu, click Complete Word to display a list box of classes and other elements recognized by IntelliSense.

    Tip You can use the keyboard shortcut, CTRL+SPACE, instead of selecting the Complete Word option on the Edit menu, to display this list box.

  6. With the list box still displayed, type a "T" after the "S" of the statement you're building in your .java file.

    Statement Completion now selects StackOverflowError in its list — the first element that starts with an "ST" in the context of this program.

  7. Now type an "R" after the "ST" in your statement and Statement Completion moves the highlight bar to String in the list box.

  8. Press the Tab bar to insert "String" into the statement you're building.

    Pressing the Tab bar or any other non-alphanumeric key, such as a period or opening parenthesis, places the selected item into a statement at the location of the insertion point.

    Tip Instead of typing the letters until Statement Completion finds the element you need, you can use the up and down arrows to highlight your selection.

To select a class name after the new operator

  1. Continue to build the statement by typing the following code after "String":
    [String] myStr = new
  2. Type a space after "new" and Statement Completion automatically displays a list of class names available within the scope of your program.

  3. Type "STR", or enough letters of "String" to select the String item from the list.

  4. Press Tab and "String" is inserted after "new".

    Your statement should look like this:

    String myStr = new String

To continue building the statement that displays a line of text, you'll need a constructor for the new String object. See Selecting an Overloaded Method for a procedure that selects a String constructor with Statement Completion's Parameter Info option.

If you know how to partially spell the name of the class or item, use the following procedure to speed up the process of typing and selecting the correct spelling and capitalization.

To finish typing a word using the Word Completion feature

  1. In your .java file, move the cursor to a new line and type "SY".

  2. Press CTRL+SPACE (the Word Completion keyboard shortcut).

    Statement Completion completes the word, "System", and inserts it into your code since it is the only item that begins with an "SY". If more than one item starts with these letters, Statement Completion displays a list box.


Displaying the Threads Debug Window

To display the Threads debug window

  • On the View menu, click Debug Windows, and then select Threads.

    – or –

    Press the key combination, CTRL+ALT+H.

    – or –

    Click the Threads button on the Debug toolbar.


Enabling/Disabling Dynamic Syntax Checking Options in the Text Editor

Within the development environment, you can enable or disable the editor's dynamic syntax checking options.

To enable dynamic syntax checking options

  1. On the Tools menu, click Options to display the Options dialog box.

  2. From the tree view in the leftmost pane of the Options dialog box, expand the Text Editor node by clicking the plus ("+") sign next to it.

  3. Select Java Tasks to display the property page for Tasks and Error display.

  4. In the Tasks group of this property page, click the check box for Check syntax as you type.

  5. In the Error Display group of the property page, click the check box for Underline syntax errors as you type.

Visual J++ enables these dynamic syntax checking options by default.

Note Clearing the check box for Check syntax as you type or Underline syntax errors as you type disables the respective option.


Enabling/Disabling Statement Completion Options in the Text Editor

Within the development environment, you can enable or disable Statement Completion's Auto list members and Parameter information options.

To enable Statement Completion options

  1. On the Tools menu, click Options to display the Options dialog box.

  2. From the tree view in the leftmost pane of the Options dialog box, expand the Text Editor and then the Per Language nodes by clicking the plus ("+") sign next to these nodes.

  3. Select Java to display the Text Editor/Per Language/Java property page.

  4. In the Statement Completion group of this property page, click the check boxes for Auto list members and Parameter information to enable these options.

Visual J++ enables Statement Completion's Auto list members and Parameter information by default.

Note Clearing the check box for Auto list members or Parameter information disables the respective option.


Finding Matching Delimiters

Source code is often grouped using delimiters such as (), {}, [], and <>. These groupings are called levels. The editor understands nested levels, and matches the correct delimiter even if the level spans several pages and contains many levels within it. The editor's functionality allows you to jump quickly between the start and end of a level.

To find a matching delimiter

  1. Place the insertion point immediately before or after any delimiter.

  2. Press the keyboard shortcut, CTRL+].

    The insertion point moves forward or backward to the matching delimiter. Choosing the command again returns the insertion point to its starting place. If a matching delimiter cannot be found, the insertion point does not move.


Finding and Replacing Text in a Single File

To find text in a single file

  1. Move the insertion point to the location in your file where you want to begin your search.

  2. On the Edit menu, click Find and Replace.

    The Find tool window appears.

  3. In the text box next to the Find button, type the search text.

    You can also use the drop-down list to select from a list of your previous search strings.

  4. From the Look In combo box, select Current Document.

  5. To begin your search, click Find.

    This highlights the first occurrence of your search item.

  6. To continue searching, click Find.

To replace text in a single file

  1. Move the insertion point to the location in your file where you want to begin your search.

  2. On the Edit menu, click Find and Replace.

    The Find tool window appears.

  3. In the text box next to the Find button, type the search text.

    You can also use the drop-down list to select from a list of your previous search strings.

  4. From the Look In combo box, select Current Document.

  5. In the text box next to the Replace button, type the replacement text.

  6. Click Replace.

    The first occurrence of your search item is highlighted in the Text editor.

    Note To replace all occurrences within the file, click Replace All.

  7. Click Replace again.

    This replaces the current selection and highlights the next occurrence of the search item.


Finding Text in Multiple Files

To find text in multiple files

  1. On the Edit menu, click Find and Replace.

    The Find tool window appears.

  2. In the text box next to the Find button, type the search text.

    You can also use the drop-down list to select from a list of your previous search strings.

  3. From the Look In combo box, choose the types of files in which to search.

  4. Click Browse, to display the Look In dialog box.

  5. Highlight the top level folder in which to begin the search.

  6. Click Add.

    The name of the folder appears in the bottom text box of the Look In dialog box.

  7. Click OK to return to the Find dialog box.

  8. Click the Subfolders check box to include files in subdirectories of the previously selected top-level folder.

  9. To begin your search, click Find.

    A list of files containing the search text appears in bottom window of the Find dialog box.

  10. Double-click an entry from the list.

    An editor window containing the file opens with the line containing the search text selected.


Navigating with Bookmarks

You can set bookmarks to mark frequently accessed lines in your source file. Once a bookmark is set, you can use menu or keyboard commands to move to it. You can remove a bookmark when you no longer need it.

To set a bookmark

  1. Move the insertion point to the line where you want to set a bookmark.

  2. On the Edit menu, click Bookmarks and then choose Toggle Bookmark from the cascading menu.

    -or-

    Press the Toggle Bookmark keyboard shortcut, CTRL+K, CTRL+K.

    A light blue rectangle appears in the margin next to the line selected if you have enabled your editor to display margins.

To navigate to the next bookmark

  • On the Edit menu, click Bookmarks and then choose Next Bookmark from the cascading menu.

    -or-

    Press the Next Bookmark keyboard shortcut, CTRL+K, CTRL+N.

To navigate to the previous bookmark

  • On the Edit menu, click Bookmarks and then choose Previous Bookmark from the cascading menu.

    -or-

    Press the Previous Bookmark keyboard shortcut, CTRL+K, CTRL+P.

To remove a bookmark

  1. Move the insertion point to the line where a bookmark exists.

  2. On the Edit menu, click Bookmarks and then choose Toggle Bookmark from the cascading menu.

    -or-

    Press the Toggle Bookmark keyboard shortcut, CTRL+K, CTRL+K.

    The light blue rectangle disappears from the margin.

To remove all bookmarks

  • On the Edit menu, click Bookmarks and then choose Clear All Bookmarks from the cascading menu.

    -or-

    Press the Clear All Bookmarks keyboard shortcut, CTRL+K, CTRL+L.


Navigation Keyboard Shortcuts for the Auto, Locals, and Watch Windows

You can use the following keys to view or hide member variables of a selected class or array or to move around in the Auto, Locals, or Watch windows:

To | Use the
Collapse the member variables list | LEFT ARROW
View the member variables | RIGHT ARROW
Toggle between hiding and viewing the variables | ENTER
Move upward in the member variables list | UP ARROW
Move downward in the member variables list | DOWN ARROW
Move up an expanded list | LEFT ARROW
Move down an expanded list | RIGHT ARROW

Note You can change the size of a column by dragging the border of the column header to the right to make the column larger or to the left to make it smaller.


Observing Thread Activity in the Threads Debug Window

The application example for this procedure creates two threads in the main() and displays output to a JVIEW console window. This procedure refers to code created in the Multithreaded Beverages Application. If you’d like to create this project to complete the following exercises, do so now. You may also use the following procedure to observe thread activity of any multithreaded application.

To observe thread activity in the Threads debug window

  1. Set a breakpoint in the Coffee class on the following statement:
         System.out.println("I Like Coffee" + “ “ + i);
  2. Set a breakpoint in the Tea class on the following statement:
         System.out.println("I Like Tea" + “ “ + i);
  3. In Class1’s main() method, place the insertion point on the following statement:
      Coffee m_Coffee = new Coffee();  //creates Coffee object
  4. Click the right mouse button and select Run To Cursor from the shortcut menu.

  5. When your application enters break mode, open the Threads debug window.

    Notice the main() thread is currently the only thread running in this window.

  6. Press F5 to run to the breakpoint set in the Coffee class.

    More information appears in the Threads debug window to identify the names, location in the code, and suspension status for the application’s three threads, main, Thread-0, and Thread-1. The yellow arrow indicates which thread is currently running, in this case it is Thread-0 of Coffee.run(). Notice the main()method's thread is no longer running, because it has passed control to the threads of the Coffee and Tea classes.

    Note Although this scenario suggests the Coffee thread will be the first thread to run, this may not always be the case. The operating system will ultimately determine the processing order of the threads in a given application unless there are statements in the code to specify conditions under which to create and run a new thread.

  7. Press F11 to execute the current statement.

  8. Switch to JVIEW’s console window and the following output appears:

    I Like Coffee 0

  9. Press F5 to run to the breakpoint set in the Tea class.

  10. Press F11 to execute the current statement and the following output appears in JVIEW’s console window:

    I Like Tea 0

  11. Continue pressing F5 and F11 alternately until one of the following output statements appears in JVIEW’s console window:

    I Like Coffee 9

    –or–

    I Like Tea 9

    Notice when a thread is destroyed information about that thread no longer appears in the Threads debug window.

In the process of observing each of your application’s threads, you may observe that a particular thread’s behavior is not what you had expected. To isolate a given thread by suspending other threads, see Suspending and Resuming Threads from the Threads Debug Window.


Selecting a Box of Text

You can select a box of text, also know as a column block of text, to perform cut, copy, delete, indent, and unindent operations.

To enable box selection of text

  1. On the Tools menu, click Options to display the Options dialog box.

  2. Expand the Text Editor node of the tree view in the Options dialog box.

  3. Expand the Per Language node and select Java.

  4. In the Settings group of options, select the Box Selection radio button.

To select a box of text

  1. Point to the beginning of the text you want to select.

  2. Hold down the left mouse button and move the mouse to highlight a box of text.

    When you release the left mouse button, a box of text is selected and is available for cut, copy, delete, and indent operations.

    Note To cancel the selected box of text, click the left mouse button.


Selecting Methods from a Member List

This example uses Statement Completion's Member list feature to help you select a method of the String class. You may also use this procedure to select class member variables from the Member list.

Note If you have completed the steps of Creating Statements with Word Completion and Selecting an Overloaded Method, continue with the following procedure. If not, take a few minutes and work through those procedures before selecting a method for the String class.

Before proceeding, make sure you have loaded a .java file into the Text editor that contains the following code:

String myStr = new String("Hello World!");

To select a class member from the Members List

  1. On a new line, type:
    if(mystr.
  2. When you type the "." (dot operator) after myStr, Statement Completion displays a list of the methods belonging to the String class.

Tip If you do not get a member list after you type the dot operator, select List Members from the Edit menu or use the keyboard shortcut, CTRL+J. If this continues to happen, make sure you've enabled the Statement Completion feature.

  3. Type "equalsI" to highlight the String class's equalsIgnoreCase method in the Members List.

  4. Press Tab to insert the equalsIgnoreCase method after the dot operator for myStr.

    Both lines of your code should look like the following:

    String myStr = new String("Hello World!");
if(myStr.equalsIgnoreCase

To continue building the next statement with Statement Completion's Parameter Info feature, see Building an Argument List with Parameter Info.


Selecting an Overloaded Method

This example uses Statement Completion to help you select an overloaded constructor method for the String class.

Note If you have completed the steps of Creating Statements with Word Completion continue working through the following procedure. If not, take a few minutes and complete the procedure before selecting an overloaded constructor method for the String object.

Before proceeding, make sure you have loaded a .java file into the Text editor that contains the following code:

String myStr = new String

To select an overloaded method for a class

  1. With the insertion point immediately after the last "String" in the statement, type an opening parenthesis, "(".

    A pop-up window appears displaying the signature of one of the constructor methods for the String class. The spin control on the left side of this window indicates how many overloaded constructor methods (11) are available for the String class and which one is being displayed (1).

    Note For methods and constructors that are not overloaded, this list box is replaced by the Parameter Info text box. See Building an Argument List with Parameter Info for an example that uses the Parameter Info feature.

  2. Click anywhere on the spin control to display the signatures of the other String constructor methods until you find one that takes a String argument.

    In this example, constructor number 11 of 11 meets this criteria.

  3. After the opening parenthesis, type "Hello World!");.

    Your completed statement should look like this:

    String myStr = new String("Hello World!");

Statement Completion also displays a class's public methods and fields. To display a member list for the String object, see Selecting Methods from a Member List.


Setting a Breakpoint Before Starting the Debugger

After you’ve created and built your Visual J++ project, you’ll need to test your application, applet or component. During this testing phase you may notice unexpected behavior and may want to correct it. Setting breakpoints on statements in your source code enables you to halt your program just before “buggy” code executes.

To set a breakpoint and start the debugger

  1. With your source code file open in the editor, place the cursor on any executable code in your application, applet, or component.

  2. Click the right mouse button and select Insert Breakpoint from the shortcut menu.

    A solid red circle is placed in the margin of the editor indicating a breakpoint was set on the statement you just selected. For more information on setting breakpoints, see Entering Break Mode at a Problem Statement.

  3. On the Debug menu, click Start or use the keyboard shortcut, F5.

    The program runs and stops (breaks) just before it executes the line on which you’ve set the breakpoint. The yellow arrow in the margin indicates the next statement to be executed.

When your program is in break mode, you can:

  • Set another breakpoint

  • Examine one or more debug windows to view the values of your program’s member variables.

See Entering Break Mode at a Problem Statement for more information about entering into break mode when you are debugging your application.

To resume the debugging session

  • On the Debug menu, click Continue.

    —or—

    Press the keyboard shortcut, F5 to run to the next breakpoint.

    —or—

    Press F11 to step into the next statement.

To end the debugging session

  • On the Debug menu, click End.

    See Ending a Debugging Sessionfor more information about how to end a debug session.


Setting a Breakpoint from the Breakpoints Dialog Box

Up to this point, you have been adding and removing breakpoints by selecting options from the shortcut menu. You can also disable and enable breakpoints as well as change a breakpoint’s properties from this same menu. The integrated debugger also provides a Breakpoints dialog box that gives you even more control to manage your application’s breakpoints.

See the following topics and procedures for information on using the debugger’s Breakpoint dialog box:

  • Breakpoints Dialog Box

  • Breakpoint Properties Dialog Box

  • New Breakpoint Dialog Box

  • Choose Breakpoints Dialog Box


Splitting a Window in the Text Editor

To split the Text editor's window

  1. Point to the splitter box at the top of the vertical scroll bar.

  2. When the pointer changes to a window-sizing cursor, drag the splitter bar to the position you want.

To return to a single window

  • Double-click the splitter bar.

To move or copy text between parts of a long document

  1. Split the window into two panes.

  2. Display the code you want to move or copy in one pane.

  3. Display the destination for the code in the other pane.

  4. Select and drag the code across the splitter bar to the destination pane.


Suspending and Resuming Threads from the Threads Debug Window

The application example for this procedure creates two threads in the main() and displays output to a JVIEW console window. This procedure refers to code created in the Multithreaded Beverages Application. If you’d like to create this project to complete the following exercises, do so now. You may also use the following procedures to suspend and resume the threads of any multithreaded application.

To suspend a thread

  1. Set a breakpoint in a statements that execute after your application’s threads have been created. In this procedure’s example, breakpoints are set in the Coffee class on the following statement:
         System.out.println("I Like Coffee" + “ “ + i);

— and —

in the Tea class on the following statement:

         System.out.println("I Like Tea" + “ “ + i);
  2. On the Debug menu, click Start, or press the keyboard shortcut, F5 to run your application and start the debugger.

  3. When your application enters break mode, open the Threads debug window.

    Note The operating system will ultimately determine the processing order of the threads in a given application unless there are statements in the code to specify conditions under which to create and run a new thread.

  4. In the Threads debug window, highlight one of the threads. For this example, highlight Thread-1 of Tea.run.

  5. Click the right mouse button and select Suspend from the shortcut menu.

    Notice the Suspension Count for Thread-1 changes from 0 to 1.

  6. Continue to run your application with at least one of the threads suspended by pressing the F5 or F11 keys.

    If you are using the application created for this procedure, you’ll see that only the output from the non-suspended thread appears in JVIEW’s console window.

At some point in the debugging of a multithreaded application you may want to re-start the suspended thread. Follow these steps to resume a suspended thread:

Note This procedure requires that you have:

  • Opened the Threads debug window

  • Have suspended a thread in this window

To resume a suspended thread

  1. In the Threads debug window, highlight a suspended thread. For this example, highlight Thread-1 of Tea.run.

  2. Click the right mouse button and select Resume from the shortcut menu.

    Notice the Suspension Count for Thread-1 changes from 1 to 0.


Viewing Compilation Errors and Warnings

Thanks for using this pre-release version of Visual J++.

To find and correct compilation errors

  1. On the View menu, click Other Windows, and then click Task List from the cascading menu.

    The Task List appears and displays any errors or warnings that were produced during the compilation of the project.

  2. Double-click one of the errors or warnings displayed in the Task List.

    Visual J++ opens the Text editor, displays the project’s code, and places the cursor on the statement that produced the error.

  3. Using the Task List, correct all compiler errors and rebuild your project.

Once you have corrected all the compilation errors, you can rebuild and run the applet.


Viewing a File in Full-Screen Mode

To begin or end full-screen mode

  • On the View menu, click Full Screen.


Viewing Information in the Auto Window

The Auto window displays the values of all variables within the scope of currently executing methods. Where the Locals window shows variables for a single thread, the Auto window shows variables for all threads. This window allows you to learn about the changes to a variable that may be caused by code executing on a different thread. A variable remains visible as long as it is in scope, reflecting any changes to its value. When the variable goes out of scope it is removed from the Auto window.

The Auto window is updated only when execution is suspended. For example, the Auto window is updated when you add a new watch variable, when you change the value of a variable, or when you switch between decimal and hexidecimal modes from the shortcut menu. Values that have changed since the last suspension are displayed in red.

To display the Auto window

  • On the View menu, click Debug Windows, and then select Auto.

    – or –

    Press the key combination, CTRL+ALT+A.

    – or –

    Click the Auto button on the Debug toolbar.

To copy a variable from the Auto window to another window

  • Drag a selected variable to the Immediate window or the Watch window.

To change the value of a variable

  • Click a value and edit it.

To view or hide class member variables and array elements

  • Expand or collapse class and array member variables to view or hide their elements.

    See Navigation Keyboard Shortcuts for the Auto, Locals, and Watch Windows for additional information on how to move around in these windows, and expand and collapse class member variables and array elements.

See Viewing Variables in the Auto Window for more information about the Auto debug window.


Viewing Information in the Call Stack Window

The Call Stack window displays a list of all active procedures or stack frames for the current thread of execution. Active procedures are the uncompleted procedures in a process.

To display the Call Stack window

  • On the View menu, click Debug Windows, and then select Call Stack.

    – or –

    Press the key combination, CTRL+ALT+C.

    – or –

    Click the Call Stack button on the Debug toolbar.

To change the active thread from the Call Stack window

  • Change the active thread by selecting it from the threads list.

See Viewing the Call Stack for information about the specific elements of this window.


Viewing Information in the Immediate Window

To view and change values, you use the Immediate window. You can evaluate any expression, variable, or object in the window and see the value that is returned, or you can see the effects of commands you enter (which must be in the language of the code that is currently executing).

Once you're in break mode, you can move the focus to the Immediate window to examine data. You can evaluate any valid expression in the Immediate window, including expressions involving properties or variables. The currently active form or class determines the scope.

To display the Immediate window

  • On the View menu, click Debug Windows, and then select Immediate.

    – or –

    Press the key combination, CTRL+ALT+I.

    – or –

    Click the Immediate button on the Debug toolbar.

You can enter expressions into the Immediate window to display or change the value of variables, properties, and expressions.

To add an expression or variable to the Immediate window

  • Drag a variable or expression from the Text editor or from the Locals, or Watch window into the Immediate window.

To evaluate an expression or variable in the Immediate window

  1. In the Immediate window, move the insertion point to the variable or expression you wish to evaluate.

    Note To examine variables or expressions that contain scripting code, insert a question mark, "?", before the variable or expression to display its value.

  2. Press Enter.

    If, you select a variable for evaluation, the Immediate window will return its current value; for expressions, the evaluated results are returned.

To execute a statement again

  1. Move the insertion point back to the statement you want to execute again.

  2. If you wish, you can edit the current statement to alter its effects.

  3. Press ENTER.

To move around in the Immediate window

  • Use the mouse or the arrow keys.

    Tip Don't press ENTER unless you are at a statement that you want to execute.

See Executing Commands and Evaluating Expressions in the Immediate Window for additional information on the Immediate debug window.


Viewing Information in the Locals Window

The Locals window displays the class member variables and their values for each method in the current stack frame. As the execution switches from method to method, the contents of the Locals window changes to reflect the local variables applicable to the current method.

The Locals window contains fields for the Name, Value, and Type for each member variable. The value of a given variable will be displayed after it has been declared in your program. If a variable is not in scope when you display the Locals window, a message appears in the Value field next to the variable’s name. You will need to step through more code before you’ll see values for these variables. The Locals window is updated only when execution is suspended. Values that have changed since the last suspension are displayed in red.

To display the Locals window

  • On the View menu, click Debug Windows, and then select Locals.

    – or –

    Press the key combination, CTRL+ALT+L.

    – or –

    Click the Locals button on the Debug toolbar.

To change class information in the Locals window

  • From the drop-down list box at the top of the Locals window, select another class.

Note When you’ve defined more than one class for your program, you may want to see values for variables in all these classes. The Locals window always displays the member variables for the class that contains your program’s entry point (main() or init()). Once you’ve either stepped into or stopped on a breakpoint in a different class, use the drop-down list box at the top of the Locals window to select this class and view its member variables.

To copy a variable from the Locals window to another window

  • Drag a selected variable to the Immediate window or the Watch window.

To change the value of a variable

  • Click a variable to edit its value.

To view or hide class member variables and array elements

  • Expand or collapse class and array member variables to view or hide their elements.

    See Navigation Keyboard Shortcuts for the Auto, Locals, and Watch Windows for additional information on how to move around in these windows and expand, and collapse class member variables and array elements.

See Viewing Local Variables in the Locals Window for more information about the Locals debug window.


Viewing Information in the Running Documents Window

The Running Documents window displays a list of documents that are currently loaded into the process you are running. For example, if you add an HTML frameset to your project, the Running Documents window shows you which pages are currently loaded in the browser.

To display the Running Documents window

  • On the View menu, click Debug Windows, and then select Running Documents.

    – or –

    Press the key combination, CTRL+ALT+R.

    – or –

    Click the Running Documents button on the Debug toolbar.

To open a document from the Running Documents window

  • Double-click on a document to open it in an editor.

To view or hide documents within the top-level documents

  • Expand or collapse the list to see or hide the pages or documents within the top level documents.


Viewing Information in the Threads Window

For multithreaded applications, the Threads window allows you to change the current thread of execution or view the threads in any attached process. The contents of the other debugging windows change to reflect the selected thread. See Threads Window for detailed information about the elements of this window.

The following procedures refer to code created in the scenario for Debugging a Multithreaded Application, however, they may be used to observe, suspend, and resume thread activity for any mulithreaded application. For specific procedures for displaying and using the Threads debug window, see:

  • Displaying the Threads Debug Window

  • Observing Thread Activity in the Threads Debug Window

  • Suspending and Resuming Threads from the Threads Debug Window

See Controlling Threads for more information about the Threads debug window.

If you are debugging an application requiring more than one process to run, you may want to watch activity across all processes. See Debugging Multi-Process Applications for information on selecting and debugging an application's processes.


Viewing Information in the Watch Window

The Watch window allows you to monitor the values of variables, properties, and expressions at run time. Many debugging problems aren't immediately traceable to a single statement, so you may need to use a watch expression to observe the behavior of a variable or expression throughout a procedure.

The development environment automatically monitors the watch expressions you define. When the application enters break mode, these watch expressions appear in the Watch window, where you can observe their values.

To display the Watch window

  • On the View menu, click Debug Windows, and then select Watch.

    – or –

    Press the key combination, CTRL+ALT+W.

    – or –

    Click the Watch button on the Debug toolbar.

The Watch window keeps track of member variables that may change at various times or locations in an application.

To add a watch expression at design time or in break mode

  • Drag an expression or variable from the Text editor, the Locals window or Immediate window to the Watch window.

To change the value of a variable

  • Click a variable to edit its value.

To view or hide class member variables and array elements

  • Expand a class or array member variable to view their elements.

  • Collapse a class or array member variable to hide their elements.

    See Navigation Keyboard Shortcuts for the Auto, Locals, and Watch Windows for additional information on how to move around in these windows, and expand and collapse class member variables and array elements.

See Inspecting Variables and Properties with the Watch Window for more information about the Watch debug window.