org.freixas.jcalendar
Class JCalendarCombo

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JComboBox
                  extended by org.freixas.jcalendar.JCalendarCombo
All Implemented Interfaces:
ActionListener, ImageObserver, ItemSelectable, MenuContainer, Serializable, EventListener, Accessible, ListDataListener

public class JCalendarCombo
extends JComboBox

This class is a combo box that allows you to select a date either by typing one in (if the combo box is editable) or through a JCalendar pop-up. Normally, a combo box expects to use a a popup that contains a list. We've perverted this a bit; while you can select a variety of dates, the list always has one item which changes to match the selected date.

You may specify a font for each of the elements that make up the pop-up calendar. If you do not specify a font (or specify a null font), a reasonable default will be generated based on the current Look & Feel.

The JCalendarCombo uses a non-mutable ComboBoModel. This means that the following methods will generate an exception:

You would be ill-advised to to call setModel() with your own ComboBoxModel unless you use some variant of a JCalendarCombo.CalendarComboBoxModel class.

The combo box listeners work pretty much as for normal combo boxes. The item changed event reports the date "unselected" (the previous date) and "selected" (the new date set), but as Strings. It's probably better to add a DateListener and ignore the ItemListener and ActionListener.

The following key bindings should work (some may depend on the selected Look-and-Feel):

This component tries to adapt it's Look-and-Feel to match the current Look-and-Feel. But it can only do so for Look-and-Feels's that it knows about. To adapt it for new Look-and-Feels, create a sub-class:


  public class MyCalendarCombo extends JCalendarCombo {
    public void updateUI() {
      ComboBoxUI cui = (ComboBoxUI)UIManager.getUI(this);
      if (cui instanceof SomeLAFComboBoxUI) {
        cui = new SomeLAFCalComboBoxUI();
      }
      else {
        super.updateUI();
      }
    }
    private class SomeLAFCalComboBoxUI extends SomeLAFComboBoxUI {
      return new CalendarComboPopup();
    }
  }
 
If it can't figure out an appropriate Look-and-Feel, it uses the Metal Look-and-Feel.

Author:
Antonio Freixas
See Also:
Serialized Form

Nested Class Summary
protected  class JCalendarCombo.CalendarComboBoxModel
           
protected  class JCalendarCombo.CalendarComboPopup
           
 
Nested classes/interfaces inherited from class javax.swing.JComboBox
JComboBox.AccessibleJComboBox, JComboBox.KeySelectionManager
 
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
static int DISPLAY_DATE
          Used to indicate that this component should display the date.
static int DISPLAY_TIME
          Used to indicate that this component should display the time.
 
Fields inherited from class javax.swing.JComboBox
actionCommand, dataModel, editor, isEditable, keySelectionManager, lightWeightPopupEnabled, maximumRowCount, renderer, selectedItemReminder
 
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 java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JCalendarCombo()
          Create an instance of JCalendarCombo using the default calendar and locale.
JCalendarCombo(Calendar calendar, Locale locale, int selectedComponents, boolean isTodayDisplayed)
          Create an instance of JCalendarCombo using the given calendar and locale.
JCalendarCombo(Calendar calendar, Locale locale, int selectedComponents, boolean isTodayDisplayed, String timePattern)
          Create an instance of JCalendarCombo using the given calendar and locale.
JCalendarCombo(int selectedComponents, boolean isTodayDisplayed)
          Create an instance of JCalendarCombo using the default calendar and locale.
 
Method Summary
 void addDateListener(DateListener listener)
          Add a date listener.
 Calendar getCalendar()
          Get a copy of the calendar used by this JCalendar.
 Date getDate()
          Get the date currently displayed by the calendar panel.
 DateFormat getDateFormat()
          Get the date format used to display the selected date in the combo box's text field.
 Font getDayFont()
          Get the day font.
 Font getDayOfWeekFont()
          Get the day-of-week font (Mon, Tue, etc.).
 Locale getLocale()
          Return the locale used by this JCalendar.
 Font getTimeFont()
          Get the time spinner font.
 Font getTitleFont()
          Get the title font.
 Font getTodayFont()
          Get the font used to display today's date as text.
 boolean isNullAllowed()
          Get whether a null date is allowed.
 boolean isTodayDisplayed()
          Returns true if today's date is displayed at the bottom of the calendar.
protected  String paramString()
          
 void removeDateListener(DateListener listener)
          Remove a date listener.
 void setDate(Date date)
          Set the calendar panel to display the given date.
 void setDateFormat(DateFormat dateFormat)
          Set the date format used to display the selected date in the combo box's text field.
 void setDayFont(Font font)
          If the font is set to null, then the day font will default to 9/11th's of the L&F's Button default font.
 void setDayOfWeekFont(Font font)
          If the font is set to null, then the day-of-week font (Mon, Tue, etc.) will default to 9/11th's of the L&F's Label default font.
 void setKeySelectionManager(JComboBox.KeySelectionManager aManager)
          This method is ignored.
 void setNullAllowed(boolean isNullAllowed)
          Set whether a null date is allowed.
 void setSelectedItem(Object anObject)
          Sets the selected item in the combo box display area to the object in the argument.
 void setTimeFont(Font font)
          If the font is set to null, then the time spinner font will default to the L&F's Spinner default font.
 void setTitleFont(Font font)
          If the font is set to null, then the title font (for the Month Year title) will default to the L&F's Label default font.
 void setTodayFont(Font font)
          If the font is set to null, then the font used to display today's date as text will default to the L&F's Label default font.
