net.mariottini.swing
Class JFontChooser

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by net.mariottini.swing.JFontChooser
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable

public final class JFontChooser
extends JComponent

A dialog box that lets the user choose a font.

An average choose font dialog is like this:

If you want you can hide the sample text area:

It can also show a custom accessory component, with wich you can control the functioning of the dialog box:

In this case the accessory component is a list that changes the sample text.

License:
  Copyright © 2006, 2007 Roberto Mariottini. All rights reserved.

  Permission is granted to anyone to use this software in source and binary forms
  for any purpose, with or without modification, including commercial applications,
  and to alter it and redistribute it freely, provided that the following conditions
  are met:

  o  Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
  o  The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  o  Altered source versions must be plainly marked as such, and must not
     be misrepresented as being the original software.
 
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.
 

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Field Summary
static int APPROVE_OPTION
          showDialog returns this value if the user has approved (chosen) a font.
static String APPROVE_SELECTION
          Action command used to notify that the user has approved (chosen) a font.
static int CANCEL_OPTION
          showDialog returns this value if the user has not chosen a font.
static String CANCEL_SELECTION
          Action command used to notify that the user has not chosen a font.
static String FONT_NAME_CHANGED_PROPERTY
          Name of the property used to notify that the user has changed the selected font name in the name list.
static String FONT_SIZE_CHANGED_PROPERTY
          Name of the property used to notify that the user has changed the selected font size in the size list or in the size text field.
static String FONT_STYLE_CHANGED_PROPERTY
          Name of the property used to notify that the user has changed the selected font style in the style list.
 
Fields inherited from class javax.swing.JComponent
TOOL_TIP_TEXT_KEY, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JFontChooser()
          Construct a font chooser with all the available fonts, showing a sample to the user.
JFontChooser(boolean showSample)
          Construct a font chooser with all the available fonts, optionally showing a sample to the user.
JFontChooser(String[] fontNames)
          Construct a font chooser with the specified fonts, showing a sample to the user.
JFontChooser(String[] fontNames, boolean showSample)
          Construct a font chooser with the specified fonts, optionally showing a sample to the user.
 
Method Summary
 void addActionListener(ActionListener listener)
          Adds an action listener to this component.
 void approveSelection()
          Called when the user approves a font.
 void cancelSelection()
          Called when the user cancels the operation.
 JComponent getAccessory()
          Returns the accessory component.
 JComponent getSampleComponent()
          Returns the component used to show the font sample.
 Font getSelectedFont()
          Returns the currently selected font.
 boolean isSampleVisible()
          Returns the sample panel visibility status.
 void removeActionListener(ActionListener listener)
          Remove an action listener from this component.
 void setAccessory(JComponent newAccessory)
          Sets the accessory component.
 void setFontNames(String[] fontNames)
          change the font names to show in the font list.
 void setSampleText(String text)
          Set the string to use as a sample for the fonts.
 void setSampleVisible(boolean visible)
          Shows/hides the sample panel.
 void setSelectedFont(Font font)
          Sets the currently selected font.
 int showDialog(Component parent)
          Show a modal "Choose Font" dialog.
 int showDialog(Component parent, String title)
          Show a modal "Choose Font" dialog with the specified title.
 int showDialog(Component parent, String title, boolean modal)
          Show a "Choose Font" dialog with the specified title and modality.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintImmediately, paintImmediately, print, printAll, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, contains, createImage, createImage, createVolatileImage, createVolatileImage, dispatchEvent, enable, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

APPROVE_OPTION

public static final int APPROVE_OPTION
showDialog returns this value if the user has approved (chosen) a font.

See Also:
showDialog(java.awt.Component), Constant Field Values

CANCEL_OPTION

public static final int CANCEL_OPTION
showDialog returns this value if the user has not chosen a font.

See Also:
showDialog(java.awt.Component), Constant Field Values

APPROVE_SELECTION

public static final String APPROVE_SELECTION
Action command used to notify that the user has approved (chosen) a font.

See Also:
addActionListener(java.awt.event.ActionListener), Constant Field Values

CANCEL_SELECTION

public static final String CANCEL_SELECTION
Action command used to notify that the user has not chosen a font.

See Also:
addActionListener(java.awt.event.ActionListener), Constant Field Values

FONT_NAME_CHANGED_PROPERTY

public static final String FONT_NAME_CHANGED_PROPERTY
Name of the property used to notify that the user has changed the selected font name in the name list. This property is of type String.

See Also:
Container.addPropertyChangeListener(java.beans.PropertyChangeListener), Constant Field Values

FONT_STYLE_CHANGED_PROPERTY

public static final String FONT_STYLE_CHANGED_PROPERTY
Name of the property used to notify that the user has changed the selected font style in the style list. This property is of type Integer, and can assume the following values: Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC.

See Also:
Container.addPropertyChangeListener(java.beans.PropertyChangeListener), Constant Field Values

FONT_SIZE_CHANGED_PROPERTY

public static final String FONT_SIZE_CHANGED_PROPERTY
Name of the property used to notify that the user has changed the selected font size in the size list or in the size text field. This property is of type Integer.

See Also:
Container.addPropertyChangeListener(java.beans.PropertyChangeListener), Constant Field Values
Constructor Detail

JFontChooser

public JFontChooser(String[] fontNames,
                    boolean showSample)
Construct a font chooser with the specified fonts, optionally showing a sample to the user. The sample text is a default text, you can change it by calling setSampleText.

Parameters:
fontNames - the font family names to show to the user.
showSample - true to show a sample of the selected font to the user.
See Also:
setSampleText(java.lang.String)

