You are previewing Learning Java, 4th Edition.

Learning Java, 4th Edition

Cover of Learning Java, 4th Edition by Daniel Leuck... Published by O'Reilly Media, Inc.
  1. Learning Java
  2. Preface
    1. Who Should Read This Book
    2. New Developments
      1. New in This Edition (Java 6 and 7)
    3. Using This Book
    4. Online Resources
    5. Conventions Used in This Book
    6. Using Code Examples
    7. Safari® Books Online
    8. How to Contact Us
    9. Acknowledgments
  3. 1. A Modern Language
    1. Enter Java
      1. Java’s Origins
      2. Growing Up
    2. A Virtual Machine
    3. Java Compared with Other Languages
    4. Safety of Design
      1. Simplify, Simplify, Simplify...
      2. Type Safety and Method Binding
      3. Incremental Development
      4. Dynamic Memory Management
      5. Error Handling
      6. Threads
      7. Scalability
    5. Safety of Implementation
      1. The Verifier
      2. Class Loaders
      3. Security Managers
    6. Application and User-Level Security
    7. A Java Road Map
      1. The Past: Java 1.0–Java 1.6
      2. The Present: Java 7
      3. The Future
      4. Availability
  4. 2. A First Application
    1. Java Tools and Environment
    2. Configuring Eclipse and Creating a Project
      1. Importing the Learning Java Examples
    3. HelloJava
      1. Classes
      2. The main() Method
      3. Classes and Objects
      4. Variables and Class Types
      5. HelloComponent
      6. Inheritance
      7. The JComponent Class
      8. Relationships and Finger Pointing
      9. Package and Imports
      10. The paintComponent() Method
    4. HelloJava2: The Sequel
      1. Instance Variables
      2. Constructors
      3. Events
      4. The repaint() Method
      5. Interfaces
    5. HelloJava3: The Button Strikes!
      1. Method Overloading
      2. Components
      3. Containers
      4. Layout
      5. Subclassing and Subtypes
      6. More Events and Interfaces
      7. Color Commentary
      8. Static Members
      9. Arrays
      10. Our Color Methods
    6. HelloJava4: Netscape’s Revenge
      1. Threads
      2. The Thread Class
      3. The Runnable Interface
      4. Starting the Thread
      5. Running Code in the Thread
      6. Exceptions
      7. Synchronization
  5. 3. Tools of the Trade
    1. JDK Environment
    2. The Java VM
    3. Running Java Applications
      1. System Properties
    4. The Classpath
      1. javap
    5. The Java Compiler
    6. JAR Files
      1. File Compression
      2. The jar Utility
      3. The pack200 Utility
    7. Policy Files
      1. The Default Security Manager
      2. The policytool Utility
      3. Using a Policy File with the Default Security Manager
  6. 4. The Java Language
    1. Text Encoding
    2. Comments
      1. Javadoc Comments
    3. Types
      1. Primitive Types
      2. Reference Types
      3. A Word About Strings
    4. Statements and Expressions
      1. Statements
      2. Expressions
    5. Exceptions
      1. Exceptions and Error Classes
      2. Exception Handling
      3. Bubbling Up
      4. Stack Traces
      5. Checked and Unchecked Exceptions
      6. Throwing Exceptions
      7. try Creep
      8. The finally Clause
      9. Try with Resources
      10. Performance Issues
    6. Assertions
      1. Enabling and Disabling Assertions
      2. Using Assertions
    7. Arrays
      1. Array Types
      2. Array Creation and Initialization
      3. Using Arrays
      4. Anonymous Arrays
      5. Multidimensional Arrays
      6. Inside Arrays
  7. 5. Objects in Java
    1. Classes
      1. Accessing Fields and Methods
      2. Static Members
    2. Methods
      1. Local Variables
      2. Shadowing
      3. Static Methods
      4. Initializing Local Variables
      5. Argument Passing and References
      6. Wrappers for Primitive Types
      7. Autoboxing and Unboxing of Primitives
      8. Variable-Length Argument Lists
      9. Method Overloading
    3. Object Creation
      1. Constructors
      2. Working with Overloaded Constructors
      3. Static and Nonstatic Initializer Blocks
    4. Object Destruction
      1. Garbage Collection
      2. Finalization
      3. Weak and Soft References
    5. Enumerations
      1. Enum Values
      2. Customizing Enumerations
  8. 6. Relationships Among Classes
    1. Subclassing and Inheritance
      1. Shadowed Variables
      2. Overriding Methods
      3. Special References: this and super
      4. Casting
      5. Using Superclass Constructors
      6. Full Disclosure: Constructors and Initialization
      7. Abstract Methods and Classes
    2. Interfaces
      1. Interfaces as Callbacks
      2. Interface Variables
      3. Subinterfaces
    3. Packages and Compilation Units
      1. Compilation Units
      2. Package Names
      3. Class Visibility
      4. Importing Classes
    4. Visibility of Variables and Methods
      1. Basic Access Modifiers
      2. Subclasses and Visibility
      3. Interfaces and Visibility
    5. Arrays and the Class Hierarchy
      1. ArrayStoreException
    6. Inner Classes
      1. Inner Classes as Adapters
      2. Inner Classes Within Methods
  9. 7. Working with Objects and Classes
    1. The Object Class
      1. Equality and Equivalence
      2. Hashcodes
      3. Cloning Objects
    2. The Class Class
    3. Reflection
      1. Modifiers and Security
      2. Accessing Fields
      3. Accessing Methods
      4. Accessing Constructors
      5. What About Arrays?
      6. Accessing Generic Type Information
      7. Accessing Annotation Data
      8. Dynamic Interface Adapters
      9. What Is Reflection Good For?
    4. Annotations
      1. Using Annotations
      2. Standard Annotations
      3. The apt Tool
  10. 8. Generics
    1. Containers: Building a Better Mousetrap
      1. Can Containers Be Fixed?
    2. Enter Generics
      1. Talking About Types
    3. “There Is No Spoon”
      1. Erasure
      2. Raw Types
    4. Parameterized Type Relationships
      1. Why Isn’t a List<Date> a List<Object>?
    5. Casts
    6. Writing Generic Classes
      1. The Type Variable
      2. Subclassing Generics
      3. Exceptions and Generics
      4. Parameter Type Limitations
    7. Bounds
      1. Erasure and Bounds (Working with Legacy Code)
    8. Wildcards
      1. A Supertype of All Instantiations
      2. Bounded Wildcards
      3. Thinking Outside the Container
      4. Lower Bounds
      5. Reading, Writing, and Arithmetic
      6. <?>, <Object>, and the Raw Type
      7. Wildcard Type Relationships
    9. Generic Methods
      1. Generic Methods Introduced
      2. Type Inference from Arguments
      3. Type Inference from Assignment Context
      4. Explicit Type Invocation
      5. Wildcard Capture
      6. Wildcard Types Versus Generic Methods
    10. Arrays of Parameterized Types
      1. Using Array Types
      2. What Good Are Arrays of Generic Types?
      3. Wildcards in Array Types
    11. Case Study: The Enum Class
    12. Case Study: The sort() Method
    13. Conclusion
  11. 9. Threads
    1. Introducing Threads
      1. The Thread Class and the Runnable Interface
      2. Controlling Threads
      3. Death of a Thread
    2. Threading an Applet
      1. Issues Lurking
    3. Synchronization
      1. Serializing Access to Methods
      2. Accessing class and instance Variables from Multiple Threads
      3. The wait() and notify() Methods
      4. Passing Messages
      5. ThreadLocal Objects
    4. Scheduling and Priority
      1. Thread State
      2. Time-Slicing
      3. Priorities
      4. Yielding
    5. Thread Groups
      1. Working with ThreadGroups
      2. Uncaught Exceptions
    6. Thread Performance
      1. The Cost of Synchronization
      2. Thread Resource Consumption
    7. Concurrency Utilities
      1. Executors
      2. Locks
      3. Synchronization Constructs
      4. Atomic Operations
    8. Conclusion
  12. 10. Working with Text
    1. Text-Related APIs
    2. Strings
      1. Constructing Strings
      2. Strings from Things
      3. Comparing Strings
      4. Searching
      5. Editing
      6. String Method Summary
      7. StringBuilder and StringBuffer
    3. Internationalization
      1. The java.util.Locale Class
      2. Resource Bundles
    4. Parsing and Formatting Text
      1. Parsing Primitive Numbers
      2. Tokenizing Text
    5. Printf-Style Formatting
      1. Formatter
      2. The Format String
      3. String Conversions
      4. Primitive and Numeric Conversions
      5. Flags
      6. Miscellaneous
    6. Formatting with the java.text Package
      1. MessageFormat
    7. Regular Expressions
      1. Regex Notation
      2. The java.util.regex API
  13. 11. Core Utilities
    1. Math Utilities
      1. The java.lang.Math Class
      2. Big/Precise Numbers
      3. Floating-Point Components
      4. Random Numbers
    2. Dates and Times
      1. Working with Calendars
      2. Time Zones
      3. Parsing and Formatting with DateFormat
      4. Printf-Style Date and Time Formatting
    3. Timers
    4. Collections
      1. The Collection Interface
      2. Iterator
      3. Collection Types
      4. The Map Interface
      5. Collection Implementations
      6. Hash Codes and Key Values
      7. Synchronized and Unsynchronized Collections
      8. Read-Only and Read-Mostly Collections
      9. WeakHashMap
      10. EnumSet and EnumMap
      11. Sorting Collections
      12. A Thrilling Example
    5. Properties
      1. Loading and Storing
      2. System Properties
    6. The Preferences API
      1. Preferences for Classes
      2. Preferences Storage
      3. Change Notification
    7. The Logging API
      1. Overview
      2. Logging Levels
      3. A Simple Example
      4. Logging Setup Properties
      5. The Logger
      6. Performance
    8. Observers and Observables
  14. 12. Input/Output Facilities
    1. Streams
      1. Basic I/O
      2. Character Streams
      3. Stream Wrappers
      4. Pipes
      5. Streams from Strings and Back
      6. Implementing a Filter Stream
    2. File I/O
      1. The java.io.File Class
      2. File Streams
      3. RandomAccessFile
      4. Resource Paths
    3. The NIO File API
      1. FileSystem and Path
      2. NIO File Operations
      3. Directory Operations
      4. Watching Paths
    4. Serialization
      1. Initialization with readObject()
      2. SerialVersionUID
    5. Data Compression
      1. Archives and Compressed Data
      2. Decompressing Data
      3. Zip Archive As a Filesystem
    6. The NIO Package
      1. Asynchronous I/O
      2. Performance
      3. Mapped and Locked Files
      4. Channels
      5. Buffers
      6. Character Encoders and Decoders
      7. FileChannel
      8. Scalable I/O with NIO
  15. 13. Network Programming
    1. Sockets
      1. Clients and Servers
      2. author="pat” timestamp="20120926T110720-0500” comment="one of those sections I hate to get rid of but is less relevant in terms of the example... should probably find a more modern example...”The DateAtHost Client
      3. The TinyHttpd Server
      4. Socket Options
      5. Proxies and Firewalls
    2. Datagram Sockets
      1. author="pat” timestamp="20120926T141346-0500” comment="I actually rewrote this as a standalone client but then decided to leave it as an applet”The HeartBeat Applet
      2. InetAddress
    3. Simple Serialized Object Protocols
      1. A Simple Object-Based Server
    4. Remote Method Invocation
      1. Real-World Usage
      2. Remote and Nonremote Objects
      3. An RMI Example
      4. RMI and CORBA
    5. Scalable I/O with NIO
      1. Selectable Channels
      2. Using Select
      3. LargerHttpd
      4. Nonblocking Client-Side Operations
  16. 14. Programming for the Web
    1. Uniform Resource Locators (URLs)
    2. The URL Class
      1. Stream Data
      2. Getting the Content as an Object
      3. Managing Connections
      4. Handlers in Practice
      5. Useful Handler Frameworks
    3. Talking to Web Applications
      1. Using the GET Method
      2. Using the POST Method
      3. The HttpURLConnection
      4. SSL and Secure Web Communications
      5. URLs, URNs, and URIs
    4. Web Services
      1. XML-RPC
      2. WSDL
      3. The Tools
      4. The Weather Service Client
  17. 15. Web Applications and Web Services
    1. Web Application Technologies
      1. Page-Oriented Versus “Single Page” Applications
      2. JSPs
      3. XML and XSL
      4. Web Application Frameworks
      5. Google Web Toolkit
      6. HTML5, AJAX, and More...
    2. Java Web Applications
      1. The Servlet Lifecycle
      2. Servlets
      3. The HelloClient Servlet
      4. The Servlet Response
      5. Servlet Parameters
      6. The ShowParameters Servlet
      7. User Session Management
      8. The ShowSession Servlet
      9. The ShoppingCart Servlet
      10. Cookies
      11. The ServletContext API
      12. Asynchronous Servlets
    3. WAR Files and Deployment
      1. Configuration with web.xml and Annotations
      2. URL Pattern Mappings
      3. Deploying HelloClient
      4. Error and Index Pages
      5. Security and Authentication
      6. Protecting Resources with Roles
      7. Secure Data Transport
      8. Authenticating Users
      9. Procedural Authorization
    4. Servlet Filters
      1. A Simple Filter
      2. A Test Servlet
      3. Declaring and Mapping Filters
      4. Filtering the Servlet Request
      5. Filtering the Servlet Response
    5. Building WAR Files with Ant
      1. A Development-Oriented Directory Layout
      2. Deploying and Redeploying WARs with Ant
    6. Implementing Web Services
      1. Defining the Service
      2. Our Echo Service
      3. Using the Service
      4. Data Types
    7. Conclusion
  18. 16. Swing
    1. Components
      1. Peers and Look-and-Feel
      2. The MVC Framework
      3. Painting
      4. Enabling and Disabling Components
      5. Focus, Please
      6. Other Component Methods
      7. Layout Managers
      8. Insets
      9. Z-Ordering (Stacking Components)
      10. The revalidate() and doLayout() Methods
      11. Managing Components
      12. Listening for Components
      13. Windows, Frames and Splash Screens
      14. Other Methods for Controlling Frames
      15. Content Panes
      16. Desktop Integration
    2. Events
      1. Event Receivers and Listener Interfaces
      2. Event Sources
      3. Event Delivery
      4. Event Types
      5. The java.awt.event.InputEvent Class
      6. Mouse and Key Modifiers on InputEvents
      7. Focus Events
    3. Event Summary
      1. Adapter Classes
      2. Dummy Adapters
    4. The AWT Robot!
    5. Multithreading in Swing
  19. 17. Using Swing Components
    1. Buttons and Labels
      1. HTML Text in Buttons and Labels
    2. Checkboxes and Radio Buttons
    3. Lists and Combo Boxes
    4. The Spinner
    5. Borders
    6. Menus
    7. Pop-Up Menus
      1. Component-Managed Pop Ups
    8. The JScrollPane Class
    9. The JSplitPane Class
    10. The JTabbedPane Class
    11. Scrollbars and Sliders
    12. Dialogs
      1. File Selection Dialog
      2. The Color Chooser
  20. 18. More Swing Components
    1. Text Components
      1. The TextEntryBox Application
      2. Formatted Text
      3. Filtering Input
      4. Validating Data
      5. Say the Magic Word
      6. Sharing a Data Model
      7. HTML and RTF for Free
      8. Managing Text Yourself
    2. Focus Navigation
      1. Trees
      2. Nodes and Models
      3. Save a Tree
      4. Tree Events
      5. A Complete Example
    3. Tables
      1. A First Stab: Freeloading
      2. Round Two: Creating a Table Model
      3. Round Three: A Simple Spreadsheet
      4. Sorting and Filtering
      5. Printing JTables
    4. Desktops
    5. Pluggable Look-and-Feel
    6. Creating Custom Components
      1. Generating Events
      2. A Dial Component
      3. Model and View Separation
  21. 19. Layout Managers
    1. FlowLayout
    2. GridLayout
    3. BorderLayout
    4. BoxLayout
    5. CardLayout
    6. GridBagLayout
      1. The GridBagConstraints Class
      2. Grid Coordinates
      3. The fill Constraint
      4. Spanning Rows and Columns
      5. Weighting
      6. Anchoring
      7. Padding and Insets
      8. Relative Positioning
      9. Composite Layouts
    7. Other Layout Managers
    8. Absolute Positioning
  22. 20. Drawing with the 2D API
    1. The Big Picture
    2. The Rendering Pipeline
    3. A Quick Tour of Java 2D
      1. Filling Shapes
      2. Drawing Shape Outlines
      3. Convenience Methods
      4. Drawing Text
      5. Drawing Images
      6. The Whole Iguana
    4. Filling Shapes
      1. Solid Colors
      2. Color Gradients
      3. Textures
      4. Desktop Colors
    5. Stroking Shape Outlines
    6. Using Fonts
      1. Font Metrics
    7. Displaying Images
      1. The Image Class
      2. Image Observers
      3. Scaling and Size
    8. Drawing Techniques
      1. Double Buffering
      2. Limiting Drawing with Clipping
      3. Offscreen Drawing
    9. Printing
  23. 21. Working with Images and Other Media
    1. Loading Images
      1. ImageObserver
      2. MediaTracker
      3. ImageIcon
      4. ImageIO
    2. Producing Image Data
      1. Drawing Animations
      2. BufferedImage Anatomy
      3. Color Models
      4. Creating an Image
      5. Updating a BufferedImage
    3. Filtering Image Data
      1. How ImageProcessor Works
      2. Converting an Image to a BufferedImage
      3. Using the RescaleOp Class
      4. Using the AffineTransformOp Class
    4. Saving Image Data
    5. Simple Audio
    6. Java Media Framework
  24. 22. JavaBeans
    1. What’s a Bean?
      1. What Constitutes a Bean?
    2. The NetBeans IDE
      1. Installing and Running NetBeans
    3. Properties and Customizers
    4. Event Hookups and Adapters
      1. Taming the Juggler
      2. Molecular Motion
    5. Binding Properties
      1. Constraining Properties
    6. Building Beans
      1. The Dial Bean
      2. Design Patterns for Properties
    7. Limitations of Visual Design
    8. Serialization Versus Code Generation
    9. Customizing with BeanInfo
      1. Getting Properties Information
    10. Handcoding with Beans
      1. Bean Instantiation and Type Management
      2. Working with Serialized Beans
      3. Runtime Event Hookups with Reflection
    11. BeanContext and BeanContextServices
    12. The Java Activation Framework
    13. Enterprise JavaBeans and POJO-Based Enterprise Frameworks
  25. 23. Applets
    1. The Politics of Browser-Based Applications
    2. Applet Support and the Java Plug-in
    3. The JApplet Class
      1. Applet Lifecycle
      2. The Applet Security Sandbox
      3. Getting Applet Resources
      4. The <applet> Tag
      5. Attributes
      6. Parameters
      7. ¿Habla Applet?
      8. The Complete <applet> Tag
      9. Loading Class Files
      10. Packages
      11. appletviewer
    4. Java Web Start
    5. Conclusion
  26. 24. XML
    1. The Butler Did It
    2. A Bit of Background
      1. Text Versus Binary
      2. A Universal Parser
      3. The State of XML
      4. The XML APIs
      5. XML and Web Browsers
    3. XML Basics
      1. Attributes
      2. XML Documents
      3. Encoding
      4. Namespaces
      5. Validation
      6. HTML to XHTML
    4. SAX
      1. The SAX API
      2. Building a Model Using SAX
      3. XMLEncoder/Decoder
    5. DOM
      1. The DOM API
      2. Test-Driving DOM
      3. Generating XML with DOM
      4. JDOM
    6. XPath
      1. Nodes
      2. Predicates
      3. Functions
      4. The XPath API
      5. XMLGrep
    7. XInclude
      1. Enabling XInclude
    8. Validating Documents
      1. Using Document Validation
      2. DTDs
      3. XML Schema
      4. The Validation API
    9. JAXB Code Binding and Generation
      1. Annotating Our Model
      2. Generating a Java Model from an XML Schema
      3. Generating an XML Schema from a Java Model
    10. Transforming Documents with XSL/XSLT
      1. XSL Basics
      2. Transforming the Zoo Inventory
      3. XSLTransform
      4. XSL in the Browser
    11. Web Services
    12. The End of the Book
  27. A. The Eclipse IDE
    1. The IDE Wars
    2. Getting Started with Eclipse
      1. Importing the Learning Java Examples
    3. Using Eclipse
      1. Getting at the Source
      2. The Lay of the Land
      3. Running the Examples
      4. Building the Ant-Based Examples
      5. Loner Examples
    4. Eclipse Features
      1. Coding Shortcuts
      2. Autocorrection
      3. Refactoring
      4. Diffing Files
      5. Organizing Imports
      6. Formatting Source Code
    5. Conclusion
  28. B. BeanShell: Java Scripting
    1. Running BeanShell
    2. Java Statements and Expressions
      1. Imports
    3. BeanShell Commands
    4. Scripted Methods and Objects
      1. Scripting Interfaces and Adapters
    5. Changing the Classpath
    6. Learning More . . .
  29. Glossary
  30. Index
  31. About the Authors
  32. Colophon
  33. Copyright
