Welcome to the next generation of Java.
In early December 1998, Sun Microsystems launched the Java 2 platform, a major new release of the Java APIs (application programmer interfaces). Java 2 is a vast improvement upon previous releases: new graphics, user interface, and enterprise capabilities make it three times as large as Java 1.1, and over seven times as large as the initial Java 1.0 release. Despite its rapid growth, Java 2 is well-designed, well-tested, fast, and robust. Java 2 marks the maturity of the Java platform.
This chapter offers a quick overview of the newly mature Java 2 platform.
When we speak of Java, it is important to distinguish between the Java programming language and the Java platform. The Java programming language is the language in which Java applications, applets, servlets, and components are (usually) written. The Java platform, on the other hand, is the predefined set of Java classes that exist on every Java installation; these classes are available for use by those applications, applets, servlets, and components. The Java platform is also sometimes referred to as the "core Java APIs" or the "Java runtime environment." The Java platform can also be extended with optional standard extensions. These APIs exist in some Java installations, but are not guaranteed to exist in all installations.
The Java programming language is a state-of-the-art, object-oriented language that has a classic syntax similar to that of C. The designers strived to make the Java language powerful, and at the same time tried to avoid the overly complex features that have bogged down other promising object-oriented languages such as C++. By keeping the language simple, the designers also made it easier for programmers to write bug-free and robust code.
As a result of its elegant design and next-generation features, the Java language has proved to be wildly popular with programmers, who typically find it a pleasure to work with Java after struggling with more difficult and less powerful languages.
Just as important as the Java programming language is the Java platform. This is the set of predefined classes that programs written in the Java language rely on. These predefined classes are the building blocks of all Java applications, applets, servlets, and components. Java classes are grouped into related groups known as packages. The Java platform defines packages for functions such as input/output, networking, graphics, user interface creation, security, and much more. The bulk of this chapter is devoted to a package-by-package exploration of the full capabilities of the Java 2 platform.
Before we proceed with our survey of the Java platform, however, it is important to understand what is meant by the term "platform." To a computer programmer, a platform is defined by the APIs that he or she can use and rely on when writing programs. These APIs are typically defined primarily by the operating system of the target computer. Thus, a programmer writing a program to run under Microsoft Windows must use a different set of APIs than a programmer writing the same program for the Macintosh or a programmer writing for a Unix-based system. Windows, Macintosh, and Unix are three distinct platforms.
Java is not an operating system.[1] Nevertheless, the Java platform - particularly the Java 2 platform - provides APIs with a comparable breadth and depth to those defined by an operating system. With the advent of the Java 2 platform, programmers can choose to write applications on the Java platform without sacrificing the advanced features that are available to programmers writing native applications targeted at a particular underlying operating system.
[1] There is a Java-based operating system, however. It is known as JavaOS.
An application written on the Java platform runs on any operating system that supports the Java platform. This means that programmers do not have to create distinct Windows, Macintosh, and Unix versions of their programs. A single Java program runs on all of these operating systems. This explains why "Write once, run anywhere" is Sun's motto for Java.
It also explains why companies such as Microsoft might feel threatened by Java. The Java platform is not an operating system, but for programmers, it is an alternative development target, and a very popular one at that. The Java platform reduces programmers' reliance on the underlying operating system, and by allowing programs to run on top of any operating system, it increases end users' freedom to choose any operating system they prefer.
Why use Java at all? Why is it worth learning a new language and a new platform? This section explores some of the key benefits of Java.
Sun identifies "Write once, run anywhere" as the "core value proposition" of the Java platform. Translated from business jargon, this means that the most important promise of Java technology is that you have to write your application only once, for the Java platform, and you'll be able to run it anywhere.
Anywhere, that is, that supports the Java platform. Fortunately, Java support is becoming ubiquitous. It is integrated, or being integrated, into practically all major operating systems. It is built into major web browsers, which places it on virtually every Internet-connected PC in the world. It is even being built into consumer electronic devices, such as television set top boxes, PDAs, and cell phones.
Java has been criticized for failing to live up to the promise of "Write once, run anywhere." With the introduction of Swing, the new platform-independent graphical user interface system, however, the Java 2 platform has taken a giant step closer to this goal. And to keep things in perspective, it is important to remember that Java is the only platform that comes anywhere close to meeting the promise of "Write once, run anywhere".
Another key benefit of Java is its security features. The language and the platform were designed from the ground up with security in mind. The Java platform allows users to download untrusted applet code over a network, and to run it in a secure environment in which it cannot do any harm: it cannot infect the host system with a virus, cannot read or write files from the hard drive, and so forth. This capability alone makes the Java platform unique.
The Java 2 platform takes the security model a step further. It makes security levels and restrictions highly configurable and extends them beyond applets. With Java 2, any Java code, whether it is an applet, a servlet, a JavaBeans component, or a complete Java application, can be run with restricted permissions that prevent it from doing harm to the host system.
The security features of the Java language and the Java platform have been subjected to intense scrutiny by security experts around the world. Security-related bugs, some of them potentially serious, have been found and fixed. The new security model will probably also have bugs in it, and these will, over time, be found and fixed as well.
Because of the security promises Java makes, it is big news when a new security bug is found. Remember, however, that no other mainstream platform can make security guarantees nearly as strong as those that Java makes. If Java's security is not yet perfect, it is has been proven strong enough for practical day-to-day use, and is certainly better than any of the alternatives.
Sun's corporate motto has always been "The network is the computer." The designers of the Java platform believed in the importance of networking and designed the Java platform to be network-centric. From a programmer's point of view, Java makes it unbelievably easy to work with resources across a network and to create network-based applications using client/server or multi-tier architectures. This means that Java programmers have a serious head start in the emerging network economy.
Java is both dynamic and extensible. Java code is organized into modular object-oriented units called classes. Classes are stored in separate files and are loaded into the Java interpreter only when needed. This means that an application can decide as it is running what classes it needs, and can load them when it needs them. In also means that a program can dynamically extend itself by loading the classes it needs to expand its functionality.
The network-centric design of the Java platform means that a Java application can dynamically extend itself by loading new classes over a network. An application that takes advantage of these features ceases to be a monolithic block of code. Instead, it becomes an interacting collection of independent software components. Thus, Java enables a powerful new metaphor of application design and development.
The Java language and the Java platform were designed from the start with the rest of the world in mind. Java is the only commonly used programming language that has internationalization features at its very core, rather than tacked on as an afterthought. While most programming languages use 8-bit characters that can represent only the alphabets of English and Western European languages, Java uses 16-bit Unicode characters that represent the phonetic alphabets and ideographic character sets of the entire world. In addition, Java's internationalization features are not restricted to just low-level character representation. These features permeate the Java platform, making it easier to write internationalized programs with Java than it is with any other environment.
Programs written in Java are compiled to a portable, intermediate-form known as "byte code", rather than to native machine language instructions. The Java Virtual Machine runs a Java program by interpreting these portable byte-code instructions. This architecture means that Java programs are faster than programs or scripts written in purely interpreted languages, but they are typically slower than C and C++ programs that are compiled to native machine language. Remember, however, that although Java programs are compiled to byte code, not all of the Java platform is implemented with interpreted byte codes. For efficiency, computationally-intensive portions of the Java platform - such as the string manipulation methods - are implemented using native machine code.
Although early releases of Java suffered from performance problems, the speed of the Java VM has improved dramatically with each new release. The VM has been higly tuned and optimized in many significant ways. Furthermore, many implementations include a just-in-time compiler, which converts Java byte codes to native machine instructions on the fly. Sun is even planning to sell a VM implementation using what they call "hot spot" technology: it performs selective just-in-time compilation only for pieces of code that are frequently executed. The result, they claim, is Java applications that execute at the speed of native C and C++ applications.
Java is a portable, interpreted language; Java programs run almost as fast as native, non-portable C and C++ programs. Performance used to be an issue that made some programmers avoid using Java. Now, with the improvements made in Java 2, performance issues should no longer keep anyone away. In fact, the winning combination of performance plus portability is a unique feature that no other language can offer.
The final, and perhaps most important, reason to use Java is that programmers like it. Java is an elegant language combined with a powerful and well-designed set of APIs. Programmers enjoy programming in Java, and are usually amazed at how quickly they can get results with it. Studies have shown consistently that switching to Java increases programmer efficiency. Because Java is a simple and elegant language with a well-designed, intuitive set of APIs, programmers write better code with fewer bugs than they do for other platforms, again reducing development time.
The announcement of the Java 2 platform caught the community of Java developers by surprise. Throughout nearly a year of beta-testing, the release had been called "Java 1.2." Then, just as the final code was released, the name was changed from "Java 1.2" to "the Java 2 platform."
This was a marketing ploy, of course. But, in addition to its marketing benefits, the name change accurately reflects the true state of the Java platform. As I noted at the beginning of this chapter, this latest release is three times as large as the Java 1.1 release and seven times as large as the original Java 1.0 release. And that's before counting the important standard extensions that are an optional part of the Java platform.
But the change is not just a quantitative one. It is highly qualitative as well. The new release provides crucial graphics and user interface features, and fills in a number of previously missing pieces. Java 2 is the first release of Java that truly defines a complete, mature, and robust platform for developers to target. It is these qualitative changes, more than the mere size increase, that justify the jump to Java 2.
With that said, note that there is bound to be confusion about the version number. As I write this, the Java interpreter supplied with the Java 2 platform reports a version number of 1.2. I imagine that the release engineers at Sun are really, really annoyed with the marketing folks who changed the number at the last minute. Right now, it has not become clear how this version number incompatibility will be resolved. The phrase "Java 2 platform" refers to the Java specification. It may be that the terms "Java 1.2" and "JDK 1.2" will continue to be used to refer to Sun's implementation of that platform.
With that matter of nomenclature behind us, let's proceed to explore the features and capabilities of the Java 2 platform.
The Java platform provides all the core features that you'd expect to find in any programming environment. The difference between Java and other platforms is that the core Java APIs are object-oriented and exceptionally well designed. The elegance of the core features makes Java programming easier and more efficient. The following sections highlight the most important core features of the Java platform.
As I already mentioned, the Java platform is made up of modular
object-oriented units known as classes. Related classes are
grouped into packages. The java.lang package
contains the classes that are most fundamental to the Java
platform and the Java programming language. It contains classes
that represent strings of text, threads of
execution, exceptions, and errors. Other classes in
java.lang are fundamental to the dynamic
class loading and security protection mechanisms of Java.
java.lang and a related package,
java.lang.reflect, contain classes
that support introspection, allowing a Java program to reflect
upon itself. The
classes represent Java packages, Java classes, and the methods
and fields of Java classes. With these classes, a Java program
can find out about the methods of a particular object, for
example. Introspection is particularly useful for
creating scripting languages and visual programming tools that
dynamically manipulate Java objects.
The java.io package contains classes for
performing input and output. The basic abstraction of the
Java I/O system is a sequential stream of bytes or
characters. The majority of the classes in this package
represent and manipulate streams of bytes or characters. Java
streams gain much of their power from their ability to be
flexibly combined. For example,
FileInputStream is a low-level class that
reads bytes from a file (assuming, of course, that the program
is not subject to security restrictions that prevent it from
reading files). An InputStreamReader reads
bytes from a byte stream, such as a
FileInputStream, and converts the stream of
bytes to a stream of characters. A
BufferedReader reads characters in bulk
from a character stream, such as an
InputStreamReader, and buffers them up for
more efficient use later. A Java program can combine these
three modular stream classes to read text from a file in an
efficient manner.
The java.io package contains numerous
stream classes. There are classes that read data from files
and write data to files. There are also classes that allow
character stream and byte stream input to and output from
strings and arrays. Other classes support pipes that transfer
data to and from other threads in the same program.
Some of the most exciting capabilities of streams occur in
conjunction with the networking capabilities of the
java.net package (covered in the next section).
The Java stream abstraction allows streams of bytes and
characters to be read from and written to the network as easily
as they can be read from and written to files on the local hard
disk.
Another important feature of the java.io
package is the ability to serialize a
Java object into a stream of bytes that can be stored in a
file or transferred across a network. Serialization is
supported by the ObjectInputStream and
ObjectOutputStream classes. The
ObjectOutputStream serializes a Java
object, while the ObjectInputStream does
the opposite, reading a stream of bytes from a file, network,
or other source and converting the data back into the Java
object that it represents. This is a tremendously powerful
capability in any object-oriented system, and is particularly
useful for networked, object-oriented enterprise software.
The input/output capabilities of Java are not restricted
entirely to streams of bytes and characters, however. The
File class represents files and directories
in the local file system and allows manipulation of those files
and directories. The RandomAccessFile class
allows random access to files, as an alternative to the
sequential access allowed by the stream classes.
Two utility packages also provide important input/output
capabilities. java.util.zip contains classes
for compressing and decompressing arbitrary streams of data and
for reading and writing compressed files in ZIP and GZIP format.
java.util.jar contains classes that support
the JAR (Java Archive) file format.
For complete coverage of all the I/O classes available in Java, see Java I/O by Elliotte Rusty Harold (O'Reilly).
Programming languages and operating system platforms that evolved before the advent of the Internet and the ubiquity of networking typically have networking capabilities tacked on in an awkward way. Networking APIs on these platforms are usually poorly documented, and are considered arcane, wizard-level stuff. Not so with Java. Networking is a central feature of the Java platform; the networking APIs were designed to be as easy to use as any other part of the system.
Java networking classes are grouped in the
java.net package. At the highest level, the
Java platform supports networking through Internet URLs. By
default, the platform supports HTTP, FTP, and local file URLs,
and can be dynamically extended to support URLs that use
other Internet protocols. The URL class
represents an arbitrary URL and can open a stream to the
network resource it refers to, so that a Java program can read
or write binary data or text from or to any network resource
that can be identified with a URL.
At a slightly lower level,
the Socket class represents a
network connection to another computer. The
Socket class also works with the classes in
the java.io package to allow stream-based
exchange of data between computers on the network. The
Socket class is used by both client and
server programs. In addition, the ServerSocket
class provides a kind of network doorbell for servers: it allows
servers to listen for and accept connection requests from
clients.
The java.net package provides an even lower
level of networking support through the
DatagramPacket and
DatagramSocket classes. These allow a Java
program to send or receive packets of data across the network.
Instead of allowing stream-based exchange of data, these classes
allow very efficient transmission of single blocks of binary data.
Like all resource-sensitive features of Java, access to networking capabilities is protected by the Java security mechanisms. Java code cannot talk to other computers unless it is explicitly granted permission to do so. By default, untrusted code is granted very limited networking permissions.
Java networking capabilities are covered in much greater detail in Java Network Programming by Elliotte Rusty Harold (O'Reilly).
The java.lang.Math class provides
floating point mathematics capabilities for the Java platform.
This class defines important numeric constants such as e and
and methods that perform trigonometric, logarithmic, and other
mathematical operations.
The java.math package contains classes that
support arbitrary-precision arithmetic on integers and
floating-point numbers.
The java.util package contains, as the name
implies, a number of utility classes. Most important among
these are the collections classes introduced with the Java 2
platform. The collection classes provide predefined,
efficient, throughly tested implementations of data structures
and algorithms for dealing with collections of objects. These
predefined collections and the algorithms that sort, search,
and perform other manipulations on them make it easier to
develop and maintain Java programs that are less prone to bugs
and more efficient and reliable.
The java.util package also contains a
number of other miscellaneous utility classes. These include
classes for working with dates, times, and time zones; a class
for generating random numbers; a class for representing an
internationalization locale; and a class for performing simple
parsing of strings.
The
java.text package contains classes that support the
internationalization and localization of Java programs, so that they
can run in any locale in the world. These classes are primarily
concerned with the correct representation and manipulation of text in
international and multilingual environments. The package also
includes classes that display numbers, dates, and currency values
according to the the accepted conventions of a given locale. In Java
2, the internationalization capabilities have even been extended to
handle the complex details of bidirectional text, as used in Hebrew
and Arabic.
Security mechanisms are found throughout the Java language,
the Java interpreter, and the Java platform. Prior to the
Java 2 platform, the SecurityManager and
ClassLoader classes in the
java.lang package were the main security
mechanisms in Java. Now, some of the most important
mechanisms are part of the java.security
package.
The Permission class represents a permission
granted to a particular piece of Java code. Numerous subclasses
of this class are found throughout other packages of the
Java platform. These subclasses represent specific types of
permissions, such as the permission to read or write a file, the
permission to network with another computer, the permission to
start a print job, and so forth.
The Policy class represents a security
policy for the Java environment. The details of a security
policy are configurable, at a fine-grained level, by the end
user or system administrator. A security policy might grant
no permissions to Java code downloaded across the network,
while granting numerous sensitive permissions to trusted Java
applications that are installed locally. However, the same
policy might restrict the permissions that are available to
the JavaBeans components that are dynamically loaded by the
trusted application.
The java.security package and its
subpackages also include classes that use the techniques of
public key cryptography to generate and manipulate public
and private keys and key certificates. These packages
define classes for
creating digital signatures based on public key cryptography,
for computing cryptographically secure message digests for
arbitrary data, and for defining and manipulating access
control lists.
However, because of restrictive U.S. export regulations, the
java.security packages stop just short of
providing actual data encryption and decryption capabilities.
Encryption and decryption fall within the domain of the Java
Cryptography Extension, or JCE, which is available as a
standard extension. Sun's implementation of the JCE is
available only within the U.S. and Canada, but other
implementations developed in other countries - and therefore
exempt from the U.S. export regulations - will presumably
become available.
For a complete discussion of the security features in Java, see Java Security, by Scott Oaks (O'Reilly). Java Cryptography, by Jonathan Knudsen (O'Reilly), delves into the details of cryptography as it relates to Java programming.
Graphical user interfaces (GUIs) were a weak spot of the initial releases of Java. Java 1.0 and Java 1.1 provided a user-interface library called the Abstract Windowing Toolkit (AWT) that was layered on top of platform-native GUI components. The task of layering a platform-independent GUI toolkit on top of multiple divergent native GUI toolkits proved to be exceedingly complex. The approach also meant that the Java GUI system was restricted to the lowest common denominator functionality of the various native toolkits. The result was a crippled GUI system; it was nearly impossible to create GUIs with Java that could compete with the GUIs of native applications.
The Java 2 platform solves these problems by abandoning the previous approach and implementing a pure-Java, cross-platform GUI library from scratch.[2] This library, commonly called "Swing," is as powerful and full-featured as any native GUI system in existence. Swing, along with Java 2D, is part of the Java Foundation Classes, or JFC. In addition to a full set of JavaBeans-compatible GUI components, Swing and the JFC define a number of application services that create a full-featured and robust framework within which GUI applications can be developed.
[2] Java 2 retains backward compatibility with previous releases, of course.
The following sections provide an overview of the GUI and application services features of Swing and the JFC.
The most visible and important part of any GUI library is the set of GUI components it provides. Swing provides a full and powerful set, summarized in Table 1.1. This set of components is impressive in its own right. It is even more impressive when you realize that each component is also a JavaBeans component, that each component offers a pluggable look-and-feel that can be configured dynamically, and that each component supports the Accessibility API (described later in this chapter) to enable assistive technologies for disabled users.
The Swing components require no further introduction. If you read through the table, they speak for themselves. Remember that although the GUI components are the most visible part of Swing, they are only a part of it. Other parts of Swing, described later in this section, provide an application framework and application services. For more complete coverage of Swing, see Java Swing, by Robert Eckstein, Marc Loy, and Dave Wood (O'Reilly).
The Swing components are contained in a package named
javax.swing. "javax" in a
package name usually indicates that the package is a standard
extension. Don't let this name confuse you. Swing was an
extension to Java 1.1, but it is a very important core part of
Java 2.
| Component Name | Description |
|---|---|
Box | A general-purpose container that arranges children
using the model of |
JApplet | An |
JButton | |
JCheckBox | A toggle button for displaying choices that are not mutually exclusive. |
JCheckBoxMenuItem | |
JColorChooser | A complex, customizable component that allows the user
to select a color from one or more color spaces. Used
in conjunction with the
|
JComboBox | A combination of a text entry field and a drop-down list of choices. The user can type a selection or choose one from the list. |
JComponent | The root of the Swing component hierarchy. Adds Swing-specific features such as tooltips and support for double-buffering. |
JDesktopPane | A container for |
JDialog | |
JEditorPane | A powerful text editor, customizable via an
|
JFileChooser | A complex component that allows the user to select a
file or directory. Supports filtering and optional
file previews. Used in conjunction with the
|
JFrame | |
JInternalFrame | A lightweight nested window container.
Behaves like a |
JLabel | A simple component that displays text, an image, or both. Does not respond to input. |
JLayeredPane | A container that allows its children to overlap. Manages the stacking order of those children. |
JList | A component that displays a selectable list of choices. The choices are usually strings or images, but arbitrary objects may also be displayed. |
JMenu | A pulldown menu in a |
JMenuBar | |
JMenuItem | |
JOptionPane | A complex component suitable for displaying simple
dialogs within a |
JPanel | A generic container for grouping components with an
appropriate |
JPasswordField | A text input field for sensitive data, such as passwords. For security, does not display the text as it is typed. |
JPopupMenu | A window that pops up to display a menu. Used by
|
JProgressBar | A component that displays the progress of a time-consuming operation. |
JRadioButton | |
JRadioButtonMenuItem | |
JRootPane | A complex container used internally by
|
JScrollBar | |
JScrollPane | A container that allows a child component to be scrolled horizontally or vertically. Supports scrolling and non-scrolling header regions at the top and left of the scrolling region. |
JSeparator | A simple component that draws a horizontal or vertical line. Used to visually divide complex interfaces into sections. |
JSlider | A component that simulates a slider control like those found on stereo equalizers. Allows the user to select a numeric value by dragging a knob. Can display tick marks and labels. |
JSplitPane | A container that displays two children by splitting itself horizontally or vertically. Allows the user to adjust the amount of space allocated to each child. |
JTabbedPane | A container that displays one child at a time, allowing the user to select the currently displayed child by clicking on tabs like those found on manila file folders. |
JTable | A complex and powerful component for displaying
tables and editing their contents. Typically used to
display strings, but may be customized to display any
type of data. Used in conjunction with the
|
JTextArea | A component for displaying and editing multiple lines
of plain text. Based on
|
JTextComponent | The root component of a powerful and highly
customizable text display and editing system. Part of the
|
JTextField | A component for the display, input, and editing of a
single line of plain text. Based on
|
JTextPane | A subclass of |
JToggleButton | |
JToolBar | A component that displays a set of user-selectable tools or actions. |
JToolTip | A lightweight popup window that displays simple documentation or tips when the mouse pointer lingers over a component. |
JTree | A powerful component for the display of
tree-structured data. Data values are typically
strings, but the component can be customized to
display any kind of data. Used in conjunction with
the |
JViewport | A fixed-size container that displays a portion of a
larger child. Usually used as part of a
|
JWindow | A top-level Swing window that does not display a titlebar, resize handles, or any other decorations. |
Swing is based on a model/view architecture that separates
component state from the object that displays and allows the
user to interact with that state. Every Swing component that
has state (for example, the currently selected item in a
JList) maintains that state in a separate
object known as its model. Swing
includes interfaces that define the state maintained by each
model and provides default implementations of those
interfaces.
Separating model objects from the components has two important
benefits. First, it allows multiple components to share a model
object and provide different views of the model. Second, it
allows application data structures to be defined in such a way
that they implement one or more model interfaces. This allows
those application-specific data structures to be displayed
directly by Swing components. For example, a data structure
that represents tree-structured data can implement the
TreeModel interface, automatically allowing
it to be displayed in a JTree object.
We've already seen that Swing components use a model/view architecture and the model is a separate object from the component itself. As it turns out, the view is also separate from the component. This leaves the component with the task of handling the interaction between the model and the view. The view object is known as the UI delegate; its job is to display the component and handle input from the user. In other words, the UI delegate is responsible for the look-and-feel of a component.
An important feature of Swing is its pluggable look-and-feel architecture. An application or an end user can specify a desired look-and-feel. When Swing components are created, their UI delegate objects are selected based on the requested look-and-feel. This allows complete customization of the appearance and behavior of any Swing application. Swing ships with a default Java look-and-feel (also known as the Metal look-and-feel), as well as implementations that mimic the look-and-feel of both Motif and Windows. A Macintosh-based look-and-feel implementation is available separately. Thus, any Swing application can have the distinctive appearance of a Java application or the familiar appearance of a platform-native application. Figure 1.1 shows examples of the Metal, Motif, and Windows look-and-feels.
The Java 2 platform includes the new
javax.accessibility package as part of the
JFC. This package defines classes that are used by assistive
technologies to make applications more accessible to disabled
people. For example, a blind person might use a screen reader
as an assistive technology.
All Swing components are accessible, which means that they implement standard methods that assistive technologies can query to obtain information about individual components. Thus, when you create an application using Swing components, your application is automatically accessible. This brings your application to a large audience of users who would not be able to use it otherwise, and it requires no extra programming effort on your part.
There are a number of miscellaneous features of Swing that are important and useful enough to warrant a mention in this overview:

Every Swing component can have a Border
object displayed around it. The
javax.swing.border package defines a
number of commonly used border types, such as beveled,
grooved, and titled borders.
Swing supports context-sensitive help through tooltips (small boxes of text that pop up when the mouse lingers over a component). Swing handles the creation and display of tooltips automatically; all you have to do is supply appropriate text for the tips.
GUI applications often allow a user to invoke an operation in a number of different ways. For example, the user may be able to save a file by either selecting an item from a menu or clicking on a button in a toolbar. The resulting operation is exactly the same; it is simply presented to the user through two different interfaces.
Swing defines a simple but powerful interface named
Action, which encapsulates
information about such an operation. An
Action object includes the
method that performs the desired operation, a short string of
text that names the operation, an image that can be used
to represent the action graphically, and a longer string
of text suitable for use in a tooltip for the action.
You can add an Action object directly to
JMenu and JToolBar components.
This makes the action's operation available to the user, displaying the
action's textual description and graphical image as appropriate.
Action objects can be enabled and
disabled. When an action is disabled, any component that presents the
action to the user does not allow the user to select or invoke it.
In this way, the Action interface
helps Swing programmers implement a very clean
separation between GUI code and application logic.
The Java platform makes it very easy to work with multiple
threads. To perform a repetitive or delayed action, such
as animation, in Java, it is common to create a new thread
that spends most of its time waiting for time to
pass. While it is relatively easy to do this in Java, it is
not as easy as it should be. To make it even easier,
Swing includes a new
Timer class that automatically
triggers a single or periodic event after a specified
period of time. Although conceptually simple, timers are
an integral part of the complete Swing application
framework and are a powerful service available to all
Swing applications.
The javax.swing.undo package provides a
standard, general-purpose framework for implementing
Undo and Redo operations in Swing
applications. The framework centers around a list of
UndoableEdit objects that describe
recent changes made in the application and allow those
changes to be undone. Note that this framework is not
limited to text editing changes; it can be used for any kind
of change to an application. While this framework does not
automate undo and redo processing for Swing applications,
it simplifies these operations considerably.
The Swing components and their pluggable look-and-feel implementations were designed to work with Swing's powerful keyboard navigation (or keyboard traversal) mechanism. All of the standard Swing components can be operated entirely from the keyboard without the use of the mouse. This is a very desirable feature, especially for advanced users.
The Java 2 platform allows Java applications to interact with native applications through drag-and-drop. This is a feature that was sorely missing from previous Java releases. Java 1.0 had no data-transfer capabilities. Java 1.1 introduced rudimentary cut and paste capabilities, but did not support drag-and-drop.
The drag-and-drop implementation in the Java 2 platform is
full-featured. For example, it includes the ability to perform
drag-over and drag-under animations. Furthermore, access to
the drag-and-drop system is controlled by the Java security
mechanisms. This prevents untrusted code from gaining access
to sensitive data that is accidentally or unknowingly dropped
on its user interface. Drag-and-drop is implemented in the
java.awt.dnd package.
An input method is a program that allows a user to enter text in an ideographic language such as Chinese or Japanese using a keyboard with a relatively small number of keys. Since words in these languages are represented as single characters, there are a vast number of possible characters, and entering a character usually requires several keystrokes. An input method operates in conjunction with an external dictionary to convert sequences of keystrokes into the desired ideographic character.
Support for input methods is required for any computer system
to be used in a country that does not use a phonetic
alphabet. Previous releases of Java could be customized to work
with input methods, but the Java 2 platform now delivers input
method support as a core part of the platform. The input method
framework is defined in the java.awt.im
package. The framework also relies on some of the
internationalization classes in java.text.
Swing text input components are implemented to support the input
method framework, so they interact well with input methods.
Note that the concept of an input method can be generalized beyond its traditional use for input of ideographic characters. A speech recognition system, for example, could be implemented as an input method. Such an input method could be automatically plugged into any Swing application so that the application could accept spoken input instead of typed input. Considered in this light, input methods are another piece of the accessibility framework.
JavaHelp is a standard extension to Java 2 that is implemented in the
javax.javahelp package and its subpackages.
JavaHelp provides a framework for defining and displaying online help
in Java applications and applets. JavaHelp uses Swing
components (and defines some of its own) to be able to display both
an expandable, tree-structured table of contents and hyperlinked,
formatted text.
No discussion of the user-interface capabilities of the Java platform would be complete without a discussion of applets. As the name implies, an applet is a mini-application. Specifically, it is a Java program designed to be downloaded across a network and executed within a web browser. Because they are loaded across an open network, applets are typically considered untrusted code and are run with a full complement of security restrictions, to prevent them from doing any damage to the local system.
Applets popularized the initial release of Java, and they have
changed little since Java 1.0. Java 2 enhances applets with
the Swing JApplet class and its new, more
flexible security model.
Both the base Applet class and the Swing
JApplet extension of that class are GUI
containers that can hold other GUI components and containers.
Thus, a discussion of applets is appropriate in this discussion
of GUI features of Java. However, the compelling features of
applets are not their user-interface capabilities. What makes
applets interesting is exactly what makes the Java platform
interesting: they are network-centric, dynamically extensible, and
secure.
Just as no discussion of GUIs in Java is complete without a mention of applets, no discussion of GUI components is complete without a mention of JavaBeans. If applets were one of the most exciting features of Java 1.0, beans were one of the most exciting features of Java 1.1. Support for beans is extended in the Java 2 platform.
JavaBeans is the Java component system. A bean is a Java object whose API follows certain conventions. These conventions allow the bean to be manipulated by various tools, such as visual application builder tools. The conventions also allow scripting languages to manipulate beans easily. To a certain extent, the conventions even allow an application to be assembled dynamically as a group of independent but interacting beans. Beans are usually, but not always, GUI components. All of the GUI components defined by the Java platform follow the JavaBeans conventions and therefore can be used as beans. A bean can be as simple as a push button or as complex as a full-featured word processor. For complete information on JavaBeans, see Developing Java Beans, by Robert Englander (O'Reilly).
Prior to Java 2, an application could be created as a collection of beans, but there was no way to nest beans. The Java 2 platform defines the notion of a bean context: a container that can hold beans and other bean contexts. A bean context may also provide a set of services - such as the ability to print - to the beans it contains. In some ways, this is an extension of the applet model: a bean context is to a bean as a web browser is to an applet. In fact, the Java 2 platform provides support for objects that can be used interchangeably as beans or applets.
The new drag-and-drop features of the Java 2 platform are particularly important for the JavaBeans component model. Drag-and-drop provides a user-driven mechanism for transferring data between independent modular beans that operate as part of the same application but know nothing about each other.
The Java 2 platform includes a standard extension known as the Java Activation Framework, or JAF. This extension is in essence a JavaBeans component registry. For any given data type (any MIME type), this registry maintains a list of beans available on the system that can operate in some way (e.g., display, edit, print) on that data.
When an application needs to operate on data of a given type, it
can use the JAF to obtain dynamically a list of operations that
are supported on the current system for that type of data. If
the application finds the operation it wants, it can use the JAF to
instantiate an appropriate bean and associate the data with it.
Then, the application can use the bean to perform the desired
operation. The JAF is defined in the
javax.activation package.
There's yet another standard extension to the Java 2 platform
that falls loosely within the domain of JavaBeans. The
InfoBus API, implemented in the
javax.infobus package, provides a mechanism
for data exchange between beans or between any group of
objects. The infobus architecture is modeled on the notion of
a bus in computer hardware: any number of beans can plug into
an infobus to share data, just as any number of computer
peripherals can plug into a computer's bus.
Prior to Java 2, graphics was another of the weak areas of the Java platform. Previous versions supported simple text rendering, line drawing, area filling, and image display functions, but these features were primitive at best, largely because of the challenges of providing complex graphics capabilities in a platform-independent way. Printing support was nonexistent in Java 1.0 and rudimentary in Java 1.1.
With the Java 2 platform, it is an entirely different story. Java 2 provides powerful, state-of-the-art two-dimensional graphics capabilities and, as a standard extension, high-quality three-dimensional graphics capabilities. Also, support for colors, fonts, image manipulation, and printing is greatly improved with Java 2. Another standard extension, the Java Media Framework, adds audio and video multimedia capabilities. The sections that follow provide an overview of the graphics features of the Java 2 platform.
Java 2D is a powerful new graphics model defined by Sun and
various industry partners. Programmers who have worked with the
PostScript or Display PostScript page description languages should
find many of its concepts familiar. The classes for Java 2D
are in the java.awt package and its subpackages.
For a complete discussion of Java 2D, see Java 2D
Graphics, by Jonathan Knudsen (O'Reilly).
The Java 2D graphics model allows you to define and manipulate
arbitrary Shape objects. Shapes can be
stroked (outlined) using lines of any width, color, dash
pattern, and join style, and they can be filled with any
color, color gradient, or pattern. There are methods to
transform shapes and images by translation, rotation, scaling,
flipping, and skewing. The entire coordinate system used for
drawing can also be transformed by any of these methods. You
can take advantage of powerful color compositing and alpha
transparency features to blend colors and make shapes and
images appear partially transparent. All Java 2D drawing may
be done directly on screen or into an offscreen image.
Java 2D also allows you to do sophisticated things with text. Text of any size can be drawn using any font available on the system. You can treat individual glyphs of a font as individual shapes, so they can be arbitrarily stroked, filled, transformed, and composited. Text, or any shape, can be rendered using automatic anti-aliasing, if desired.
Java 2D shapes can distinguish their inside from their outside, which means they can be used to define arbitrary clipping regions and perform hit detection for mouse clicks. Java 2D includes a number of classes that represent commonly used shapes, and allows arbitrary shapes and curves to be defined out of line segments and Bézier curves. It also allows shapes to be combined through addition, intersection, and subtraction to produce compound shapes.
Figure 1.2 shows some of capabilities of Java 2D.

Java 2D defines a ColorSpace object that
supports arbitrary color spaces. It defines mechanisms for
converting colors from any one color space to any other
color space, including the standard sRGB
color space. It also supports international standards for
the specification of device-independent color. The
java.awt.color package contains classes
that implement color handling, but most applications should
not need to use these classes. Instead, use the
java.awt.Color class, which has been
modified to support the new color functionality.
The earlier releases of Java supported only a handful of
supposedly platform-independent fonts. The Java 2 platform,
through Java 2D, can now use any font installed on the host
system. This is a substantial step forward, and will go a
long way towards improving the graphic design of Java
applications. As with color, the low-level implementation
of fonts is provided in a subpackage, the
java.awt.font package. You don't have to
use the classes in this package to take advantage of the new
font features. Instead, you can rely on the higher-level
text display features of java.awt and
javax.swing. You can also use the
java.awt.Font class, which has been
modified to support the new features.
In Java 1.0, an application could choose one of 14 predefined mouse pointers for each window it displayed. With Java 1.1, each component could have its own pointer, but could still only choose from 14 predefined ones. This arbitrary restriction has been lifted by the Java 2 platform. An application can now use any small image as a mouse pointer.
The image-processing model of the initial releases of Java
was optimized for use with images downloaded over a slow
network. At best, the model was confusing and difficult to
use. The Java 2 platform includes a new image-processing
model as part of Java 2D. This model is compatible with the
Java 1.0 APIs, but works well with images that are resident
in memory. It includes powerful image filters that can
perform common image-processing tasks. The Java 2D image-processing
model is implemented by classes in the
java.awt.image package.
Java 1.0 had no printing capabilities at all. Java 1.1 had
rudimentary capabilities that did not interact well with the
native printing systems on various platforms. For example,
it did not bring up the standard Print dialog box on Windows systems.
The Java 2 platform includes full-featured printing
capabilities as part of Java 2D in the
java.awt.print package. The printing API
supports single-page and multi-page documents, as well as
variable page and margins sizes. These new printing
capabilities interact well with the native printing systems
on host computers.
Just as Java 2D brings state-of-the-art
two-dimensional graphics to the Java 2 platform, the Java 3D API
brings powerful state-of-the-art three-dimensional graphics
capabilities to the platform. Unlike Java 2D, however, the Java 3D API
is a standard extension to the Java platform, defined in the
javax.media.j3d package. This means that it is not
guaranteed to be available on every Java installation. Figure 1.3 shows some of the capabilities of Java
3D.

The designers of Java 3D studied existing 3D graphics systems, such as OpenGL, Direct3D, and QuickDraw3D, and picked the best features of each to create a powerful, high-level API. Programming with Java 3D involves a number of steps. First, the three-dimensional geometry of each object to be rendered is defined. This can be done by a program, or the geometry data can be read in from a file or network using an existing data format, such as that used by a CAD program or VRML. The next step is to place the virtual objects into a virtual world by linking their geometry descriptions into a tree structure called a scene graph. Next, rendering attributes such as lighting and viewing angle are defined. Finally, the virtual world is drawn, using one of three possible rendering modes, each of which has different tradeoffs between flexibility and efficiency.
In addition to three-dimensional graphics, Java 3D also
provides classes to describe and play
"three-dimensional" sounds, a powerful capability
that is useful in virtual reality and immersive game
environments. The javax.vecmath package is
an auxiliary API that is part of the Java 3D framework. This
package contains classes that perform the vector and matrix
arithmetic required for 3D graphics.
The Java Media Framework, or JMF, is another standard extension to the Java 2 platform. It defines a framework for working with time-based media such as audio and video. In addition to its capabilities for playing audio data and displaying video data encoded in a wide variety of formats, JMF includes features for processing, controlling, and synchronizing streams of multimedia data. JMF works with data stored locally in files and with compressed streaming data delivered in real time across a network.
A pure-Java implementation of JMF is available for use on any Java platform. In addition, there are OS-specific implementations that use native code to increase performance and support media formats that are not practical in the pure-Java version.
Future versions of JMF will also include capabilities for media capture (recording) and conferencing.
The first two releases of Java supported only very rudimentary sound capabilities. Only sounds encoded in Sun's AU format could be played. The API was such that only applets, not applications, could easily play sounds.
The implementation of the Java 2 platform includes a new sound engine that supports a complete set of commonly used audio file formats. In addition, there have been API changes that allow sounds to be played by any Java code, not just applets. Note also that the JMF handles a wide variety of sound formats.
The sound engine included in the core Java 2 platform can be controlled using the new Java Sound API, a standard extension that is under development as of this writing. While the current core APIs support the playing of simple sounds, Java Sound will offer complete audio control.
The largest and most visible new features of the Java 2 platform are in the area of graphical user interfaces and graphics. The most strategically important features, however, may be the Java Enterprise APIs. These are APIs that allow Java to be used for mission critical business applications that must run in large, heterogenous, networked environments that include legacy systems.
Some of the Java Enterprise APIs were available in Java 1.1, while others are new in Java 2. Some are core APIs, while others are standard extensions. Still, the Enterprise APIs stand out in the Java 2 platform because, for the first time, the Java platform offers a complete, mature set of APIs for enterprise applications.
The sections that follow briefly describe each of the Enterprise APIs found in the Java 2 platform.
The Java Database Connectivity (JDBC) API allows a Java program
to send SQL query and update statements to a database server
and to retrieve and iterate through query results returned by
the server. JDBC also allows you to get metainformation about
the database and its tables from the database server. The
JDBC architecture relies upon a Driver class
that hides the details of communicating with a database server.
Each database server product requires a custom
Driver implementation so that Java programs
can communicate with it. Major database vendors have made
JDBC drivers available for their products. In addition, a
"bridge" driver exists to enable Java programs to
communicate with databases through existing ODBC drivers.
The JDBC API is found in the java.sql
package, which was introduced in Java 1.1. The Java 2
platform adds a number of new classes to this package to
support advanced database features. Java 2 also adds
additional features in the javax.sql
standard extension package. javax.sql
provides features for treating database query results as
JavaBeans, for pooling database connections, and for obtaining
database connection information from a name service.
The JDBC API is simple and well-designed. Programmers who are familiar with SQL and database programming in general should find it very easy to work with databases in Java. For more details about JDBC, see Database Programming with JDBC and Java, by George Reese (O'Reilly).
Distributed objects offer a powerful model for object-oriented network
programming that has become quite popular in recent years.
This model holds that a client should be able to invoke methods of
remote server objects
as if those remote objects existed locally on the client. This
general model can be implemented in a number of ways. One of
those ways is the Java Remote Method Invocation (RMI) API. RMI is
implemented in the java.rmi package, which was
introduced in Java 1.1 and has been enhanced for the Java 2 platform.
The Java RMI implementation is full-featured, but still simple
and easy to use. It gains much of its simplicity by being
built on top of a network-centric and dynamically extensible
platform, of course. But it also gains simplicity by
requiring both client and server to be implemented in Java.
This requirement ensures that both client and server share a
common set of data types and have access to the object
serialization and deserialization features of the
java.io package, for example. On the other
hand, this means that RMI cannot be used with
distributed objects written in languages other than Java, such
as objects that exist on legacy servers. It also means that
servers written using RMI can be used only by clients written
in Java. In practice, RMI is an excellent distributed object
solution for situations where it is clear that clients and
servers will always be written in Java. Fortunately, there
are many such situations.
The java.rmi package makes it easy to
create networked, object-oriented programs. Programmers who
have spent time writing networked applications using
lower-level technologies are usually amazed by the power of
RMI. By making RMI so easy, java.rmi
points the way to future applications and systems that consist
of loose groups of objects interacting with each other over a
network, These objects may act both as clients, by calling
methods of other objects, and as servers, by exposing their
own methods to other objects. See Java Distributed
Computing, by Jim Farley (O'Reilly) for more
complete coverage of RMI.
As we've just seen, RMI is a distributed object solution that works well when both client and server are written in Java. It does not work, however, in heterogenous environments where clients and servers may be written in arbitrary languages. For environments like these, the Java 2 platform includes a CORBA-based distributed object solution.
CORBA (Common Object Request Broker Architecture) is a
widely used standard defined by the Object Management Group (OMG).
This standard is implemented as a core part of
the Java 2 platform in the org.omg.CORBA package
and its subpackages. The implementation includes an Object Request
Broker (ORB) that a Java application can use to communicate, as both a
client and a server, with other ORBs, and thus with other CORBA
objects.
The interfaces to remote CORBA objects are described in a platform- and language-independent way with the Interface Description Language (IDL). The Java Development Kit (JDK) shipped by Sun includes an IDL compiler that translates an IDL description of a remote interface into the Java stub classes necessary to implement the IDL interface in Java or to connect to a remote implementation of the interface from your Java code.
The Java Naming and Directory Interface (JNDI) API is a
protocol-independent interface to network name services and
directory services. For example, it allows arbitrary Java
objects to be looked up by name or searched for according
to specified attribute values. JNDI is implemented in the
javax.jndi package as a standard extension to
the Java 2 platform.
The JNDI API is not specific to any particular name or directory server protocol. Instead, it is a generic API that is general enough to work with any name or directory server. To support a particular protocol, plug a service provider for that protocol into a JNDI installation. Service providers have been implemented for most common protocols, such as LDAP, DNS, and NIS.
The JavaMail API is a protocol-independent interface to
electronic mail services. It contains all the features
required to send and receive electronic mail, as well as
features for filing and searching email. JavaMail is
implemented in the javax.mail package (and
subpackages) as a standard extension to the Java 2 platform.
Like JNDI, the JavaMail API is not tied to any one protocol for sending or receiving email. Instead, the JavaMail API is general enough to work with any email protocol. To support a particular protocol, plug a service provider for that protocol into a JavaMail installation. Sun supplies service providers for the SMTP and IMAP protocols, and, as of this writing, a POP3 provider is under development.
Enterprise JavaBeans do for server-side enterprise programs what JavaBeans do for client-side GUIs. Enterprise JavaBeans (EJB) is a component model for units of business logic and business data. Thin client programming models that take business logic out of the client and put it on a server or in a middle tier have many advantages in enterprise applications. However, the task of writing this middleware has always been complicated by the fact that business logic must be mixed in with code for handling transactions, security, networking, and so on.
The EJB model separates high-level business logic from low-level housekeeping chores. A bean in the EJB model is purely business logic or business data. There are actually two types of beans: session beans represent a process or interaction with a client, and entity beans represent persistent data stored in a database. EJB beans run within an EJB container, which in turn runs within an EJB server. The container and server provide features such as security, transactional integrity, lifecycle management, name services, distribution services, and so on. The beans running within the container are free to focus purely on business logic.
The EJB specification is a document that specifies the contracts
to be maintained and conventions to be followed by EJB servers,
containers, and beans. Writing EJB beans is easy: you simply
write code to implement your business logic, taking care to
follow the rules and conventions imposed by the EJB model. The
javax.ejb and
javax.ejb.deployment packages
are standard extensions
to the Java 2 platform that contain the classes needed to write
and deploy EJB beans. The EJB architecture also relies on the
JNDI standard extension described earlier, as well as another standard
extension known as Java Transaction Services, or JTS.
Of course, writing an EJB bean is not the end of the story. You must also obtain an EJB server and EJB container in which to run the bean. As you might guess from their previous descriptions, these can be very complex pieces of software. An enterprise typically purchases a commercial EJB server and container that implement whatever features are required for its applications. A number of vendors have adapted or are currently adapting their server products to work with Enterprise JavaBeans.
A servlet is a piece of Java code that runs within a server to provide a service to a client. The name servlet is a takeoff on "applet" - a servlet is a server-side applet. The Java Servlet API provides a generic mechanism for extending the functionality of any kind of server that uses a protocol based on requests and responses.
Right now, servlets are in use primarily by web servers. On the growing number of web servers that support them, servlets are a Java-based replacement for CGI scripts. They can also replace competing technologies, such as ASP or Server-Side JavaScript. The advantage of servlets over these other technologies is that servlets are portable among operating systems and among servers. Servlets are persistent between invocations, which gives them major performance benefits over CGI programs. Servlets also have full access to the rest of the Java platform, so things like database access are automatically supported. For more information on servlets, see Java Servlet Programming, by Jason Hunter with William Crawford (O'Reilly).
The Servlet API is a standard extension to the Java 2
platform, implemented in the javax.servlet
and javax.servlet.http packages. The
javax.servlet package defines classes that
represent generic client requests and server responses. The
javax.servlet.http package provides
specific support for the HTTP protocol, including classes for
tracking multiple client requests that are all part of a
single client session.
The core APIs in the Java 2 platform are mature, and I'd say we can expect that core to remain fairly stable in future releases. But obviously there are areas of the Java platform that are still under development. For this reason, the Java 2 platform includes a standard extensions framework for installing and using standard extensions to the platform. Furthermore, Sun has documented and published the process by which proposed extensions become standard extensions.
As we've seen in this chapter, there are already a number of important standard extensions to the Java 2 platform. There are a number of others in various stages of development, and we can expect to see continued activity in this area. I'm going to conclude this overview of the Java 2 platform by mentioning some of the important standard extensions that are under development:
Provides high-end, state-of-the-art image-processing capabilities, including support for arbitrarily large images using a tile-based storage mechanism.
Offers an API for speech synthesis and voice recognition systems.
The code name for an extension that supports the XML markup language.
Allows Java to use the serial and parallel ports of the host computer.
An innovative and exciting set of packages that enable "plug-and-play" networking among computers, computer peripherals, and consumer electronic devices.
Provides an API for enterprise-level asynchronous exchange of messages.
These APIs define a transaction manager and an API for communicating with it. They implement the X/Open XA and OMG OTS standards for transaction management.
A framework that enables electonic commerce, using a "wallet" metaphor on the client side.
Defines APIs for centralized management of a dynamic and distributed Java computing environment.
Copyright © 2009 O'Reilly Media, Inc.