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


A component is the fundamental user interface object in Java. Everything you see on the display in a Java application is a component. This includes things like windows, panels, buttons, checkboxes, scrollbars, lists, menus, and text fields. To be used, a component usually must be placed in a container. Container objects group components, arrange them for display using a layout manager, and associate them with a particular display device. All Swing components are derived from the abstract javax.swing.JComponent class, as you saw in Figure 16-1. For example, the JButton class is a subclass of AbstractButton, which is itself a subclass of the JComponent class.

JComponent is the root of the Swing component hierarchy, but it descends from the AWT Container class. At this bottom level, Swing is based on AWT, so our conversation occasionally delves into the AWT package. Container’s superclass is Component, the root of all AWT components, and Component’s superclass is, finally, Object. Because JComponent inherits from Container, it has the capabilities of both a component and a container.

AWT and Swing, then, have parallel hierarchies. The root of AWT’s hierarchy is Component, while Swing’s components are based on JComponent. You’ll find similar classes in both hierarchies, such as Button and JButton, List, and JList. But Swing is much more than a replacement for AWT—it contains sophisticated components as well as a real implementation of the Model-View-Controller (MVC) paradigm, which we’ll discuss later.

For the sake of simplicity, we can split the functionality of the JComponent class into two categories: appearance and behavior. The JComponent class contains methods and variables that control an object’s general appearance. This includes basic attributes, such as its visibility, its current size and location, and certain common graphical defaults, such as font and background color, used by different subclasses in different ways. The JComponent class also contains graphics and event-handling methods, which are overridden by subclasses to produce all of the different kinds of widgets that we will see.

When a component is first displayed, it’s associated with a particular display device. The JComponent class encapsulates access to its display area on that device. It includes tools for rendering graphics, for working with off-screen resources, and for receiving user input. Under the covers, JComponent makes heavy use of the Java 2D API to handle things like font smoothing, rendering optimizations, and rendering hints. With recent versions of Java (6 and later), rendering speed and quality are often indistinguishable from native applications on popular operating systems.

When we talk about a component’s behavior, we mean the way it responds to user-driven events. When the user performs an action (such as pressing the mouse button) within a component’s display area, a Swing thread delivers an event object that describes what happened. The event is delivered to objects that have registered themselves as listeners for that type of event from that component. For example, when the user clicks on a button, the button generates an ActionEvent object. To receive those events, an object registers with the button as an ActionListener.

Events are delivered by invoking designated event handler methods within the receiving object (the “listener”). A listener object receives specific types of events through methods of its listener interfaces (for example, through the actionPerformed() method of the ActionListener interface) for the types of events in which it is interested. Specific types of events cover different categories of component user interaction. For example, MouseEvents describe activities of the mouse within a component’s area, KeyEvents describe keypresses, and higher-level events (such as ActionEvents) indicate that a user interface component has done its job.

We will describe events thoroughly in this chapter because they are so fundamental to the way in which user interfaces function in Java. But they aren’t limited to building user interfaces; they are an important interobject communications mechanism, which may be used by completely nongraphical parts of an application, as well. They are particularly important in the context of JavaBeans, which uses events as a generalized change-notification mechanism.

Swing’s event architecture is very flexible. Instead of requiring every component to listen for and handle events for its own bit of the user interface, an application may register arbitrary event “handler” objects to receive the events for one or more components and “glue” those events to the correct application logic. A container might, for example, process some of the events relating to its child components.

In the graphical realm, the primary responsibility of a container is to lay out the components it contains visually, within its borders. A component informs its container when it does something that might affect other components in the container, such as changing its size or visibility. The container then tells its layout manager that it is time to rearrange the child components.

As we mentioned, Swing components are all fundamentally derived from Container. This doesn’t mean that all Swing components can meaningfully contain arbitrary GUI elements within themselves. It does mean that the container-component relationship is built in at a low level. Containers can manage and arrange JComponent objects without knowing what they are or what they are doing. Components can be swapped and replaced with new versions easily and combined into composite user interface objects that can be treated as individual components themselves. This lends itself well to building larger, reusable user interface items.