O'Reilly logo

The JApplet Class

A JApplet is a Swing JPanel with a mission. It is a GUI container that has some extra structure to allow it to be used in the “alien” environment of a web browser. Applets also have a lifecycle that lets them act more like an application than a static component. Although applets tend to be relatively simple, there’s no inherent restriction on their complexity other than the issues of downloading and caching their content. Historically, applets have tended to be small “widgets.”

The javax.swing.JApplet class defines the core functionality of an applet. (java.awt.Applet is the older, AWT-based form.)

Structurally, an applet is a wrapper for your Java code. In contrast to a standalone graphical Java application, which starts up from a main() method and creates a GUI, an applet itself is a component that expects to be dropped into someone else’s GUI. Thus, an applet can’t run by itself; it runs in the context of a web browser or a special applet-viewer program (which we’ll talk about later). Instead of having your application create a JFrame to hold your GUI, you stuff your application inside a JApplet (which itself extends Container) and let the browser add your applet to the page.

Applets are placed on web pages with the <applet> HTML tag, which we’ll cover later in this chapter. At its simplest, you just specify the name of the applet class and a size in pixels for the applet:

    <applet code="AnalogClock" width="100" height="100"></applet>

Pragmatically, an applet is an intruder into someone else’s environment and therefore has to be treated with suspicion. The web browsers that run applets impose restrictions on what the applet is allowed to do. The restrictions are enforced by an applet security manager. The browser provides everything the applet needs through an applet context—the API the applet uses to interact with its environment.

