Class AutoCompleteSupport<E>
- java.lang.Object
-
- ca.odell.glazedlists.swing.AutoCompleteSupport<E>
-
public final class AutoCompleteSupport<E> extends java.lang.ObjectThis classinstall(javax.swing.JComboBox, ca.odell.glazedlists.EventList<E>)s support for filtering and autocompletion into a standardJComboBox. It also acts as a factory class forcreating autocompleting table cell editors.All autocompletion behaviour provided is meant to mimic the functionality of the Firefox address field. To be explicit, the following is a list of expected behaviours which are installed:
Typing into the ComboBox Editor
- typing any value into the editor when the popup is invisible causes the popup to appear and its contents to be filtered according to the editor's text. It also autocompletes to the first item that is prefixed with the editor's text and selects that item within the popup.
- typing any value into the editor when the popup is visible causes the popup to be refiltered according to the editor's text and reselects an appropriate autocompletion item.
- typing the down or up arrow keys in the editor when the popup is invisible causes the popup to appear and its contents to be filtered according to the editor's text. It also autocompletes to the first item that is prefixed with the editor's text and selects that item within the popup.
- typing the up arrow key when the popup is visible and the selected element is the first element causes the autocompletion to be cleared and the popup's selection to be removed.
- typing the up arrow key when no selection exists causes the last element of the popup to become selected and used for autocompletion
- typing the down arrow key when the popup is visible and the selected element is the last element causes the autocompletion to be cleared and the popup's selection to be removed
- typing the down arrow key when no selection exists causes the first element of the popup to become selected and used for autocompletion
- typing the delete key while in strict mode will select the prior text rather than delete it. Attempting to delete all text results in a beep unless the autcomplete support has been configured to not beep.
- clicking the arrow button when the popup is invisible causes the popup to appear and its contents to be shown unfiltered
- clicking the arrow button when the popup is visible causes the popup to be hidden
- the popup is always at least as wide as the
autocompleting
JComboBox, but may be wider to accomodate aprototype display valueif a non-null prototype display value exists - as items are filtered in the ComboBoxModel, the popup height is
adjusted to display between 0 and
JComboBox.getMaximumRowCount()rows before scrolling the popup
A single
ActionEventis fired from the JComboBox in these situations:- the user hits the enter key
- the selected item within the popup is changed (which can happen due to a mouse click, a change in the autocompletion term, or using the arrow keys)
- the JComboBox loses focus and contains a value that does not appear in the ComboBoxModel
ComboBoxEditor Focusnullvalues located in the ComboBoxModel are considered identical to empty Strings ("") for the purposes of locating autocompletion terms.- the text in the ComboBoxEditor is selected if
getSelectsTextOnFocusGain()returns true - the JPopupMenu is hidden when the ComboBoxEditor loses focus if
getHidesPopupOnFocusLost()returns true
Each value in the ComboBoxModel must be converted to a String for many reasons: filtering, setting into the ComboBoxEditor, displaying in the renderer, etc. By default, JComboBox relies on
Object.toString()to map elements to their String equivalents. Sometimes, however, toString() is not a reliable or desirable mechanism to use. To deal with this problem, AutoCompleteSupport provides an install method that takes aFormatobject which is used to do all converting back and forth between Strings and ComboBoxModel objects.In order to achieve all of the autocompletion and filtering behaviour, the following occurs when
install(javax.swing.JComboBox, ca.odell.glazedlists.EventList<E>)is called:- the JComboBox will be made editable
- the JComboBox will have a custom ComboBoxModel installed on it containing the given items
- the ComboBoxEditor will be wrapped with functionality and set back into the JComboBox as the editor
- the JTextField which is the editor component for the JComboBox will have a DocumentFilter installed on its backing Document
Warning: This class must be mutated from the Swing Event Dispatch Thread. Failure to do so will result in an
IllegalStateExceptionthrown from any one of:-
install(JComboBox, EventList) -
install(JComboBox, EventList, TextFilterator) -
install(JComboBox, EventList, TextFilterator, Format) -
isInstalled() -
uninstall() -
setCorrectsCase(boolean) -
setStrict(boolean) -
setBeepOnStrictViolation(boolean) -
setSelectsTextOnFocusGain(boolean) -
setHidesPopupOnFocusLost(boolean) -
setFilterMode(int) -
setFirstItem(Object) -
removeFirstItem()
- Author:
- James Lemieux
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classAutoCompleteSupport.AutoCompleteCellEditor<E>This extension of DefaultCellEditor exists solely to provide a handle to the AutoCompleteSupport object that is providing autocompletion capabilities to the JComboBox.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description static <E> AutoCompleteSupport.AutoCompleteCellEditor<E>createTableCellEditor(EventList<E> source)This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor.static <E> AutoCompleteSupport.AutoCompleteCellEditor<E>createTableCellEditor(TableFormat<E> tableFormat, EventList<E> tableData, int columnIndex)This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor.static <E> AutoCompleteSupport.AutoCompleteCellEditor<E>createTableCellEditor(java.util.Comparator uniqueComparator, TableFormat<E> tableFormat, EventList<E> tableData, int columnIndex)This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor.booleangetBeepOnStrictViolation()Returns true if a beep sound is played when the user attempts to violate the strict invariant; false if no beep sound is played.javax.swing.JComboBoxgetComboBox()booleangetCorrectsCase()Returns true if user specified strings are converted to the case of the autocompletion term they match; false otherwise.intgetFilterMode()Returns the manner in which the contents of theComboBoxModelare filtered.EgetFirstItem()Returns the optional single value used as the first element in theComboBoxModelor null if no first item has been set.booleangetHidesPopupOnFocusLost()Returns true if the popup menu is hidden whenever the combo box editor loses focus; false otherwise.EventList<E>getItemList()Returns the filteredEventListof items which backs theComboBoxModelof the autocompletingJComboBox.booleangetSelectsTextOnFocusGain()Returns true if the combo box editor text is selected when it gains focus; false otherwise.TextFilterator<? super E>getTextFilterator()Returns theTextFilteratorthat extracts searchable strings from each item in theComboBoxModel.java.lang.ObjectgetTextMatchingStrategy()Returns the manner in which the contents of theComboBoxModelare filtered and autocompletion terms are matched.static <E> AutoCompleteSupport<E>install(javax.swing.JComboBox comboBox, EventList<E> items)Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities.static <E> AutoCompleteSupport<E>install(javax.swing.JComboBox comboBox, EventList<E> items, TextFilterator<? super E> filterator)Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities.static <E> AutoCompleteSupport<E>install(javax.swing.JComboBox comboBox, EventList<E> items, TextFilterator<? super E> filterator, java.text.Format format)Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities.booleanisInstalled()Returns true if this autocomplete support instance is currently installed and altering the behaviour of the combo box; false if it has beenuninstall()ed.booleanisStrict()Returns true if the user is able to specify values which do not appear in the popup list of suggestions; false otherwise.EremoveFirstItem()Removes and returns the optional single value used as the first element in theComboBoxModelor null if no first item has been set.voidsetBeepOnStrictViolation(boolean beepOnStrictViolation)Sets the policy for indicating strict-mode violations to the user by way of a beep sound.voidsetCorrectsCase(boolean correctCase)IfcorrectCaseis true, user specified strings will be converted to the case of the element they match.voidsetFilterMode(int mode)Sets the manner in which the contents of theComboBoxModelare filtered.voidsetFirstItem(E item)This method set a single optional value to be used as the first element in theComboBoxModel.voidsetHidesPopupOnFocusLost(boolean hidesPopupOnFocusLost)IfhidesPopupOnFocusLostis true, then the popup menu of the combo box is always hidden whenever the combo box editor loses focus.voidsetSelectsTextOnFocusGain(boolean selectsTextOnFocusGain)IfselectsTextOnFocusGainis true, all text in the editor is selected when the combo box editor gains focus.voidsetStrict(boolean strict)Ifstrictis false, the user can specify values not appearing within the ComboBoxModel.voidsetTextMatchingStrategy(java.lang.Object strategy)Sets the manner in which the contents of theComboBoxModelare filtered and autocompletion terms are matched.voiduninstall()This method removes autocompletion support from theJComboBoxit was installed on.
-
-
-
Method Detail
-
install
public static <E> AutoCompleteSupport<E> install(javax.swing.JComboBox comboBox, EventList<E> items)
Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities. The support object is returned so that the caller may invokeuninstall()at some later time to remove the autocompletion features.This method assumes that the
itemscan be converted into reasonable String representations viaObject.toString().The following must be true in order to successfully install support for autocompletion on a
JComboBox:- The JComboBox must use a
JTextFieldas its editor component - The JTextField must use an
AbstractDocumentas its model
- Parameters:
comboBox- theJComboBoxto decorate with autocompletionitems- the objects to display in thecomboBox- Returns:
- an instance of the support class providing autocomplete features
- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
- The JComboBox must use a
-
install
public static <E> AutoCompleteSupport<E> install(javax.swing.JComboBox comboBox, EventList<E> items, TextFilterator<? super E> filterator)
Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities. The support object is returned so that the caller may invokeuninstall()at some later time to remove the autocompletion features.This method assumes that the
itemscan be converted into reasonable String representations viaObject.toString().The
filteratorwill be used to extract searchable text strings from each of theitems. Anullfilterator implies the item's toString() method should be used when filtering it.The following must be true in order to successfully install support for autocompletion on a
JComboBox:- The JComboBox must use a
JTextFieldas its editor component - The JTextField must use an
AbstractDocumentas its model
- Parameters:
comboBox- theJComboBoxto decorate with autocompletionitems- the objects to display in thecomboBoxfilterator- extracts searchable text strings from each item;nullimplies the item's toString() method should be used when filtering it- Returns:
- an instance of the support class providing autocomplete features
- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
- The JComboBox must use a
-
install
public static <E> AutoCompleteSupport<E> install(javax.swing.JComboBox comboBox, EventList<E> items, TextFilterator<? super E> filterator, java.text.Format format)
Installs support for autocompletion into thecomboBoxand returns the support object that is actually providing those facilities. The support object is returned so that the caller may invokeuninstall()at some later time to remove the autocompletion features.This method uses the given
formatto convert the givenitemsinto Strings and back again. In other words, this method does NOT rely onObject.toString()to produce a reasonable String representation of each item. Likewise, it does not rely on the existence of a valueOf(String) method for creating items out of Strings as is the default behaviour of JComboBox.It can be assumed that the only methods called on the given
formatare:Format.format(Object)Format.parseObject(String, ParsePosition)
As a convenience, this method will install a custom
ListCellRendereron thecomboBoxthat displays the String value returned by theformat. Though this is only done if the givenformatis notnulland if thecomboBoxdoes not already use a custom renderer.The
filteratorwill be used to extract searchable text strings from each of theitems. Anullfilterator implies one of two default strategies will be used. If theformatis not null then the String value returned from theformatobject will be used when filtering a given item. Otherwise, the item's toString() method will be used when it is filtered.The following must be true in order to successfully install support for autocompletion on a
JComboBox:- The JComboBox must use a
JTextFieldas its editor component - The JTextField must use an
AbstractDocumentas its model
- Parameters:
comboBox- theJComboBoxto decorate with autocompletionitems- the objects to display in thecomboBoxfilterator- extracts searchable text strings from each item. If theformatis not null then the String value returned from theformatobject will be used when filtering a given item. Otherwise, the item's toString() method will be used when it is filtered.format- a Format object capable of convertingitemsinto Strings and back.nullindicates the standard JComboBox methods of converting are acceptable.- Returns:
- an instance of the support class providing autocomplete features
- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
getComboBox
public javax.swing.JComboBox getComboBox()
-
getTextFilterator
public TextFilterator<? super E> getTextFilterator()
Returns theTextFilteratorthat extracts searchable strings from each item in theComboBoxModel.
-
getItemList
public EventList<E> getItemList()
Returns the filteredEventListof items which backs theComboBoxModelof the autocompletingJComboBox.
-
getCorrectsCase
public boolean getCorrectsCase()
Returns true if user specified strings are converted to the case of the autocompletion term they match; false otherwise.
-
setCorrectsCase
public void setCorrectsCase(boolean correctCase)
IfcorrectCaseis true, user specified strings will be converted to the case of the element they match. Otherwise they will be left unaltered.Note: this flag only has meeting when strict mode is turned off. When strict mode is on, case is corrected regardless of this setting.
- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread- See Also:
setStrict(boolean)
-
isStrict
public boolean isStrict()
Returns true if the user is able to specify values which do not appear in the popup list of suggestions; false otherwise.
-
setStrict
public void setStrict(boolean strict)
Ifstrictis false, the user can specify values not appearing within the ComboBoxModel. If it is true each keystroke must continue to match some value in the ComboBoxModel or it will be discarded.Note: When strict mode is enabled, all user input is corrected to the case of the autocompletion term, regardless of the correctsCase setting.
- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread- See Also:
setCorrectsCase(boolean)
-
getBeepOnStrictViolation
public boolean getBeepOnStrictViolation()
Returns true if a beep sound is played when the user attempts to violate the strict invariant; false if no beep sound is played. This setting is only respected ifisStrict()returns true.- See Also:
setStrict(boolean)
-
setBeepOnStrictViolation
public void setBeepOnStrictViolation(boolean beepOnStrictViolation)
Sets the policy for indicating strict-mode violations to the user by way of a beep sound.- Parameters:
beepOnStrictViolation- true if a beep sound should be played when the user attempts to violate the strict invariant; false if no beep sound should be played- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
getSelectsTextOnFocusGain
public boolean getSelectsTextOnFocusGain()
Returns true if the combo box editor text is selected when it gains focus; false otherwise.
-
setSelectsTextOnFocusGain
public void setSelectsTextOnFocusGain(boolean selectsTextOnFocusGain)
IfselectsTextOnFocusGainis true, all text in the editor is selected when the combo box editor gains focus. If it is false the selection state of the editor is not effected by focus changes.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
getHidesPopupOnFocusLost
public boolean getHidesPopupOnFocusLost()
Returns true if the popup menu is hidden whenever the combo box editor loses focus; false otherwise.
-
setHidesPopupOnFocusLost
public void setHidesPopupOnFocusLost(boolean hidesPopupOnFocusLost)
IfhidesPopupOnFocusLostis true, then the popup menu of the combo box is always hidden whenever the combo box editor loses focus. If it is false the default behaviour is preserved. In practice this means that if focus is lost because of a MouseEvent, the behaviour is reasonable, but if focus is lost because of a KeyEvent (e.g. tabbing to the next focusable component) then the popup menu remains visible.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
getFilterMode
public int getFilterMode()
Returns the manner in which the contents of theComboBoxModelare filtered. This method will return one ofTextMatcherEditor.CONTAINSorTextMatcherEditor.STARTS_WITH.TextMatcherEditor.CONTAINSindicates elements of theComboBoxModelare matched when they contain the text entered by the user.TextMatcherEditor.STARTS_WITHindicates elements of theComboBoxModelare matched when they start with the text entered by the user.In both modes, autocompletion only occurs when a given item starts with user-specified text. The filter mode only affects the filtering aspect of autocomplete support.
-
setFilterMode
public void setFilterMode(int mode)
Sets the manner in which the contents of theComboBoxModelare filtered. The givenmodemust be one ofTextMatcherEditor.CONTAINSorTextMatcherEditor.STARTS_WITH.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread- See Also:
getFilterMode()
-
setTextMatchingStrategy
public void setTextMatchingStrategy(java.lang.Object strategy)
Sets the manner in which the contents of theComboBoxModelare filtered and autocompletion terms are matched. The givenstrategymust be one ofTextMatcherEditor.IDENTICAL_STRATEGYorTextMatcherEditor.NORMALIZED_STRATEGYor the Unicode strategy of the ICU4J extension.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread- See Also:
getTextMatchingStrategy()
-
getTextMatchingStrategy
public java.lang.Object getTextMatchingStrategy()
Returns the manner in which the contents of theComboBoxModelare filtered and autocompletion terms are matched. The returnedstrategyis one ofTextMatcherEditor.IDENTICAL_STRATEGYorTextMatcherEditor.NORMALIZED_STRATEGYor the Unicode strategy of the ICU4J extension.
-
setFirstItem
public void setFirstItem(E item)
This method set a single optional value to be used as the first element in theComboBoxModel. This value typically represents "no selection" or "blank". This value is always present and is not filtered away during autocompletion.- Parameters:
item- the first value to present in theComboBoxModel
-
getFirstItem
public E getFirstItem()
Returns the optional single value used as the first element in theComboBoxModelor null if no first item has been set.- Returns:
- the special first value presented in the
ComboBoxModelor null if no first item has been set
-
removeFirstItem
public E removeFirstItem()
Removes and returns the optional single value used as the first element in theComboBoxModelor null if no first item has been set.- Returns:
- the special first value presented in the
ComboBoxModelor null if no first item has been set
-
isInstalled
public boolean isInstalled()
Returns true if this autocomplete support instance is currently installed and altering the behaviour of the combo box; false if it has beenuninstall()ed.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
uninstall
public void uninstall()
This method removes autocompletion support from theJComboBoxit was installed on. This method is useful when theEventListof items that backs the combo box must outlive the combo box itself. Calling this method will return the combo box to its original state before autocompletion was installed, and it will be available for garbage collection independently of theEventListof items.- Throws:
java.lang.IllegalStateException- if this method is called from any Thread other than the Swing Event Dispatch Thread
-
createTableCellEditor
public static <E> AutoCompleteSupport.AutoCompleteCellEditor<E> createTableCellEditor(TableFormat<E> tableFormat, EventList<E> tableData, int columnIndex)
This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor. The values within the table column are used as autocompletion terms within theComboBoxModel.This version of
createTableCellEditorassumes that the values stored in the TableModel at the givencolumnIndexare allComparable, and that the natural ordering defined by thoseComparablevalues also determines which are duplicates (and thus can safely be removed) and which are unique (and thus must remain in theComboBoxModel).Note that this factory method is only appropriate for use when the values in the
ComboBoxModelshould be the unique set of values in a table column. If some other list of values will be used thencreateTableCellEditor(EventList)is the appropriate factory method to use.If the appearance or function of the autocompleting
JComboBoxis to be customized, it can be retrieved usingDefaultCellEditor.getComponent().- Parameters:
tableFormat- specifies how each row object within a table is broken apart into column valuestableData- theEventListbacking the TableModelcolumnIndex- the index of the column for which to return aAutoCompleteSupport.AutoCompleteCellEditor- Returns:
- a
AutoCompleteSupport.AutoCompleteCellEditorwhich contains an autocompleting combobox whose contents remain consistent with the data in the table column at the givencolumnIndex
-
createTableCellEditor
public static <E> AutoCompleteSupport.AutoCompleteCellEditor<E> createTableCellEditor(java.util.Comparator uniqueComparator, TableFormat<E> tableFormat, EventList<E> tableData, int columnIndex)
This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor. The values within the table column are used as autocompletion terms within theComboBoxModel.This version of
createTableCellEditormakes no assumption about the values stored in the TableModel at the givencolumnIndex. Instead, it uses the givenuniqueComparatorto determine which values are duplicates (and thus can safely be removed) and which are unique (and thus must remain in theComboBoxModel).Note that this factory method is only appropriate for use when the values in the
ComboBoxModelshould be the unique set of values in a table column. If some other list of values will be used thencreateTableCellEditor(EventList)is the appropriate factory method to use.If the appearance or function of the autocompleting
JComboBoxis to be customized, it can be retrieved usingDefaultCellEditor.getComponent().- Parameters:
uniqueComparator- theComparatorthat strips away duplicate elements from theComboBoxModeltableFormat- specifies how each row object within a table is broken apart into column valuestableData- theEventListbacking the TableModelcolumnIndex- the index of the column for which to return aAutoCompleteSupport.AutoCompleteCellEditor- Returns:
- a
AutoCompleteSupport.AutoCompleteCellEditorwhich contains an autocompleting combobox whose contents remain consistent with the data in the table column at the givencolumnIndex
-
createTableCellEditor
public static <E> AutoCompleteSupport.AutoCompleteCellEditor<E> createTableCellEditor(EventList<E> source)
This factory method creates and returns aAutoCompleteSupport.AutoCompleteCellEditorwhich adapts an autocompletingJComboBoxfor use as a Table Cell Editor. The values within thesourceare used as autocompletion terms within theComboBoxModel.If the appearance or function of the autocompleting
JComboBoxis to be customized, it can be retrieved usingDefaultCellEditor.getComponent().- Parameters:
source- the source of data for the JComboBox within the table cell editor- Returns:
- a
AutoCompleteSupport.AutoCompleteCellEditorwhich contains an autocompleting combobox whose model contents are determined by the givensource
-
-