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

Text Components

Swing offers sophisticated text components, from plain-text entry boxes to HTML renderers. For full coverage of Swing’s text capabilities, see O’Reilly’s Java Swing. In that encyclopedic book, several meaty chapters are devoted to text. It’s a huge subject; we’ll just scratch the surface here.

Let’s begin by examining the simpler text components. JTextField is a single-line text editor and JTextArea is a simple, multiline text editor. Both JTextField and JTextArea derive from the JTextComponent class, which provides the functionality they have in common. This includes methods for setting and retrieving the displayed text, specifying whether the text is “editable” or read-only, manipulating the cursor position within the text, and manipulating text selections.

Observing changes in text components requires an understanding of how the components implement the Model-View-Controller (MVC) architecture. You may recall from the last chapter that Swing components implement a true MVC architecture. It’s in the text components that you first get an inkling of a clear separation between the M and VC parts of the MVC architecture. The model for text components is an object called a Document. When you add or remove text from a JTextField or a JTextArea, the corresponding Document is changed. It’s the document itself, not the visual components, that generates text-related events when something changes. To receive notification of JTextArea changes, therefore, you register with the underlying Document, not with the JTextArea component itself:

    JTextArea textArea = new JTextArea();
    Document doc = textArea.getDocument();
    doc.addDocumentListener(someListener);

As you’ll see in an upcoming example, you can easily have more than one visual text component use the same underlying Document data model.

In addition, JTextField components generate ActionEvents whenever the user presses the Return key within the field. To get these events, just implement the ActionListener interface and register your listener using the addActionListener() method.

The next sections contain a couple of simple applications that show you how to work with text areas and fields.

The TextEntryBox Application

Our first example, TextEntryBox, creates a JTextArea and ties it to a JTextField, as you can see in Figure 18-1.

The TextEntryBox application

Figure 18-1. The TextEntryBox application

When the user hits Return in the JTextField, we receive an ActionEvent and add the line to the JTextArea’s display. Try it out. You may have to click your mouse in the JTextField to give it focus before typing in it. If you fill up the display with lines, you can test-drive the scroll bar:

    //file: TextEntryBox.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class TextEntryBox {

      public static void main(String[] args) {
        JFrame frame = new JFrame("Text Entry Box");

        final JTextArea area = new JTextArea();
        area.setFont(new Font("Serif", Font.BOLD, 18));
        area.setText("Howdy!\n");
        final JTextField field = new JTextField();

        frame.add(new JScrollPane(area), BorderLayout.CENTER);
        frame.add(field, BorderLayout.SOUTH);
        field.requestFocus();

        field.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            area.append(field.getText() + '\n');
            field.setText("");
          }
        });

        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(200, 300);
        frame.setVisible(true);
      }
    }

TextEntryBox is exceedingly simple; we’ve done a few things to make it more interesting. We give the text area a bigger font using Component’s setFont() method; fonts are discussed in Chapter 20. Finally, we want to be notified whenever the user presses Return in the text field, so we register an anonymous inner class as a listener for action events.

Pressing Return in the JTextField generates an action event, and that’s where the fun begins. We handle the event in the actionPerformed() method of our inner ActionListener implementation. Then, we use the getText() and setText() methods to manipulate the text that the user has typed. These methods can be used for JTextField and JTextArea, as these components are both derived from the JTextComponent class and, therefore, have some common functionality.

The event handler, actionPerformed(), calls field.getText() to read the text that the user typed into our JTextField. It then adds this text to the JTextArea by calling area.append(). Finally, we clear the text field by calling the method field.setText(""), preparing it for more input.

Remember, the text components really are distinct from the text data model, the Document. When you call setText(), getText(), or append(), these methods are shorthand for operations on an underlying Document.

By default, JTextField and JTextArea are editable; you can type and edit in both text components. They can be changed to output-only areas by calling setEditable(false). Both text components also support selections. A selection is a range of text that is highlighted for copying, cutting, or pasting in your windowing system. You select text by dragging the mouse over it; you can then cut, copy, and paste it into other text windows using the default keyboard gestures. On most systems, these are Ctrl-C for copy, Ctrl-V for paste, and Ctrl-X for cut (on the Mac it’s Command-C, Command-V, and Command-X). You can also programmatically manage these operations using the JTextComponent’s cut() , copy(), and paste() methods. You could, for example, create a pop-up menu with the standard cut, copy, and paste options using these methods. The current text selection is returned by getSelectedText(), and you can set the selection using selectText(), which takes an index range or selectAll().