A JApplet expects to be embedded in a page and used in a viewing environment that provides it with resources. In all other respects, however, applets are just ordinary Panel objects. As Figure 23-1 shows, an applet is a kind of Panel. Like any other Panel, a JApplet can contain user interface components and use all the basic drawing and event-handling capabilities of the Component class. You can draw on a JApplet by overriding its paint() method and respond to events in the JApplet’s display area by providing the appropriate event listeners. Applets also have additional structure that helps them interact with the browser environment.

Aside from the top-level structure and the security restrictions, there is no difference between an applet and an application. If your application can live within the limits imposed by a browser’s security manager, you can structure it to function as both an applet and a standalone application. Normally, you’ll use your applet class itself only as a thin wrapper to manage the lifecycle and appearance of your application—create the GUI, start, and stop. So, the bulk of your code should be easily adaptable to either a standalone or applet deployment.

The java.applet package

Figure 23-1. The java.applet package

Applet Lifecycle

The Applet class contains four methods that can be overridden to guide it through its lifecycle. The init(), start(), stop(), and destroy() methods are called by the appletviewer or web browser to direct the applet’s behavior. init() is called once, after the applet is created. The init() method is where you perform basic setup such as parsing parameters, building a user interface, and loading resources.

By convention, applets don’t provide an explicit constructor to do any setup. The reason for this is that the constructor is meant to be called by the applet’s environment, for simple creation of the applet. This might happen before the applet has access to certain resources, such as information about its environment. Therefore, an applet doesn’t normally do any work there; instead it should rely on the default constructor for the JApplet class and do its initialization in the init() method.

