com.ccg.swing
Class TextFieldFormat

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.text.JTextComponent
                  extended by javax.swing.JTextField
                      extended by com.ccg.swing.TextFieldFormat
All Implemented Interfaces:
ActionListener, ImageObserver, MenuContainer, Serializable, EventListener, Accessible, Scrollable, SwingConstants, TableCellRenderer
Direct Known Subclasses:
DateFieldFormat, DoubleFieldFormat, IntegerFieldFormat

public class TextFieldFormat
extends JTextField
implements ActionListener, TableCellRenderer

Class to create text input fields that have a corresponding parser.

Often one needs to gather input from users for Object types which are not strings. For example, if one wants the user to enter a integer number, there is not a each GUI component that can be created to facilitate this.

This class allows one to associate a Format object with a text field component. In doing so, one gets the string->object and object->string translation for free.

The easy way to use this class is to see if one of the static creation methods will suit your needs. If the static methods won't work for you, then take the following approach:

Since:
1.0
Version:
$Revision: 1.4 $
Author:
$Author: pkb $
See Also:
Format, Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JTextField
JTextField.AccessibleJTextField
 
Nested classes/interfaces inherited from class javax.swing.text.JTextComponent
JTextComponent.AccessibleJTextComponent, JTextComponent.KeyBinding
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
 
Fields inherited from class javax.swing.JTextField
notifyAction
 
Fields inherited from class javax.swing.text.JTextComponent
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, 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 javax.swing.SwingConstants
BOTTOM, CENTER, EAST, HORIZONTAL, LEADING, LEFT, NEXT, NORTH, NORTH_EAST, NORTH_WEST, PREVIOUS, RIGHT, SOUTH, SOUTH_EAST, SOUTH_WEST, TOP, TRAILING, VERTICAL, WEST
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
TextFieldFormat(Format f)
          Construct with a specific Format for translating between object/string representation.
 
Method Summary
 void actionPerformed(ActionEvent e)
          Handle the action event (when user presses enter on text field).
static TextFieldFormat createDateEntry(DateFormat df, Date init, TimeSpan ts)
          Create a date entry field (where user can type strings like: "1963-Dec-25").
static TextFieldFormat createDoubleEntry(NumberFormat nf, double init, double min, double max)
          Create a double entry field (where user can type strings like: "550.2457").
static TextFieldFormat createIntegerEntry(NumberFormat nf, int init, int min, int max)
          Create a integer entry field (where user can type strings like: "550").
 Format getFormat()
          Get the format/parse object used to go between a String and the object's native form.
 Object getObject()
          Get the Object which this field is used to edit
 Component getTableCellRendererComponent(JTable table, Object val, boolean isSelected, boolean hasFocus, int row, int col)
          Allows component to be used as a JTable cell renderer.
 boolean isNullAllowed()
          Indicates whether "blank" or null values are permitted.
 void setFormat(Format val)
          Set the format/parse object used to go between a String and the object's native form
 void setNullAllowed(boolean val)
          Set whether "blank" or null values permitted.
 void setObject(Object val)
          Set the Object which this field is used to edit
 Object validateText()
          Validate user input WITHOUT updating internal state of object.
 boolean validateTextOrFix()
          Validate user input and update internal state of object (or "fix" user input).
 boolean validateUserInput()
          Deprecated.  
 
Methods inherited from class javax.swing.JTextField
addActionListener, configurePropertiesFromAction, createActionPropertyChangeListener, createDefaultModel, fireActionPerformed, getAccessibleContext, getAction, getActionListeners, getActions, getColumns, getColumnWidth, getHorizontalAlignment, getHorizontalVisibility, getPreferredSize, getScrollOffset, getUIClassID, isValidateRoot, paramString, postActionEvent, removeActionListener, scrollRectToVisible, setAction, setActionCommand, setColumns, setDocument, setFont, setHorizontalAlignment, setScrollOffset
 
Methods inherited from class javax.swing.text.JTextComponent
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paste, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, write
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, 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, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, 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, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

TextFieldFormat

public TextFieldFormat(Format f)
Construct with a specific Format for translating between object/string representation.

Parameters:
fmt - The format object to use to convert to/from the string representation.
Method Detail

actionPerformed

public void actionPerformed(ActionEvent e)
Handle the action event (when user presses enter on text field).

If the user presses the enter key after typing in some text, we validate what they entered - if what is entered is invalid, we silently replace it with the last valid value.

Specified by:
actionPerformed in interface ActionListener
Parameters:
ae - ActionEvent which triggered event - we ignore call back if the source is NOT from this component.
Since:
1.0
See Also:
validateTextOrFix()

validateText

public Object validateText()
                    throws IllegalStateException
Validate user input WITHOUT updating internal state of object.

This method verifies that what the user has entered is correct for the format associated with the component. It returns the resulting value (if user entry is valid). It is possible that this method will return null, if you indicate that the field is optional (and the user is allowed to leave it blank).

