Java™ Swing, 2nd Edition. By Brian Cole, Robert Eckstein, James Elliott, Marc Loy, David Wood. Publisher.: O'Reilly. Pub Date.: November ISBN. ISBN.: Pages.: This second edition of Java Swing thoroughly .. of you still working with JDK , we've included a PDF containing the. ISBN: Pages: This second edition of Java Swing or just trying to find out what Java can do, you'll find Java Swing, 2nd edition an.
|Language:||English, Spanish, Arabic|
|Genre:||Fiction & Literature|
|Distribution:||Free* [*Register to download]|
ISBN (pbk): Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1. Trademarked names may appear in this book. Rather than use. Head First Servlets and JSP™, Second Edition, and related trade dress are Java Swing -- O'REILLY Modern Compiler Implementation in Java, 2nd ed. ISBN: Pages: This second edition of Java Swing thoroughly covers all the features available in Java 2 SDK and
The SpringLayout Class Section Other Panes Chapter Chooser Dialogs Section The File Chooser Package Section The Color Chooser Section Developing a Custom Chooser Panel Section Developing a Custom Preview Panel Section Developing a Custom Dialog Chapter Borders Section Introducing Borders Section Painting Borders Correctly Section Swing Borders Section Creating Your Own Border Chapter Menus and Toolbars Section Introducing Swing Menus Section Menu Bar Selection Models Section The JMenu Class Section Selectable Menu Items Section Toolbars Chapter Tables Section The JTable Class Section Implementing a Column Model Section Table Data Section Selecting Table Entries Section Rendering Cells Section Next Steps Chapter Advanced Table Examples Section A Table with Row Headers Section Large Tables with Paging Section Charting Data with a TableModel Chapter Trees Section A Simple Tree Section Tree Models Section The JTree Class Section Tree Nodes and Paths Section Tree Selections Section Tree Events Section Rendering and Editing Section What Next?
Chapter Undo Section The Swing Undo Facility Section The UndoManager Class Section Extending UndoManager Chapter Text Section The Swing Text Components Section A Simple Form Section How It All Works Chapter Formatted Text Fields Section Handling Numerics Section The DefaultFormatter Class Section The MaskFormatter Class Section The InternationalFormatter Class Section The DateFormatter Class Section The NumberFormatter Class Section Formatting with Regular Expressions Section The InputVerifier Class Chapter Carets, Highlighters, and Keymaps Section Carets Section Highlighters Section Keymaps Chapter Styled Text Panes Section AttributeSets and Styles Section The Document Model Section Document Events Section The DocumentFilter Class Section The NavigationFilter Class Chapter Editor Panes and Editor Kits Section Overview of the Editor Kits Section Hyperlink Events Section A Custom EditorKit Chapter Drag and Drop Section What Is Drag and Drop?
Section Rearranging Trees Section Finishing Touches Chapter Programming with Accessibility Section How Accessibility Works Section The Accessibility Package Section Other Accessible Objects Section Types of Accessibility Section Classes Added in SDK 1. The Accessibility Utility Classes Section Interfacing with Accessibility Chapter Look and Feel Section How Does It Work? Auditory Cues Section Look-and-Feel Customization Section Creation of a Custom Look-and-Feel Chapter Swing Utilities Section Utility Classes Section The Timer Class Section Tooltips Section Rendering Odds and Ends Section Event Utilities Chapter Swing Under the Hood Section Working with Focus Section Multithreading Issues in Swing Section Lightweight Versus HeavyweightComponents Section Painting and Repainting Section Look-and-Feel Resources Appendix B.
Component Actions Section B. JButton Section B. JCheckBox Section B. JComboBox Section B. JDesktopPane Section B. JEditorPane Section B.
JInternalFrame Section B. JLabel Section B. JList Section B. JMenu Section B. JMenuBar Section B. JMenuItem Section B. JOptionPane Section B. JPasswordField Section B. JPopupMenu Section B. JProgressBar Section B. JRadioButton Section B. JRootPane Section B. JScrollBar Section B.
JScrollPane Section B. JSlider Section B. JSpinner Section B. JSplitPane Section B. JTabbedPane Section B. JTable Section B. JTextArea Section B. JTextField Section B. JTextPane Section B. JToggleButton Section B.
JToolBar Section B. JToolTip Section B. JTree Section B. JViewport Section B. Printed in the United States of America. Online editions are also available for most titles http: Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. It supported everything you could do in an HTML form and provided free-standing frames, menus, and a few other objects, but you'd be hard-pressed to implement an application as complex as Quicken or Lotus Notes.
AWT also had its share of portability problems; it relied heavily on the runtime platform's native user interface components, and it wasn't always possible to hide differences in the way these components behaved. JDK 1. We got a ScrollPane and a PopupMenu, but that was about it. Furthermore, AWT still relied on the native components and therefore continued to have portability problems.
A major part of the JFC was a set of much more complete, flexible, and portable user interface components called "Swing. With Swing, you can design interfaces with tree components, tables, tabbed dialogs, tooltips, and a growing set of other features that computer users are accustomed to.
In addition to the new components, Swing made three major improvements to the AWT. First, Swing doesn't rely on the runtime platform's native components. It's written entirely in Java and creates its own components. This approach solved most of the portability problems since components don't inherit weird behaviors from the runtime environment or do they work against its grain.
Second, because Swing is in complete control of the components, it's in control of the way components look on the screen and gives you more control over how your applications look. Third, Swing makes a very clear distinction between the data a component displays the "model" and the actual display the "view". While the fine points of this distinction are appreciated mostly by computer scientists, it has important implications for all developers.
This separation means that components are extremely flexible. It's easy to adapt components to display new kinds of data that their original design didn't anticipate or to change the way a component looks without getting tangled up in assumptions about the data it represents.
The first official release of Swing, for use with JDK 1. This book shows you how to join the revolution. Of course, it shows you how to use all of the components: You'd expect that in any Swing book.
This book goes much further. It goes into detail about the model-delegate architecture behind the components and discusses all of the data models. Understanding the models is essential when you're working on an application that requires something significantly different from the components' default behavior.
For example, if you need a component that displays a different data type or one that structures data in some nonstandard way, you'll need to work with the data models. This book also discusses how to write "accessible" user interfaces and how to create your own look-and-feel.
There are a few topics this book doesn't cover, despite its girth. We assume you know the Java language. For Swing, it's particularly important to have a good grasp of inner classes both named and anonymous , which are used by Swing itself and in our examples.
We assume that you understand the JDK 1. Swing introduced many new event types, all of which are discussed in this book, but we provide only an overview of the event mechanism as a whole. We also assume that you understand the older AWT components, particularly the Component and Container classes, which are superclasses of the Swing's JComponent. We assume that you understand the AWT layout managers, all of which are usable within Swing applications.
We do cover the JFC Accessibility API, which is supported by every Swing component, as well as the drag-and-drop facility, since this functionality is a requirement for modern user interfaces.
The major Swing classes fall into the following packages: Covered in Chapter Covered in Chapter 3 -Chapter 14 and Chapter 27 -Chapter Covered throughout the book.
Covered in Chapter 15 and Chapter Covered in Chapter 19 -Chapter The text. We've tried to highlight the changes from 1. For brevity's sake, we refer to Java versions by their SDK version number, describing this or that feature as having been introduced in SDK 1.
This new edition incorporated your feedback from the first edition! The first edition was too heavy on the documentation side for many readers. The Javadoc for the Swing packages continues to improve, and more and more people are familiar with the patterns of Java classes and methods.
With those two facts in mind, we try to focus on the parts of the API that are interesting and useful rather than just including them because they exist. We added many new examples and improved the existing examples. This book is a true and thorough revision of the first edition, not a mere update.
As a quick reference to some of the changes you'll find in the 1. We detail these changes throughout the book as we discuss the particular components. Table P Swing changes in the Java 2 SDK 1. JTable Chapter 15 Improved general performance and cell rendering. A new property, acceptAllFileFilterUsed, was added. JInternalFrame Chapter 9 Several fixes and newly public classes and methods. Text components Chapter 19 -Chapter 23 Several fixes applied.
XHTML documents are still not supported. JViewport Chapter 11 New scrollMode property added. JComponent Chapter 3 New print methods added: InputVerifier Chapter 20 New class added. Keyboard binding Chapter 3 , Appendix B New keyboard binding mechanism added.
Borders Chapter 13 New LineBorder constructor to support rounded corners added. JToolBar Chapter 14 Support for titling undocked toolbars added. JSpinner Chapter 7 Added new spinner class. Focus Chapter 3 , Chapter 28 A new focus model and methodology was introduced. Several of the old-style focus methods and classes were deprecated as of 1.
Drag and Drop Chapter 24 New architecture introduced, and dragEnabled and transferHandler properties added to several components. Box Chapter 11 Now descends from JComponent. JButton Chapter 5 More control over mnemonic underline location granted. JFileChooser Chapter 12 Added support for modifying the properties of the Open button such as its text and tooltip.
Also added support for selecting multiple files.
The multiple file selection mode was introduced in the 1. JInternalFrame Chapter 9 Long titles are now truncated, and the title bar is rendered with a gradient.
Text components Chapter 19 -Chapter 23 Tooltip support was improved. New replace method added to AbstractDocument.
JOptionPane Chapter 10 New input dialog methods added.
JPopupMenu Chapter 14 Now properly supports key bindings. JTabbedPane Chapter 11 Introduced scrollable tabs for panes with a large number of tabs. Mnemonic support for accessing tabs was also added. JTree Chapter 17 Null roots are now allowed, and first-letter keyboard navigation was added. JList Chapter 7 Items can now be arranged horizontally, and first-letter keyboard navigation was added. Access to Windows desktop properties was also added. JRootPane Chapter 10 Look-and-feel can now supply window decoration.
JScrollPane Chapter 11 Now supports mouse wheel events. This support can be turned off. SpringLayout Chapter 11 New class and supporting classes added. The files named swing-1e were tested against JDK 1. The files named swing-old were written with the beta releases of Swing and use the com. We also include a few free utilities on the site that you may want to check out: See Section This is the utility we used to build Appendix B.
You can download PDFs of the entire book. The web site also includes some expanded material that we couldn't shoehorn into this edition of the book.
For those of you still working with JDK 1. Regardless of your version of Java, if you're planning on extending the HTMLEditorKit, you should check out the expanded material online. We cover the basics of this editor kit in Chapter 23 , but for those of you who want to dig in deep, you should download PDFs of the two chapters devoted to this topic.. Understanding these conventions up-front makes it easier to use this book.
This book uses the following font conventions: Italic Used for filenames, file extensions, URLs, application names, emphasis, and new terms when they are first introduced Constant width Used for Java class names, functions, variables, components, properties, data types, events, and snippets of code that appear in text Constant width bold Used for commands you enter at the command line and to highlight new code inserted in a running example Constant width italic Used to annotate output This icon designates a note, which is an important aside to the nearby text.
This icon designates a warning relating to the nearby text. Properties Tables Swing components are all JavaBeans. Properties provide a powerful way to work with JavaBeans, so we use tables throughout the book to present lists of properties.
Table P-3 is an example from the hypothetical JFoo class that shows how we use these tables. Properties tables tell you the data type; whether it has is, get, and set methods; and its default value, if any. We use "overridden" to mean both actual overridden methods in the case of a concrete parent class and implemented methods in the case of an abstract parent class or an interface. If it is a recent addition, the version of the SDK that added the property is noted assume 1. The property was introduced in the 1.
This property has accessor methods with the signatures: Please let us know about any errors you find, as well as your suggestions for future editions, by writing to: To be put on the mailing list or request a catalog, send a message to: You can access this page at: Marc Loy I'll start off the mutual admiration society by thanking my cohorts Jim and Brian.
They came to the table after we lost Dave and Bob from the first edition to other books, and well, life in general. This update would not have been possible without them. Our editor Deb Cameron has the patience and diligence of some very patient and diligent god.
Gratitude for the inspiration to keep writing even if it is technical goes to Amy Hammond, my sister and confidante. A special thanks to Kathy Godeken for an early push in the right direction. Words are not enough to thank my partner Ron, so I'll not waste the space. Brian Cole Thanks to my family for putting up with me as an author.
This goes tenfold for my partner, Beth, for that and more. Thanks to Deb, who was very understanding about deadlines, and especially to Marc and Jim, who were always willing to lend a hand despite deadlines of their own. Thanks to my employers and coworkers, who were willing to accommodate my schedule. Finally, thanks to the anonymous programmer who discovered that running java with -Dsun.
You saved me a lot of time. James Elliott Any list of thanks has to start with my parents for fostering my interest in computing even when we were living in countries that made that a major challenge, and with my partner Joe for putting up with it today when it has flowered into a major obsession. I'd also like to acknowledge my Madison employer, Berbee, for giving me an opportunity to delve deeply into Java and build skills as an architect of reusable APIs; for letting me stay clear of the proprietary, platform-specific tar pit that is engulfing so much of the programming world; for surrounding me with such incredible colleagues; and for being supportive when I wanted to help with this book.
Of course, I have Marc to thank for getting me involved in this crazy adventure in the first place, and Deb for helping make sense of it. I wanted to be sure this edition gave good advice about how to work with Swing on Mac OS X, Apple's excellent, Unix-based environment for Java development, so I asked for some help.
Lee Ann Rucker who should also be thanked for her heroic work of single-handedly implementing the new Mac OS Look-and-Feel while on loan from Sun to Apple shared some great ideas and approaches to writing solid, cross-platform Java applications, including the MacMetrics theme described in Chapter Count me among the many people wishing Sun or Apple would put her back on the Mac Java team!
Finally, Matt Drance at Apple's Developer Technical Support sent me an early and helpful version of his technical note on how to make Java applications as Mac-friendly as possible.
There are many others to whom I'm indebted, but I've already used more than my fair share of space, so the rest of you know who you are! We all want to thank the many members of O'Reilly's production department, who put in lots of work under a tight schedule. Introducing Swing Welcome to Swing! By now, you're probably wondering what Swing is and how you can use it to spice up your Java applications. Or perhaps you're curious as to how the Swing components fit into the overall Java strategy.
Then again, maybe you just want to see what all the hype is about. Well, you've come to the right place; this book is all about Swing and its components. So let's dive right in and answer the first question that you're probably asking right now, which is If you poke around the Java home page http: In reality, however, Swing is much more than this. By enterprise development, we mean that programmers can use Swing to create large-scale Java applications with a wide array of powerful components.
In addition, you can easily extend or modify these components to control their appearance and behavior.
Swing is not an acronym. The name represents the collaborative choice of its designers when the project was kicked off in late When released, the Swing 1. Growth has continued since then: Swing builds on the event model introduced in the 1. In addition, you must have a Java 1. The Java 2 SDK 1. Swing is fully integrated into both the developer's kit and the runtime environment of all Java 2 releases SDK 1.
The FC is a suite of libraries designed to assist programmers in creating enterprise applications with Java. Accessibility The accessibility package provides assistance to users who have trouble with traditional user interfaces.
Accessibility tools can be used in conjunction with devices such as audible text readers or braille keyboards to allow direct access to the Swing components. Accessibility is split into two parts: All Swing components support accessibility, so this book dedicates an entire chapter Chapter 25 to accessibility design and use.
Drag and Drop Drag and Drop DnD is one of the more common metaphors used in graphical interfaces today. The user is allowed to click and "hold" a GUI object, moving it to another window or frame in the desktop with predictable results. The DnD API allows users to implement droppable elements that transfer information between Java applications and native applications. Although DnD is not part of Swing, it is crucial to a commercial-quality application.
We tackle this topic in Chapter Figure enumerates the various components of the Java Foundation Classes. Figure Swing is actually built on top of the core AWT libraries. Because Swing does not contain any platform-specific native code, you can deploy the Swing distribution on any platform that implements the Java 1.
In fact, if you have JDK 1. If you use a JDK version prior to 1. In JDK 1. For completeness, the other JAR files are: In addition, Swing contains many design advances over AWT. For example, Swing introduced an Action class that makes it easier to coordinate GUI components with their functionality. You'll also find that a much cleaner design prevails throughout Swing; this cuts down on the number of unexpected surprises that you're likely to face while coding.
Swing depends extensively on the event-handling mechanism of AWT 1.
Each Swing component also contains a variable number of exportable properties. This combination of properties and events in the design was no accident. Each of the Swing components, like the AWT 1. As you might have guessed, this means that you can import all of the Swing components into various GUI builder tools, which is useful for powerful visual programming.
When Sun released the Java Development Kit on the Internet, it ignited a firestorm of excitement that swept through the computing industry.
At first, developers primarily experimented with Java for applets, mini-programs embedded in web browsers. In addition, you must have a Java 1. The Java 2 SDK 1. Swing is fully integrated into both the developer's kit and the runtime environment of all Java 2 releases SDK 1. The FC is a suite of libraries designed to assist programmers in creating enterprise applications with Java. Accessibility The accessibility package provides assistance to users who have trouble with traditional user interfaces.
Accessibility tools can be used in conjunction with devices such as audible text readers or braille keyboards to allow direct access to the Swing components. All Swing components support accessibility, so this book dedicates an entire chapter Chapter 25 to accessibility design and use. Drag and Drop Drag and Drop DnD is one of the more common metaphors used in graphical interfaces today. The user is allowed to click and "hold" a GUI object, moving it to another window or frame in the desktop with predictable results.
The DnD API allows users to implement droppable elements that transfer information between Java applications and native applications. Although DnD is not part of Swing, it is crucial to a commercial-quality application. We tackle this topic in Chapter Figure Swing is actually built on top of the core AWT libraries. Because Swing does not contain any platform-specific native code, you can deploy the Swing distribution on any platform that implements the Java 1.
In fact, if you have JDK 1. If you use a JDK version prior to 1. In JDK 1. For completeness, the other JAR files are: swing. In addition, Swing contains many design advances over AWT.
For example, Swing introduced an Action class that makes it easier to coordinate GUI components with their functionality. You'll also find that a much cleaner design prevails throughout Swing; this cuts down on the number of unexpected surprises that you're likely to face while coding. Swing depends extensively on the event-handling mechanism of AWT 1. Each Swing component also contains a variable number of exportable properties.
This combination of properties and events in the design was no accident. Each of the Swing components, like the AWT 1. As you might have guessed, this means that you can import all of the Swing components into various GUI builder tools, which is useful for powerful visual programming. When Sun released the Java Development Kit on the Internet, it ignited a firestorm of excitement that swept through the computing industry.
At first, developers primarily experimented with Java for applets, mini-programs embedded in web browsers. However, as Java matured over the course of the next two years, many developers began using Java to develop full-scale applications. Or at least they tried. As developers ported Java to more and more platforms, its weak points started to show. The primary criticism, however, was that it was an interpreted language, which means that by definition it executed code slower than its native, compiled equivalents.
This solved many problems, but one weak point that continually received scathing criticism was the graphical widgets that Java was built on: the Abstract Window Toolkit AWT. The primary issue here was that AWT provided only the minimal amount of functionality necessary to create a windowing application.
For enterprise applications, it quickly became clear that programmers needed something bigger. After nearly a year of intense scrutiny, the AWT classes were ready for a change. From Java 1. This meant that instead of propagating events through a predefined hierarchy of components, interested classes simply registered with other components to receive noteworthy events. Because events typically involve only the sender and receiver, this eliminated much of the overhead in propagating them.
When component events were triggered, an event object was passed only to those classes interested in receiving them. Sun developers also began to see that relying on native widgets for the AWT components was proving to be troublesome. Similar components looked and behaved differently on many platforms, and coding for the ever-expanding differences of each platform became a maintenance nightmare.
In addition, reusing the component widgets for each platform limited the abilities of the components and proved to be expensive on system memory. Clearly, Sun knew that AWT wasn't enough. It wasn't that the AWT classes didn't work; they simply didn't provide the functionality necessary for full-scale enterprise applications.
Since JDK 1. Here is an overview of some of the more popular features. Many users are familiar with the Motif style of user interface, which was common in Windows 3. In practice, nobody really does this, but it's still pretty cool from a geeky point of view. In the purest sense, this means that components are not dependent on native peers to render themselves. Instead, they use simplified graphics primitives to paint themselves on the screen and can even allow portions to be transparent.
Prior to that, Java programmers had no choice but to subclass java. Canvas or java. Panel if they wished to create their own components. With both classes, Java allocated an opaque peer object from the underlying operating system to represent the component, forcing each component to behave as if it were its own window, thereby taking on a rectangular, solid shape.
Hence, these components earned the name "heavyweight" because they frequently held extra baggage at the native level that Java did not use.
A list component on one platform, for example, may work differently than a list component on another. Trying to coordinate and manage the differences between components was a formidable task. With lightweight components, each component renders itself using the drawing primitives of the Graphics object e. Lightweight components always render themselves onto the surface of the heavyweight top-level component they are contained in.
With the arrival of JDK 1. Component or java. Container classes when creating lightweight components. Unlike java. Panel, these classes do not depend on a native peer and allow the developer to render quickly to the graphics context of the container. This results in faster, less memory-intensive components than were previously available in Java. Almost all of the Swing components are lightweight; only a few top-level containers are not. In addition, the design of the Swing components supports easy modification of component behavior.
For example, you can tell almost any Swing component whether you wish it to accept or decline focus and how it should handle keyboard input. Swing components support the replacement of their insets with an arbitrary number of nested borders. A tooltip is a textual pop up that momentarily appears when the mouse cursor rests inside the component's painting region.
Tooltips can be used to give more information about the component in question. We discuss each of these features in greater detail as we move through the next three chapters. Not everyone uses Swing for the same reasons. In fact, the Swing libraries have many levels of use, with varying levels of prerequisite knowledge. The first approach is what the vast majority of Swing programmers use.
Here, using Swing components is just like using the AWT components. A familiar set of components, containers, and layout managers are all available in the Swing packages to help you get your application up and running quickly.
If you're adept at AWT programming, you probably need only a cursory introduction to each component to get started.
You will we need to get into broader issues only if you use some of the larger and newer component families, such as tables and text. If you are planning to use each component as a JavaBean for visual programming, you also fall into this category. Creating your own component, or extending an existing one, requires a deeper understanding of Swing.
This includes a firm understanding of Swing architecture, events, and lower-level classes. This book strives to help you with each of these issues. Because we anticipate that the vast majority of readers are in the first category, we spend a great deal of time reviewing each component's properties and methods, as well as providing source code for various scenarios that use these components.
We try to document and illustrate the useful parts of the components. The online documentation called Javadoc has matured along with the rest of Java; the current stuff is always there first. However, we don't want to leave you in the dark. If you are an experienced Swing programmer already, and you're looking for a concise introduction on how to get started, see Chapter Assistive technologies cover a broad range of items, from audible text readers to screen magnification.
Although the accessibility classes are technically not part of Swing, they are used extensively throughout the Swing components. We discuss the accessibility package in greater detail in Chapter Contains the core Swing components, including most of the model interfaces and support classes. Borders are not components; instead, they are special graphical elements that Swing treats as properties and places around components in place of their insets.
If you wish to create your own border, you can subclass one of the existing borders in this package, or you can code a new one from scratch. To create your own events, you can subclass various events in this package or write your own event class.
Contains support for the JFileChooser component, discussed in Chapter Using the lower-level classes, you can manipulate how tables are viewed and selected, as well as how they display their information in each cell.
The text classes are among the more advanced Swing classes to learn, so we devote several chapters Chapter 19 - to both the design fundamentals and the implementation of text applications. By far the most widely used package is javax. In fact, almost all the Swing components, as well as several utility classes, are located inside this package. The only exceptions are borders and support classes for the trees, tables, and text-based components. Because the latter components are much more extensible and often have many more classes to work with, these classes have been divided into separate packages.
At first glance, the class hierarchy looks very similar to AWT. Each Swing component with an AWT equivalent shares the same name, except that the Swing class is preceded by a capital J. In most cases, if a Swing component supersedes an AWT component, it can be used as a drop-in replacement. The Swing component hierarchy Upon closer inspection, however, you will discover that there are welcome differences between the Swing and AWT components. For example, the menu components, including JMenuBar, are now descendants of the same base component as the others: JComponent.
This is a change from the older AWT menu classes.