protected  Date stringToDate(String string)
          Given a date in String form, convert it to a Date object.
 void updateUI()
          Resets the UI property to a value from the current look and feel.
 
Methods inherited from class javax.swing.JComboBox
actionPerformed, addActionListener, addItem, addItemListener, addPopupMenuListener, configureEditor, configurePropertiesFromAction, contentsChanged, createActionPropertyChangeListener, createDefaultKeySelectionManager, fireActionEvent, fireItemStateChanged, firePopupMenuCanceled, firePopupMenuWillBecomeInvisible, firePopupMenuWillBecomeVisible, getAccessibleContext, getAction, getActionCommand, getActionListeners, getEditor, getItemAt, getItemCount, getItemListeners, getKeySelectionManager, getMaximumRowCount, getModel, getPopupMenuListeners, getPrototypeDisplayValue, getRenderer, getSelectedIndex, getSelectedItem, getSelectedObjects, getUI, getUIClassID, hidePopup, insertItemAt, installAncestorListener, intervalAdded, intervalRemoved, isEditable, isLightWeightPopupEnabled, isPopupVisible, processKeyEvent, removeActionListener, removeAllItems, removeItem, removeItemAt, removeItemListener, removePopupMenuListener, selectedItemChanged, selectWithKeyChar, setAction, setActionCommand, setEditable, setEditor, setEnabled, setLightWeightPopupEnabled, setMaximumRowCount, setModel, setPopupVisible, setPrototypeDisplayValue, setRenderer, setSelectedIndex, setUI, showPopup
 
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, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, 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, addInputMethodListener, 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, getInputMethodRequests, getKeyListeners, 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, processInputMethodEvent, processMouseWheelEvent, 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
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DISPLAY_DATE

public static final int DISPLAY_DATE
Used to indicate that this component should display the date.

See Also:
Constant Field Values

DISPLAY_TIME

public static final int DISPLAY_TIME
Used to indicate that this component should display the time.

See Also:
Constant Field Values
Constructor Detail

JCalendarCombo

public JCalendarCombo()
Create an instance of JCalendarCombo using the default calendar and locale. Display the date but not the time. Don't display today's date.


JCalendarCombo

public JCalendarCombo(int selectedComponents,
                      boolean isTodayDisplayed)
Create an instance of JCalendarCombo using the default calendar and locale. Display a calendar and a time spinner as requested (to display both use DISPLAY_DATE | DISPLAY_TIME). Display today's date if requested. Use the default pattern to display the time in the time spinner field (if there is one).

Parameters:
selectedComponents - Use DISPLAY_DATE, DISPLAY_TIME or (DISPLAY_DATE | DISPLAY_TIME).
isTodayDisplayed - True if today's date should be displayed.

JCalendarCombo

public JCalendarCombo(Calendar calendar,
                      Locale locale,
                      int selectedComponents,
                      boolean isTodayDisplayed)
Create an instance of JCalendarCombo using the given calendar and locale. Display a calendar and a time spinner as requested (to display both use DISPLAY_DATE | DISPLAY_TIME). Display today's date if requested. Use the default pattern to display the time in the time spinner field (if there is one).

Parameters:
calendar - The calendar to use.
locale - The locale to use.
selectedComponents - Use DISPLAY_DATE, DISPLAY_TIME or (DISPLAY_DATE | DISPLAY_TIME).
isTodayDisplayed - True if today's date should be displayed.

JCalendarCombo

public JCalendarCombo(Calendar calendar,
                      Locale locale,
                      int selectedComponents,
                      boolean isTodayDisplayed,
                      String timePattern)
Create an instance of JCalendarCombo using the given calendar and locale. Display a calendar and a time spinner as requested (to display both use DISPLAY_DATE | DISPLAY_TIME). Display today's date if requested. Use the default pattern to display the time in the time spinner field (if there is one).

Parameters:
calendar - The calendar to use.
locale - The locale to use.
selectedComponents - Use DISPLAY_DATE, DISPLAY_TIME or (DISPLAY_DATE | DISPLAY_TIME).
isTodayDisplayed - True if today's date should be displayed.
See Also:
DateFormat, SimpleDateFormat
Method Detail

addDateListener

public void addDateListener(DateListener listener)
Add a date listener. This listener will receive events each time the selected date changes.

Parameters:
listener - The date listener to add.

removeDateListener

public void removeDateListener(DateListener listener)
Remove a date listener.

Parameters:
listener - The date listener to remove.

isNullAllowed

public boolean isNullAllowed()
Get whether a null date is allowed.

Returns:
The whether a null date is allowed.

setNullAllowed