Peers and Look-and-Feel

Swing components are sometimes referred to as peerless, or lightweight. These terms refer to the relationship that AWT has (and Swing does not have, respectively) with the native toolkits for rendering components on each platform. To get native components on the screen, AWT utilizes a set of peer objects that bridge the gap from pure Java to the host operating system.

At some level, of course, all our components have to talk to objects that contain native methods to interact with the host operating environment; the difference is at what level this occurs. AWT uses a set of peer interfaces. The peer interface makes it possible for a pure Java-language graphic component to use a corresponding real component—the peer object—in the native environment. With AWT, you don’t generally deal directly with peer interfaces or the objects behind them; peer handling is encapsulated within the Component class.

AWT relies heavily on peers. For example, if you create a window and add eight buttons to it, AWT creates nine peers for you—one for the window and one for each of the buttons. As an application programmer, you don’t have to worry about the peers, but they are always lurking under the surface, doing the real work of interacting with the operating system’s windowing toolkit.

In Swing, by contrast, most components are peerless, or lightweight. This means that Swing components don’t have any direct interaction with the underlying windowing system. They draw themselves in their parent container and respond to user events in pure Java, with no native code involved. In Swing, only the top-level (lowest API level) windows interact with the windowing system. These Swing containers descend from AWT counterparts, and, thus, still have peers. In Swing, if you create a window and add eight buttons to it, only one peer is created—for the window. Because it has fewer interactions with the underlying windowing system than AWT, Swing is less vulnerable to the peculiarities of any particular platform.

With lightweight components, it is easy to change their appearance. Because each component draws itself instead of relying on a peer, it can decide at runtime how to render itself. Accordingly, Swing supports different look-and-feel schemes, which can be changed at runtime. (A look-and-feel is the collected appearance of components in an application.) Look-and-feels based on Windows, Macintosh, and Motif are available (though licensing issues may encumber their use on various platforms), as well as several entirely original Java creations, including Metal, Synth and Nimbus. Metal is the default cross-platform look-and-feel. It has a flat minimalist aesthetic and is very functional but, at this point, appears dated when compared to current versions of popular desktop environments. Synth makes Java applications “skinnable” at a high level using an XML descriptor file and images as resources. Java SE 6 update 10 introduced Nimbus, the first Java look-and-feel that is aesthetically on par with modern desktop operating systems such as OS X and Windows. Nimbus is vector-based, which allows components to be smoothly scaled for use on the new generation of high-density displays. If you want a consistent cross-platform look-and-feel, Nimbus is the best option.

The MVC Framework

Before continuing our discussion of GUI concepts, we want to make a brief aside and talk about the MVC framework. As we’ve discussed, MVC is a method of building reusable components that logically separates the structure, presentation, and behavior of a component into separate pieces. MVC is primarily concerned with building user interface components, but the basic ideas can be applied to many design issues; its principles can be seen throughout Java.

The fundamental idea behind MVC is the separation of the data model for an item from its presentation. For example, we can draw different representations of the data in a spreadsheet (e.g., bar graphs, pie charts). The data is the model; the particular representation is the view. A single model can have many views that present the data differently. A user interface component’s controller defines and governs its behavior. Typically, this includes changes to the model, which, in turn, cause the view(s) to change. For a checkbox component, the data model could be a single Boolean variable, indicating whether it’s checked or not. The behavior for handling mouse-click events would alter the model, and the view would examine that data when it draws the on-screen representation.

The way in which Swing objects communicate, by passing events from sources to listeners, is part of this MVC concept of separation. Event listeners are “observers” (controllers) and event sources are “observables” (models).[38] When an observable changes or performs a function, it notifies all its observers of the activity.

