Java Swing, 2nd Edition

Java Swing, 2nd Edition

Code Examples

The file (3.2MB) contains all of the code examples from the book in one lump. (It also includes the index of individual examples you see below.) The various tools (EEL and MacMetrics, for example) and miscellaneous resources like the classic Key Events discussion or the expanded HTML Editor Kit section can be found here.

Chapter 2 Chapter 11 Chapter 20
Chapter 3 Chapter 12 Chapter 21
Chapter 4 Chapter 13 Chapter 22
Chapter 5 Chapter 14 Chapter 23
Chapter 6 Chapter 15 Chapter 24
Chapter 7 Chapter 16 Chapter 25
Chapter 8 Chapter 17 Chapter 26
Chapter 9 Chapter 18 Chapter 27
Chapter 10 Chapter 19 Chapter 28

Chapter 2
CCPHandlerA simple event handler to display cut/copy/paste events.
CopyActionA simple Action that copies text from a PageFrame object.
CutActionA simple Action that copies text from a PageFrame object.
LnFListenerA listener that can change the look-and-feel of a frame based on the actionCommand of an ActionEvent object. Supported look-and-feels are: Mac, Metal, Motif, Windows. Not all L&Fs will be available on a given machine. Notably, the Mac and Windows L&Fs work only on their specific platforms.
PageFrameA simple extension of the JInternalFrame class that contains a list object. Elements of the list represent HTML pages for a web site.
PasteActionA simple Action that pastes text into a PageFrame object.
SimpleInternalFrameA quick demonstration of setting up an internal frame in an application.
SiteFrameA simple extension of the JInternalFrame class that contains a list object. Elements of the list represent HTML pages for a web site.
SiteManagerA sample Swing application that manages several internal frames. This is the main class for working with the SiteFrame and PageFrame classes.
ToolbarFrame1A simple frame containing a "toolbar" made up of several java.awt.Button objects. We'll be converting the Buttons to JButtons in the file.
ToolbarFrame2The Swing-ified button example.
ToolbarFrame3The Swing-ified button example. The buttons in this toolbar all carry images but no text.
Chapter 3
ActionExampleThis example creates a menubar and toolbar both populated with Action objects.
GuiScreensA quick utility to print out graphic device information. Will work on systems with multiple monitors.
Chapter 4
AlignmentExampleA simple demonstration of text alignment in JLabels.
AnimationAppletThe classic animation applet rewritten to use an animated GIF.
DynamicIconExampleExample of an icon that changes form.
HtmlLabelA JLabel that uses inline HTML to format its text.
ImageLabelExampleVariations on a text & icon label. The icon and text are aligned in different ways for each label.
MnemonicLabelsShows how displayedMnemonic and labelFor properties work together
OvalIconA simple icon implementation that draws ovals.
SimpleJLabelExampleA quick application to show a simple JLabel.
TestOvalA simple application to test the functionality of the OvalIcon class.
Chapter 5
ActionExampleAn application that shows the Action class in, well, action.
DefaultButtonExampleExample using defaultButton and JRootPane.setDefaultButton()
FancyButtonCreate a JButton that does not show focus, does not paint a border, and displays different icons when rolled-over and pressed.
JButtonEventsA simple demonstration of button events including Action, Item and Change event types.
JToggleButtonEventsThe event demonstration program for JToggleButton.
SimpleButtonGroupExampleA ButtonGroup voting booth.
Chapter 6
BoundedA demonstration of the ChangeEvents generated by the BoundedRangeModel.
ProgressBarExampleA demonstration of the JProgressBar component. The component tracks the progress of a for loop.
ProgressMonitorExampleA demonstration of the ProgressMonitor toolbar. A timer is used to induce progress. This example also shows how to use the UIManager properties associated with progress monitors.
ProgressMonitorInputExampleSimilar to the ProgressMonitorExample except that we can now use an actual input file to monitor rather than inducing progress manually. The file to load should be passed as a command line argument.
ScrollBarExampleA quick demonstration of JScrollBar (both vertical and horizontal).
SliderExampleAn example of JSlider with default labels.
Chapter 7
BookCellRendererA custom cell renderer for BookEntry objects.
BookEntryA simple aggregate class to store a book's title and icon.
ComboBoxEditorExampleA custom combobox editor for use with the EditableComboBox class.
EditableComboBoxA fancy example of JComboBox with a custom renderer and editor used to display a list of JLabel objects that include both text and icons.
IconEditorAn editor for use with the JSpinner component. This editor can display an icon from a list stored in the spinner.
IconSpinnerAn implementation of JSpinner with customized content--icons in this case. A standard spinner model is used with a custom editor (
ListExampleAn example of the JList component in action. This program uses a custom renderer ( to show a list of books with icons of their covers.
ListModelExampleAn example of JList with a DefaultListModel that we build up at runtime.
MonthSpinnerAn example of JSpinner with a custom editor that allows the user to spin through dates of the mm/yy format.
RolloverSpinnerListModelA custom spinner model that rolls over the end of a list back to the beginning (or vice versa).
SelectionMonitorA graphical list selection monitor.
SimpleListA simple example of a JList object built from an array of Strings.
SimpleList2A variation on SimpleList. This version modifies the selection model used.
SpinnerTestA quick test of various spinners.
Chapter 8
ExitFrameA very simple extension of JFrame that defaults to EXIT_ON_CLOSE for its close operation. Relies on the 1.3 or higher SDK.
FrameClose1A demonstration of the SDK 1.3 EXIT_ON_CLOSE behavior for JFrames.
FrameClose2A demonstration of the WindowListener approach to closing JFrames.
GlassExampleShow how a glass pane can be used to block mouse events. updated GlassExample
OpaqueExampleCreates two JPanels (opaque), one containing another opaque JPanel, and the other containing a non-opaque JPanel.
RevalidateExampleAn example of using the revalidate() method to dynamically update the appearance of a component. This example changes the size of a button's font on the fly.
RootExampleAn example of interacting directly with the JRootPane of a JFrame.
RootExample2Another example of interacting with the root pane. We set the menubar for the frame directly through the root pane in this example.
RootExample3Similar to RootExample2, but this version uses the setJMenuBar() method from JFrame to attach the menu. No (direct) interaction with JRootPane is needed.
SimpleAppletAn example of the JApplet class. For use with the applet.html file.
SimpleApplet2A contrived example of how to add components to an applet after it has been initialized. Code to disable the event queue checking is included (but commented out) for use with older plug-ins.
SimpleFrameA simple example of the JFrame class.
SimpleLayersA demonstration of the JLayeredPane class.
SplashScreenA simple application to show a title screen in the center of the screen for the amount of time given in the constructor. This class includes a sample main() method to test the splash screen, but it's meant for use with other applications.
Chapter 9
Figure3An example that shows how to do a few interesting things using JInternalFrames, JDesktopPane, and DesktopManager.
SampleDesktopAnother example that shows how to do a few interesting things using JInternalFrames, JDesktopPane, and DesktopManager.
SampleDesktopMgrA DesktopManager that keeps its frames inside the desktop.
SimpleInternalFrameA quick demonstration of setting up an Internal Frame in an application.
TileActionAn action that tiles all internal frames when requested.
Chapter 10
DialogDesktopA frame that can easily support internal frame dialogs.
ManyOptionsAn example of using the JOptionPane with a custom list of options in an input dialog.
OptPaneComparisonA quick utility class to help you see the differences between various types of option panes, both via internal frames and using standalone popups.
Chapter 11
CompassButtonsA demonstration of the SpringLayout class. This application puts directional buttons on a panel and keeps them close to the edges of the panel regardless of the panel's size.
CompassScrollerA simple ActionListener that can move the view of a viewport north, south, east and west by specified units.
FractionSpringA Spring extension that calculates its values based on an anchor Spring and a multiplier (> 0.0). Note that values greater than 1.0 can be used.
HBoxA quick test of the BoxLayout manager using the Box utility class.
HBoxWithGlueA quick test of the BoxLayout manager using the Box utility class.
HBoxWithStrutAnother test of the BoxLayout manager using the Box utility class. This version separates several components with a fixed width gap.
OverlayTestA test of the OverlayLayout manager allowing experimentation.
ScrollDemoA simple JScrollPane demonstration.
ScrollDemo2Another JScrollPane demonstration. This version activates some of the features of JScrollPane such as row and column headers.
ScrollListA simple JScrollPane for a JList component.
SimpleSplitPaneA quick test of the JSplitPane class.
SimpleTabA quick test of the JTabbedPane component.
SysConfigA demonstration of the JTabbedPane class for displaying and manipulating configuration information. The BoxLayout class is used to lay out the first tab quickly.
TooManyTabsA demonstration of the new tab wrapping property of JTabbedPane.
VBoxA quick test of the BoxLayout manager using the Box utility class. This box is laid out vertically.
Chapter 12
AccessoryFileChooserAn example of the JFileChooser class in action with an accessory. This accessory (see will play simple audio files within the file chooser.
AudioAccessoryAn accessory for JFileChooser that lets you play music clips. Only the simple .au, .aiff and .wav formats available through the Applet sound classes can be played.
ColorPickerA quick test of the JColorChooser dialog.
ColorPicker2A quick test of the JColorChooser dialog. This one installs the custom GrayScalePanel picker tab.
ColorPicker3A quick test of the JColorChooser dialog. This example adds a custom preview pane.
FontChooserA font chooser that allows users to pick a font by name, size, style, and color. The color selection is provided by a JColorChooser pane. This dialog builds an AttributeSet suitable for use with JTextPane.
FontPickerA quick test of the FontChooser dialog. (see
GrayScalePanelA simple implementation of the AbstractColorChooserPanel class. This class provides a slider and a text field for picking out a shade of gray.
MyFilterChooserJust a simple example to see what it takes to make one of these filters work.
MyViewChooserAn example that uses custom file views to show thumbnails of graphic files rather than the regular file icon. (see
SimpleFileChooserA simple file chooser to see what it takes to make one of these work.
SimpleFileFilterA straightforward extension-based example of a file filter. This should be replaced by a "first class" Swing class in a later release of Swing.
ThumbNailFileViewA simple implementation of the FileView class that provides a 16x16 image of each GIF or JPG file for its icon. This could be SLOW for large images, as we simply load the real image and then scale it.
Chapter 13
BevelExampleAn example of borders with a BevelBorder used on JLabels as a highlight as the mouse rolls over them.
CurvedBorderA custom border that draws round rectangle borders.
CurvedExampleA quick program to demonstrate the custom CurvedBorder class. (see
MatteExampleAn example of the MatteBorder class.
RoundedLineBorderA simple demontstration of the LineBorder class built with rounded corners.
TitledExampleAn example of using a titled border on a label.
Chapter 14
CheckBoxMenuItemExampleA quick demonstration of checkbox menu items.
IntroExampleAn introduction to building menus and menu items. Accelerators and mnemonics are added to various items.
MenuElementExampleAn example of the JPopupMenu in action.
MenuExampleA simple example of constructing and using menus.
PopupMenuExampleA simple example of JPopupMenu. (See for another.)
RadioButtonMenuItemExampleAn example of radio button menu items in action.
SeparatorExampleA quick demonstration of the JSeparator() component used in a toolbar-like container.
ToolBarExampleAn example of JToolBar. The actions used to build the toolbar are also placed in a JMenu to further demonstrate the flexibility of the Action class. (See the examples in Chapter 3 for more details on Action.)
Chapter 15
BigRendererA renderer for numbers that shows an icon in front of big numbers.
ColorTableA table that allows the user to pick a color from a pulldown list. This is accomplished by using the DefaultCellRenderer and DefaultCellEditor classes.
ColumnExampleA test of JTable with a custom column model. The model used is a sorting model that keeps columns in alphabetical order. (see
DatabaseTestLet's try to make one of these databases work with a JTable for ouptut.
FileModelA custom table model to display information on a directory of files.
FileTableA test frame for the custom table model, FileModel.
FileTable2A test frame for the custom table model, FileModel. This version uses a custom renderer ( to flag large files with an exclamation point icon.
MYOSMMake Your Own Stock Market: A simple stock market simulator that contains a few stocks and their current prices (and deltas). It randomly adjusts the prices on stocks to give a dynamic feel to the data.
MarketDataModelA custom table model for use with the MYOSM environment.
MarketTableAn application that displays stock market data in a JTable. The table uses the MarketDataModel class for its model. MYOSM should be running to make the data dynamic.
QueryTableModelA basic implementation of the TableModel interface that fills out a Vector of String[] structures from a query's result set.
SelectionExampleA simple multiplication table with the ability to play with row and column selections. You can alter the cell, column and row selection properties of the table at runtime.
SimpleTableA test of the JTable class using default table models and a convenience constructor.
SortingColumnModelA simple extension of the DefaultTableColumnModel class that sorts incoming columns alphabetically. This version is case-sensitive.
StockA simple aggregate class for storing stock market information on a single stock (symbol, price, etc.).
TableFeatureA test of the JTable class using default table models and a convenience constructor. Resizing and selection defaults are altered.
Chapter 16
ArrowIconA simple implementation of the Icon interface that can make Up and Down arrows.
ChartPainterA simple chart-drawing UI base class. This class tracks the basic fonts and colors for various types of charts including pie and bar. The paint() method is abstract and must be implemented by subclasses for each type.
ChartTesterA test harness for the various table charting classes. (see,, and
MixerModelAn audio mixer table data model. This model contains the following columns:
+ Track name (String)
+ Track start time (String)
+ Track stop time (String)
+ Left channel volume (Volume, 0 . . 100)
+ Right channel volume (Volume, 0 . . 100)
MixerTestA test application for showing Volume data in a JTable using the custom VolumneRenderer class.
MixerTest2A test of the MixerModel and sliders for rendering volume values. This version also includes adjustable sliders for editing the volume values.
PagingModelA larger table model that performs "paging" of its data. This model reports a small number of rows (like 100 or so) as a "page" of data. You can switch pages to view all of the rows as needed using the pageDown() and pageUp() methods. Presumably, access to the other pages of data is dictated by other GUI elements such as up/down buttons, or maybe a text field that allows you to enter the page number you want to display.
PagingTesterA quick application that demonstrates the PagingModel.
PagingTester2A quick application that demonstrates the PagingModel. This version has an input field for dynamically altering the size of a page.
PieChartPainterA pie chart implementation of the ChartPainter class.
RecordA simple data structure for use with the PagingModel demo.
RowHeaderTableA simple application that demonstrates the use of the TableColumnModel class to build a row header column that scrolls with the regular data rows.
TableChartA chart-generating class that uses the TableModel interface to get its data.
TableChartPopupA popup framework for showing a chart of table data. This class also turns on tooltips for the chart.
VolumeA simple data structure for managing volumes on a mixer.
VolumeEditorA slider Editor for volume values in a table.
VolumeRendererA slider renderer for volume values in a table.
Chapter 17
EditorComboBoxA CellEditor JComboBox subclass for use with Trees (and possibly tables). This version will work with any list of values passed as an Object[].
EmailEditorAn extension of JTextField that requires an "@" somewhere in the field. Meant to be used as a cell editor within a JTable or JTree.
EmailTreeA simple test to see how we can build a tree and populate it. This application also uses custom renderers and editors.
EmailTreeCellEditorAn editor that actually manages two separate editors: one for folders (nodes) that uses a combo box; and one for files (leaves) that uses a text field.
IconAndTipCarrierA simple interface that can be used with IconAndTipRenderer tree cell renderer.
IconAndTipRendererA renderer for our tree cells that have icons and tooltips.
ObjectTreeA simple test to see how we can build a tree and populate it. This version builds the tree from hashtables.
SortTreeDemoThis class creates a tree model using the SortTreeModel with a File hierarchy as input.
SortTreeModelThis class is similar to the DefaultTreeModel, but it keeps a node's children in alphabetical order.
TestTreeA simple test to see how we can build a tree and populate it. We build the tree structure up by hand in this case.
TestTree3A variation on TestTree that installs custom icons. The icons installed will appear on *every* tree.
TestTree4Another test to see how we can build a tree and customize its icons. This example does not affect the icons of other trees.
TreeEventsAn example of using EEL to show off all the events coming from a tree. You can add and remove nodes and watch for TreeModelEvents as well.
TreeStringComparatorThis class compares the contents of the userObject as strings. It's case-insensitive.
VSXA simple XML parser that builds a tree from SAX events. The xml file should be passed as a command line argument.
VSX2VSX2: A reasonably simple XML utility class. This class has two main methods: parse() and write(). Both work with the TreeModel class and are meant to help you view XML documents with JTree. This version will embed icons and tooltip text in nodes if icon or tiptext attributes are found in the tag.
Chapter 18
ExtendedUndoManagerAn extension of UndoManager that provides two additional features: (1) The ability to add & remove listeners and (2) the ability to gain more extensive access to the edits being managed.
SampleUndoableEditAn example of an undoable edit. Used with the UndoManagerDetails class.
UndoManagerDetailsAn example that shows lots of little UndoManager details
UndoableJToggleButtonSample undoable toggle button class. Supports only a single listener to simplify the code.
UndoableJToggleButton2Sample undoable toggle button class using UndoableEditSupport.
UndoableToggleAppA sample app showing the use of UndoableToggleEdit.
UndoableToggleApp2A sample app showing the use of UndoableToggleEdit and CompoundEdit.
UndoableToggleApp3A sample app showing the use of UndoManager.
UndoableToggleApp4A sample app showing the use of StateEdit(able).
UndoableToggleEditAn UndoableEdit used to undo the pressing of a JToggleButton.
Chapter 19
JTextFieldExampleAn example of setting up a text field and modifying its horizontal alignment at runtime.
OffsetTestShow line start/end offsets in a JTextArea.
TextComponentSamplerAn example of several text components including password fields and formatted fields.
TextFormA simple label/field form panel
WidthHackA hack to make a JTextField _really_ 2 columns wide
Chapter 20
CombinationFormatterInput: string of form "15-45-22" (any number of hyphen-delimeted numbers)
Output: int array
FactoryDemoDemo 1: field with different formats with focus and without.
Demo 2: Change the format of a field when the user presses a button.
FtfInputVerifierAn example of using an InputVerifier with a formatted text field.
RegexPatternFormatterA formatter for regular expressions to be used with JFormattedTextField.
SimpleFTFA quick demonstration of JFormattedTextField.
Chapter 21
CornerCaretA custom caret class.
FancyCaretAnother (fancier) custom caret class.
KeymapExampleA simple example showing how to add Actions for KeyStrokes.
LineHighlightPainterAn implementation of HighlightPainter that underlines text with a thick line.
MultiHighlightAn example of highlighting multiple, discontiguous regions of a text component.
Chapter 22
ColorPaneA simple extension of JTextPane that allows the user to easily append colored text to the document.
LiveParenMatcherLike ParenMatcher but continuously colors as the user edits the document.
MaxLengthDocumentAn extension of PlainDocument that restricts the length of its content.
PaneInsertionMethodsShow how Icons, Components, and text can be added to a JTextPane.
ParenMatcherA simple parenthesis matcher.
StyleBoxA control panel that can be used to edit a style's paragraph attributes.
StyleFrameA JTextPane with a menu for Style manipulation.
TabExampleDemonstrate a TabSet in a JTextPane.
UndoStyleFrameAdd undo support to the StyleFrame example. This example only retains the most recent edit, to keep things simple.
UpcaseFilterA simple DocumentFilter that maps lowercase letters to uppercase.
Chapter 23
DebugHTMLEditorKitA simple extension of the HTMLEditor kit that uses a verbose ViewFactory.
HTMLEditorAn extension of StyledEditor that adds HTML-related features.
HTMLExampleA very simple browser using the basic HTML support built into JEditorPane.
IOStyledEditorAn extension of StyledEditor that adds document serialization.
MiniBrowserAnother implementation of a minimal browser. This one is tracks mouseover events on hyperlinks and shows the destination of the link in a status bar at the bottom of the window.
SimpleEditorAn example showing several DefaultEditorKit features. This class is designed to be easily extended for additional functionality.
SimpleLinkListenerA hyperlink listener for use with JEditorPane. This listener changes the cursor over hyperlinks based on enter/exit events and also loads a new page when a valid hyperlink is clicked.
StyledEditorAn extension of SimpleEditor that adds styled-text features.
StyledEditor2An extension of SimpleEditor that adds styled-text features. This version also adds the ability to save a styled document as an HTML file.
TextActionExampleA simple TextAction example.
Chapter 24
DragTestA test of the DragSource classes to see if we can create a draggable object in a Java application. This version works with 1.3 and higher SDKs.
DragTest14A test of the drag capabilities built into the JDK 1.4.
DropTestA simple drag & drop tester application.
DropTest14A simple drop tester application for JDK 1.4 Swing components.
DropTest2Another simple drag & drop tester application.
FSTestA quick test environment for the FSTree component.
FSTreeA sample component for dragging & dropping a collection of files into a tree.
GestureTestA test of the DragGesture classes to see if we can recognize a simple drag gesture.
TransferableTreeNodeA Transferable TreePath to be used with Drag & Drop applications.
TreeDragSourceA drag source wrapper for a JTree. This class can be used to make a rearrangeable DnD tree with the TransferableTreeNode class as the transfer data type.
TreeDragTestA simple starting point for testing the DnD JTree code.
TreeDropTargetA quick DropTarget that's looking for drops from draggable JTrees.
UTestA test framework for the UberHandler drop handler. This version has no fancy Unicode characters for ease of use. (Note that "ease of use" only applies to humans...the Java tools are quite happy with Unicode characters. Not all text editors are, though...)
UberHandlerA TransferHandler that will accept any drop at all. If a text area is registered, debugging information will be sent there. Otherwise, all debug information will be sent to stdout.
Chapter 25
ActionExampleAn example of getting the Accessible information from a Button object. (You could see this information by attaching an AssistiveExample object to the button. See for an example of that attachment.)
AssistiveExampleA GUI to show accessible information coming from the components in an application. See for example of how to use this class.
BigExampleA quick (contrived) application to create some accessible components for viewing through the AssistiveExample GUI.
Chapter 26
MetalModExampleAn example of modifying an existing L&F. This example replaces the standard scrollbar UI with a custom version.
MyMetalScrollBarUIA simple extension of MetalScrollBarUI that draws the thumb as a solid black rectangle.
RedThemeA "Mars" theme for Metal. All of the primary colors used by Metal are set to shades of red.
ResourceModExampleAn example of using UIManager resources to tweak the look of applications.
StdOutButtonUIAn alternate button resource that dumps accessibility information when it gains or loses focus.
StdOutLookAndFeelA *simple* L&F that puts our StdOutButton to work. UIs for all the other components would be needed to make this L&F truly functional.
UIManagerDefaultsAn informational utility to print the various UIManager defaults.
Chapter 27
ClockLabelAn extension of the JLabel class that listens to events from a Timer object to update itself with the current date & time.
ClockTestA demonstration framework for the Timer driven ClockLabel class
SecretLabelAn extension of the JLabel class that listens to mouse clicks and converts them to ActionEvents, which in turn are reported via an EventListenersList object
SecretTestA demonstration framework for the EventListenerList-enabled SecretLabel class
Chapter 28
AlphaButtonPolicyA custom focus traversal policy that uses alphabetical ordering of button labels to determine "next" and "previous" buttons for keyboard traversal.
BasicJogShuttleUIA UI class for our custom JogShuttle component.
FocusExampleAn example of focus traversal using the keyboard to navigate through a small set of buttons.
FocusTraversalExampleSimilar to the FocusExample, this class uses the custom AlphaButtonPolicy focus traversal policy to navigate another small set of buttons.
InvokeExampleThis class demonstrates several examples of how to handle long-running tasks (such as querying a remote resource). Some of the examples are good, and some are not!
JogShuttleA custom jog shuttle component. (Some VCRs have such a thing for doing variable speed fast-forward and fast-reverse.) An example of using the JogShuttle can be found in
JogShuttleUIFill out the proper UIClassID information for our JogShuttle.
SimpleModelAn example of a custom data model that could be used in any MVC scenario.
SimpleModelInterfaceAn example of a data model interface that could be used in any MVC scenario. This interface is implemented in the SimpleModel class.
SketchA sketching application with two dials: one for horizontal movement, one for vertical movement. The dials are instances of the JogShuttle class.

Copyright 2003, O'Reilly & Associates