Java Utililty Methods JComboBox Value

List of utility methods to do JComboBox Value

Description

The list of methods to do JComboBox Value are organized into topic(s).

Method

voidreplaceContents(JComboBox combob, Object[] values)
Replace the options in a combo box with a new set.
Object cur = combob.getSelectedItem();
DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
m.removeAllElements();
if (values != null)
    for (Object v : values)
        if (v != null)
            m.addElement(v);
combob.setSelectedItem(cur);
...
voidsavePrefs(Preferences prefs, String prefKey, JComboBox combo, String newValidValue)
save Prefs
if (newValidValue == null) {
    return;
DefaultComboBoxModel comboModel = (DefaultComboBoxModel) combo.getModel();
int existingIndex = comboModel.getIndexOf(newValidValue);
if (existingIndex >= 0) {
    comboModel.removeElementAt(existingIndex);
comboModel.insertElementAt(newValidValue, 0);
combo.setSelectedIndex(0);
StringBuilder entries = new StringBuilder();
int size = Math.min(comboModel.getSize(), 20);
for (int i = 0; i < size; i++) {
    entries.append(comboModel.getElementAt(i));
    if (i != size - 1) {
        entries.append(DELIMITER);
while (entries.length() > Preferences.MAX_VALUE_LENGTH) {
    int lastIndex = entries.lastIndexOf(DELIMITER);
    if (lastIndex == -1) {
        break;
    } else {
        entries.delete(lastIndex, entries.length());
prefs.put(prefKey, entries.toString());
try {
    prefs.flush();
} catch (Throwable e) {
    e.printStackTrace();
voidsetComboBoxIndex(final JComboBox aComboBox, final int aIndex)
set Combo Box Index
int idx = aIndex;
if (idx < 0) {
    idx = aComboBox.getSelectedIndex();
} else if (idx > aComboBox.getItemCount()) {
    idx = idx % aComboBox.getItemCount();
aComboBox.setSelectedIndex(idx);
Objectvalue(JComboBox cb, Object[] val)
value
int selIndex = cb.getSelectedIndex();
if (selIndex == -1)
    return null;
return val[selIndex];