The start() method is called whenever the applet becomes visible; it shouldn’t be a surprise then that the stop() method is called whenever the applet becomes invisible. init() is called only once in the life of an applet, but start() and stop() can be called any number of times (although always in the logical sequence). The start() method is called when the applet is displayed, such as when it scrolls onto the screen; stop() will be called if the applet scrolls off the screen, or the viewer leaves the document. start() tells the applet it should be active. The applet may want to create threads, animate, or otherwise perform useful (or annoying) activity. stop() is called to let the applet know it should go dormant. Applets should cease CPU-intensive or wasteful activity when they are stopped and resume when (and if) they are restarted. However, there’s no requirement that an invisible applet stop computing; in some applications, it may be useful for the applet to continue running in the background. Just be considerate of your user, who doesn’t want an invisible applet dragging down system performance.

Finally, the destroy() method gives the applet a last chance to clean up before it’s removed—some time after the last call to stop(). For example, an applet might want to gracefully close down suspended communications channels at this time. Exactly when destroy() is called depends on the browser; Netscape calls destroy() just prior to deleting the applet from its cache. This means that although an applet can cling to life after being told to stop(), how long it can go on is unpredictable. If you want to maintain an applet as the user progresses through other pages of activities, you may have to put it in an HTML frame, so that it remains visible and won’t be told to stop() (see Applet persistence and navigation).