Notice how JTextArea fits neatly inside a JScrollPane. The scroll pane gives us the expected scrollbars and scrolling behavior if the text in the JTextArea becomes too large for the available space.

Formatted Text

The JFormattedTextField component provides explicit support for editing complex formatted values such as numbers and dates. JFormattedTextField acts somewhat like a JTextField, except that it accepts a format-specifying object in its constructor and manages a complex object type (such as Date or Integer) through its setValue() and getValue() methods. The following example shows the construction of a simple form with different types of formatted fields:

    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.util.Date;

    public class
               
    FormattedFields
    {
        public static void main( String[] args ) throws Exception {
            Box form = Box.createVerticalBox();
            form.add( new JLabel("Name:") );
            form.add( new JTextField("Joe User") );

            form.add( new JLabel("Birthday:") );
            JFormattedTextField birthdayField =
                new JFormattedTextField(new SimpleDateFormat("MM/dd/yy"));
            birthdayField.setValue( new Date() );
            form.add( birthdayField );

            form.add( new JLabel("Age:") );
            form.add(new JFormattedTextField(new Integer(32)));

            form.add( new JLabel("Hairs on Body:") );
            JFormattedTextField hairsField
                = new JFormattedTextField( new DecimalFormat("###,###") );
            hairsField.setValue(new Integer(100000));
            form.add( hairsField );

            form.add( new JLabel("Phone Number:") );
            JFormattedTextField phoneField =
                new JFormattedTextField( new MaskFormatter("(###)###-####") );
            phoneField.setValue("(314)555-1212");
            form.add( phoneField );

            JFrame frame = new JFrame("User Information");
            frame.getContentPane().add(form);
            frame.pack();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setVisible(true);
        }
    }

JFormattedTextField can be constructed in a variety of ways. You can use a plain instance of java.lang.Number (e.g., Integer and Float) as a prototype or set the layout explicitly using a formatting object from the java.text package: java.text.NumberFormat, java.text.DateFormat, or the more arbitrary java.text.MaskFormatter. The NumberFormat and DateFormat classes of the java.text package are discussed in Chapters 10 and 11. MaskFormatter allows you to construct arbitrary physical layout conventions. In a moment, we’ll discuss input filtering and component validation, which also allow you to restrict the kinds of characters that could fill the fields or perform arbitrary checks on the data. Finally, we should mention that in this example, we’ve used a Box container. A Box is just a Swing container that uses a BoxLayout, which we’ll discuss more in Chapter 19.

After construction, you can set a valid value using setValue() and retrieve the last valid value with getValue(). To do this, you’ll have to cast the value back to the correct type based on the format you are using. For example, this statement retrieves the date from our birthday field:

    Date bday = (Date)birthdayField.getValue();

JFormattedTextField validates its text when the user attempts to shift focus to a new field (either by clicking with the mouse outside of the field or using keyboard navigation). By default, JFormattedTextField handles invalid input by simply reverting to the last valid value. If you wish to allow invalid input to remain in the field for further editing, you can set the setFocusLostBehavior() method with the value JFormattedTextField.COMMIT (the default is COMMIT_OR_REVERT). In any case, invalid input does not change the value property retrieved by getValue().

Filtering Input

JFormattedTextField does not know about all format types itself; instead, it uses AbstractFormatter objects that know about particular format types. The AbstractFormatters, in turn, provide implementations of two interfaces: DocumentFilter and NavigationFilter. A DocumentFilter attaches to implementations of Document and allows you to intercept editing commands, modifying them as you wish. A NavigationFilter can be attached to JTextComponents to control the movement of the cursor (as in a mask-formatted field). You can implement your own AbstractFormatters for use with JFormattedTextField, and, more generally, you can use the DocumentFilter interface to control how documents are edited in any type of text component. For example, you could create a DocumentFilter that maps characters to uppercase or strange symbols. DocumentFilter provides a low-level, edit-by-edit means of controlling or mapping user input. We will show an example of this now. In the following section, we discuss how to implement higher-level field validation that ensures the correctness of data after it is entered, in the same way that the formatted text field did for us earlier.