It should be noted, that this only verifies that the user input is valid - it doesn't actually update the internal state of the component. You may want to pass the value returned to the setObject method if you want to update the internal state of the object.

This method is provided mainly for the purpose of checking multiple fields on a panel PRIOR to accepting ANY of the values. If you simply want to validate and update the internal state (or possibly fix a bad value), you may want to use the validateTextOrFix() method.

Returns:
The resulting object from parsing the text entered by the user (possibly null if you permit empty entries and user didn't enter anything).
Throws:
IllegalStateException - If the text entered is not valid for the format rules.
Since:
1.0

validateTextOrFix

public boolean validateTextOrFix()
Validate user input and update internal state of object (or "fix" user input).

This method verifies that what the user has entered is correct for the format associated with the component. If the user input is valid, then the internal representation is updated to correspond to the text entered, reformatted and shown in the text area. If the user intput is invalid, then the prior valid value is restored.

Returns:
true if user input was accepted, false if old value was restored.
Since:
1.0

validateUserInput

public final boolean validateUserInput()
Deprecated. 

Deprecated - use validateTextOrFix or validateText instead.

Returns:
true if user input was accepted, false if old value was restored.
Since:
1.0
See Also:
validateTextOrFix()

setFormat

public void setFormat(Format val)
Set the format/parse object used to go between a String and the object's native form

Parameters:
val - New Format value to assign.
See Also:
getFormat()

getFormat

public Format getFormat()
Get the format/parse object used to go between a String and the object's native form.

Returns:
Current Format value assigned.
See Also:
setFormat(java.text.Format)

setObject

public void setObject(Object val)
               throws ParseException
Set the Object which this field is used to edit

Parameters:
val - New Object value to assign.
Throws:
ParseException
See Also:
getObject()

getObject

public Object getObject()
Get the Object which this field is used to edit

Returns:
Current Object value assigned.
See Also:
setObject(java.lang.Object)

getTableCellRendererComponent

public Component getTableCellRendererComponent(JTable table,
                                               Object val,
                                               boolean isSelected,
                                               boolean hasFocus,
                                               int row,
                                               int col)
Allows component to be used as a JTable cell renderer.

Specified by:
getTableCellRendererComponent in interface TableCellRenderer
Parameters:
table - Table the which is to use this object as a renderer.
val - The value to put into the component.
sel - Whether the component is selected.
hasFocus - Whether the component has the focus.
row - Row index in table - ignored.
col - Column index in table - ignored.
Returns:
Reference to self.
Since:
1.0

setNullAllowed

public void setNullAllowed(boolean val)
Set whether "blank" or null values permitted.

Parameters:
val - New boolean value to assign. see #getNullAllowed

isNullAllowed

public boolean isNullAllowed()
Indicates whether "blank" or null values are permitted.

Returns:
Current boolean value assigned. see #setNullAllowed

createDateEntry

public static TextFieldFormat createDateEntry(DateFormat df,
                                              Date init,
                                              TimeSpan ts)
Create a date entry field (where user can type strings like: "1963-Dec-25").

Parameters:
df - The DateFormat to use for the parsing date information (may be null in which case we'll use a ISO looking version).
init - Initial date to start with. May be null in which case will either use the earlies time in the time span allowed, or the current time if no time span limit is in affect.
ts - The TimeSpan to enforce. This may be null if ALL dates are accepted.
Returns:
A new TextFieldFormat that can validate a user's input.
Since:
1.0

createIntegerEntry

public static TextFieldFormat createIntegerEntry(NumberFormat nf,
                                                 int init,
                                                 int min,
                                                 int max)
Create a integer entry field (where user can type strings like: "550").

Parameters:
nf - The NumberFormat to use for the parsing integer values with (may be null in which case we'll create what we think is best).
init - Initial value to start with.
min - The minimim value allowed (use Integer.MIN_VALUE for no minimum).
max - The maximim value allowed (use Integer.MAX_VALUE for no minimum). Must be larger or equal to min.
Returns:
A new TextFieldFormat that can validate a user's input.
Since:
1.0

createDoubleEntry

public static TextFieldFormat createDoubleEntry(NumberFormat nf,
                                                double init,
                                                double min,
                                                double max)
Create a double entry field (where user can type strings like: "550.2457").

Parameters:
nf - The NumberFormat to use for the parsing double values with (may be null in which case we'll create what we think is best - kind of a HP looking form).
init - Initial value to start with.
min - The minimim value allowed (use Double.MIN_VALUE for no minimum).
max - The maximim value allowed (use Double.MAX_VALUE for no minimum). Must be larger or equal to min.
Returns:
A new TextFieldFormat that can validate a user's input.
Since:
1.0


Copyright 1998-1998-2006 null. All Rights Reserved.