Skip to Main Content
Java Swing, 2nd Edition
book

Java Swing, 2nd Edition

by Dave Wood, Robert Eckstein, Marc Loy, James Elliott, Brian Cole
November 2002
Intermediate to advanced content levelIntermediate to advanced
1278 pages
38h 26m
English
O'Reilly Media, Inc.
Content preview from Java Swing, 2nd Edition

Developing a Custom Dialog

While you might rely entirely on the standard color chooser dialog, it is possible to create a color chooser component and use it inside your own dialogs or applications. Let’s take a look at a fancy font chooser that lets you pick the face, style, and color. Figure 12-10 shows an example of such a dialog.

A custom dialog window, with a JColorChooser as one piece of it

Figure 12-10. A custom dialog window, with a JColorChooser as one piece of it

It looks like a lot is going on in the code that built this dialog window, but it’s not really that bad. The first part of the code is devoted to the tedious business of setting up the graphical-interface pieces. Notice that we create a regular JColorChooser object and never call either the showDialog( ) or createDialog( ) methods. You can also see the piece of code required to catch color updates in that section. We attach a ChangeListener to the ColorSelectionModel for the chooser. The event handler for that listener simply calls updatePreviewColor( ) to keep our custom previewer in sync with the color shown in the chooser.

You’ll notice that we’re storing our font information in a SimpleAttributeSet object. This object is used with the JTextPane class (and you can find out more about it in Chapter 22). For right now, just know that it has some convenient methods for storing text attributes, such as the font name, bold/italic, and size.

Here’s the startup code:

// FontChooser.java ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Threads, 3rd Edition

Java Threads, 3rd Edition

Scott Oaks, Henry Wong

Publisher Resources

ISBN: 0596004087Errata PageSupplemental Content