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
      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 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


Tables present information in orderly rows and columns. This is useful for presenting financial figures or representing data from a relational database. Like trees, tables in Swing are incredibly powerful and customizable. If you go with the default options, they’re also pretty easy to use.

The JTable class represents a visual table component. A JTable is based on a TableModel, one of a dozen or so supporting interfaces and classes in the javax.swing.table package.

A First Stab: Freeloading

JTable has one constructor that creates a default table model for you from arrays of data. You just need to supply it with the names of your column headers and a 2D array of Objects representing the table’s data. The first index selects the table’s row; the second index selects the column. The following example shows how easy it is to get going with tables using this constructor:

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

    public class DullShipTable {
      public static void main(String[] args) {
        // create some tabular data
        String[] headings =
          new String[] {"Number", "Hot?", "Origin",
                        "Destination", "Ship Date", "Weight" };
        Object[][] data = new Object[][] {
          { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA",
              "02/06/2000", new Float(450) },
          { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ",
              "05/20/2000", new Float(1250) },
          { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX",
              "03/20/2000", new Float(1745) },
          { "101891", Boolean.FALSE, "Boston MA", "Albany NY",
              "04/04/2000", new Float(88) }

        // create the data model and the JTable
        JTable table = new JTable(data, headings);

        JFrame frame = new JFrame("DullShipTable v1.0");
        frame.add(new JScrollPane(table));

        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(500, 200);

This small application produces the display shown in Figure 18-7.

A rudimentary JTable

Figure 18-7. A rudimentary JTable

For very little typing, we’ve gotten some pretty impressive stuff. Here are a few things that come for free:

Column headings

The JTable has automatically formatted the column headings differently than the table cells. It’s clear that they are not part of the table’s data area.

Cell overflow

If a cell’s data is too long to fit in the cell, it is automatically truncated and shown with an ellipsis (...). This is shown in the Origin cell in the second row in Figure 18-7.

Row selection

You can click on any cell in the table to select its entire row. This behavior is controllable; you can select single cells, entire rows, entire columns, or some combination of these. To configure the JTable’s selection behavior, use the setCellSelectionEnabled(), setColumnSelectionAllowed(), and setRowSelectionAllowed() methods.

Cell editing

Double-clicking on a cell opens it for editing; you’ll get a little cursor in the cell. You can type directly into the cell to change the cell’s data.

Column sizing

If you position the mouse cursor between two column headings, you’ll get a little left-right arrow cursor. Click and drag to change the size of the column to the left. Depending on how the JTable is configured, the other columns may also change size. The resizing behavior is controlled with the setAutoResizeMode() method.

Column reordering

If you click and drag on a column heading, you can move the entire column to another part of the table.

Play with this for a while. It’s fun!

Round Two: Creating a Table Model

JTable is a very powerful component. You get a lot of very nice behavior for free. However, the default settings are not quite what we wanted for this simple example. In particular, we intended the table entries to be read-only; they should not be editable. Also, we’d like entries in the Hot? column to be checkboxes instead of words. Finally, it would be nice if the Weight column were formatted appropriately for numbers rather than for text.

To achieve more flexibility with JTable, we’ll write our own data model by implementing the TableModel interface. Fortunately, Swing makes this easy by supplying a class that does most of the work, AbstractTableModel. To create a table model, we’ll just subclass AbstractTableModel and override whatever behavior we want to change.

At a minimum, all AbstractTableModel subclasses have to define the following three methods:

public int getRowCount(), public int getColumnCount()

Returns the number of rows and columns in this data model

public Object getValueAt(int row , int column )

Returns the value for the given cell

When the JTable needs data values, it calls the getValueAt() method in the table model. To get an idea of the total size of the table, JTable calls the getRowCount() and getColumnCount() methods in the table model.

A very simple table model looks like this:

    public static class ShipTableModel extends AbstractTableModel {
      private Object[][] data = new Object[][] {
        { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA",
            "02/06/2000", new Float(450) },
        { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ",
            "05/20/2000", new Float(1250) },
        { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX",
            "03/20/2000", new Float(1745) },
        { "101891", Boolean.FALSE, "Boston MA", "Albany NY",
            "04/04/2000", new Float(88) }

      public int getRowCount() { return data.length; }
      public int getColumnCount() { return data[0].length; }

      public Object getValueAt(int row, int column) {
        return data[row][column];

We’d like to use the same column headings that we used in the previous example. The table model supplies these through a method called getColumnName(). We could add column headings to our simple table model like this:

    private String[] headings = new String[] {
      "Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight"

    public String getColumnName(int column) {
      return headings[column];

By default, AbstractTableModel makes all its cells noneditable, which is what we wanted. No changes need to be made for this.

The final modification is to have the Hot? column and the Weight column formatted specially. To do this, we give our table model some knowledge about the column types. JTable automatically generates checkbox cells for Boolean column types and specially formatted number cells for Number types. To give the table model some intelligence about its column types, we override the getColumnClass() method. The JTable calls this method to determine the data type of each column. It may then represent the data in a special way. This table model returns the class of the item in the first row of its data:

    public Class getColumnClass(int column) {
      return data[0][column].getClass();

That’s really all there is to do. The following complete example illustrates how you can use your own table model to create a JTable using the techniques just described:

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

    public class ShipTable {
      public static class ShipTableModel extends AbstractTableModel {
        private String[] headings = new String[] {
          "Number", "Hot?", "Origin", "Destination", "Ship Date", "Weight"
        private Object[][] data = new Object[][] {
          { "100420", Boolean.FALSE, "Des Moines IA", "Spokane WA",
              "02/06/2000", new Float(450) },
          { "202174", Boolean.TRUE, "Basking Ridge NJ", "Princeton NJ",
              "05/20/2000", new Float(1250) },
          { "450877", Boolean.TRUE, "St. Paul MN", "Austin TX",
              "03/20/2000", new Float(1745) },
          { "101891", Boolean.FALSE, "Boston MA", "Albany NY",
              "04/04/2000", new Float(88) }

        public int getRowCount() { return data.length; }
        public int getColumnCount() { return data[0].length; }

        public Object getValueAt(int row, int column) {
          return data[row][column];

        public String getColumnName(int column) {
          return headings[column];

        public Class getColumnClass(int column) {
          return data[0][column].getClass();

      public static void main(String[] args)
        // create the data model and the JTable
        TableModel model = new ShipTableModel();
        JTable table = new JTable(model);


        JFrame frame = new JFrame("ShipTable v1.0");
        frame.getContentPane().add(new JScrollPane(table));
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(500, 200);

The running application is shown in Figure 18-8.

Customizing a table

Figure 18-8. Customizing a table

Round Three: A Simple Spreadsheet

To illustrate just how powerful and flexible the separation of the data model from the GUI can be, we’ll show a more complex model. In the following example, we’ll implement a very slim but functional spreadsheet (see Figure 18-9) using almost no customization of the JTable. All of the data processing is in a TableModel called SpreadSheetModel.

A simple spreadsheet

Figure 18-9. A simple spreadsheet

Our spreadsheet does the expected stuff—allowing you to enter numbers or mathematical expressions such as (A1*B2)+C3 into each cell.[41] All cell editing and updating is driven by the standard JTable. We implement the methods necessary to set and retrieve cell data. Of course, we don’t do any real validation here, so it’s easy to break our table. (For example, there is no check for circular dependencies, which may be undesirable.)

As you will see, the bulk of the code in this example is in the inner class used to parse the value of the equations in the cells. If you don’t find this part interesting, you might want to skip ahead. But if you have never seen an example of this kind of parsing before, we think you will find it to be very cool. Through the magic of recursion and Java’s powerful String manipulation, it takes us only about 50 lines of code to implement a parser capable of handling basic arithmetic with arbitrarily nested parentheses.

Here’s the code:

    import java.util.StringTokenizer;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import java.awt.event.*;

    public class SpreadsheetModel extends AbstractTableModel {
      Expression [][] data;

      public SpreadsheetModel( int rows, int cols ) {
        data = new Expression [rows][cols];

      public void setValueAt(Object value, int row, int col) {
        data[row][col] = new Expression( (String)value );

      public Object getValueAt( int row, int col ) {
        if ( data[row][col] != null )
          try { return data[row][col].eval() + ""; }
          catch ( BadExpression e ) { return "Error"; }
        return "";
      public int getRowCount() { return data.length; }
      public int getColumnCount() { return data[0].length; }
      public boolean isCellEditable(int row, int col) { return true; }

      class Expression {
        String text;
        StringTokenizer tokens;
        String token;

        Expression( String text ) { this.text = text.trim(); }

        float eval() throws BadExpression {
          tokens = new StringTokenizer( text, " */+-()", true );
          try { return sum(); }
          catch ( Exception e ) { throw new BadExpression(); }

        private float sum() {
          float value = term();
          while( more() && match("+-") )
            if ( match("+") ) { consume(); value = value + term(); }
            else { consume(); value = value - term(); }
          return value;
        private float term() {
          float value = element();
          while( more() && match( "*/") )
            if ( match("*") ) { consume(); value = value * element(); }
            else { consume(); value = value / element(); }
          return value;
        private float element() {
          float value;
          if ( match( "(") ) { consume(); value = sum(); }
          else {
            String svalue;
            if ( Character.isLetter( token().charAt(0) ) ) {
            int col = findColumn( token().charAt(0) + "" );
            int row = Character.digit( token().charAt(1), 10 );
            svalue = (String)getValueAt( row, col );
          } else
            svalue = token();
            value = Float.parseFloat( svalue );
          consume(); // ")" or value token
          return value;
        private String token() {
          if ( token == null )
            while ( (token=tokens.nextToken()).equals(" ") );
          return token;
        private void consume() { token = null; }
        private boolean match( String s ) { return s.indexOf( token() )!=-1; }
        private boolean more() { return tokens.hasMoreTokens(); }

      class BadExpression extends Exception { }

      public static void main( String [] args ) {
        JFrame frame = new JFrame("Excelsior!");
        JTable table = new JTable( new SpreadsheetModel(15, 5) );
        table.setPreferredScrollableViewportSize( table.getPreferredSize() );
        frame.getContentPane().add( new JScrollPane( table ) );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

Our model extends AbstractTableModel and overrides just a few methods. As you can see, our data is stored in a 2D array of Expression objects. The setValueAt() method of our model creates Expression objects from the strings typed by the user and stores them in the array. The getValueAt() method returns a value for a cell by calling the expression’s eval() method. If the user enters some invalid text in a cell, a BadExpression exception is thrown, and the word error is placed in the cell as a value. The only other methods of TableModel we must override are getRowCount(), getColumnCount(), and isCellEditable() in order to determine the dimensions of the spreadsheet and to allow the user to edit the fields. That’s it! The helper method findColumn() is inherited from the AbstractTableModel.

Now on to the good stuff. We’ll employ our old friend StringTokenizer to read the expression string as separate values and the mathematical symbols (+-*/()) one by one. These tokens are then processed by the three parser methods: sum(), term(), and element(). The methods call one another generally from the top down, but it might be easier to read them in reverse to see what’s happening.

At the bottom level, element() reads individual numeric values or cell names (e.g., 5.0 or B2). Above that, the term() method operates on the values supplied by element() and applies any multiplication or division operations. And at the top, sum() operates on the values that are returned by term() and applies addition or subtraction to them. If the element() method encounters parentheses, it makes a call to sum() to handle the nested expression. Eventually, the nested sum returns (possibly after further recursion), and the parenthesized expression is reduced to a single value, which is returned by element(). The magic of recursion has untangled the nesting for us. The other small piece of magic here is in the ordering of the three parser methods. Having sum() call term() and term() call element() imposes the precedence of operators; that is, “atomic” values are parsed first (at the bottom), then multiplication, and finally, addition or subtraction.

The grammar parsing relies on four simple helper methods that make the code more manageable: token(), consume(), match(), and more(). token() calls the string tokenizer to get the next value, and match() compares it with a specified value. consume() is used to move to the next token, and more() indicates when the final token has been processed.

Sorting and Filtering

Java 6 introduced easy-to-use sorting and filtering for JTables. The following example demonstrates use of the default TableRowSorter and a simple regular expression filter.

    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.BorderLayout;
    import java.util.regex.PatternSyntaxException;
    public class SortFilterTable extends JFrame {
        private JTable table;
        private JTextField filterField;
        public SortFilterTable() {
            super("Table Sorting & Filtering");
            setSize(500, 200);
            setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            // Create a simple table model
            TableModel model = new AbstractTableModel() {
                private String[] columns = {"Name", "Pet", "Children"};
                private Object[][] people = {
                        {"Dan Leuck", "chameleon", 1},
                        {"Pat Niemeyer", "sugar glider", 2},
                        {"John Doe", "dog", 3},
                        {"Jane Doe", "panda", 2}
                public int getColumnCount() { return columns.length; }
                public int getRowCount() { return people.length; }
                public Object getValueAt(int row, int col) { 
                    return people[row][col]; 

                public Class getColumnClass(int col) {
                    return getValueAt(0, col).getClass();

            table = new JTable(model);
            // Create the filter area
            JPanel filterPanel = new JPanel(new BorderLayout());
            JLabel filterLabel = new JLabel("Filter ", 
            filterPanel.add(filterLabel, BorderLayout.WEST);
            filterField = new JTextField();
            // Apply the filter when the filter text field changes
                new DocumentListener() {
                    public void changedUpdate(DocumentEvent e) {
                    public void insertUpdate(DocumentEvent e) {
                    public void removeUpdate(DocumentEvent e) {
                2, 2, 2));
            add(filterPanel, BorderLayout.NORTH);
            add(new JScrollPane(table));
        // Filter on the first column
        private void filter() {
            RowFilter<TableModel, Object> filter = null;
            // Update if the filter expression is valid
            try {
                // Apply the regular expression to columns 0 and 1
                filter = RowFilter.regexFilter(filterField.getText(),
                    0, 1);
            } catch (PatternSyntaxException e) {
        public static void main(String[] args) {
            new SortFilterTable().setVisible(true);       

Try clicking on the column headers to sort. We are using the default sorting behavior, which utilizes the natural sort order of cell values (i.e., alphabetical for strings, value for numbers, etc.). You can easily override the sorting behavior by implementing your own comparator and setting it on the TableRowSorter:

    TableRowSorter<TableModel> reverseSorter 
        = new TableRowSorter<TableModel>(table.getModel()); 
    reverseSorter.setComparator(0, new Comparator<String>() {
        public int compare(String a, String b) {
            return -a.compareTo(b);

If you require more advanced sorting, you can subclass TableRowSorter or its superclass, DefaultRowSorter.

Entering text in the field above the table will apply a filter using the text as a regular expression over the values in the first two columns (indices 0 and 1). For example, try entering “Doe”. The table will now display only John Doe and Jane Doe.

Printing JTables

Swing makes the printing of JTables a snap. Think we’re kidding? If you accept the basic default behavior, all that is required to pop up a print dialog box is the following:


That’s it. The default behavior scales the printed table to the width of the page. This is called “fit width” mode. You can control that setting using the PrintMode enumeration of JTable, which has values of NORMAL and FIT_WIDTH:

    table.print( JTable.PrintMode.NORMAL );

The “normal” (ironically, nondefault) mode will allow the table to split across multiple pages horizontally to print without sizing down. In both cases, the table rows may span multiple pages vertically.

Other forms of the JTable print() method allow you to add header and footer text to the page and to take greater control of the printing process and attributes. We’ll talk a little more about printing when we cover 2D drawing in Chapter 20.

[41] You may need to double-click on a cell to edit it.

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