If you’ve read this entire book up until now, you’ve already seen a couple of applets that snuck in among other topics. In Chapter 9, we created a simple clock applet, and in Chapter 13, we used an applet to send packets of information from a web browser. Now let’s try a simple Swing-based example using JApplet. The following example, ShowApplet, shown in Figure 23-2, does nothing special, but you can use it to test the version of Java that’s running in your browser (and see if the Plug-in is installed) and to see when the applet is started and stopped. It’s a good reference.

    import javax.swing.*;
    import java.awt.event.*;

    public class ShowApplet extends JApplet {
       JTextArea text = new JTextArea();
       int startCount;

       public void init() {
          JButton button = new JButton("Press Me");
          button.addActionListener( new ActionListener() {
             public void actionPerformed( ActionEvent e ) {
                text.append("Button Pressed!\n");
             }
          } );
          getContentPane().add( "Center", new JScrollPane( text ) );
          JPanel panel = new JPanel();
          panel.add( button );
          getContentPane().add( "South", panel );
          text.append( "Java Version: "
             +System.getProperty("java.version")+"\n" );
          text.append( "Applet init()\n" );
       }
       public void start() {
          text.append( "Applet started: "+ startCount++ +"\n" );
       }
       public void stop() {
          text.append( "Applet stopped.\n" );
       }
    }
ShowApplet

Figure 23-2. ShowApplet

After compiling the applet, we have to create an HTML page in which to embed it. The following will do:

    <html><head><title>ShowApplet</title></head>
    <body>
    <applet code="ShowApplet" width="300" height="300">
       Your browser does not understand Java.</applet>
    </body>
    </html>

We’ll discuss the applet tag and other issues related to embedding applets in documents in detail later in this chapter. For now, just save this in a file called showapplet.html. Load the file with your favorite web browser and see what happens. (We’re assuming you have installed Java on your computer by this point; you may have to enable Java in your browser to see the applet if it is disabled by default.) If you have access to a web server, you can use it. Otherwise, you can open the file locally using either the browser’s Open File menu option or a URL such as:

    file:///Users/somedir/showapplet.html

The applet shows the version of Java running it and prints messages when its button is pressed. If you have installed the latest Java Plug-in you should see “Java version: 1.7” in the box, regardless of which browser you are using (including Microsoft Internet Explorer). The applet prints messages when its start() and stop() methods are called, along with a count. You can use this to experiment with different browsers and page-layout configurations to see when your applet is reloaded or restarted. If your browser fails to display the applet with the correct version of Java, don’t worry. Later in this chapter, we’ll talk about how to convert the HTML to force the browser to use the Java Plug-in explicitly.

The Applet Security Sandbox

Applets are quarantined within the browser by an applet SecurityManager. The SecurityManager is part of the web browser or appletviewer application. It is installed before the browser loads any applets and implements the basic restrictions that let the user run untrusted applets (loaded over the Internet) safely. Remember, there are no inherent security restrictions on a standalone Java application. It is the browser that limits what applets are allowed to do using a security policy.

