The worldwide JFC bestseller, updated for J2SE 1.3 and new Swing enhancements!
Core JFC delivers:
In-depth coverage of all the Swing components.
With Java 2 Standard Edition Version 1.3, Sun has enhanced the Java Foundation Classes with new features and superior performance. In Core JFC, Second Edition, Kim Topley updates his bestselling guide to JFC, giving serious developers the detailed information they need to make the most of the latest version.
Using industrial-strength examples, Core JFC, Second Edition presents JFC in depth and introduces key JFC features that are new to J2SE 1.3, including Swing enhancements, input validation, and new key binding schemes. Topley presents powerhouse JFC techniques that are of value to all JFC programmers, from beginner to expert.
Topley's advanced Swing coverage includes solutions to many of the key problems developers face most often. He introduces expert techniques for working with tree components, using custom renderers and editors, working with text components, using the internal frames feature to create multi-document applications, and much more.
If you're ready to use all the power JFC gives you, you're ready for Core JFC, Second Edition!About the CD-ROM
The accompanying CD-ROM contains an extensive source code library that can be compiled and run from Windows, Solaris, and Linux, along with complete versions of Borland's JBuilder 4, Foundation Edition for all three platforms.
Every Core Series Book:
(NOTE: Each chapter concludes with a Summary.)
Who This Book Is For. What You'll Need. How This Book Is Organized. Conventions Used in This Book. About the CD-ROM. Feedback. Further Information. Acknowledgments.
I. FROM AWT TO SWING.1. Introduction to the Java Foundation Classes.
What Are the Java Foundation Classes? Overview of JFC Features. The Swing Packages. The Model-View-Controller Architecture.2. Frames, Labels and buttons.
The Shell of an Application: The JFrame Class. Components and Their Properties. Containers and Layout Managers. Event Handling. Using Buttons. Images on Components: Icons.3. Managing the User Interface.
Layout Managers. Component Orientation. Working with the Application Window.4. Graphics, Text Handling and Printing.
Working with Graphics. A Graphics Application. Rendering Text. Printing Graphics and Text.
II. USING SWING TO BUILD BETTER APPLICATIONS.5. Keyboard Handling, Actions, and Scrolling.
Implementing Mouseless Operation. Scrolling Components. Logical Scrolling and Forcing Visibility of an Area. Implementing Scrolling with JscrollBar. Scrolling with the Keyboard. Component Autoscrolling.6. Menus and Toolbars.
The Menu Bar and the Menu System. Toolbars. Actions and Java 2 Version 1.3.7. Using Standard Dialogs.
Basic Dialogs. The JFileChooser Component.8. Creating Custom Dialogs.
Creating Custom Dialog Boxes. Tabbed Panes and Borders. Swing Components Often Used in Dialogs.
III. ADVANCED TOPICS.9. Text Controls.
Simple Text Controls. Input Verification. Text Components: Under the Hood. Getting Multiple Views of a Document. Documents with Nontext elements: JTextPane and JeditorPane.10. The Tree Control.
The Tree Control. Custom Tree Rendering and Editing.11. The Table Control.
An Overview of the Table Control. The Table Model. Table Columns and the Table Column Model. The Table Control. Customized Table Rendering and Editing.12. Multiple-Document Applications.
Internal Frames. Layered Panes. Working with Internal Frames. Icons, the Desktop Pane and the Desktop Manager. An Example Multiple-Document Application.13. The Pluggable Look-And-Feel.
The Look-and-Feel and the UIManager. Changing Component Look-and-Feel.Appendix A: SWING AND APPLETS.
The Java Foundation Classes (JFC) are a collection of user interface features that are included as part of the Standard Edition of Java 2 platform. Many of these features, most notably the Swing user interface toolkit, were actually initially developed before the Java 2 was released and can also be used with JDK 1.1. The JFC is such a large topic area that to cover it in one volume and give it the treatment that it deserves, and that an experienced programmer would expect, is an impossible task. So, this volume doesn't attempt to describe everything that falls under the JFC banner. Instead, I have chosen to concentrate on the parts that are of the most immediate interest to programmers working in the commercial Java development environment today. More advanced topics are discussed at length in this book's companion volume, Core Swing: Advanced Programming, which is also published by Prentice Hall PTR.
Most of this book is concerned with the subset of the JFC that you can use with both JDK 1.1 and the Java 2 platform. Specifically, this means the Abstract Windows Toolkit (AWT) as it existed in JDK 1.1, which is briefly covered as introductory or refresher material; printing, a JDK 1.1 feature that is deemed to be part of the JFC; and the Swing component set, which is the main focus of this book.
In writing about Swing, I have tried to include material that is of immediate interest to programmers who will want to use it to create real applications. The approach I have taken throughout is to explain how the Swing components and the various new Swing mechanisms (such as keyboard accelerators) work by giving an overview of each topic and then presenting examples that show the basic principles. Then, typically, I move on to show more complex use of the component or feature and how it can be used together with other components and features to solve real application-related problems. Much of the time, you can find out some of what you want to know by reading the documentation that comes with the JDK or Swing package, but this documentation often falls short of explaining the more complex features and how they interact. These are the things that programmers usually need to understand before they can make full use of what is available. You'll find those explanations in this book.
I have tried to write this book as I would have liked to have seen it as an experienced programmer wanting to learn about Swing for the first time. By reading the documentation, studying the source code, disassembling the class files, and trying various test cases, I have tried to do more than just scratch the surface of this large and complex topic by gathering together material and examples that are not available in Sun's documentation and presenting it in an organized, focused manner.
This book is for experienced Java programmers who want to find out about the Java Foundation Classes and, in particular, the Swing component set. Because this book is aimed at experienced Java programmers, you'll find that most of the examples are not trivial, with the exception of some of those in the early chapters that illustrate basic points that, for reasons of clarity, can't be embedded. Many of the examples that you'll find in this book are intended to be used as a starting point for writing production code that you can include in your own applications; some of the material here has been included specifically to address the most common questions that have been aired in the various news and discussion groups since the early versions of Swing were released. In particular, I have tried to address the following issues that seemed to cause the most confusion:
The focus in this book is entirely on writing Java applications rather than on applets. However, if you're already thoroughly familiar with applets, you'll find that you can use write applets using Swing very quickly and most of this book will still apply, since Swing components can be used in applets just as easily as in applications. To make the task even easier, there is an appendix devoted entirely to using Swing in the applet environment, including discussion on some of the topics that cause problems for developers, such as how to use Swing with a browser that doesn't include it and how to access non-code resources, such as image files, in a browser- and location-independent way.
This book is written with the assumption that you are familiar with the Java language and the core Java classes and that you can compile and run Java applications. Although this book is mainly about the Swing components, the first few chapters cover the basic principles of the Abstract Windows Toolkit (AWT), knowledge of which is a prerequisite for understanding Swing. You'll get the most from this book if you have read Core Java 2, Volume IFundamentals by Cay S. Horstmann and Gary Cornell, also published by Prentice Hall PTR, and if you understand inner classes, which are heavily used both in the Swing source code and in the examples shown in this book. Core Java includes excellent coverage of this topic.
Assuming that you have a computer running Windows 95, Windows 98, Windows 2000, Windows NT version 4 or later, Linux or Solaris, everything else that you need, including the Java 2 platform itself and a professional development environment (JBuilder 4 Foundation Edition), is included on the CD-ROM that accompanies this book.
The book is divided into three sections. Section 1, "From AWT to Swing" (Chapters 1 through 4), describes the relationship between the Abstract Windows Toolkit and Swing. Because Swing is based on the AWT, some understanding of the latter is needed before you can make full use of Swing. Therefore, this book opens by presenting the fundamentals of the AWT for those who are not entirely confident that they fully understand them and as a revision for those who do. These early chapters are, however, written not simply as a short course on the AWT, but they deliberately have a Swing slant to them so that as early as Chapter 2 you will meet and use your first Swing components. I recommend that everybody reads Chapter 1 and then, depending on your background, you should read, or at least skim, Chapters 2 through 4.
Section 2, "Using Swing to Build Better Applications" (Chapters 5 through 8), deals with the various new mechanisms and components that Swing offers that have no real parallel in the AWT. Much of this section deals with individual Swing components or Swing concepts and, to a certain extent, the chapters here can be read in any order. Finally, Section III, "Advanced Topics" (Chapters 9 through 13), covers larger topic areas such as the tree and table components and the pluggable look-and-feel.
Chapter 1 introduces the Java Foundation Classes (JFC) and puts them into perspective by comparing them to the AWT. You'll learn the scope of the JFC and get a quick overview of the main features of the Swing component set. The last part of this chapter introduces you to one of the more novel features of Swingthe so-called "pluggable look-and-feel," which allows applications to adapt their appearance to suit the platform that they are running on or to take on the same appearance across all platforms. It also explains the basis of this facility, the Model/View/Controller architecture (MVC).
Chapter 2 is the first of the AWT revision chapters. This chapter begins by introducing the Swing
JFrame class as the top-level window of an application and uses it to illustrate basic AWT concepts such as components, containers, position, size, color, fonts, and so on. The second half of this chapter includes material on event handling and introduces Swing's
JButton classes, which allow you to include text and an image on the same component. Here, you'll also find out about some Swing features that don't really exist in the AWT, such as icons and accelerator keys.
Chapter 3 is concerned with global user-interface issues, principal among which is controlling the layout of components in the interface. With this in mind, almost the whole chapter is devoted to in-depth coverage of the AWT and Swing layout managers. Layout managers are a topic that is often given only fleeting coverage in Java books and yet represents a large proportion of the questions that are asked in the Java-related Internet newsgroups. Here, I have tried to create a consistent picture of all of the layout managers and to address the most common misunderstandings by illustrating how each of them lays out its container and how resizing the container affects the positioning of the components.
Swing includes a useful new feature that can help with understanding problems with component layoutGraphics Debugging. This feature allows you to see how your components are drawn, line-by-line, in slow motion. Chapter 3 looks at this feature and shows you how to use it, concluding with a look at the events generated by windows and by individual components.
Chapter 4 covers the AWT
Graphics object and describes how you can use it to render text and draw graphics. The main body of this chapter is devoted to building a complete Swing application that allows you to use the mouse to draw and fill colored graphic shapes. While constructing this application, you'll put into practice much of what was covered in the previous two chapters and you'll also discover how to create custom icons and components with borders. The completed application will serve as a starting point for several improvements that will be made to it in the rest of the book. Chapter 4 closes with a discussion of printing, another topic that has caused much confusion in the past.
Chapter 5 shows you how to develop applications that work well when the user prefers to use the keyboard rather than the mouse, and introduces focus handling and the powerful concept of
Actions are often used in Swing to abstract an action to be performed from the stimulus to perform itsuch as a keystroke or a button press. The second half of the chapter looks at how Swing supports scrolling using the new
JScrollBar components, which are much more powerful than their AWT counterparts.
Chapter 6 introduces the Swing menu system. Swing menus are more consistent than those available with AWT. Keyboard accelerators are available on any menu or menu item and you can use icons as well as, or instead of, text. You'll also see how to integrate the Actions that were introduced in Chapter 5 with the menu system and with another new Swing facility, the toolbar.
Chapter 7 is the first of two chapters that contain extensive coverage of dialogs. This chapter concentrates on the basic dialogs that you can easily create using the JOptionPane component, which allow you to post error, warning, and information messages, or present options to the user and wait for a choice to be made. Two more complex, but extremely useful standard dialogs, the file chooser and color chooser, are also covered in this chapter.
Chapter 8 shows you how to use the Swing JDialog class to create your own dialogs. This chapter also introduces many of the Swing components that are useful in dialogs, such as tabbed panes, list boxes, combo boxes, progress controls, and sliders.
In Chapter 9, you'll find an in-depth description of the Swing text controls, starting with the simple JTextField and JTextArea components, which are related to the AWT TextField and TextArea controls. The Swing controls are underpinned by a complex but powerful document model that is covered in detail in this chapter. The description of the document model is followed by a description of two new Swing text controls-JTextPane, which allows multiple fonts, colors, images, and event components to be mixed in a view of a document, and the flexible JEditorPane, which adapts itself to render documents held as plain text, HTML, Rich Text Format, and a potentially infinite number of other formats.
Chapter 10 describes the Swing tree control and shows you how to build a tree, how to control which parts of it are expanded or collapsed, and how to traverse the tree in various different ways. This chapter also shows you a custom control based on the tree that presents a file system in a manner familiar to users of the Windows platform. It describes in detail how to customize trees using specially-developed renderers to control how the various pieces of the tree are drawn.
Chapter 11 is concerned with the table component. This component allows you to present data in a tabular form. You'll see how to determine the order of columns and their sizes and how to change the way in which the data in the table is displayed. There is also a section on table cell editors, which shows you how to present to the user a suitable interface for changing the content of the table.
Chapter 12 discusses Swing's support for multiple-document applications. Starting with a discussion of the basic components that make multiple-document applications possible, the chapter moves on to discuss desktop panes and icons and the desktop manager. You'll also see how to create a custom desktop pane that automatically cascades or tiles the windows that it manages and how to customize the desktop manager itself.
Finally, Chapter 13 returns to the theme of the pluggable look-and-feel that was first touched on in Chapter 1. This chapter shows the underlying support for changing the look-and-feel of an application, then shows you how to create your own user interface for the Swing button component. Finally, you'll see various ways to introduce look-and-feel related customizations into your application and how to create your own look-and-feel.
This book covers all of the Swing components and most of the other important Swing features. For ease of reference, the following table lists the Swing components, along with the chapters in which they are described.
The CD-ROM that accompanies this book contains the following:
For convenience, the example code contains three JBuilder project files that allow you to compile and run all of the source code from within the development environment. With the exception of the applet examples in Appendix A, all of the book's source code can be conveniently accessed by opening the project file CoreJFCExamples.jpr in the directory into which you installed them. To open this project file, run JBuilder, open the File menu, select Open Project and then navigate to the CoreJFCExamples.jpr file and click on it. When you do this, you will see a set of folders in the left-hand pane of the JBuilder main window, as shown in Figure P-1.
Each folder is labeled for one of the chapters of this book and contains all of the examples for that chapter, with the exception of the Cjfc folder which contains additional files used in Chapter 13. In Figure P-1, the Chapter2 folder has been opened to show the example code for Chapter 2. To view a source file, double click on the name and it will be opened in the main window of the IDE.To compile the source code, open the Project menu and select Rebuild Project "CoreJFCExamples.jpr". This will compile all of the source code, placing each class file in the same directory as its corresponding source file. You should also open the other two project files, CoreJFCAppendixBNative.jpr and CoreJFCAppendixAPlugin.jpr, and follow the same process to compile the remaining source code.
Since JBuilder 4 comes with a complete copy of the Java Runtime Environment version 1.3, you can use it to compile and run all of the source code in this book. It is a simple matter to run any given example. For example, in Chapter 2, you will find an instruction to run the first example using the command
To run this example from within the IDE, do the following:
This apparently long-winded process (which will get easier with time!) makes BasicFrame the current example. In order to run it, open the Run menu and select Run Project, or just press F9. Incidentally, you can also use the debug features of JBuilder to step through any of the example source code by using the Debug Project menu item. Usually, you would first open the source file and apply a breakpoint before doing this.
If you prefer not to use a development environment, you can compile and run the examples using the Java Development Kit.
Swing is not part of the core Java platform in JDK 1.1. Therefore, if you want to use the examples with JDK 1.1, you will need to download and install both JDK 1.1 and Swing version 1.1.1. You can download the Java Development Kit from the JavaSoft Web site at
and Swing version 1.1.1 from
Instructions for installing both products are available as part of the download. For the purpose of the descriptions that follow, we assume that you install the Java Development Kit in the directory c:\jdk1.1.8 and Swing in c:\Swing-1.1.1.
Having completed the installation, you need to set your PATH and CLASSPATH variables so that all of the executables and classes that you need to access are readily available. The instructions here assume that you are using a DOS session under Windows. Similar commands should be substituted if you are installing under Solaris or Linux.
The PATH variable must be set so that the javac and java commands are accessible when compiling and running the examples. Assuming that the JDK has been installed as described above, the following command will set the PATH variable appropriately:
The CLASSPATH variable should be set to include both the JDK classes, the Swing classes, and the classes for the book's examples. Having installed Swing, you need to add the appropriate JAR files to your CLASSPATH. Swing contains several JAR files, all of which are found in the
You can either choose to include the optimal set of files for your platform, or you can simply add
swingall.jar to your CLASSPATH. If you just want to use the standard Metal look-and-feel, you can get away with adding
swing.jar. If you want to use the Windows, Mac, or Motif look-and-feel as well, add
motif.jar. If you plan to develop Java Accessibility features (a topic outside the scope of this book), you need to add
multi.jar. You won't need to use
beaninfo.jar file unless you need to recreate your own version of
The following commands are sufficient to use Swing with the Metal, Windows, or Motif look-and-feels:
set CLASSPATH=c:\jdk1.1.8\lib\classes.zip;%CLASSPATH%set CLASSPATH=c:\swing-1.1.1\swingall.jar;%CLASSPATH%set CLASSPATH=c:\CoreJFCExamples;%CLASSPATH%
In order to make these settings persistent, you should add these commands to your AUTOEXEC.BAT file.
Having installed the necessary software, the next step is to compile the example code. This process is described in "Compiling and Running the Example Code."
Swing 1.1.1 is the last version of Swing that will be issued by JavaSoft for use with JDK version 1.1. As of October 2002, it will no longer be supported. JDK version 1.1 is itself undergoing its "end of life cycle" and will also no longer be supported by JavaSoft at around the same time.
The Java 2 platform includes the Swing classes, so you do not need to install a separate Swing package. The example code in this book works with both Java 2 version 1.2 and Java 2 version 1.3, which you can download from the following locations:
Both of these downloads include installation instructions.
As with JDK 1.1, following installation you need to set both the PATH and CLASSPATH variables. In the descriptions that follow, we assume that you have installed the JDK in the directory c:\jdk1.3.
The PATH variable should be set to include the locations of the javac and java commands:
By comparison with JDK 1.1, the CLASSPATH variable does not need to include the location of the JDK core classes, since these are located by other means when the Java 2 platform is being used. Therefore, only the location of the example code needs to be added to the CLASSPATH:
If you did not unpack the examples when you installed them, you should do so now. Make the directory in which the examples.zip file has been installed (
c:\CoreJFCExamples) your working directory, then execute the following command:
jar xvf examples.zip
This will extract all of the examples. You should now have a directory called
JFCBook in your
CoreJFCExamples directory, with one subdirectory per chapter. A typical layout might be as follows:
and so on. If you do not have this layout, you have done something wrong and the example programs will not work. One possible problem you might have at this stage is an inability to run the jar command or an error while running it. If this is the case, either your PATH variable or your CLASSPATH variable is not correctly set. Check that you have correctly followed the instructions in this section, then reboot your computer to make sure that the settings have been incorporated into your environment.
The examples for each chapter are held in a directory named after that chapter and all the examples in that directory must be compiled together. You must also build the examples in ascending chapter-number order, apart from those in Chapter 13, which must be built after those in the directory Cjfc. The correct build order, therefore, is as follows:
To build the examples for Chapter 2, for example, do the following:
cd C:\CoreJFCExamples\JFCBook\Chapter2javac *.java
This process should be repeated for each chapter, in the order just shown.
Some of the chapters have additional examples that can be used with different versions of the Java 2 platform. For example, the
Chapter2 directory has subdirectories called
jdk13. The examples in the
jdk12 directory can be used with any version of the Java 2 platform, whereas those in the
jdk13 directory apply only to Java 2 version 1.3 or later. To use these examples, you will need to compile them first; for example:
cd C:\CoreJFCExamples\JFCBook\Chapter2\jdk1.2javac *.java
Do not attempt to compile the examples in the jdk13 subdirectories unless you are using Java 2 version 1.3.
To run the examples, you must have the directory
C:\CoreJFCExamples in your CLASSPATH, as described earlier. You must then supply the full class name of the example that you want to run along with any required parameters as described in the appropriate chapter. For example, to run the first example in Chapter 2, use the following command:
In most cases, at appropriate points throughout the text, you will find explicit instructions that tell you how to run particular examples. Usually, however, you just need to use the example's class name and its chapter number as shown here.
SwingBuilder is a utility that allows you to visually create Swing-based user interfaces. Unlike JBuilder, it is not a complete development environment. Instead, it is one component of a suite of IDE tools produced by SwingSoft, a UK-based company who can be contacted via their Web site at www.swingsoft.com, where you can also find details of their other IDE components. Unlike most GUI builders, SwingBuilder does not generate code from your user interface design. Instead, it saves either a compact binary representation of your component layout, or it creates an XML file. At runtime, software provided by SwingSoft (and included with SwingBuilder) reads either of these formats and recreates the user interface.
The CD-ROM contains an evaluation copy of SwingBuilder for Windows platforms. In the directory Software\SwingBuilder, you'll find a ZIP file that you can expand onto your hard drive. The set of files extracted from this archive contains a file, sb.bat, that can be used to run SwingBuilder. You must pass the name of the directory into which SwingBuilder has been installed as a command line argument. If you expand the ZIP archive into a directory called C:\SwingBuilder, then the following commands will start SwingBuilder:
cd C:\SwingBuildersb.bat c:\SwingBuilder
No book is perfect and this one is unlikely to be an exception to that rule. Even though it has been through a long period of revision and technical review, there are, of course, errors still to be found and improvements still to be made. If you find an error or if there is something that you think might make the book more useful, we want to know. Please send comments and corrections to the following e-mail address:
Java is a fast-moving subject. To keep up with developments, reading books is not enough. The best place for up-to-date information is, of course, the JavaSoft Web site at:
You can get the most recent information on Swing and download the latest version of the software from the following page:
JavaSoft also provides an online Swing magazine called The Swing Connection, which is periodically updated and can be found at:
Finally, there are several active newsgroups devoted to the discussion of the Java platform. The following two groups in particular frequently discuss Swing and JFC-related issues: