Why does JFC, and more specifically Swing, overshadow all other Java APIs? Because 99.9 percent of modern applications require rich GUI front ends. Whatever application domain you specialize in, we all need to clothe our applications in modern graphical user interfaces. This GUI facade doesn't only make or break modern applications, it also severely impacts your software development efforts. Huge chunks of your (and my) code are there purely and simply for the sake of user friendliness, and have nothing to do with core product functionality. GUIs are really the software equivalent of automatic transmissions, vanity mirrors, central locking, and adjustable seats in cars. That is, the essential non-essentials without which you don't sell products.

GUI capability was the sole reason for the often-criticized AWT's original raison d'etre. Unfortunately, AWT's multitude of flaws and imperfections have led many to feel that Java's original GUI capability is just another Java Achilles heel (performance being the first). Thankfully, JavaSoft seems quite adept at quickly and skillfully addressing Java aspects that fall below expectations (possibly excluding politically too-hot-to-handle issues like its unpopular Collections API), so we now have Java Foundation Classes (JFC) to relegate AWT to the history books.

If you're a regular visitor to Sun's Java Developer Connection (JDC) discussion groups, you know that the volume of GUI questions is at least an order of magnitude greater than for some other "hot" Java APIs. In light of this, I decided it was time JavaWorld took a closer look at books that aim to flatten the JFC/Swing learning curve, and bulldoze AWT from the Java map in the process. This month I'm reviewing four quick-off-the-mark JFC books (and, as always, taking my dope-test kit along.)

At the time of writing, four books were available that include the words Java Foundation Classes, JFC, or Swing in their titles:

Here's a bird's-eye view of each title's main attributes. The table orders the books by price.

Up to Speed with Swing (Manning)

JFC: Java Foundation Classes (IDG Books)

Java Foundation Classes (McGraw-Hill)

Programming with JFC (John Wiley)

Price (US$)

2.95

9.99

9.95

9.99

Pages, chapters (appendices)

498, 13 (4)

541, 11 (3)

1040, 13 (0)

560, 19 (2)

Index

Average

Good

Good

Average

Glossary

No

No

No

No

CD-ROM

No

Yes

Yes

Yes

Authors

1

2

1

2

Listings density (lines/page)

48

44

54

45

MVC framework

Yes

Yes

No

No

Pluggable look-and-feel framework

Yes

No

Yes

Yes

Document framework

Yes

No

Yes

Yes

Undo/redo framework

No

Yes

No

Yes

Drag-and-drop framework

No

Yes

Yes

No

Printing framework

No

Yes

Yes (*)

No

Accessibility framework

No

Yes

Yes

Yes (*)

Java2D

No

Yes (*)

Yes

No

No. of "real-life" examples

None

4

4

2

Overall score

7

7

6

7

*Strictly speaking, yes, but only touched upon.

In the absence of tools to calculate the true cost-per-bit equivalent of a book, the Listings density row gives you an idea of how dense or "aerated" the source listings are. Low lines and/or page values usually mean unreadable listings and a high page-fill factor, so the higher this value, the better (up to some limit determined by your own eyesight, of course).

The Pluggable look-and-feel framework row indicates whether or not the text explains and demonstrates Swing's pluggable look and feel (PLAF).

The Document framework row indicates whether or not the text attacks the nontrivial subject of Swing's Text Document framework (that is, package com.sun.java.swing.text and its subpackages).

The Accessibility framework row indicates whether or not the text explains Swing's accessibility support for people with disabilities.

The Drag-and-drop framework row indicates whether or not the text discusses JFC's drag-and-drop support, as provided by the classes and interfaces in the java.awt.dnd package.

The Undo/redo framework row indicates whether or not the text discusses JFC's undo/redo support as provided by the classes and interfaces in the com.sun.java.swing.undo package.

The Java2D row indicates whether or not the text explores JFC's Java2D API. Most texts don't, since Java2D is most definitely a subject worthy of its own book(s). Any JFC books reviewed here that do write about Java2D do so only superficially.

The No. of "real-life" examples row indicates how many mini-projects are presented that begin to approach a real-life project.

Up to Speed with Swing: User Interfaces with Java Foundation Classes by Steven Gutz (Manning)

