O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required