DocumentFilter

The following example, DocFilter, applies a document filter to a JTextField. Our DocumentFilter simply maps any input to uppercase. Here is the code:

    import java.text.*;
    import javax.swing.*;
    import javax.swing.text.*;

    public class DocFilter
    {
       public static void main( String[] args ) throws Exception
       {
          JTextField field = new JTextField(30);

          ((AbstractDocument)(field.getDocument())).setDocumentFilter(
             new DocumentFilter()
          {
             public void insertString(
                FilterBypass fb, int offset, String string, AttributeSet attr)
                   throws BadLocationException
                {
                   fb.insertString( offset, string.toUpperCase(), attr );
                }

             public void replace(
                FilterBypass fb, int offset, int length, String string,
                AttributeSet attr) throws BadLocationException
                {
                   fb.replace( offset, length, string.toUpperCase(), attr );
                }
          } );

          JFrame frame = new JFrame("User Information");
          frame.add( field );
          frame.pack();
          frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          frame.setVisible(true);
       }
    }

The methods insertString() and replace() of the DocumentFilter are called when text is added to the document or modified. Within them, we have an opportunity to filter the text before passing it on. When we are ready to apply the text, we use the FilterBypass reference to pass it along. FilterBypass has the same set of methods, which apply the changes directly to the document. The DocumentFilter remove() method can also be used to intercept edits to the document that remove characters. One thing to note in our example is that not all Documents have a setDocumentFilter() method. Instead, we have to cast our document to an AbstractDocument. Only document implementations that extend AbstractDocument accept filters (unless you implement your own). This sad state of affairs is because the Document Filter API was added in Java 1.4, and it was decided that changes could not be made to the original Document interface.

Validating Data

Low-level input filtering prevents you from doing such things as entering a number where a character should be. In this section, we’re going to talk about high-level validation, which accounts for things like February having only 28 days or a credit card number being for a Visa or MasterCard. Whereas character filtering prevents you from entering incorrect data, field validation happens after data has been entered. Normally, validation occurs when the user tries to change focus and leave the field, either by clicking the mouse or through keyboard navigation. Java 1.4 added the InputVerifier API, which allows you to validate the contents of a component before focus is transferred. Although we are going to talk about this in the context of text fields, an InputVerifier can actually be attached to any JComponent to validate its state in this way.

The following example creates a pair of text fields. The first allows any value to be entered, while the second accepts only numbers between 0 and 100. When both fields are happy, you can freely move between them. However, when you enter an invalid value in the second field and try to leave, the program just beeps and selects the text. The focus remains trapped until you correct the problem.

    import javax.swing.*;

    public class Validator
    {
        public static void main( String[] args ) throws Exception {
            Box form = Box.createVerticalBox();
            form.add( new JLabel("Any Value") );
            form.add( new JTextField("5000") );

            form.add( new JLabel("Only 0-100") );
            JTextField rangeField = new JTextField("50");
            rangeField.setInputVerifier( new InputVerifier() {
                public boolean verify( JComponent comp ) {
                    JTextField field = (JTextField)comp;
                    boolean passed = false;
                    try {
                        int n = Integer.parseInt(field.getText());
                        passed = ( 0 <= n && n <= 100 );
                    } catch (NumberFormatException e) { }
                    if ( !passed ) {
                        comp.getToolkit().beep();
                        field.selectAll();
                    }
                    return passed;
                }
            } );
            form.add( rangeField );

            JFrame frame = new JFrame("User Information");
            frame.add(form);
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
        }
    }

We’ve created an anonymous inner class extending InputVerifier with this code. The API is very simple; at validation time, our verify() method is called, and we are passed a reference to the component needing checking. Here we cast to the correct type (we know what we are verifying, of course) and parse the number. If it is out of range, we beep and select the text. We then return true or false indicating whether the value passes validation.

You can use an InputVerifier in combination with a JFormattedTextField to both guide user input into the correct format and validate the semantics of what the user entered.

