Praise for the First Edition
“What’s significant about this book is that the examples are nontrivial. It’s clear that
much effort went into thinking out useful designs that both demonstrate the technolo-
gies and leave the reader with a practical starting point for professional development …
the book is full of pragmatic solutions … the very kind you need to address in produc-
tion and can’t typically find answers for anywhere. I recommend this book to any serious
Swing developer. If you’re a Swing beginner, you’ll get something out of this book, thanks
to its frank, no-nonsense approach to teaching Swing development. What impressed me
most was the focus on developing comprehensive examples… All in all, this is a real value
for any Swing developer.”
–Claude Duguay
JavaZone
“UI development is a very time consuming business. Even with such a powerful next gen-
eration API at your fingertips it can be still overwhelming. Swing is a wonderful book that
lightens the burden. It presents a complex subject in smaller manageable portions for the
programmer who has learnt the basics and wants to go much further. This excellent book
is impossible to take in at the first reading, because of the scope and breadth of its subject
matter. I think you will find that it hits its target audience and goals repeatedly. A massive
quality and quantity win for the publisher, Manning.”
–Peter Pilgrim
C Vu Journal
“How many times have you opened a book in search of a solution and found not only an
answer, but also an elegant enhancement to your application? How many times have
you ignored an O’Reilly book on the same subject lying on your table? The answer is
Manning’s new book Swing authored by Matthew Robinson and Pavel Vorobiev. And
that is my final answer.”
–Jayakrishnan
Slashdot
“An excellent resource for the developer of mid-level and advanced Swing applications. Many
of the techniques I’ve had to investigate and develop over the last two years are described in
this text. One of the few books to address the needs of serious Java 2 apps (e.g. printing,
Swing. It is packed full with good examples and explanations of those examples. The
examples are very detailed and can be used as a starting point for your own projects.”
–John Sullivan
Amazon
“…one of the best books available for learning the more advanced Swing features.”
–Marty Hall
Johns Hopkins University
“I strongly recommend this book … especially for developers serious about getting
into Java.”
–Mark Newman
GTE
“I love the use of detailed examples … sets it apart from all the other books on Swing.”
–Joel Goldberg
FedEx
“This is a must-have book for any kind of sophisticated UI development using Swing.”
–Jaideep Baphna
Dataware Technologies
“The JTree text and detailed examples alone have already saved me many hours of work
and have expedited my research code development.”
–P. Pazandak, Ph.D.
Object Services and Consulting
“…will satisfy readers from beginner to advanced starts with easy-to-understand
concepts and then drills down until it hits advanced intellectual pay dirt.”
–Kirk Brown
Sun Microsystems
“Looking for a book on Swing with in-depth coverage of the how’s and why’s? Then
Swing by Matthew Robinson and Pavel Vorobiev is it. Overall this is an excellent book,
and I would recommend it for the intermediate to advanced Swing developer.
–AnnMarie Ziegler
JavaRanch.com
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1930110-88-X
Printed in the United States of America
12345678910–VHG–0706050403
To Deirdre—
Matt
To my wife, Maria—
Pavel
ix
brief contents
Part I Foundation 1
1 Swing overview 3
2Swing mechanics15
Part II The basics 71
3Frames, panels, and borders73
4Layout managers89
5 Labels and buttons 155
6 Tabbed panes 187
7 Scrolling panes 202
8 Split panes 220
9 Combo boxes 227
10 List boxes and Spinners 256
11 Text components and undo 292
12 Menus, toolbars, and actions 332
13 Progress bars, sliders, and scroll bars 373
14 Dialogs 418
x BRIEF CONTENTS
Part III Advanced topics 469
15 Layered panes 471
Properties 15, Size and positioning 18
2.2 Event handling and dispatching 19
EventListenerList 22, Event-dispatching thread 22
2.3 Multithreading 23
Special cases 26, How do we build our own
thread-safe methods 26,
2.4 Timers 27
2.5 AppContext services 28
xii CONTENTS
2.6 Inside Timers and the TimerQueue 30
2.7 JavaBeans architecture 31
The JavaBeans component model 31, Introspection 31,
Properties 32, Customization 32, Communication 32,
Persistency 32, A simple Swing-based JavaBean 33
2.8 Fonts, colors, graphics, and text 38
Fonts 38, Colors 40, Graphics and text 40
2.9 Using the Graphics clipping area 47
2.10 Graphics debugging 49
Graphics debugging options 50, Graphics debugging caveats 51,
Using graphics debugging 51
2.11 Painting and validation 54
Double buffering 55, Optimized drawing 55,
Root validation 56, RepaintManager 57, Revalidation 57,
Repainting 58, Painting 59, Custom painting 61
2.12 Focus Management 61
KeyboardFocusManager 64, Key events and focus management 64,
Focus and Window events 64,
Focusability and traversal policies 65
2.13 Keyboard input 66
Listening for keyboard input 66,
ipadx and ipady constraints 99, Using weightx and
weighty constraints 100, Using gridwidth and gridheight
constraints 101, Using anchor constraints 102, Using fill
constraints 103, Putting it all together: constructing a
complaints dialog 104, A simple helper class example 109
4.4 Choosing the right layout 114
Understanding the code 119, Running the code 121
4.5 Custom layout manager, part I: labels/field pairs 121
Understanding the code 125, Running the code 128
4.6 Custom layout manager, part II: common interfaces 128
Understanding the code 136, Running the code 139
4.7 Dynamic layout in a JavaBeans container 140
Understanding the code 151, Running the code 153
5 Labels and buttons 155
5.1 Labels and buttons overview 155
JLabel 155, Text alignment157, Icons and icon
alignment 158, GrayFilter 158, The labelFor and the
displayedMnemonic properties 158, AbstractButton 158,
The ButtonModel interface 159, JButton 159,
JToggleButton 161, ButtonGroup 161, JCheckBox and
JRadioButton 162, JToolTip and ToolTipManager 163,
Labels and buttons with HTML text 163
5.2 Custom buttons, part I: transparent buttons 165
Understanding the code 168, Running the code 170
5.3 Custom buttons, part II: polygonal buttons 171
Understanding the code 176, Running the code 178
5.4 Custom buttons, part III: tooltip management 180
Understanding the code 183, Running the code 186
xiv CONTENTS
6 Tabbed panes 187
Understanding the code 243, Running the code 245
9.4 Combo boxes with memory 246
Understanding the code 250, Running the code 252
9.5 Custom editing 253
Understanding the code 255, Running the code 255
CONTENTS xv
10 List boxes and Spinners 256
10.1 JList 256
The ListModel interface 259, AbstractListModel 259,
DefaultListModel 259, The ListSelectionModel
interface 259, DefaultListSelectionModel 260,
The ListCellRenderer interface 260, The ListDataListener
interface 261, ListDataEvent 261, The ListSelectionListener
interface 261, ListSelectionEvent 261
10.2 Basic JList example 261
Understanding the code 263, Running the code 263
10.3 Custom rendering 264
Understanding the code 271, Running the code 273
10.4 Processing keyboard input and searching 273
Understanding the code 275, Running the code 276
10.5 List of check boxes 276
Understanding the code 279, Running the code 281
10.6 JSpinner 281
The SpinnerModel interface 282, AbstractSpinnerModel 283
SpinnerDateModel 283, SpinnerListModel 283
SpinnerNumberModel 283
10.7 Using JSpinner to select numbers 283
Understanding the code 284, Running the code 284
10.8 Using JSpinner to select dates 285
Understanding the code 286, Running the code 286
12 Menus, toolbars, and actions 332
12.1 Menus, toolbars, and actions overview 332
The SingleSelectionModel interface 332,
DefaultSingleSelectionModel 333, JMenuBar 333, JMenuItem 333,
JMenu 334, JPopupMenu 335, JSeparator 337,
JCheckBoxMenuItem 337, JRadioButtonMenuItem 337,
The MenuElement interface 338, MenuSelectionManager 339,
The MenuDragMouseListener interface 340,
MenuDragMouseEvent 340, The MenuKeyListener interface 340,
MenuKeyEvent 340, The MenuListener interface 341,
MenuEvent 341, The PopupMenuListener interface 341,
PopupMenuEvent 341, JToolBar 341, Custom JToolBar
separators 343, Changing JToolBar’s floating frame behavior 344,
The Action interface 345, AbstractAction 345
12.2 Basic text editor, part I: menus 346
Understanding the code 353, Running the code 354
12.3 Basic text editor, part II: toolbars and actions 355
Understanding the code 358, Running the code 358
12.4 Basic text editor, part III: custom toolbar components 359
Understanding the code 364, Running the code 366
12.5 Basic text editor, part IV: custom menu components 366
Understanding the code 370, Running the code 371
13 Progress bars, sliders, and scroll bars 373
13.1 Bounded-range components overview 373
The BoundedRangeModel interface 373,
DefaultBoundedRangeModel 374, JScrollBar 374,
JSlider 375, JProgressBar 377, ProgressMonitor 381,
ProgressMonitorInputStream 381
CONTENTS xvii
13.2 Basic JScrollBar example 382
ZipEntry 452, The java.util.jar package 452, Manifest 452,
Understanding the code 465, Running the code 468
Part III Advanced topics 469
15 Layered panes 471
15.1 JLayeredPane 473
15.2 Using JLayeredPane to enhance interfaces 473
15.3 Creating a custom MDI 475
xviii CONTENTS
16 Desktops & internal frames 476
16.1 JDesktopPane and JInternalFrame 476
JDesktopPane 476, JInternalFrame 476,
JInternalFrame.JDesktopIcon 477, The DesktopManager
interface 477, DefaultDesktopManager 479, Capturing
internal frame close events 479, The InternalFrameListener
interface 480, InternalFrameEvent 480,
InternalFrameAdapter 481, Outline dragging mode 481
16.2 Cascading and outline dragging mode 484
Understanding the code 485, Running the code 487
16.3 Adding MDI to a text editor application 487
Understanding the code 494, Running the code 495
16.4 Examples from the first edition 495
17 Trees 498
17.1 JTree 498
Tree concepts and terminology 498, Tree traversal 499,
JTree 499, The TreeModel interface 500,
DefaultTreeModel 501, The TreeNode interface 501,
The MutableTreeNode interface 501, DefaultMutableTreeNode 501,
TreePath 502, The TreeCellRenderer interface 502,
DefaultTreeCellRenderer 502, CellRenderPane 503,
The CellEditor interface 501, The TreeCellEditor interface 504,
JTable selection 548, Column width and resizing 550,
JTable Appearance 551, JTable scrolling 552
18.2 Stocks table, part I: basic JTable example 552
Understanding the code 557, Running the code 559
18.3 Stocks table, part II: custom renderers 559
Understanding the code 563, Running the code 564
18.4 Stocks table, part III: sorting columns 564
Understanding the code 569, Running the code 570
18.5 Stocks table, part IV: JDBC 571
Understanding the code 575, Running the code 576
18.6 Stocks table, part V: column addition and removal 576
Understanding the code 579, Running the code 580
18.7 Expense report application 580
Understanding the code 589, Running the code 591
18.8 Expense report application with variable height rows 591
Understanding the code 594, Running the code 594
18.9 A JavaBeans property editor 595
Understanding the code 601, Running the code 603
19 Inside text components 605
19.1 Text package overview 605
More about JTextComponent 605, The Document interface 608,
The StyledDocument interface 608, AbstractDocument 609,
The Content interface 612, The Position interface 613,
The DocumentEvent interface 613, The DocumentListener
interface 614, The Element interface 614, PlainDocument 615,
DefaultStyledDocument 617, The AttributeSet interface 620,
The MutableAttributeSet interface 622, The Style interface 622,
StyleConstants 623, StyleContext 623, The Highlighter
interface 624, DefaultHighlighter 625, The Caret interface 625,
DefaultCaret 625, The CaretListener interface 627,
21.2 Custom look and feel, part I: using custom resources 733
Understanding the code 740, Running the code 741
21.3 Custom look and feel, part II: creating custom UI delegates 741
Understanding the code 749, Running the code 751
21.4 Examples from the first edition 751
Part IV Special topics 755
22 Printing 757
22.1 Java printing overview 757
PrinterJob 758, The Printable interface 758,
The Pageable interface 759, The PrinterGraphics
interface 760, PageFormat 760, Paper 761,
CONTENTS xxi
Book 761, PrinterException 762
22.2 Printing images 762
Understanding the code 765, Running the code 767
22.3 Print preview 767
Understanding the code 773, Running the code 776
22.4 Printing text 776
Understanding the code 780, Running the code 781
22.5 Printing tables 781
Understanding the code 785, Running the code 787
23 Constructing an XML editor 789
23.1 XML editor, part I: viewing nodes 790
Understanding the code 795, Running the code 796
23.2 XML editor, part II: viewing attributes 796
Understanding the code 800, Running the code 801
23.3 XML editor, part III: editing nodes and attributes 801
Understanding the code 807, Running the code 808
23.4 XML editor, part IV: adding, editing,
and removing nodes and attributes 808
plete applications. This is a great way to inter-relate all of the parts of the Swing API.
James Gosling
Vice President and Fellow
Sun Microsystems
xxv
preface
This book is best described as a programmer’s guide, serving both as a reference and a tutorial.
Emphasis is placed on using Swing to solve a broad selection of realistic and creative problems.
We assume an intermediate knowledge of Java, including the basics of putting together an AWT-
based GUI, how the event model works, and familiarity with anonymous and explicit inner
classes. Those who do not have this background can pick it up in any beginner book on AWT or
Swing. However, the first edition of this book has proven to be most useful to those who come to
it with an intermediate understanding of Swing. For this reason we do not recommend this book
to Swing beginners. For beginners we suggest Manning’s own Up to Speed with Swing by Steven
Gutz.
Our goal was to produce a book that contains enough explanation and examples to satisfy
the most demanding Swing developer. We feel we have accomplished this goal again with the
updates in this edition, but please judge for yourself and we welcome all constructive feedback.
Unlike the first edition, however, this version is not freely available on the publisher’s web site.
The first edition will remain available online at www.manning.com/sbe, but we hope that we
have developed enough of a following to generate more sales with the second edition without giv-
ing it away for free. Let’s hope this is true!
What’s changed since the first edition?
Java 1.4 (aka Merlin) is the first major release of the Java platform that was planned through a
Java Community Process (JCP), allowing participants outside of Sun to have an influence on the
overall feature set. Each new feature, whether an addition or a change, had a dedicated expert
group which handled the description of that functionality according to certain rules underlying
Java Specification Requests (JSRs), which are the building blocks of any JCP. Similar to an open-
source project, but with actual development still done by Sun engineers, this process allowed Java