Most browsers impose the following restrictions on untrusted applets:

  • Untrusted applets can’t read or write files on the local host.

  • Untrusted applets can open network connections (sockets) only to the server from which they originated.

  • Untrusted applets can’t start other processes on the local host.

  • Untrusted applets can’t have native methods.

The motivation for these restrictions should be fairly obvious: you clearly wouldn’t want a program coming from some random Internet site to access your files or run arbitrary programs. Although untrusted applets can’t directly read and write files on the client side or talk to arbitrary hosts on the network, applets can work with servers to store data and communicate. For example, an applet can use Java’s RMI facility to do processing on its server. An applet can communicate with other applets on the Net by proxy through its server.

Trusted applets

We’ve been using the term untrusted applet, so it should come as no surprise that it is also possible to have such a thing as a trusted applet. Applets become trusted through the use of digital signatures, by signing the JAR file containing your applet code. Because a signature identifies the applet’s origin unambiguously, the user can distinguish between trusted applets (i.e., applets that come from a site or person you trust not to do anything harmful) and run-of-the-mill untrusted applets. In browser environments that support signing, trusted applets can be granted permission to “go outside” of the applet security sandbox. Trusted applets can be allowed to do all of the things that standalone Java applications can do: read and write files, open network connections to arbitrary machines, and interact with the local operating system by starting processes. Trusted applets still can’t have native methods, but including native methods in an applet would destroy its portability anyway.

Because signed applets are now a fairly niche topic, we no longer cover them in this chapter. If you need more details on them, please visit the “extras” page for this book, where we post additional material not included in the book as well as the example source code.

Getting Applet Resources

An applet must communicate with its browser or applet viewer. For example, it may need configuration parameters from the HTML document in which it appears. An applet may also need to load images, audio clips, and other items. It may also want to ask the viewer about other applets on the same HTML page in order to communicate with them. To get resources from the environment, applets use the AppletStub and AppletContext interfaces, provided by the browser.

Applet parameters

An applet can get configuration parameters from <param> tags placed inside the <applet> tag in the HTML document, as we’ll describe later. You can retrieve these parameters using Applet’s getParameter() method. For example, the following code reads parameters called imageName and sheep from its HTML page:

    String imageName = getParameter( "imageName" );
    try  {
        int numberOfSheep = Integer.parseInt( getParameter( "sheep" ) );
    } catch ( NumberFormatException e ) { /* use default */ }

There is an API that allows an applet to provide information (help) about the parameters it accepts. The applet’s getParameterInfo() can return an array of string arrays, listing and describing the applet’s parameters. However, it’s unclear that anyone uses this API.

Applet resources

An applet can find out where it lives using the getDocumentBase() and getCodeBase() methods. getDocumentBase() returns the base URL of the document in which the applet appears; getCodeBase() returns the base URL of the Applet’s class files (these two are often the same). An applet can use these methods to construct relative URLs from which to load other resources from its server, such as images, sounds, and other data. The getImage() method takes a URL and asks for an image from the viewer environment. The image may be cached or loaded when later used. The getAudioClip() method, similarly, retrieves sound clips.

The following example uses getCodeBase() to construct a URL and load a properties configuration file, located in the same remote directory on the web server as the applet’s class file:

    Properties props = new Properties();
    try {
      URL url = new URL( getCodeBase(), "appletConfig.props" );
      props.load( url.openStream() );
    } catch ( IOException e ) { /* failed */ }

A better way to load resources is by calling the getResource() and getResourceAsStream() methods of the Class class, which search the applet’s JAR files (if any) as well as its codebase, which is an extension of the classpath for applets. The following code loads the same properties file in a more portable way:

    Properties props = new Properties();
    try {
      props.load( getClass().getResourceAsStream( "appletConfig.props") );
    } catch ( IOException e ) { /* failed */ }

An applet can ask its viewer to retrieve an image by calling the getImage() method. The location of the image to be retrieved is given as a URL, either absolute or fetched from an applet’s resources:

    public class MyApplet extends javax.swing.JApplet {
      public void init() {
        try {
          // absolute URL
          URL monaURL =
              new URL( "http://myserver/images/mona_lisa.gif");
          Image monaImage = getImage( monaURL );
          // applet resource URL
          URL daffyURL =
              getClass().getResource("cartoons/images/daffy.gif");
          Image daffyDuckImage = getImage( daffyURL );
        }
        catch ( MalformedURLException e ) {
            // unintelligable url
        }
      }
      // ...
    }

Again, using getResource() is preferred; it looks for the image in the applet’s JAR file (if there is one), before looking elsewhere in the applet’s classpath on the server. (We’ll talk more later about how classes are located for applets.)

Driving the browser

The status line is a blurb of text that usually appears somewhere in the web browser’s display, indicating a current activity. An applet can request that some text be placed in the status line with the showStatus() method. (The browser isn’t required to do anything in response to this call, but most browsers will oblige you.)

An applet can also ask the browser to show a new document. To do this, the applet makes a call to the showDocument(url) method of the AppletContext. You can get a reference to the AppletContext with the applet’s getAppletContext() method. Calling showDocument(url) replaces the currently showing document, which means that your currently running applet will be stopped.

Another version of showDocument() takes an additional String argument to tell the browser where to display the new URL:

    getAppletContext().showDocument( url, name );

The name argument can be the name of an existing labeled HTML frame; the document referenced by the URL is displayed in that frame. You can use this method to create an applet that “drives” the browser to new locations dynamically but keeps itself active on the screen in a separate frame. This is common for applets that act like navigation controls or menus. If the named frame doesn’t exist, the browser creates a new top-level window to hold it. Alternatively, name can have one of the following special values:

self

Show in the current frame

_parent

Show in the parent of our frame

_top

Show in outermost (top-level) frame

_blank

Show in a new top-level browser window

Both showStatus() and showDocument() requests may be ignored by a cold-hearted viewer or web browser. Nothing in browser-land is ever certain.