While the first part of this book's title is spot-on accurate, the second part isn't. Up to Speed with Swing is all about Swing's GUI component classes, and very little, if at all, about any of the other JFC APIs (see comparative table). Despite this little titling error (which publishers seem to make more and more often, and which always seems to broaden the scope of a book), the book's content does deliver on its title's core promise.

The book is subdivided into three parts: Part I, "Getting started;" Part II, "Swing components;" and Part III, "Advanced topics." Chapter 1, "A Java refresher," is really an AWT (and not Java) refresher that concentrates on event handling and layout managers, two aspects that have remained unchanged from AWT to Swing. Chapter 2, "Swing basics," therefore, is the beginning of the real meat on this particular bone. After an overview of the Swing packages, the author delves into the Model-View-Controller (MVC) design pattern, the architectural foundation for everything Swing -- especially its pluggable look and feel, custom rendering, and custom model capabilities. The chapter closes with a thorough "open-top bus tour" of class JComponent, the abstract grandaddy of all Swing GUI components.

Chapter 3, "Panels and panes," is the first in a list of chapters discussing Swing classes by logical grouping and steadily-increasing complexity. The remaining chapters in the list (4 through 11) include "Labels and buttons," "Text Management," "Progress bars, scroll bars, and sliders," "Menus and toolbars," "Dialogs and internal frames," "List boxes," "Trees," and "Tables." Together, these chapters form Part II, which is also the heart of the book (340 pages out of 500), and hence, the basis on which to judge the book as a whole.

For each class discussed in the text, the author provides an introduction, one or more examples on how to use the class, and reference-style information (a discussion of any class variables, constructors, and the most important class methods). This reference material is not grouped together and located at the end of the book as you might expect; instead, it is placed right after the example(s) for every discussed class. This reinforces the feeling that Up to Speed with Swing was designed according to a sensible pedagogical plan, meant to be read in a very linear fashion, building your understanding and experience of Swing with each passing chapter.

Finally, Part III consists of just two chapters, "Creating custom look-and-feel" (Chapter 12) and "Optimizing JFC Applications" (Chapter 13). The former chapter is very valuable, the topic being one that few JFC/Swing books tackle with vigor -- due, one suspects, to the daunting amount of work required to create a brand-new Swing look and feel. The last chapter in the book, on optimization, was disappointing. Its bulk is consumed with profiling and generic Java code optimizations -- not, as the chapter's title suggests, with any techniques specific to JFC and/or GUI implementation. Furthermore, the very few GUI-specific suggestions, which relate to the use of multiple threads, were flawed. The author claims that using Swing's Timer class is more CPU-efficient than using Thread.sleep() because the latter, according to the author, consumes cycles while sleeping (which is false, as any programmer who has studied properly implemented multithreaded or multitasking systems will confirm).

I found the author's consistent writing style and paced approach to introducing Swing classes very easy to follow, almost as if I was back in school with a good teacher in front of the class, explaining every detail slowly and clearly. For the more mature or adventurous reader, on the other hand, the code examples do not contain much that will excite the old gray matter: The examples demonstrate only how to instantiate every Swing component and exploit the resultant object's features. No cool example applications, no higher-level reusable classes, no creative uses -- just a straightforward course in how to use Swing classes. Clearly, beginning to intermediate programmers will appreciate Gutz's zero-risk, highly-focused approach, as the book truly will bring them "up to speed" on Swing.

One cautionary note: the first printing of this book contained many annoying errors. The publisher assures me that the second printing, which should be available by the time you read this, has been thoroughly corrected in this respect. In any event, the book and example source code are available in electronic form from the publisher's Web site, so as always, browse before you buy.

is organized into four parts: Part I, "JFC Overview;" Part II, "JFC Services;" Part III, "JFC Case Studies;" and Part IV, "Quick Reference Section." Parts I and II really constitute a single logical group of chapters that introduce you to Swing's catalog of GUI components and JFC's other diverse services. Chapter 2, "Looking at Swing's Basic Components," is a whirlwind tour of Swing's simpler classes (that is, almost all classes except those relating to

(the latter hardly being a "sophisticated component"). This chapter adequately deals with all the main programming obstacles of

JTable

and

JTree