Say the Magic Word

Before we move on from our discussion of formatted text, we should mention that Swing includes a class just for typing passwords, called JPasswordField. A JPasswordField behaves just like a JTextField (it’s a subclass), except every character typed is echoed as the same, obfuscating character, typically an asterisk. Figure 18-2 shows the option dialog example that was presented in Chapter 17. The example includes a JTextField and a JPasswordField.

The creation and use of JPasswordField is basically the same as for JTextField. If you find asterisks distasteful, you can tell the JPasswordField to use a different character using the setEchoChar() method.

Normally, you would use getText() to retrieve the text typed into the JPasswordField. This method, however, is deprecated; you should use getPassword() instead. The getPassword() method returns a character array rather than a String object. This is done because character arrays are a little less vulnerable than Strings to discover by memory-snooping password sniffer programs and they can be erased directly and easily. If you’re not that concerned, you can simply create a new String from the character array. Note that methods in the Java cryptographic classes accept passwords as character arrays, not strings, so you can pass the results of a getPassword() call directly to methods in the cryptographic classes without ever creating a String.

Using a JPasswordField in a dialog

Figure 18-2. Using a JPasswordField in a dialog

Sharing a Data Model

Our next example shows how easy it is to make two or more text components share the same Document; Figure 18-3 shows what the application looks like.

Three views of the same data model

Figure 18-3. Three views of the same data model

Anything the user types into any text area is reflected in all of them. All we had to do is make all the text areas use the same data model, like this:

    JTextArea areaFiftyOne = new JTextArea();
    JTextArea areaFiftyTwo = new JTextArea();
    areaFiftyTwo.setDocument(areaFiftyOne.getDocument());
    JTextArea areaFiftyThree = new JTextArea();
    areaFiftyThree.setDocument(areaFiftyOne.getDocument());

We could just as easily make seven text areas sharing the same document—or seventy. While this example may not look very useful, keep in mind that you can scroll different text areas to different places in the same document. That’s one of the beauties of putting multiple views on the same data; you get to examine different parts of it. Another useful technique is viewing the same data in different ways. You could, for example, view some tabular numerical data as both a spreadsheet and a pie chart. The MVC architecture that Swing uses means that it’s possible to do this in an intelligent way so that if numbers in a spreadsheet are updated, a pie chart that uses the same data is automatically updated, too.

This example works because, behind the scenes, there are a lot of events flying around. When you type in one of the text areas, the text area receives the keyboard events. It calls methods in the document to update its data. In turn, the document sends events to the other text areas telling them about the updates so that they can correctly display the document’s new data. But don’t worry about any of this; you just tell the text areas to use the same data, and Swing takes care of the rest:

    //file: SharedModel.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class SharedModel {
        public static void main(String[] args) {
        JFrame frame = new JFrame("Shared Model");

        JTextArea areaFiftyOne = new JTextArea();
        JTextArea areaFiftyTwo = new JTextArea();
        areaFiftyTwo.setDocument(areaFiftyOne.getDocument());
        JTextArea areaFiftyThree = new JTextArea();
        areaFiftyThree.setDocument(areaFiftyOne.getDocument());

        frame.setLayout(new GridLayout(3, 1));
        frame.add(new JScrollPane(areaFiftyOne));
        frame.add(new JScrollPane(areaFiftyTwo));
        frame.add(new JScrollPane(areaFiftyThree));

        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(300, 300);
        frame.setVisible(true);
      }
    }

Setting up the display is simple. We use a GridLayout (discussed in the next chapter) and add three text areas to the layout. Then, all we have to do is tell the text areas to use the same Document.

HTML and RTF for Free

Most user interfaces will use only two subclasses of JTextComponent. These are the simple JTextField and JTextArea classes that we just covered. That’s just the tip of the iceberg, however. Swing offers sophisticated text capabilities through two other subclasses of JTextComponent: JEditorPane and JTextPane.