Swing components explicitly support MVC. Each component is actually composed of two pieces. One piece, called the UI-delegate, is responsible for the “view” and “controller” roles. It takes care of drawing the component and responding to user events. The second piece is the data model itself. This separation makes it possible for multiple Swing components to share a single data model. For example, a read-only text box and a drop-down list box could use the same list of strings as a data model.


In an event-driven environment such as Swing, components can be asked to draw themselves at any time. In a more procedural programming environment, you might expect a component to be involved in drawing only when first created or when it changes its appearance. In Java, however, components act in a way that is closely tied to the underlying behavior of the display environment. For example, when you obscure a component with another window and then reexpose it, a Swing thread may ask the component to redraw itself.

Swing asks a component to draw itself by calling its paint() method. paint() may be called at any time, but in practice, it’s called when the object is first made visible, whenever it changes its appearance, or whenever some tragedy in the display system messes up its area. Because paint() can’t generally make any assumptions about why it was called, it must redraw the component’s entire display. The system may limit the drawing if only part of the component needs to be redrawn, but you don’t have to worry about this. Swing is fairly smart and will do everything it can to avoid asking components to redraw themselves (including using “backing store” where applicable).

A component never calls its paint() method directly. Instead, if a component requires redrawing, it requests a call to paint() by invoking repaint(). The repaint() method asks Swing to schedule the component for repainting. At some point after that, a call to paint() occurs. Swing is allowed to manage these requests in whatever way is most efficient. If there are too many requests to handle, or if there are multiple requests for the same component, the thread can collapse a number of repaint requests into a single call to paint(). This means that you don’t normally know exactly when paint() is called in response to a repaint(); all you can expect is that it happens at least once, after you request it.

Calling repaint() is normally an implicit request to be updated as soon as possible. Another form of repaint() allows you to specify a time period within which you would like an update, giving the system more flexibility in scheduling the request. The system tries to repaint the component within the time you specify, but if you happen to make more than one repaint request within that time period, the system may simply condense them to carry out a single update within the time you specified. An application performing simple animation could use this method to govern its refresh rate (by specifying a period that is the inverse of the desired frame rate).

