Class SsDbComboBox2<K,D,D2>
- Type Parameters:
K- list item key typeD- list item displayValue typeD2- list item optional extra data field type
- All Implemented Interfaces:
RSC, SsComponent, ActionListener, ImageObserver, ItemSelectable, MenuContainer, Serializable, EventListener, Accessible, ListDataListener
<K>, the 'bound' value, and <D>, the
'display' value, are pulled from a database table.
<K> is
the 'key' and the display value the 'text' which appears in the combo box.
This is sometimes used as a Navigator in conjunction with
SyncManager.
Generally the key represents a foreign key to another
table, and the combobox displays the <D>.
Optional data for combobox's item, <D2>, may be specified,
see setD2ColumnName(String). This data may be displayed by the
ListItem, see SsComboBox2.setD2DisplayEnabled(boolean) and SsComboBox2.getListItemFormat()
Refer to SsComboBox2 for warnings and caveats.
Builders and generic type parameter capture
The ComboBox hierarchy depends on generic parameter type capture. It is used so that the data read from a database column is converted to the concrete type specified by the parameter type.
When you have a SsDbComboBox2 with param types that you frequently use, it is convenient to incorporate it into a re-usable class. Here's a simple example where you lock in the types, don't add anything else, MyDbComboBox.Builder just works.
static class MyDbComboBox extends SsDbComboBox2<Integer, String, Byte> {
public static class Builder
extends SsDbComboBox2.AbstractBuilder<Integer, String, Byte, Builder> {
@Override
protected Builder self() {
return this;
}
@Override
public MyDbComboBox build() {
return new MyDbComboBox(this);
}
}
private MyDbComboBox(Builder builder) {
super(builder);
}
}
MyDbComboBox dbCombo = new MyDbComboBox
.Builder() // NOTE: "{ }" not needed
.primaryKeyColumnName("keyCol")
.displayColumnName("dispCol")
.build();
// System.out.println(""+dbCombo.getD2Type()); // output: class java.lang.Byte
This next example, DbComboBox2Extra, does a lot.
- lock in
<K>and<D>types - leaves
<D2>for programmer - adds new generic
<D3>for programmer - captures the type of
<D3> - has an AbstractBuilder so the class and Builder are extendable
- has a concrete Builder to instantiate the class
static class DbComboBox2Extra<D2, D3> extends SsDbComboBox2<Integer, String, D2> {
private final D3 d3Value; // Note: not part of combo list item.
private final TypeToken<D3> d3TypeToken;
public abstract static class AbstractBuilder<D2, D3, T extends AbstractBuilder<D2, D3, T>>
extends SsDbComboBox2.AbstractBuilder<Integer, String, D2, T> {
private D3 d3Value;
// captures D3 for whatever runtime class extends this Abstractbuilder
private final TypeToken<D3> d3TypeToken = new TypeToken<D3>(getClass()) {};
public AbstractBuilder() {
// check if TypeToken is generic; verifyTypeClass throws useful msg
verifyTypeClass(d3TypeToken, getClass());
}
public T d3Data(D3 val) {
d3Value = val;
return self();
}
}
// Regular Builder for direct instantiation
public static class Builder<D2, D3> extends AbstractBuilder<D2, D3, Builder<D2, D3>> {
// self type idiom
@Override
protected Builder<D2, D3> self() {
return this;
}
@Override
public DbComboBox2Extra<D2, D3> build() {
return new DbComboBox2Extra<>(this);
}
}
protected DbComboBox2Extra(AbstractBuilder<D2, D3, ?> builder) {
super(builder);
d3Value = builder.d3Value;
d3TypeToken = builder.d3TypeToken;
}
public D3 getD3() {
return d3Value;
}
public TypeToken<D3> getD3TypeToken() {
return d3TypeToken;
}
}
DbComboBox2Extra<Double, List<Double>> cbExtra = new DbComboBox2Extra
.Builder<Double, List<Double>>() {}
// <- "{ }" NEEDED
.primaryKeyColumnName("aaa")
.displayColumnName("bbb")
.d3Data(new ArrayList<>())
.build();
cbExtra.getD3().addAll(List.of(7D, 6D, 5D));
System.out.println("" + cbExtra.getKeyType());
System.out.println("" + cbExtra.getDisplayValueType());
System.out.println("" + cbExtra.getD2Type());
System.out.println("" + cbExtra.getD3TypeToken());
System.out.println("" + cbExtra.getD3());
class java.lang.Integer
class java.lang.String
class java.lang.Double
java.util.List<java.lang.Double>
[7.0, 6.0, 5.0]
Example with two tables
- part_data (part_id, part_name, ...)
- shipment_data (shipment_id, part_id, quantity, ...)
Assume you would like to develop a screen for the shipment_data table including a combobox where the user can choose a part and a textbox where the user can specify a quantity.
In the combobox you would want to display the part name rather than part_id so that it is easier for the user to choose. At the same time you want to store the id of the part chosen by the user in the shipment table.
/**
* Create NavigateActions for shipment_data and ComboBox to select part_id.
* The ComboBox displays part_name and provides part_id.
* Add the comboBox to this JFrame.
* @param connection used by SSDBComboBox
* @param rowSet to connect to shipment_data
*/
void init(Connection connection, JdbcRowSet rowSet) {
try {
// Table to examine and traverse.
rowSet.setCommand("SELECT * FROM shipment_data;");
rowSet.execute();
// 2nd arg is DbOps, if null use default.
rowsModel = RowsModel.create(rowSet, null);
// Query for the combobox to map part_id to part_name.
String query = "SELECT * FROM part_data;";
// Create an instance of the SsDbComboBox2 with the connection object,
// query, and column names.
combo = new SsDbComboBox2
.Builder<Long, String, Long>() {} // <- "{ }" NEEDED
.connection(connection)
.query(query)
.primaryKeyColumnName("part_id")
.displayColumnName("part_name")
.build();
// Execute the query.
combo.execute();
// Specifies the column bound to the combo.
rowsModel.bind(combo, "part_id");
} catch (Exception ex) {
// Exception handler here...
}
// Add the ssdbcombobox to the JFrame.
getContentPane().add(combo);
}
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSsDbComboBox2.AbstractBuilder<K, D, D2, T extends SsDbComboBox2.AbstractBuilder<K,D, D2, T>> To build a SsDbComboBox2 with the specified parameters.static classBuilder.Nested classes/interfaces inherited from class SsComboBox2
SsComboBox2.BaseGlazedModel<K,D, D2>, SsComboBox2.BaseModel<K, D, D2>, SsComboBox2.ComboBox2Listener, SsComboBox2.MissingDisplayValueControl, SsComboBox2.Model, SsComboBox2.ModelType Nested classes/interfaces inherited from class JComboBox
JComboBox.AccessibleJComboBox, JComboBox.KeySelectionManagerNested classes/interfaces inherited from class JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategyNested classes/interfaces inherited from interface SsComponent
SsComponent.Hook, SsComponent.ValidationResult -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final SsComboBox2.ModelTypedefault model typeprotected intcounter for # times that execute() method is called - for testing.Fields inherited from class SsComboBox2
DEFAULT_MODEL_COMBO2, keyVisual, nullItemFields inherited from class JComboBox
actionCommand, dataModel, editor, isEditable, keySelectionManager, lightWeightPopupEnabled, maximumRowCount, renderer, selectedItemReminderFields inherited from class JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
ConstructorsModifierConstructorDescriptionCreate a DBComboBox2.protectedSsDbComboBox2(SsDbComboBox2.AbstractBuilder<K, D, D2, ?> builder) -
Method Summary
Modifier and TypeMethodDescriptionvoidexecute()Executes the query specified with setQuery(), populates combobox, and turns on AutoCompleteSupport.Returns the rowSet column name used to populate the<D2>field of the combobox list item.Returns the pattern in which dates are displayed.Returns the column name whose values are displayed in the combo box.Retrieves the database column (normally a primary key) from which to query the keys for the bound column.getQuery()Returns the query used to retrieve values from database for the combo box.Returns the text displayed in the combobox.final booleanhasD2()This returns whether or not<D2>is populated.protected booleanA combobox used as a navigator has some restriction; for example, it can not have nullItem.voidsetBoundColumnName(String boundColumnName) Deprecated.Use bind()voidsetChosenDisplayValue(D displayValue) Finds the listItem having displayValue that matches the specified displayValue and make it the selected listItem.voidsetD2ColumnName(String d2ColumnName) Sets the column name .voidsetDateFormat(String dateFormat) When a display column is of type date you can choose the format in which it has to be displayed.<T extends Enum<T>>
voidsetDisplayValues(Class<T> enumDisplayValues) Unconditionally throws UnsupportedOperationException.voidsetDisplayValues(List<D> displayValues) Unconditionally throws UnsupportedOperationException.voidsetDisplayValues(List<D> displayValues, List<K> keys) Unconditionally throws UnsupportedOperationException.voidSets the query used to display items in the combo box.booleanupdateDisplayValue(K key, D displayValue) Update displayValue of an item in the combobox's item list for given key.Methods inherited from class SsComboBox2
addDisplayValue, addDisplayValue, addUndoableChange, adjustForNullItem, cleanField, createNullItem, customInit, establishListItemFormat, getAllowNull, getAutoComplete, getChosenD2, getChosenDisplayValue, getChosenEnum, getChosenItem, getChosenItem, getChosenKey, getD2DisplayEnabled, getD2FormatIndex, getD2Type, getDisplayValueFormatIndex, getDisplayValues, getDisplayValueType, getEnumDisplayValue, getKeyFormatIndex, getKeys, getKeyType, getListItemFormat, getNullItem, getSsComponentHook, glazedListArrowHandler, hasItems, hasSelection, isAutoGeneratedKeys, isConcrete, isSelectionPending, metadataChange, removeKey, setAllowNull, setChosenEnum, setChosenKey, setD2DisplayEnabled, setDisplayValues, setDisplayValuesInternal, setListItemFormat, setMissingDisplayValueControl, setModel, setSelectionPending, toString, undoRedoUpdateObject, verifyTypeClassMethods inherited from class JComboBox
actionPerformed, actionPropertyChanged, 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, paramString, processKeyBinding, processKeyEvent, removeActionListener, removeAllItems, removeItem, removeItemAt, removeItemListener, removePopupMenuListener, selectedItemChanged, selectWithKeyChar, setAction, setActionCommand, setEditable, setEditor, setEnabled, setKeySelectionManager, setLightWeightPopupEnabled, setMaximumRowCount, setPopupVisible, setPrototypeDisplayValue, setRenderer, setSelectedIndex, setSelectedItem, setUI, showPopup, updateUIMethods inherited from class JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, 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, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, 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, updateMethods inherited from class 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, transferFocusDownCycle, validate, validateTreeMethods inherited from class 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, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, 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, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, transferFocus, transferFocusBackward, transferFocusUpCycleMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface SsComponent
allValidate, baseValidate, bind, bind, checkColumnType, checkRowOK, checkRowOK, componentValidate, configureTraversalKeys, createDefaultDecorator, createDefaultTextDecorator, dbChange, decorate, decorateText, finishBind, finishSsCommon, getBoundColumnType, getColumn, getColumnArray, getColumnForLog, getColumnIndex, getColumnJDBCType, getColumnName, getColumnObject, getColumnObject, getColumnReader, getColumnText, getColumnUpdater, getDecorateTarget, getDecorator, getFocusTarget, getLogColumnName, getRowSet, getRowsModel, getSsCommon, getSsFormat, getTextDecorator, isComposite, isDirty, isFullyBound, setColumn, setColumnArray, setColumnObject, setColumnReader, setColumnText, setColumnUpdater, setDecorateTarget, setDecorator, setFocusTarget, setLogColumnName, setPluginValidator, setSsFormat, setTextDecorator, setupUndoRedoKeys
-
Field Details
-
executeCount
counter for # times that execute() method is called - for testing. -
DEFAULT_MODEL_DB_COMBO2
default model type
-
-
Constructor Details
-
SsDbComboBox2
- Parameters:
builder-
-
SsDbComboBox2
public SsDbComboBox2()Create a DBComboBox2.
-
-
Method Details
-
execute
-
getPrimaryKeyColumnName
Retrieves the database column (normally a primary key) from which to query the keys for the bound column.- Returns:
- name of the PK value to query for the bound column keys
-
getDateFormat
-
setDateFormat
When a display column is of type date you can choose the format in which it has to be displayed. For the pattern refer SimpleDateFormat in java.text package.- Parameters:
dateFormat- pattern in which dates have to be displayed
-
getDisplayColumnName
Returns the column name whose values are displayed in the combo box.- Returns:
- returns the name of the column used to get values for combo box items.
-
getD2ColumnName
Returns the rowSet column name used to populate the<D2>field of the combobox list item.- Returns:
- returns the column name
<D2>values
-
setD2ColumnName
Sets the column name . If there's extra data to store in the combobox list item then use this.- Parameters:
d2ColumnName- column name whose values populate<D2>.
-
getSelectedStringValue
Returns the text displayed in the combobox.- Returns:
- value corresponding to the selected item in the combo. return null if no item is selected.
-
hasD2
Description copied from class:SsComboBox2This returns whether or not<D2>is populated.- Overrides:
hasD2in classSsComboBox2<K,D, D2> - Returns:
-
setChosenDisplayValue
Finds the listItem having displayValue that matches the specified displayValue and make it the selected listItem. If no matching item is found the displayValue is used forsetSelectedItem(displayValue).- Overrides:
setChosenDisplayValuein classSsComboBox2<K,D, D2> - Parameters:
displayValue- element of list item- Throws:
IllegalStateException- if d2 enabled
-
getQuery
-
setQuery
-
updateDisplayValue
Update displayValue of an item in the combobox's item list for given key.If more than one item is present in the combo for that key, only the first one is changed.
- Overrides:
updateDisplayValuein classSsComboBox2<K,D, D2> - Parameters:
key- typically a primary key value corresponding to the chosenDisplayValue to be updateddisplayValue- chosenDisplayValue that should be updated in the combobox- Returns:
- returns true if update is successful otherwise returns false.
-
setDisplayValues
Unconditionally throws UnsupportedOperationException.- Overrides:
setDisplayValuesin classSsComboBox2<K,D, D2> - Parameters:
displayValues-keys-
-
setDisplayValues
Unconditionally throws UnsupportedOperationException.- Overrides:
setDisplayValuesin classSsComboBox2<K,D, D2> - Parameters:
displayValues-
-
setDisplayValues
Unconditionally throws UnsupportedOperationException.- Overrides:
setDisplayValuesin classSsComboBox2<K,D, D2> - Type Parameters:
T-- Parameters:
enumDisplayValues-
-
setBoundColumnName
Deprecated.Use bind()After this, make some adjustments. Sets the database column name bound to the Swingset component Deprecated in SSComponentInterface.- Parameters:
boundColumnName- the columnName to set
-