Inter-applet communication

Although it’s not very common, applets that are embedded in documents loaded from the same location on a website can use a simple mechanism to locate one another and coordinate their activities on a page. Once an applet has a reference to another applet, it can communicate with it just as with any other object, by invoking methods and sending events. The getApplet() method of the applet context looks for an applet by name:

    Applet clock = getAppletContext().getApplet("theClock");

Give an applet a name within your HTML document using the name attribute of the <applet> tag. Alternatively, you can use the getApplets() method to enumerate all the available applets in the pages.

The tricky thing with applet communications is that applets run inside the security sandbox. An untrusted applet can “see” and communicate only with objects that were loaded by the same class loader. Currently, the only reliable criterion for when applets share a class loader is when they share a common base URL. For example, all the applets contained in web pages loaded from the base URL of http://foo.bar.com/mypages/ should share a class loader and should be able to see each other. This includes documents such as mypages/foo.html and mypages/bar.html, but not mypages/morestuff/foo.html.

When applets do share a class loader, other techniques are possible, too. As with any other class, you can call static methods in applets by name. So you could use static methods in one of your applets as a “registry” to coordinate your activities.

Applet persistence and navigation

One of the biggest shortcomings of the Applet API is the lack of a real context for coordinating their activities during navigation across a multipage document or web application. The Applet API simply wasn’t designed for this. Although an applet’s life cycle is well defined in terms of its API, it is not well defined in terms of management by the browser or scope of visibility. As we described in the previous section, applets loaded from the same codebase can rendezvous at runtime using their name attributes. But there are no guarantees about how long an applet will live—or whether it will be stopped as opposed to being destroyed—once it is out of view. If you experiment with our ShowApplet in various browsers and in the Java Plug-in (which we’ll discuss later), you’ll see that, in some cases, the applet is stopped and restarted when the user leaves the page, but more often the applet is reinitialized from scratch. This makes designing multipage applications that work in all browsers difficult.

One solution has been to use static methods as a shared “registry,” as mentioned earlier. However, the details governing how classes loaded by applets are managed are even less well-defined than the management of the applets themselves. In Java 1.4, a pair of methods was added to the AppletContext to support short-term applet persistence: setStream() and getStream(). With these methods, an applet can ask the context to save a stream of byte data by a key value and return it later. The notion of providing the state to the context as a stream is a little odd, but easy enough to accommodate. Here is an example:

    getAppletContext.setStream("myStream",
        new ByteArrayInputStream( "This is some test data...".getBytes() ) );

Later, the stream data can be retrieved:

    InputStream in = getAppletContext.getStream( "myStream" );

Currently, the data is retained only as long as the browser is running. If you need more complex state and navigation capabilities, you might consider using a signed applet to write to a file or taking advantage of the Java Web Start API to install your application locally.

The <applet> Tag

Applets are embedded in HTML documents with the <applet> tag. The <applet> tag resembles the HTML <img> image tag. It contains attributes that identify the applet to be displayed and, optionally, give the web browser hints about how it should be shown.[48]

The standard image tag sizing and alignment attributes, such as height and width, can be used inside the applet tag. However, unlike images, applets have both an opening <applet> and a closing </applet> tag. Sandwiched between these can be any number of <param> tags that contain configuration data to be passed to the applet:

    <applet attributeattribute ... >
        <param parameter >
        <param parameter >
        ...
    </applet>

Attributes

Attributes are name/value pairs that are interpreted by a web browser or applet viewer. Attributes of the <applet> tag specify general features that apply to any applet, such as size and alignment. The definition of the <applet> tag lists a fixed set of recognized attributes; specifying an incorrect or nonexistent attribute should be considered an HTML error.

Three attributes are required in the <applet> tag. Two of these attributes, width and height, specify the space that the applet occupies on the screen. The third required attribute must be either code or object; you must supply one of these attributes, and you can’t specify both. The code attribute specifies the class file from which the applet is loaded; the object attribute specifies a serialized representation of an applet. Most often, you’ll use the code attribute.

The following is an HTML fragment for a simple clock applet that takes no parameters and requires no special HTML layout:

    <applet code="AnalogClock" width="100" height="100"></applet>

The HTML file that contains this <applet> tag must be stored in the same directory as the AnalogClock.class class file. The applet tag is not sensitive to spacing in the HTML, so the previous tag could be also be formatted a little more readably like so:

    <applet
        code="AnalogClock"
        width="100"
        height="100">
    </applet>

Parameters

Parameters are analogous to command-line arguments; they provide a way to pass information to an applet. Each <param> tag contains a name and a value that are passed as string values to the applet:

    <param name = "parameter_name" value = "parameter_value">

Parameters provide a means of embedding application-specific data and configuration information within an HTML document. Our AnalogClock applet, for example, might accept a parameter that selects between local and universal time:

    <applet code="AnalogClock" width="100" height="100">
        <param name="zone" value="GMT">
    </applet>

Presumably, this AnalogClock applet is designed to look for a parameter named zone with a possible value of GMT.

Parameter names and values should be quoted and can contain spaces and other whitespace characters. The parameters a given applet expects are, of course, determined by the developer of that applet. There is no standard set of parameter names or values; it’s up to the applet to interpret the parameter name/value pairs that are passed to it. Any number of parameters can be specified, and the applet may choose to use or ignore them as it sees fit.

¿Habla Applet?

Web browsers are supposed to ignore tags they don’t understand; if the web browser doesn’t know about the <applet> or <param> tags, we would expect them to disappear, and any HTML between the <applet> and </applet> tags to appear normally. By convention, Java-enabled web browsers ignore any extra HTML between the <applet> and </applet> tags. Combined, this means we can place some alternative HTML inside the <applet> tag, which is displayed only by web browsers that can’t run the applet.