As we’ve mentioned, Swing components can act as containers holding other components. Because every Swing component does its own drawing, Swing components are responsible for telling any contained components to draw themselves. Fortunately, this is all taken care of for you by a component’s default paint() method. If you override this method, however, you have to make sure to call the superclass’s implementation like this:

    public void paint(Graphics g) {

There’s a cleaner way around this problem. All Swing components have a method called paintComponent(). While paint() is responsible for drawing the component as well as its contained components, paintComponent()’s sole responsibility is drawing the component itself. If you override paintComponent() instead of paint(), you won’t have to worry about drawing contained components.

Both paint() and paintComponent() receive a single argument: a Graphics object. The Graphics object represents the component’s graphics context. It corresponds to the area of the screen on which the component can draw and provides the methods for performing primitive drawing and image manipulation. (We’ll look at the Graphics class in detail in Chapter 18.)

Enabling and Disabling Components

Standard Swing components can be turned on and off by calling the setEnabled() method. When a component such as a JButton or JTextField is disabled, it becomes “ghosted” or “greyed out” and doesn’t respond to user input.

For example, let’s see how to create a component that can be used only once. This requires getting ahead of the story; we won’t explain some aspects of this example until later. Earlier, we said that a JButton generates an ActionEvent when it is pressed. This event is delivered to the listeners’ actionPerformed() method. The following code disables the component that generated the event:

    public boolean void actionPerformed(ActionEvent e ) {

This code calls getSource() to find out which component generated the event. We cast the result to JComponent because we don’t necessarily know what kind of component we’re dealing with; it might not be a button, because other kinds of components can generate action events. Once we know which component generated the event, we disable it.

You can also disable an entire container. Disabling a JPanel, for instance, disables all the components it contains.

Focus, Please

In order to receive keyboard events, a component has to have keyboard focus. The component with the focus is the currently selected component on the screen and is usually highlighted visually. It receives all keyboard event information until the focus changes to a new component. Typically, a component receives focus when the user clicks on it with the mouse or navigates to it using the keyboard. A component can ask for focus with the JComponent ’s requestFocus() method. You can configure whether a given component is eligible to receive focus with the setFocusable() method. By default, most components, including things such as buttons and checkboxes, are “focusable.” To make an entire window and its components nonfocusable, use the Window setFocusableWindowState() method.

The control of focus is often at the heart of the user’s experience with an application. Especially with text entry fields and forms, users are accustomed to a smooth transfer of focus with the use of keyboard navigation cues (e.g., Tab and Shift-Tab for forward and backward field navigation). The management of focus in a large GUI with many components could be complex. Fortunately, in Java 1.4 and later, Swing handles almost all this behavior for you, so, in general, you don’t have to implement code to specify how focus is transferred. Java 1.4 introduced an entirely new focus subsystem. The flexible KeyboardFocusManager API provides the expected common behavior by default and allows customization via FocusTraversalPolicy objects. We’ll discuss focus-related events later in this chapter and focus navigation more in Chapter 18.

Other Component Methods

The JComponent class is very large; it has to provide the base-level functionality for all the various kinds of Java GUI objects. It inherits a lot of functionality from its parent Container and Component classes. We don’t have room to document every method of the JComponent class here, but we’ll flesh out our discussion by covering some of the more important ones:

Container getParent()
String getName()
void setName(String name)

Get or assign the String name of this component. Naming a component is useful for debugging. The name is returned by toString().

void setVisible(boolean visible)

Make the component visible or invisible within its container. If you change the component’s visibility, the container’s layout manager automatically lays out its visible components.

Color getForeground()
void setForeground(Color c)
void setBackground(Color c)
Color getBackground()

Get and set the foreground and background colors for this component. The foreground color of any component is the default color used for drawing. For example, it is the color used for text in a text field as well as the default drawing color for the Graphics object passed to the component’s paint() and paintComponent() methods. The background color is used to fill the component’s area when it is cleared by the default implementation of update().

Dimension getSize()
void setSize(int width, int height)

Get and set the current size of the component. Note that a layout manager may change the size of a component even after you’ve set its size yourself. To change the size a component “wants” to be, use setPreferredSize(). There are other methods in JComponent to set its location, but this is normally the job of a layout manager.

Dimension getPreferredSize()
void setPreferredSize(Dimension preferredSize)

Use these methods to examine or set the preferred size of a component. Layout managers attempt to set components to their preferred sizes. If you change a component’s preferred size, you must call the method revalidate() on the component to get it laid out again.

Cursor getCursor()
void setCursor(Cursor cursor)

Get or set the type of cursor (mouse pointer) used when the mouse is over this component’s area. For example:

    JComponent myComponent = ...;
    Cursor crossHairs =
        Cursor.getPredefinedCursor( Cursor.CROSSHAIR_CURSOR );
    myComponent.setCursor( crossHairs );


A container is a kind of component that holds and manages other components. Three of the most useful general container types are JFrame, JPanel, and JApplet. A JFrame is a top-level window on your display. JFrame is derived from java.awt.Window, which is pretty much the same but lacks a border (JWindow is the swing version of Window). A JPanel is a generic container element that groups components inside JFrames and other JPanels. The JApplet class is a kind of container that provides the foundation for applets that run inside web browsers. Like other containers, a JApplet can hold other user-interface components. You can also use the JComponent class directly, like a JPanel, to hold components inside another container. With the exception of JFrame, JWindow, JApplet, and JDialog (another window-like container), which are derived from AWT components, all the components and containers in Swing are lightweight.

A container maintains the list of “child” components it manages and has methods for dealing with those components. Note that this child relationship refers to a visual hierarchy, not a subclass/superclass hierarchy. By themselves, most components aren’t very useful until they are added to a container and displayed. The add() method of the Container class adds a component to the container. Thereafter, this component can be displayed in the container’s display area and positioned by its layout manager. You can remove a component from a container with the remove() method.

Layout Managers

A layout manager is an object that controls the placement and sizing of components within the display area of a container. A layout manager is like a window manager in a display system; it controls where the components go and how big they are. Every container has a default layout manager, but you can install a new one by calling the container’s setLayout() method.

Swing comes with a few layout managers that implement common layout schemes. The default layout manager for a JPanel is a FlowLayout, which tries to place objects at their preferred size from left to right and top to bottom in the container. The default for a JFrame is a BorderLayout, which places objects at specific locations within the window, such as NORTH, SOUTH, and CENTER. Another layout manager, GridLayout, arranges components in a rectangular grid. The most general (and difficult to use) layout manager is GridBagLayout, which lets you do the kinds of things you can do with HTML tables. (We’ll get into the details of all these layout managers in Chapter 19.)

When you add a component to a container using a simple layout manager, you’ll often use the version of add() that takes a single Component as an argument. However, if you’re using a layout manager that uses “constraints,” such as BorderLayout or GridBagLayout, you must specify additional information about where to put the new component. For that, you can use the version that takes a constraint object. Here’s how to place a component at the top edge of a container that uses a BorderLayout manager:

    myContainer.add(myComponent, BorderLayout.NORTH);

In this case, the constraint object is the static member variable NORTH. GridBagLayout uses a much more complex constraint object to specify positioning.


Insets specify a container’s margins; the space specified by the container’s insets won’t be used by a layout manager. Insets are described by an Insets object, which has four public int fields: top, bottom, left, and right. You normally don’t need to worry about the insets; the container sets them automatically, taking into account extras like the menu bar that may appear at the top of a frame. To find the insets, call the component’s getInsets() method, which returns an Insets object.

Z-Ordering (Stacking Components)

With the standard layout managers, components are not allowed to overlap. However, if you use custom-built layout managers or absolute positioning, components within a container may overlap. If they do, the order in which components were added to a container matters. When components overlap, they are “stacked” in the order in which they were added: the first component added to the container is on top, and the last is on the bottom. To give you more control over stacking, two additional forms of the add() method take an extra integer argument that lets you specify the component’s exact position in the container’s stacking order. Again, you don’t normally need to think about this, but it’s nice to know for the sake of completeness that it’s there.

The revalidate() and doLayout() Methods

A layout manager arranges the components in a container only when it is asked to do so. Several things can mess up a container after it’s initially laid out:

  • Changing its size

  • Resizing or moving one of its child components

  • Adding, showing, removing, or hiding a child component

Any of these actions cause the container to be marked invalid. This means that it needs to have its child components readjusted by its layout manager. In most cases, Swing readjusts the layout automatically. All components, not just containers, maintain a notion of when they are valid or invalid. If the size, location, or internal layout of a Swing component changes, its revalidate() method is automatically called. Internally, the revalidate() method first calls the method invalidate() to mark the component and all its enclosing containers as invalid. It then validates the tree. Validation descends the hierarchy, starting at the nearest validation root container, recursively validating each child. Validating a child Container means invoking its doLayout() method, which asks the layout manager to do its job and then notes that the Container has been reorganized by setting its state to valid again. A validation root is a container that can accommodate children of any size such as JScrollPane (and, hence, can accommodate any possible changes in its child hierarchy without upsetting its own parents).

There are a few cases in which you may need to tell Swing to fix things manually. One example is when you change the preferred size of a component (as opposed to its actual onscreen size). To clean up the layout, call the revalidate() method. For example, if you have a small JPanel—say, a keypad holding some buttons—and you change the preferred size of the JPanel by calling its setPreferredSize() method, you should also call revalidate() on the panel or its immediate container. The layout manager of the panel then rearranges its buttons to fit inside its new area.

Managing Components

There are a few additional tools of the Container class we should mention:

Component[] getComponents()

Returns the container’s components in an array.

void list(PrintWriter out, int indent)

Generates a list of the components in this container and writes them to the specified PrintWriter.

Component getComponentAt(int x, int y)

Tells you what component is at the specified coordinates in the container’s coordinate system.

Listening for Components

You can use the ContainerListener interface to automate setting up a container’s new components. A container that implements this interface can receive an event whenever it gains or loses a component. This facility makes it easy for a container to micromanage its components.

Windows, Frames and Splash Screens

Windows and frames are the top-level containers for Java components. A JWindow is simply a plain, graphical screen that displays in your windowing system. Windows have no frills; they are mainly suitable for pop-up windows and in situations where drop-down components such as menus and combo boxes extend outside their parent frame. JFrame, on the other hand, is a subclass of JWindow that has a titlebar, window-managed buttons (close, minimize, etc.), and border. You can drag a frame around on the screen and resize it, using the ordinary controls for your windowing environment. Figure 16-2 shows a JFrame on the left and a JWindow on the right.

All other Swing components and containers must be held, at some level, inside a JWindow or JFrame. Applets are a kind of Container. Even applets must be housed in a frame or window, though normally you don’t see an applet’s parent frame because it is part of (or simply is) the browser or appletviewer displaying the applet.

A frame and a window

Figure 16-2. A frame and a window

JFrames and JWindows are the only components that can be displayed without being added or attached to another Container. After creating a JFrame or JWindow, you can call the setVisible() method to display it. The following short application creates a JFrame and a JWindow and displays them side by side, just as in Figure 16-2.

    import javax.swing.*;

    public class TopLevelWindows {
      public static void main(String[] args) {
        JFrame frame = new JFrame("The Frame");
        frame.setSize(300, 300);
        frame.setLocation(100, 100);

        JWindow window = new JWindow();
        window.setSize(300, 300);
        window.setLocation(500, 100);


The JFrame constructor can take a String argument that supplies a title, displayed in the JFrame’s titlebar. (Or you can create the JFrame with no title and call setTitle() to supply the title later.) The JFrame’s size and location on your desktop are determined by the calls to setSize() and setLocation(). After creating the JFrame, we create a JWindow in almost exactly the same way. The JWindow doesn’t have a titlebar, so there are no arguments to the JWindow constructor.

Once the JFrame and JWindow are set up, we call setVisible(true) to get them on the screen. The setVisible() method returns immediately, without blocking. Fortunately, our application does not exit, even though we’ve reached the end of the main() method, because the windows are still visible. You can close the JFrame by clicking on the close button in the titlebar. JFrame’s default behavior is to hide itself when you click on the box by calling setVisible(false). You can alter this behavior by calling the setDefaultCloseOperation() method or by adding an event listener, which we’ll cover later. Because we haven’t arranged any other means here, you will need to hit Ctrl-C or whatever keystroke kills a process on your machine in order to stop execution of the TopLevelWindows application.

Use of a SplashScreen, which is an AWT class used to control a specialized container, is the preferred way to display a start-up screen for Swing applications. Prior to Java 1.6, applications were forced to use Window or JWindow for this purpose, but these are suboptimal solutions for a splash screen because they are only displayed after the JVM, AWT, and Swing libraries are initialized. The new splash screen object allows you to specify an image file in your application jar’s manifest (see Chapter 3) that will be displayed immediately after launch without having to wait for the JVM to initialize. Specifying a splash screen image in your jar manifest is trivial.

Manifest-Version: 1.0
Main-Class: MangoMango1
SplashScreen-Image: ripe_mango.png

No code is required to display a splash screen. The ripe_mango.png image will appear centered on the screen until the first AWT or Swing window is shown by the MangoMango1 application. Supported image types are GIF, JPEG, and PNG.

Other Methods for Controlling Frames

The setLocation() method of the Component class can be used on a JFrame or JWindow to set its position on the screen. The x and y coordinates are relative to the screen’s origin (the top-left corner).

You can use the toFront() and toBack() methods to place a JFrame or JWindow in front of, or behind, other windows. By default, a user is allowed to resize a JFrame, but you can prevent resizing by calling setResizable(false) before showing the JFrame.

On most systems, frames can be “iconified”—that is, they can be shrunk down and represented by a little icon image. You can get and set a frame’s icon image by calling getIconImage() and setIconImage(). As you can with all components, you can set the cursor by calling the setCursor() method.

Content Panes

Windows and frames have a little more structure than simple containers. Specifically, to support some of the fancier GUI features that require overlaying graphics (such as pop ups and menus), windows and frames actually consist of a number of separate overlapping container “panes” (as in glass) with names such as the root pane, layered pane, and glass pane. The primary pane of interest is usually the content pane. The content pane is just a Container that covers the visible area of the JFrame or JWindow; it is the container to which we want to add child components.

For convenience, JFrame and JWindow delegate methods such as add() and setLayout() to their ContentPane. In other words, calling myFrame.add(component) is equivalent to calling myFrame.getContentPane().add(component).

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

    public class MangoMango1 {
      public static void main(String[] args) {
        JFrame frame = new JFrame("The Frame");
     // The three methods below are delegated to the frame's ContentPane.
        frame.setLayout(new FlowLayout());
        frame.add(new JLabel("Mango"));
        frame.add(new JButton("Mango"));

        frame.setLocation(100, 100);

The call to JFrame’s pack() method tells the frame window to resize itself to the minimum size required to hold all its components. Instead of having to determine the size of the JFrame, pack tells it to be “just big enough.” If you do want to set the absolute size of the JFrame yourself, call setSize() instead.

We’ll cover labels and buttons in Chapter 17 and layouts in Chapter 19.

Desktop Integration

One of the focuses of Java 6 was improving desktop integration so that Swing apps can stand toe-to-toe with native apps. The new desktop features provide access to the system tray, browser, email client and file/application associations.

The Desktop class in java.awt provides the ability to:

  • Navigate to a URI with the default browser

  • Launch the default mail client and populate the “To:” field

  • Open, edit, or print a file utilizing its associated application

The Desktop class has a very simple API. The following example opens the default browser and navigates to the Duke Lemur Center’s home page.

    import java.awt.*;

    public class DisplayLemur {
        public static void main(String[] args) {
            URI uri = null;
            try {
                uri = new URI("");
            } catch(IOException ioe) {
                System.out.println("Cannot browse to " + uri);
            } catch(URISyntaxException use) {
                System.out.println("The URI " + uri + " is malformed");

All the aforementioned desktop features are similarly available as single method calls on the Desktop singleton: open(File file), edit(File file), print(File file), and mail(URI mailtoURI).

The SystemTray class, also found in java.awt, provides access to the area of the desktop that allows menu items to perform actions on currently running programs. On Windows, this is the Taskbar Status Area. On OS X, it’s the Menu Extras area on the right of the system menu. On GNOME, it’s the Notification Area.

The following example creates a TrayIcon, places it in the SystemTray, and attaches a single menu item. Selecting the menu item will cause a greeting dialog to appear.

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

    public class AlohaTray {
        public static void main(String[] args) throws AWTException {
            MenuItem greetItem = new MenuItem("Greet me");
            // Listen for a menu selection and display a greeting dialog
            greetItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null, "Aloha!");
            // Create the TrayIcon's PopupMenu and add the MenuItem
            PopupMenu popup = new PopupMenu();
            // Create the TrayIcon and add it to the SystemTray
            TrayIcon trayIcon = new TrayIcon(getIconImage(), 
                "A friendly greeting", popup);
        // Grabbing a default Swing icon for the SystemTray
        private static Image getIconImage() {
            Icon icon = UIManager.getIcon("OptionPane.informationIcon");
            BufferedImage image = new BufferedImage(icon.getIconWidth(), 
                icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
            icon.paintIcon(null, image.getGraphics(), 0, 0);
            return image;        

[38] In Chapter 11, we described the Observer class and Observable interface of the java.util package. Swing doesn’t use these classes directly, but it does use exactly the same design pattern for handling event sources and listeners.

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