The first of these, JEditorPane, can display HTML and Rich Text Format (RTF) documents out of the box and provides a plug-in framework for support of other content types. It fires one more type of event, a HyperlinkEvent. Subtypes of this event are fired off when the mouse enters, exits, or clicks on a hyperlink. Combined with JEditorPane’s HTML display capabilities, it’s easy to build a simple browser. The following browser, as shown in Figure 18-4, has only about 70 lines of code.

    //file: CanisMinor.java
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.event.*;

    public class CanisMinor extends JFrame {
      protected JEditorPane mEditorPane;
      protected JTextField mURLField;

      public CanisMinor(String urlString) {
        super("CanisMinor v1.0");
        createGUI(urlString);
      }

      protected void createGUI( String urlString ) {
        setLayout(new BorderLayout());

        JToolBar urlToolBar = new JToolBar();
        mURLField = new JTextField(urlString, 40);
        urlToolBar.add(new JLabel("Location "));
        urlToolBar.add(mURLField);
        add(urlToolBar, BorderLayout.NORTH);
        mEditorPane = new JEditorPane();
        mEditorPane.setEditable(false);
        add(new JScrollPane(mEditorPane), BorderLayout.CENTER);

        openURL(urlString);

        mURLField.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            openURL(ae.getActionCommand());
          }
        });

        mEditorPane.addHyperlinkListener(new LinkActivator());

        setSize(500, 600);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      }

      protected void openURL(String urlString) {
        try {
          URL url = new URL(urlString);
          mEditorPane.setPage(url);
          mURLField.setText(url.toExternalForm());
        }
        catch (Exception e) {
          System.out.println("Couldn't open " + urlString + ":" + e);
        }
      }

      class LinkActivator implements HyperlinkListener {
        public void hyperlinkUpdate(HyperlinkEvent he) {
          HyperlinkEvent.EventType type = he.getEventType();
          if (type == HyperlinkEvent.EventType.ACTIVATED)
            openURL(he.getURL().toExternalForm());
        }
      }

      public static void main(String[] args) {
        String urlString = "http://en.wikinews.org/wiki/Special:Random";
        if (args.length > 0)
           urlString = args[0];
        new CanisMinor( urlString ).setVisible( true );
      }
    }
The CanisMinor application, a simple web browser

Figure 18-4. The CanisMinor application, a simple web browser

JEditorPane is the center of this little application. Passing a URL to setPage() causes the JEditorPane to load a new page, either from a local file or from somewhere across the Internet. To go to a new page, enter it in the text field at the top of the window and press Return. This fires an ActionEvent that sets the new page location of the JEditorPane. It can display RTF files, too (RTF is the text or nonbinary storage format for Microsoft Word documents).

Responding to hyperlinks correctly is simply a matter of responding to the HyperlinkEvents thrown by the JEditorPane. This behavior is encapsulated in the LinkActivator inner class. In this case, the only activity we are interested in is when the user “activates” the hyperlink by clicking on it. We respond by setting the location of the JEditorPane to the location given under the hyperlink. Surf away!

Behind the scenes, something called an EditorKit handles displaying documents for the JEditorPane. Different kinds of EditorKits can display different kinds of documents. For HTML, the HTMLEditorKit class (in the javax.swing.text.html package) handles the display. Currently, this class supports HTML 3.2. Sun says that future enhancements will move the HTMLEditorKit toward the HTML 4.0 standard, but even with Java 7 this area hasn’t seen much progress. The HTMLEditorKit handles other features of HTML, including HTML forms, in the expected way—automatically submitting results when a submit button is pushed. A FormSubmitEvent enables programmatic involvement in form submission.

If you browse around with this example browser, you will quickly find that most modern web pages can’t be rendered well by the current HTMLEditorKit. In their current state, JEditorPane and HTMLEditorKit are best suited for simple uses such as an HTML help system. There is an excellent commercial Java browser component from JadeLiquid called WebRenderer.

There’s another component here that we haven’t covered before—the JToolBar. This nifty container houses our URL text field. Initially, the JToolBar starts out at the top of the window. But you can pick it up by clicking on the little dotted box near its left edge, then drag it around to different parts of the window. You can place this toolbar at the top, left, right, or bottom of the window, or you can drag it outside the window entirely, where it will inhabit a window of its own. This behavior comes for free from the JToolBar class. We only had to create a JToolBar and add some components to it. The JToolBar is just a container, so we add it to the content pane of our window to give it an initial location.

