Program: Custom Font Chooser
Problem
You want to allow the user to select a font, but standard Java doesn’t yet include a Font Chooser dialog.
Solution
Use my FontChooser
dialog class.
Discussion
As we saw in Section 12.4, you can manually select a
font by calling the
java.awt.Font
class constructor, passing in the name of
the font, the type you want (plain, bold, italic, or bold+italic),
and the point size:
Font f = new Font("Helvetica", Font.BOLD, 14); setfont(f);
But this is not very flexible for interactive applications. You normally want the user to be able to choose fonts with the same ease as using a File Chooser dialog. Until the Java API catches up with this, you are more than welcome to use the Font Chooser that I wrote when faced with a similar need.
The source code is shown in Example 13-7; it ends, as many of my classes do, with a short main method that is both a test case and an example of using the class in action. The display is shown in Figure 13-13.
Example 13-7. FontChooser.java
import com.darwinsys.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** A font selection dialog. AWT version. * <p>Note: can take a LONG time to start up on systems * with (literally) hundreds of fonts. */ public class FontChooser extends Dialog { /** The font the user has chosen */ protected Font resultFont; /** The resulting font name */ protected String resultName; /** The resulting font size */ protected int resultSize; /** The resulting boldness */ protected boolean ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.