JFontChooser

public JFontChooser(String[] fontNames)
Construct a font chooser with the specified fonts, showing a sample to the user. The sample text is a default text, you can change it by calling setSampleText.

Parameters:
fontNames - the font family names to show to the user.
See Also:
setSampleText(java.lang.String)

JFontChooser

public JFontChooser(boolean showSample)
Construct a font chooser with all the available fonts, optionally showing a sample to the user. The sample text is a default text, you can change it by calling setSampleText. The font list is acquired by calling GraphicsEnvironment.getAvailableFontFamilyNames().

Parameters:
showSample - true to show a sample of the selected font to the user.
See Also:
setSampleText(java.lang.String)

JFontChooser

public JFontChooser()
Construct a font chooser with all the available fonts, showing a sample to the user. The sample text is a default text, you can change it by calling setSampleText. The font list is acquired by calling GraphicsEnvironment.getAvailableFontFamilyNames().

See Also:
setSampleText(java.lang.String)
Method Detail

setFontNames

public void setFontNames(String[] fontNames)
change the font names to show in the font list.

Parameters:
fontNames - the font family names to show to the user.

setSampleText

public void setSampleText(String text)
Set the string to use as a sample for the fonts. Pass null to use the currently selected font family name as sample.

Parameters:
text - the sample string, or null to use the font family name as sample.

setSampleVisible

public void setSampleVisible(boolean visible)
Shows/hides the sample panel.

Parameters:
visible - true to show it, false to hide it.

isSampleVisible

public boolean isSampleVisible()
Returns the sample panel visibility status.

Returns:
true if it's visible, false if it's hidden.

getSampleComponent

public JComponent getSampleComponent()
Returns the component used to show the font sample. This function is provided to customize the appearance of the component, in particular foreground and background colors. There's no way to change this component, to customize deeper the sample panel hide it and use the accessory component instead.

Returns:
the sample component.
See Also:
setAccessory(javax.swing.JComponent)

getAccessory

public JComponent getAccessory()
Returns the accessory component.

Returns:
the accessory component.
See Also:
setAccessory(javax.swing.JComponent)

setAccessory

public void setAccessory(JComponent newAccessory)
Sets the accessory component. The accessory component is used to customize the dialog. You can use a single component or a container with many components of your choice to extend the functionality of the dialog. Register the appropriate listeners to react to user input. The accessory component will become part of the dialog, and will be disposed along with it: remove it before disposal if you want to preserve it.

Parameters:
newAccessory - the accessory component to use, or null to hide and remove any accessory component previously set.
See Also:
addActionListener(java.awt.event.ActionListener), Container.addPropertyChangeListener(java.beans.PropertyChangeListener), FONT_NAME_CHANGED_PROPERTY, FONT_STYLE_CHANGED_PROPERTY, FONT_SIZE_CHANGED_PROPERTY

addActionListener

public void addActionListener(ActionListener listener)
Adds an action listener to this component. The actionPerformed method will be called when the user press one of the two buttons "OK" and "Cancel". The two different action command used are APPROVE_SELECTION and CANCEL_SELECTION.

Parameters:
listener - the listener to add to the listeners list.
See Also:
APPROVE_SELECTION, CANCEL_SELECTION

removeActionListener

public void removeActionListener(ActionListener listener)
Remove an action listener from this component.

Parameters:
listener - the listener to remove from the list.
See Also:
addActionListener(java.awt.event.ActionListener)

approveSelection

public void approveSelection()
Called when the user approves a font. Call this method to close the dialog and approve the currently selected font.


cancelSelection

public void cancelSelection()
Called when the user cancels the operation. Call this method to close the dialog without selecting a font.


getSelectedFont

public Font getSelectedFont()
Returns the currently selected font. The Font object returned comprehends the style and size chosen by the user.

Returns:
the currently selected font.

setSelectedFont

public void setSelectedFont(Font font)
Sets the currently selected font. The dialog will try to change the listboxes selections according to the font set.

Parameters:
font - the font to select.

showDialog

public int showDialog(Component parent)
Show a modal "Choose Font" dialog.

Parameters:
parent - the parent component, or null to use a default root frame as parent.
Returns:
APPROVE_OPTION if the user chose a font, CANCEL_OPTION if the user canceled the operation.
See Also:
APPROVE_OPTION, CANCEL_OPTION

showDialog

public int showDialog(Component parent,
                      String title)
Show a modal "Choose Font" dialog with the specified title.

Parameters:
parent - the parent component, or null to use a default root frame as parent.
title - the title for the dialog.
Returns:
APPROVE_OPTION if the user chose a font, CANCEL_OPTION if the user canceled the operation.
See Also:
APPROVE_OPTION, CANCEL_OPTION

showDialog

public int showDialog(Component parent,
                      String title,
                      boolean modal)
Show a "Choose Font" dialog with the specified title and modality.

Parameters:
parent - the parent component, or null to use a default root frame as parent.
title - the title for the dialog.
modal - true to show a modal dialog, false to show a non-modal dialog (in this case the function will return immediately after making visible the dialog).
Returns:
APPROVE_OPTION if the user chose a font, CANCEL_OPTION if the user canceled the operation. CANCEL_OPTION is always returned for a non-modal dialog, use an ActionListener to be notified when the user approves/cancels the dialog.
See Also:
APPROVE_OPTION, CANCEL_OPTION, addActionListener(java.awt.event.ActionListener)


Copyright © 2006, 2007 Roberto Mariottini. All Rights Reserved.