(How to) Create a Font Dialog With Java
How to : Create a Font Dialog With Java
Introduction
As the culminating project for last semester’s Java programming class, I demonstrated how to emulate the features found in Windows Notepad in a Java application. Most of the algorithms were routine as the Java API is pretty robust. The one glaring omission in the API is a dialog analogous to the JFileChooser or JColorChooser to choose a font. Rather than omit the ability to choose a font, I chose to implement it myself.
The requirements for the font dialog were straightforward:
- The dialog must display all the available fonts on the user’s system.
- The user must be able to manipulate the font’s family, style, and size.
- The implementation must include a preview of the font.
- The implementation must expose a font object for use elsewhere.
Using the code
Layout the form
The code for the GUI aspects of the dialog is contained within the initComponents() method. I used a BorderLayout as the main layout for the form. The center component is a JPanel which uses a GridLayout manager. The GridLayout itself contains two JPanels – one for the user controls (fontPanel) and one for the preview (previewPanel). The user control panel uses the GridBagLayout manager and the preview panel uses a BorderLayout. The south component of the main BorderLayout contains the third significant panel for the buttons on the form (buttonPanel), and it uses a FlowLayout with the components aligned on the right side of the panel. All of the code is available in the code listing.
The initComponents() method also does a number of other things: it declares and initializes the components, and creates anonymous inner listener classes for each of the controls that need them. I used three JList components as the user controls in the dialog – one to list the available font families (lstFont), one to list the available styles (lstStyle), and one to list the potential sizes (lstSize). It also positions the dialog in the middle of the user’s screen upon creation.
The code that initiates the font family list box is the only noteworthy code in the initComponents() method:
Courtesy :- Codeproject.com
- guru's blog
- Login to post comments