public void setNullAllowed(boolean isNullAllowed)
Set whether a null date is allowed. A null date means that no date is selected. The user can select a null date by pressing DELETE anywhere within the calendar.

If nulls are not allowed, a setDate(null) will be ignored without error. The DELETE key will do nothing.

If you switch from allowing nulls to not allowing nulls and the current date is null, it will remain null until a date is selected.

The component default is to allow nulls.

Parameters:
isNullAllowed - The whether a null date is allowed.

getDate

public Date getDate()
Get the date currently displayed by the calendar panel. If null, then no date was selected.

Returns:
The date currently displayed.
See Also:
getCalendar()

setDate

public void setDate(Date date)
Set the calendar panel to display the given date. This will fire a DateEvent.

Parameters:
date - The date to set.

getDateFormat

public DateFormat getDateFormat()
Get the date format used to display the selected date in the combo box's text field.

Returns:
The date format used to display the selected date in the combo box's text field.

setDateFormat

public void setDateFormat(DateFormat dateFormat)
                   throws NullPointerException
Set the date format used to display the selected date in the combo box's text field. Nulls are not allowed.

Parameters:
dateFormat - The date format used to display the selected date in the combo box's text field.
Throws:
NullPointerException

getCalendar

public Calendar getCalendar()
Get a copy of the calendar used by this JCalendar. This calendar will be set to the currently selected date, so it is an alternative to the getDate() method.

Returns:
A copy of the calendar used by JCalendar.
See Also:
getDate()

getLocale

public Locale getLocale()
Return the locale used by this JCalendar.

Overrides:
getLocale in class Component
Returns:
The locale used by this JCalendar.

isTodayDisplayed

public boolean isTodayDisplayed()
Returns true if today's date is displayed at the bottom of the calendar.

Returns:
True if today's date is displayed at the bottom of the calendar.

getTitleFont

public Font getTitleFont()
Get the title font.

Returns:
The title font.

setTitleFont

public void setTitleFont(Font font)
If the font is set to null, then the title font (for the Month Year title) will default to the L&F's Label default font.

Otherwise, the title font is set as given.

Parameters:
font - The font to set.

getDayOfWeekFont

public Font getDayOfWeekFont()
Get the day-of-week font (Mon, Tue, etc.).

Returns:
The day-of-week font.

setDayOfWeekFont

public void setDayOfWeekFont(Font font)
If the font is set to null, then the day-of-week font (Mon, Tue, etc.) will default to 9/11th's of the L&F's Label default font.

Otherwise, the day-of-week font is set as given.

Parameters:
font - The font to set.

getDayFont

public Font getDayFont()
Get the day font.

Returns:
The day font.

setDayFont

public void setDayFont(Font font)
If the font is set to null, then the day font will default to 9/11th's of the L&F's Button default font.

Otherwise, the day font is set as given.

Parameters:
font - The font to set.

getTimeFont

public Font getTimeFont()
Get the time spinner font.

Returns:
The time spinner font.

setTimeFont

public void setTimeFont(Font font)
If the font is set to null, then the time spinner font will default to the L&F's Spinner default font.

Otherwise, the time spinner font is set as given.

Parameters:
font - The font to set.

getTodayFont

public Font getTodayFont()
Get the font used to display today's date as text.

Returns:
The font used to display today's date.

setTodayFont

public void setTodayFont(Font font)
If the font is set to null, then the font used to display today's date as text will default to the L&F's Label default font.

Otherwise, the font used to display today's date is set as given.

Parameters:
font - The font to set.

setSelectedItem

public void setSelectedItem(Object anObject)
Sets the selected item in the combo box display area to the object in the argument. The object should be a String representation of a date.

If this constitutes a change in the selected item, ItemListeners added to the combo box will be notified with one or two ItemEvents. If there is a current selected item, an ItemEvent will be fired and the state change will be ItemEvent.DESELECTED. If anObject is in the list and is not currently selected then an ItemEvent will be fired and the state change will be ItemEvent.SELECTED.

ActionListeners added to the combo box will be notified with an ActionEvent when this method is called (assuming the date actually changed).

Overrides:
setSelectedItem in class JComboBox
Parameters:
anObject - The object to select.

setKeySelectionManager

public void setKeySelectionManager(JComboBox.KeySelectionManager aManager)
This method is ignored. You cannot change the KeySelectionManager for JCalendarCombo.

Overrides:
setKeySelectionManager in class JComboBox
Parameters:
aManager - The new key selection manager.

updateUI

public void updateUI()
Resets the UI property to a value from the current look and feel. Read the class documentation for instructions on how to override this to make the JCalendarCombo support a new Look-and-Feel.

Overrides:
updateUI in class JComboBox

paramString

protected String paramString()

Overrides:
paramString in class JComboBox

stringToDate

protected Date stringToDate(String string)
Given a date in String form, convert it to a Date object. If no conversion is possible, return null. This method tries to parse the string using DateFormat and SHORT, MEDIUM, LONG and FULL forms. If none of these work, a null date is returned.

Parameters:
string - The date in String form.
Returns:
The equivalent Date object or null.

Copyright 2004-2005 Antonio Freixas
Licensed under the Artistic License