: custom models, cell or path selection, custom editors, and custom renderers. (Steer well clear of any JFC/Swing book that doesn't go into these nontrivial subjects, which you will have to confront sooner or later.)

Chapter 5, "Text Operations Under the JFC," introduces a shift in approach and the beginning of Part II. Instead of focusing on individual GUI components, the authors start exploring JFC's many class frameworks. Chapter 5 deals with JFC's clipboard and undo/redo frameworks. (It is not a discussion of JFC's most complex framework, the Text Document framework -- though you'd be forgiven for thinking so, given the title of the chapter.) Chapter 6, "Printing Under the JFC," deals with Java's (still rather immature) printer and printing support framework. Chapter 7, "Tweaking a JFC User Interface," is not about custom components, nor custom rendering, nor even Swing's pluggable look and feel. Rather, it's about Swing's DebugGraphics and SwingUtilities classes, and Swing's enhanced keyboard support (keyboard shortcuts using KeyStroke objects). Chapter 8, "An Introduction to More JFC Enhancements," very briefly discusses accessibility by concentrating on event trapping rather than the arguably more-logical approach of exploring the com.sun.java.accessibility package. Finally, still in Chapter 8, you'll find a thorough discussion of JFC's Drag-and-Drop API.

Many of the examples presented in the chapters of Parts I and II go beyond giving the reader bare-bones descriptions of how to use class X, Y, or Z. With several examples, for instance, the authors grab the opportunity to extend or embed the class of interest to create a reusable component that is less "low-level" than Swing's raw classes. Additionally, the authors now and again use one of three mini-applications to put Swing's components (or one or more of JFC's frameworks) in a more realistic context. These applications are a Microsoft-legal-department-defying Windows 95 Notepad clone, an image viewer, and a video database. If these mini-applications (of which more advanced and enhanced versions are located on the CD-ROM that accompanies the book) aren't enough, the reader is further treated to three more "Case Studies" in Part III. Chapter 9, "Client/Server Solutions Using the JFC and JDBC," fleshes out the video database application to include database load and save, record edit, and add and delete. Chapter 10, "Network-Centric JFC Solutions," presents a currency exchange calculator, which obtains its live exchange rate information from the Web. Chapter 11, "Creating JavaBeans with JFC Components," presents MapBean, a map and geographical coordinate (latitude and longitude) display JavaBean.

The code examples all seem to use some form of Hungarian notation convention (as does Gutz's book, for that matter). Unfortunately, the convention isn't applied consistently (again, as with Gutz's book), which totally defeats the purpose of using any naming convention. Code layout is generally okay, with the occasional typesetting disaster (see page 242, for example). This apparently befits every average Java book these days. Code comments are few and far between, but the text usually includes a "Stepping through the Code" section to accompany any nontrivial code. In some cases, though, explanations deteriorate to the just-swallow-and-don't-ask-questions level. For example, as part of the explanation of the authors' TextReader class, which uses a separate thread to perform text file loading in parallel with other tasks, the authors write, "It [the thread's run() method] starts by sleeping for 100 milliseconds to avoid deadlock." The authors then remain forever silent on how any deadlock could have occurred, or how a simple Thread.sleep() can ever give you a guaranteed fix for a race condition. Several examples also use large switch statements to determine what core functionality to invoke, instead of using Swing's Action interface designed to replace such obsolete '80's/Cstyle (and problematic) switch coding. (The virtues and far-reaching implications of using Action objects are not discussed at all in the main text of this book.)

Java Foundation Classes by Matthew T. Nelson (McGraw-Hill)

This huge book (1040 pages) suffers from lack of structure. Its linear 13-chapter presentation should have been split up in a trio of tutorial, case study, and reference parts. Chapters 1 through 7 -- "Getting Started with the JFC," "Moving from AWT to JFC," "The JComponent Class," "Pluggable Look and Feel," "JFC Documents and Text Components," "Accessibility," and "JFC by Concept" -- all logically belong in the tutorial part of the book. The first four chapters start off strongly, though: Chapter 1 breaks the ice by presenting a (trivial) example that combines everyday GUI elements like a window, menubar, buttons and some internal windows (

) under the microscope and discusses its API in groups of feature-related methods. Chapter 4 devotes itself to explaining and demonstrating Swing's unique pluggable look-and-feel feature.

Chapter 5, "JFC Documents and Text Components," is where content quality starts to erode. As the author himself writes, "JFC's text-related classes can be very hard to understand for several reasons. First, there are so many classes that interact. Second, [it's not clear what they do]. Third, [the domain is complex]." In view of the author's own acknowledgment of the complexity of the com.sun.java.text packages, it is disappointing and surprising that this chapter doesn't contain a single figure or class, object, or interaction diagram; nor does it contain a single example of how all the pieces work together in practice. In hindsight, this really wasn't surprising considering just over 10 pages were reserved for the subject, which, if it is to be treated in proportion to its size and complexity, could almost do with a small book of its own! Chapter 6, "Accessibility," repeats its predecessor's poor features: too brief, no diagrams, no examples. However, it does discuss the use of some accessibility-support development tools (JavaMonitor, Explorer, Monkey).

Chapter 7, "JFC by Concept," is a threadless enumeration of GUI topics that JFC is expected to impact in one way or another (for example, event handling, double-buffering, component borders, layout managers, scrolling, and the like). This chapter's approach feels more like a notepad of topics to be turned into full-fledged chapters than a polished chapter of its own. Because this chapter is slightly more than 50 pages, yet addresses several very complex topics (i.e., trees, tables and JFC's collection of Container classes, each of which can easily require that number of pages to discuss), it is no surprise that "JFC by Concept" fails to deliver.

Chapter 8, "JFC by Class," is the alphabetically-sorted reference part of the book (all 700-plus pages of it). By this point the reader is necessarily assumed to know enough about JFC's packages, interfaces and classes to exploit this reference material. Unfortunately, the preceding chapters do not feature sufficient step-by-step, logically progressing material (containing code examples and explaining the use of JFrames, JLabels, JButtons, JMenus, JTextFields, and so on -- that is, Swing's bread-and-butter components) to amply prepare the reader for what comes next. Instead, "JFC by Class" itself contains explanations and examples on how to use Swing's many components, but there's not a trace of a thread guiding the reader from easy to difficult topics, because the classes are discussed in alphabetical order (starting with AbstractAction and AbstractBorder). Each class or interface is discussed using (more or less consistently) the following template:

Introduction

Ancestors (that is, class or interface hierarchy)

Steps for creating and using the class

Basic code examples

Public methods

The example code is generously commented, properly laid out, and generally uses good, readable identifiers. The only thing that reduces the readability of the source examples is the use of a very fat (bold?) Courier type. My visual system almost morphed characters like a,e, and m into meaningless ink splats (and, according to a recent eye test, I have extremely sharp vision). Another silly, annoying detail scattered throughout the book is the poor use of screenshots: The vast majority of them are much too small, and some of them, quite literally, are thumbnail size!

Chapter 9, "Future JFC Technologies," leaves all reference material behind to continue on the path to JFC enlightenment. It discusses drag-and-drop and custom cursors (not one of the most earth-shattering JFC features), and spends 30 pages on an overview of Java's answer to Postscript: Java2D.

Finally, Chapters 10 through 14 present complete example applications that show off the use and elegant ballet of cooperating JFC classes. Chapters 10 and 11 concentrate on JTree and all its powers and complexity, Chapter 12 presents a simple paint program, and Chapter 13 a simple word processor. The latter still fails to adequately explain JFC's Document framework, and neither of the last two projects employ JFC's undo/redo framework to provide such a ubiquitous service. Apart from that, these ending chapters contain some badly needed added-value to complement the rest of the book.

Unlike McGraw-Hill's Java Foundation Classes, this title is structured in a logical and well-thought-out manner to give the reader a steady learning slope. Enumerating Programming with JFC's chapter titles will convince you of this. The first 10 chapters form the gentle foothills of this book's learning curve: "Introduction," "Lightweight Components," "Layout Managers, Boxes, and Borders," "Buttons, Actions, and Mouse Events," "Combo Boxes and Lists," "Sliders, Watch Events, and Scroll Panes," "Handling Simple Text Using Swing," "Menus and Tool Bars," "Dialogs and Option Panes," and "Timers and Progress Bars." The next 6 chapters (11 through 16) form the mountaineering equivalents of the mountain proper: "Trees," "Tables," "Tabbed and Split Panes," "Root Panes, Layers, and Internal Frames," "Styled Text," and "Creating Custom JFC Components." Once you've scaled those heights, you can relax with Chapter 17, "Other JFC Topics," and enjoy the view from the top with Chapters 18 and 19: "Zip and Jar Viewer Example" and "Search Program Example."

This book concentrates on showing you lots of examples (100-plus) on how to use JFC classes. The examples are focused and the source code further helps you to separate the trees from the forest by highlighting only the lines at the heart of each example. Thus, while the source code for the first "ToolTips" example is one page long, the authors draw the reader's attention to the only two lines necessary to enable and control the magic of tool tips. This time-saving approach should be especially effective for experienced AWT programmers who need to learn the essential differences between AWT and JFC programming (many aspects remain unchanged).

Somewhat like those in Gutz's book, the examples in the tutorial section are very straightforward, purely aiming to show you how to use one or more JFC classes. Their simplicity guarantees that the authors' conservative pedagogical approach pays off. Only one example shows any form of daring: Chapter 12, "Tables," shows how to combine JDBC with the JTable class to form a component that is more than the sum of its parts. Those readers needing stronger intellectual stimuli will find satisfaction in the (almost) real-life mini-projects of Programming with JFC's last two chapters. The first project, a zip/jar archive viewer and extractor, combines the use of JTable, JMenuBar, keyboard shortcuts, JToolBar, and JProgressBar with a by-the-book application architecture based around Action objects (not to be confused with ActionEvents!) to encapsulate the application's main function points (Open, Extract, and Quit). The second project, DocSearch (a fast javadoc documentation search application), omits tool and progress bars, but adds multithreading and HTML page viewing.

One criticism I have on the coding of the examples, and which also applies to other books in this review, is that the majority of examples repeat code verbatim from previous examples. Nearly all examples require a main() method, which remains almost identical from one example to the next, involving a JFrame to which the authors consistently add a WindowListener to kill the window and application on a window-close event. This recurring code amounts to some 25 lines; multiply this by the number of times it occurs in the book's 100-odd examples and you're looking at a stack of wasted pages. If you ignore the trees in this picture (which I'd prefer you didn't), this might not be such a crime, but Java is an object-oriented language, so one would expect Java books to rely on more state of the art, object-oriented techniques to achieve code reuse, rather than simple, but obsolete and highly problematic, cut-and-paste page-fill.

The majority of chapters end with a "Style Guidelines" section, instead of the more conservative summary. While no substitute for a textbook on GUI design, these guidelines should at least help the reader to avoid some of the worst types of GUI design faux pas.

The authors of Programming with JFC wisely decided not to include any comprehensive reference material, no doubt in recognition of the fact that the majority of Java reference books (bar those coming straight from Sun [Addison Wesley's Java Series]) fail to add value to the freely-available JDK javadocs. Constructor and method signatures are introduced on an as-needed basis, which, in my opinion, is a much more sensible approach (the javadocs should always be your first port of call when in need of API reference material!)

If you look back at the comparative table, you'll notice that I gave this month's books fairly average and comparable marks. That's because none excited my reader's senses with above-average writing style; or code quality; or cool/wow! examples; or quality of typesetting, diagrams, figures or screenshots. At the same time, none of these books have any lethal flaws either, so it's very difficult to pick clear winners or clear losers.

Gutz's Up to Speed With Swing may be the best book for beginners, as it really delivers on its promise to bring you up to speed with Swing's most important classes. If you really need introduction to the whole of JFC, rather than just Swing, any of the three remaining books will quench that initial thirst for new API enlightenment. If you really twist my arm, I'd suggest either Programming with JFC (John Wiley) or JFC -- Java Foundation Classes (IDG Books).

Laurence Vanhelsuwé is an independent
software engineer. Self-taught, he dropped out of college and
immediately started a professional career writing arcade games. He
has worked on such diverse technologies as X.25 WAN routers,
virtual reality flight simulation, Postscript, and realtime
digitized video-based traffic analysis.

Learn more about this topic

Swing comes with its own "Swing Connection" newsletter. http://java.sun.com/products/jfc/tsc

Read Laurence's other great book reviews. http://www.javaworld.com/common/jw-ti-bookreviews.html

Check out the JavaWorld Bookstore, which showcases books recommended for Java developers and allows you purchase hundreds of other Java books. http://www.javaworld.com/books/jw-clbooks.html

Can't find a particular title in the JavaWorld Bookstore? The JavaWorld Book Catalog provides an exhaustive listing of every book in the field, including foreign-language and out-of-print titles. http://www.javaworld.com/books/jw-books-index.html