Managing Text Yourself

Swing offers one last subclass of JTextComponent that can do just about anything you want: JTextPane. The basic text components, JTextField and JTextArea, are limited to a single font in a single style. But JTextPane, a subclass of JEditorPane, can display multiple fonts and multiple styles in the same component. It also includes support for highlighting, image embedding, and other advanced features.

We’ll take a peek at JTextPane by creating a text pane with some styled text. Remember, the text itself is stored in an underlying data model, the Document. To create styled text, we simply associate a set of text attributes with different parts of the document’s text. Swing includes classes and methods for manipulating sets of attributes, like specifying a bold font or a different color for the text. Attributes themselves are contained in a class called SimpleAttributeSet; these attribute sets are manipulated with static methods in the StyleConstants class. For example, to create a set of attributes that specifies the color red, you could do this:

    SimpleAttributeSet redstyle = new SimpleAttributeSet();
    StyleConstants.setForeground(redstyle, Color.red);

To add some red text to a document, you would just pass the text and the attributes to the document’s insertString() method, like this:

    document.insertString(6, "Some red text", redstyle);

The first argument to insertString() is an offset into the text. An exception is thrown if you pass in an offset that’s greater than the current length of the document. If you pass null for the attribute set, the text is added in the JTextPane’s default font and style.

Our simple example creates several attribute sets and uses them to add plain and styled text to a JTextPane, as shown in Figure 18-5:

    //file: Styling.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;

    public class Styling extends JFrame {
      private JTextPane textPane;

      public Styling() {
        super("Stylin' v1.0");
        setSize(300, 200);

        textPane = new JTextPane();
        textPane.setFont(new Font("Serif", Font.PLAIN, 24));

        // create some handy attribute sets
        SimpleAttributeSet red = new SimpleAttributeSet();
        StyleConstants.setForeground(red, Color.red);
        StyleConstants.setBold(red, true);
        SimpleAttributeSet blue = new SimpleAttributeSet();
        StyleConstants.setForeground(blue, Color.blue);
        SimpleAttributeSet italic = new SimpleAttributeSet();
        StyleConstants.setItalic(italic, true);
        StyleConstants.setForeground(italic, Color.orange);

        // add the text
        append("In a ", null);
        append("sky", blue);
        append(" full of people\nOnly some want to ", null);
        append("fly", italic);
        append("\nIsn't that ", null);
        append("crazy", red);
        append("?", null);

        add(new JScrollPane(textPane), BorderLayout.CENTER);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      }

      protected void append(String s, AttributeSet attributes) {
        Document d = textPane.getDocument();
        try { d.insertString(d.getLength(), s, attributes); }
        catch (BadLocationException ble) {}
      }

      public static void main(String[] args) {
        new Styling().setVisible(true);
      }
    }
Using styled text in a JTextPane

Figure 18-5. Using styled text in a JTextPane

This example creates a JTextPane, which is saved in a member variable. Three different attribute sets are created using combinations of text styles and foreground colors. Then, using a helper method called append(), text is added to the JTextPane.

The append() method tacks a text String on the end of the JTextPane’s document, using the supplied attributes. Remember that if the attributes are null, the text is displayed with the JTextPane’s default font and style.

You can go ahead and add your own text if you wish. If you place the caret inside one of the differently styled words and type, the new text comes out in the appropriate style. Pretty cool, eh? You’ll also notice that JTextPane gives us word-wrapping behavior for free. And because we’ve wrapped the JTextPane in a JScrollPane, we get scrolling for free, too. Swing allows you to do some really cool stuff without breaking a sweat. Just wait—there’s plenty more to come.

This simple example should give you some idea of what JTextPane can do. It’s reasonably easy to build a simple word processor with JTextPane, and complex commercial-grade word processors are definitely possible.

If JTextPane still isn’t good enough for you, or you need some finer control over character, word, and paragraph layout, you can actually draw text, carets, and highlight shapes yourself. A class in the 2D API called TextLayout simplifies much of this work, but it’s outside the scope of this book. For coverage of TextLayout and other advanced text drawing topics, see Java 2D Graphics by Jonathan Knudsen (O’Reilly).

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