For our AnalogClock example, we could display a small text explanation and an image of the clock applet as a teaser:

    <applet code="AnalogClock" width="100" height="100">
        <param name="zone" value="GMT">
        <strong>If you see this, you don't have a Java-enabled Web
        browser. Here's a picture of what you are missing.</strong>
        <img src="clockface.gif">
    </applet>

The Complete <applet> Tag

We’ll now spell out the complete syntax for the <applet> tag:

    <applet
        code = class_name

or:

        object = serialized_applet_name

        width = pixels_high
        height = pixels_wide

        [ codebase = location_URL ]
        [ archive = comma_separated_list_of_archive_files ]
        [ name = applet_instance_name ]
        [ alt = alternate_text ]
        [ align = style ]
        [ vspace = vertical pad pixels ]
        [ hspace = horizontal pad pixels ]
    >
        [ <param name = parameter_name value = parameter_value> ]
        [ <param ...  ]

        [ HTML code for non-Java-aware browsers ]
    </applet>

Either the code attribute or the object attribute must be present to specify the applet to run. The code attribute specifies the applet’s class file; you’ll see this most frequently. The object attribute specifies a serialized representation of an applet. When you use the object attribute to load an applet, the applet’s init() method is not called. However, the serialized applet’s start() method is called.

The width, height, align, vspace, and hspace attributes determine the preferred size, alignment, and padding, respectively. The width and height attributes are required.

The codebase attribute specifies the base URL to be searched for the applet’s class files. If this attribute isn’t present, the browser looks in the same location as the HTML file. The archive attribute specifies a list of JAR or ZIP files in which the applet’s class files are located. To put two or more files in the list, separate the filenames with commas; for example, the following attribute tells the browser to load and search three archives for the applet’s classes:

    archive="Part1.jar,Part2.jar,Utilities.jar"

The archive files listed by the archive tag are loaded from the codebase URL. When searching for classes, a browser checks the archives before searching any other locations on the server.

The alt attribute specifies alternate text that is displayed by browsers that understand the <applet> tag and its attributes but have Java disabled or don’t run applets. This attribute can also describe the applet because in this case, any alternate HTML between <applet> and </applet> is, by convention, ignored by Java-enabled browsers.

The name attribute specifies an instance name for the executing applet. This is a name specified as a unique label for each copy of an applet on a particular HTML page. For example, if we include our clock twice on the same page (using two applet tags), we should give each instance a unique name to differentiate them:

    <applet code="AnalogClock" name="bigClock" width="300" height="300">
    </applet>
    <applet code="AnalogClock" name="smallClock" width="50" height="50">
    </applet>

Applets can use instance names to recognize and communicate with other applets on the same page. We could, for instance, create a “clock setter” applet that knows how to set the time on an AnalogClock applet and pass it the instance name of a particular target clock on this page as a parameter. This might look something like:

    <applet code="ClockSetter">
        <param name="clockToSet" value="bigClock">
    </applet>

Loading Class Files

The code attribute of the <applet> tag should specify the name of an applet. This is either a simple class name or a package path and class name. For now, let’s look at simple class names; we’ll discuss packages in a moment. By default, the Java runtime system looks for the class file in the same location as the HTML document that contains it. This location is known as the base URL for the document.

Consider an HTML document, clock.html, that contains our clock applet example:

    <applet code="AnalogClock" width="100" height="100"></applet>

Let’s say we retrieve the document at the following URL:

    http://www.time.ch/documents/clock.html

Java tries to retrieve the applet class file from the same base location:

    http://www.time.ch/documents/AnalogClock.class

The codebase attribute of the <applet> tag specifies an alternative base URL for the class file search. Let’s say our HTML document now specifies codebase, as in the following example:

    <applet
        codebase="http://www.joes.ch/stuff/"
        code="AnalogClock"
        width="100"
        height="100">
    </applet>

Java now looks for the applet class file at:

    http://www.joes.ch/stuff/AnalogClock.class

Packages

For “loose” applet class files that are not packaged into archives, Java uses the standard package name to directory path mapping to locate files on the server. The only difference is that the requests are not local file lookups, but instead are requests to the web server at the applet’s codebase URL. Before a class file is retrieved from a server, its package name component is translated by the client into a relative pathname under the applet’s codebase.

Let’s suppose that our AnalogClock has been placed into a package called time.clock (a subordinate package for clock-related classes, within a package for time-related classes). The fully qualified name of our class is time.clock.AnalogClock. Our simple <applet> tag would now look like:

    <applet code="time.clock.AnalogClock" width="100" height="100"></applet>

Let’s say the clock.html document is once again retrieved from:

    http://www.time.ch/documents/clock.html

Java now looks for the class file in the following location:

    http://www.time.ch/documents/time/clock/AnalogClock.class

The same is true when specifying an alternative codebase:

    <applet
        codebase="http://www.joes.ch/stuff/"
        code="time.clock.AnalogClock"
        width="100"
        height="100">
    </applet>

Java now tries to find the class in the corresponding path under this base URL:

    http://www.joes.ch/stuff/time/clock/AnalogClock.class

appletviewer

The Java SDK comes with an applet viewer program, aptly called appletviewer. To use appletviewer, specify the URL of the document on the command line. For example, to view our (still only theoretical) AnalogClock at the URL shown earlier, use the following command:

    % appletviewer http://www.time.ch/documents/clock.html

appletviewer retrieves all applets in the specified document and displays each one in a separate window. appletviewer isn’t a web browser; it doesn’t attempt to display HTML. It was primarily useful before the Java Plug-in as a way to test an applet in a specific version of the Java runtime.



[48] If you aren’t familiar with HTML or other markup languages, you may want to refer to HTML & XHTML: The Definitive Guide by Chuck Musciano and Bill Kennedy (O’Reilly) for a complete reference on HTML and structured web documents.

The best content for your career. Discover unlimited learning on demand for around $1/day.