Example usage for javax.swing ComboBoxModel getElementAt

List of usage examples for javax.swing ComboBoxModel getElementAt

Introduction

In this page you can find the example usage for javax.swing ComboBoxModel getElementAt.

Prototype

E getElementAt(int index);

Source Link

Document

Returns the value at the specified index.

Usage

From source file:de.fhg.iais.asc.ui.parts.TransformersPanel.java

/**
 * helper/* w  w  w  .  j a v a2  s.  c om*/
 */
private boolean setSelectedString(JComboBox comboBox, String stringToSelect) {
    final ComboBoxModel model = comboBox.getModel();

    int size = model.getSize();
    for (int index = 0; index < size; index++) {
        if (model.getElementAt(index).toString().equals(stringToSelect)) {
            comboBox.setSelectedIndex(index);
            return true;
        }
    }

    return false;
}

From source file:com.anrisoftware.prefdialog.fields.historycombobox.HistoryComboBoxField.java

private MutableComboBoxModel<?> createMutableModel(ComboBoxModel<?> model) {
    if (model instanceof MutableComboBoxModel) {
        return (MutableComboBoxModel<?>) model;
    }/*  ww  w.  ja  v a  2s .  c o  m*/
    DefaultComboBoxModel<Object> mutableModel = new DefaultComboBoxModel<Object>();
    for (int i = 0; i < model.getSize(); i++) {
        mutableModel.addElement(model.getElementAt(i));
    }
    return mutableModel;
}

From source file:MultiKeyCombo.java

public int selectionForKey(char aKey, ComboBoxModel aModel) {
    // Reset if invalid character
    if (aKey == KeyEvent.CHAR_UNDEFINED) {
        currentSearch.setLength(0);/*from   w ww . j a va  2 s. co m*/
        return -1;
    }
    // Since search, don't reset search
    resetTimer.stop();
    // Convert input to uppercase
    char key = Character.toUpperCase(aKey);
    // Build up search string
    currentSearch.append(key);
    // Find selected position within model to starting searching from
    Object selectedElement = aModel.getSelectedItem();
    int selectedIndex = -1;
    if (selectedElement != null) {
        for (int i = 0, n = aModel.getSize(); i < n; i++) {
            if (aModel.getElementAt(i) == selectedElement) {
                selectedIndex = i;
                break;
            }
        }
    }
    boolean found = false;
    String search = currentSearch.toString();
    // Search from selected forward, wrap back to beginning if not found
    for (int i = 0, n = aModel.getSize(); i < n; i++) {
        String element = aModel.getElementAt(selectedIndex).toString().toUpperCase();
        if (element.startsWith(search)) {
            found = true;
            break;
        }
        selectedIndex++;
        if (selectedIndex == n) {
            selectedIndex = 0; // wrap
        }
    }
    // Restart timer
    resetTimer.start();
    return (found ? selectedIndex : -1);
}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * Create the UI for the panel/*  w  w w.ja v a  2 s .  com*/
 */
protected void createUI() {
    createForm("Preferences", "Formatting"); //$NON-NLS-1$ //$NON-NLS-2$

    UIValidator.setIgnoreAllValidation(this, true);

    JLabel fontNamesLabel = form.getLabelFor("fontNames"); //$NON-NLS-1$
    ValComboBox fontNamesVCB = form.getCompById("fontNames"); //$NON-NLS-1$

    JLabel fontSizesLabel = form.getLabelFor("fontSizes"); //$NON-NLS-1$
    ValComboBox fontSizesVCB = form.getCompById("fontSizes"); //$NON-NLS-1$

    JLabel controlSizesLabel = form.getLabelFor("controlSizes"); //$NON-NLS-1$
    ValComboBox controlSizesVCB = form.getCompById("controlSizes"); //$NON-NLS-1$

    formTypesCBX = form.getCompById("formtype"); //$NON-NLS-1$

    fontNames = fontNamesVCB.getComboBox();
    fontSizes = fontSizesVCB.getComboBox();
    controlSizes = controlSizesVCB.getComboBox();

    testField = form.getCompById("fontTest"); //$NON-NLS-1$
    if (testField != null) {
        testField.setText(UIRegistry.getResourceString("FormattingPrefsPanel.THIS_TEST")); //$NON-NLS-1$
    }
    if (UIHelper.isMacOS_10_5_X()) {
        fontNamesLabel.setVisible(false);
        fontNamesVCB.setVisible(false);
        fontSizesLabel.setVisible(false);
        fontSizesVCB.setVisible(false);
        testField.setVisible(false);

        int inx = -1;
        int i = 0;
        Vector<String> controlSizeTitles = new Vector<String>();
        for (UIHelper.CONTROLSIZE cs : UIHelper.CONTROLSIZE.values()) {
            String titleStr = getResourceString(cs.toString());
            controlSizeTitles.add(titleStr);
            controlSizesHash.put(titleStr, cs);
            controlSizes.addItem(titleStr);
            if (cs == UIHelper.getControlSize()) {
                inx = i;
            }
            i++;
        }
        controlSizes.setSelectedIndex(inx);

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.addItem(baseFont.getFamily());
            fontSizes.addItem(Integer.toString(baseFont.getSize()));
            fontNames.setSelectedIndex(0);
            fontSizes.setSelectedIndex(0);
        }

    } else {
        controlSizesLabel.setVisible(false);
        controlSizesVCB.setVisible(false);

        Hashtable<String, Boolean> namesUsed = new Hashtable<String, Boolean>();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        for (Font font : ge.getAllFonts()) {
            if (namesUsed.get(font.getFamily()) == null) {
                fontNames.addItem(font.getFamily());
                namesUsed.put(font.getFamily(), true); //$NON-NLS-1$
            }
        }
        for (int i = BASE_FONT_SIZE; i < 22; i++) {
            fontSizes.addItem(Integer.toString(i));
        }

        Font baseFont = UIRegistry.getBaseFont();
        if (baseFont != null) {
            fontNames.setSelectedItem(baseFont.getFamily());
            fontSizes.setSelectedItem(Integer.toString(baseFont.getSize()));

            if (testField != null) {
                ActionListener al = new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        testField.setFont(new Font((String) fontNames.getSelectedItem(), Font.PLAIN,
                                fontSizes.getSelectedIndex() + BASE_FONT_SIZE));
                        form.getUIComponent().validate();
                        clearFontSettings = false;
                    }
                };
                fontNames.addActionListener(al);
                fontSizes.addActionListener(al);
            }
        }
    }

    //-----------------------------------
    // Do DisciplineType Icons
    //-----------------------------------

    String iconName = AppPreferences.getRemote().get(getDisciplineImageName(), "CollectionObject"); //$NON-NLS-1$ //$NON-NLS-2$

    List<Pair<String, ImageIcon>> list = IconManager.getListByType("disciplines", IconManager.IconSize.Std16); //$NON-NLS-1$
    Collections.sort(list, new Comparator<Pair<String, ImageIcon>>() {
        public int compare(Pair<String, ImageIcon> o1, Pair<String, ImageIcon> o2) {
            String s1 = UIRegistry.getResourceString(o1.first);
            String s2 = UIRegistry.getResourceString(o2.first);
            return s1.compareTo(s2);
        }
    });

    disciplineCBX = (ValComboBox) form.getCompById("disciplineIconCBX"); //$NON-NLS-1$

    final JLabel dispLabel = form.getCompById("disciplineIcon"); //$NON-NLS-1$
    JComboBox comboBox = disciplineCBX.getComboBox();
    comboBox.setRenderer(new DefaultListCellRenderer() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public Component getListCellRendererComponent(JList listArg, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) value;
            JLabel label = (JLabel) super.getListCellRendererComponent(listArg, value, index, isSelected,
                    cellHasFocus);
            if (item != null) {
                label.setIcon(item.second);
                label.setText(UIRegistry.getResourceString(item.first));
            }
            return label;
        }
    });

    int inx = 0;
    Pair<String, ImageIcon> colObj = new Pair<String, ImageIcon>("colobj_backstop", //$NON-NLS-1$
            IconManager.getIcon("colobj_backstop", IconManager.IconSize.Std16)); //$NON-NLS-1$
    comboBox.addItem(colObj);

    int cnt = 1;
    for (Pair<String, ImageIcon> item : list) {
        if (item.first.equals(iconName)) {
            inx = cnt;
        }
        comboBox.addItem(item);
        cnt++;
    }

    comboBox.addActionListener(new ActionListener() {
        @SuppressWarnings("unchecked") //$NON-NLS-1$
        public void actionPerformed(ActionEvent e) {
            JComboBox cbx = (JComboBox) e.getSource();
            Pair<String, ImageIcon> item = (Pair<String, ImageIcon>) cbx.getSelectedItem();
            if (item != null) {
                dispLabel.setIcon(IconManager.getIcon(item.first));
                form.getUIComponent().validate();
            }
        }
    });

    comboBox.setSelectedIndex(inx);

    //-----------------------------------
    // Date Field
    //-----------------------------------
    dateFieldCBX = form.getCompById("scrdateformat"); //$NON-NLS-1$
    fillDateFormat();

    //-----------------------------------
    // FormType
    //-----------------------------------
    fillFormTypes();

    //-----------------------------------
    // Do App Icon
    //-----------------------------------

    final JButton getIconBtn = form.getCompById("GetIconImage"); //$NON-NLS-1$
    final JButton clearIconBtn = form.getCompById("ClearIconImage"); //$NON-NLS-1$
    final JLabel appLabel = form.getCompById("appIcon"); //$NON-NLS-1$
    final JButton resetDefFontBtn = form.getCompById("ResetDefFontBtn"); //$NON-NLS-1$

    String imgEncoded = AppPreferences.getRemote().get(iconImagePrefName, ""); //$NON-NLS-1$
    ImageIcon innerAppImgIcon = null;
    if (StringUtils.isNotEmpty(imgEncoded)) {
        innerAppImgIcon = GraphicsUtils.uudecodeImage("", imgEncoded); //$NON-NLS-1$
        if (innerAppImgIcon != null && innerAppImgIcon.getIconWidth() != 32
                || innerAppImgIcon.getIconHeight() != 32) {
            innerAppImgIcon = null;
            clearIconBtn.setEnabled(false);
        } else {
            clearIconBtn.setEnabled(true);
        }
    }

    if (innerAppImgIcon == null) {
        innerAppImgIcon = IconManager.getIcon("AppIcon"); //$NON-NLS-1$
        clearIconBtn.setEnabled(false);
    } else {
        clearIconBtn.setEnabled(true);
    }
    appLabel.setIcon(innerAppImgIcon);

    getIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            chooseToolbarIcon(appLabel, clearIconBtn);
        }
    });

    clearIconBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ImageIcon appIcon = IconManager.getIcon("AppIcon");
            IconEntry entry = IconManager.getIconEntryByName(INNER_APPICON_NAME);
            entry.setIcon(appIcon);
            if (entry.getIcons().get(IconManager.IconSize.Std32) != null) {
                entry.getIcons().get(IconManager.IconSize.Std32).setImageIcon(appIcon);
            }

            appLabel.setIcon(IconManager.getIcon("AppIcon")); //$NON-NLS-1$
            clearIconBtn.setEnabled(false);
            AppPreferences.getRemote().remove(iconImagePrefName);
            form.getValidator().dataChanged(null, null, null);
        }
    });

    resetDefFontBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Font sysDefFont = UIRegistry.getDefaultFont();
            ComboBoxModel model = fontNames.getModel();
            for (int i = 0; i < model.getSize(); i++) {
                //System.out.println("["+model.getElementAt(i).toString()+"]["+sysDefFont.getFamily()+"]");
                if (model.getElementAt(i).toString().equals(sysDefFont.getFamily())) {
                    fontNames.setSelectedIndex(i);
                    clearFontSettings = true;
                    break;
                }
            }

            if (clearFontSettings) {
                fontSizes.setSelectedIndex(sysDefFont.getSize() - BASE_FONT_SIZE);
                clearFontSettings = true; // needs to be redone 
            }

            form.getValidator().dataChanged(null, null, null);
        }
    });

    //-----------------------------------
    // Do Banner Icon Size
    //-----------------------------------

    String fmtStr = "%d x %d pixels";//getResourceString("BNR_ICON_SIZE");
    bnrIconSizeCBX = form.getCompById("bnrIconSizeCBX"); //$NON-NLS-1$

    int size = AppPreferences.getLocalPrefs().getInt(BNR_ICON_SIZE, 20);
    inx = 0;
    cnt = 0;
    for (int pixelSize : pixelSizes) {
        ((DefaultComboBoxModel) bnrIconSizeCBX.getModel())
                .addElement(String.format(fmtStr, pixelSize, pixelSize));
        if (pixelSize == size) {
            inx = cnt;
        }
        cnt++;
    }

    bnrIconSizeCBX.getComboBox().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            form.getUIComponent().validate();
        }
    });

    bnrIconSizeCBX.getComboBox().setSelectedIndex(inx);

    UIValidator.setIgnoreAllValidation(this, false);
    fontNamesVCB.setChanged(false);
    fontSizesVCB.setChanged(false);

    form.getValidator().validateForm();
}

From source file:io.github.jeddict.jpa.modeler.source.generator.ui.GenerateCodeDialog.java

private void setPackage(JComboBox packageCombo, String _package) {
    ComboBoxModel model = packageCombo.getModel();
    for (int i = 0; i < model.getSize(); i++) {
        if (model.getElementAt(i).toString().equals(_package)) {
            model.setSelectedItem(model.getElementAt(i));
            return;
        }/* www.j  ava 2 s  . c  o  m*/
    }
    ((JTextComponent) packageCombo.getEditor().getEditorComponent()).setText(_package);
}

From source file:edu.ku.brc.af.ui.forms.validation.ValComboBox.java

@Override
public void setValue(final Object valueArg, final String defaultValue) {
    if (multiView == null) {
        multiView = getMultiView();// w ww  .ja v a  2  s. c om
    }

    if (multiView != null) {
        isNew = isFormObjNew = multiView.isNewForm();
    }

    String defVal = StringUtils.isEmpty(defaultValue) ? null : defaultValue;
    Object value = valueArg == null ? defVal : valueArg;
    Integer fndInx = -1;

    if (value != null) {
        ComboBoxModel<?> model = comboBox.getModel();
        boolean isFormObjIFace = value instanceof FormDataObjIFace;

        if (adapter != null) {
            for (int i = 0; i < comboBox.getItemCount(); i++) {
                PickListItemIFace pli = (PickListItemIFace) model.getElementAt(i);
                Object valObj = pli.getValueObject();

                //log.debug(pli.getValue());
                if (valObj != null) {
                    if (isFormObjIFace && valObj instanceof FormDataObjIFace) {
                        //log.debug(((FormDataObjIFace)value).getId().longValue()+"  "+(((FormDataObjIFace)valObj).getId().longValue()));
                        if (((FormDataObjIFace) value).getId()
                                .intValue() == (((FormDataObjIFace) valObj).getId().intValue())) {
                            fndInx = i;
                            break;
                        }
                    } else {
                        Object pliVal = pli.getValue() == null ? pli.getTitle() : pli.getValue();
                        if (pliVal != null && pliVal.equals(value.toString())) {
                            fndInx = i;
                            break;
                        }
                    }
                } else {
                    Object pliObj = pli.getValue();
                    if (pliObj != null && pliObj.equals(value.toString())) // really should never be null!
                    {
                        fndInx = i;
                        break;
                    }
                }
            }

            // Decided to just let non-existent vales pass on by
            if (fndInx == -1 && adapter != null) {
                ComboBoxModel<?> cbxModel = comboBox.getModel();
                if (cbxModel instanceof PickListDBAdapterIFace) {
                    PickListDBAdapterIFace pla = (PickListDBAdapterIFace) comboBox.getModel();
                    PickListIFace pickList = pla.getPickList();
                    if (!pickList.getReadOnly()) {
                        textEditor.setText(value.toString());

                    } else {
                        UIRegistry.showLocalizedError("ValComboBox.PL_ITEM_NOTFND", value.toString());//$NON-NLS-1$
                    }
                } else {
                    if (adapter.isReadOnly()) {
                        UIRegistry.showLocalizedError("ValComboBox.PL_ITEM_NOTFND", value.toString());//$NON-NLS-1$
                    }
                }
            }

        } else {
            for (int i = 0; i < comboBox.getItemCount(); i++) {
                Object item = model.getElementAt(i);
                if (item instanceof String) {
                    String val = value != null && StringUtils.isEmpty(value.toString())
                            && StringUtils.isNotEmpty(defaultValue) ? defaultValue
                                    : (value != null ? value.toString() : "");
                    if (((String) item).equals(val)) {
                        fndInx = i;
                        break;
                    }
                } else if ((isFormObjIFace && item == value) || item.equals(value)) {
                    fndInx = i;
                    break;

                } else if (item instanceof PickListItemIFace) {
                    PickListItemIFace pli = (PickListItemIFace) item;
                    String pliValue = pli.getValue();
                    if (pliValue != null && pliValue.equals(value)) {
                        fndInx = i;
                        break;
                    }
                }
            }
        }

        if (fndInx != -1) {
            this.valState = UIValidatable.ErrorType.Valid;

        } else {
            this.valState = (adapter != null && isRequired) || isRequired ? UIValidatable.ErrorType.Incomplete
                    : UIValidatable.ErrorType.Valid;
        }
    } else {
        if (nullIndex == null) {
            if (adapter != null) {
                int inx = 0;
                for (PickListItemIFace item : adapter.getList()) {
                    if (item != null && item.getValue() != null) {
                        if (item.getValue().equals("|null|")) {
                            nullIndex = inx;
                            comboBox.setSelectedIndex(nullIndex);
                            break;
                        }
                    } else if (item != null && item.getValueObject() == null) {
                        log.error("PickList item's value was null and it can't be. Title[" + item.getTitle()
                                + "]");
                    }
                    inx++;
                }
                if (nullIndex == null) {
                    nullIndex = -1;
                }
            }
        } else if (nullIndex > -1) {
            comboBox.setSelectedIndex(nullIndex);
            return;
        }

        if (isRequired && comboBox.getSelectedIndex() == -1 && adapter != null && adapter.getList() != null
                && adapter.getList().size() == 1) {
            fndInx = -1;
            valState = isRequired ? UIValidatable.ErrorType.Incomplete : UIValidatable.ErrorType.Valid;
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (isNew) {
                        valState = UIValidatable.ErrorType.Valid;
                        comboBox.setSelectedIndex(0);
                    }
                }
            });

        } else {
            valState = isRequired && comboBox.getSelectedIndex() == -1 ? UIValidatable.ErrorType.Incomplete
                    : UIValidatable.ErrorType.Valid;
            if (textEditor != null) {
                textEditor.setText("");
            }
        }
    }

    if ((adapter instanceof PickListTableAdapter)
            || Java2sAutoComboBox.shouldSetComboboxIndex(comboBox, fndInx)) {
        comboBox.setSelectedIndex(fndInx);
    }

    if (textEditor != null && fndInx == -1 && (value != null || defaultValue != null)) {
        textEditor.setText(value != null ? value.toString() : defaultValue);
    }

    repaint();
}

From source file:io.github.jeddict.jpa.modeler.source.generator.ui.GenerateCodeDialog.java

private void populatePackageCombo(JComboBox packageCombo, ProjectInfo projectInfo) {
    if (projectInfo.getSourceGroup() != null) {
        packageCombo.setRenderer(PackageView.listRenderer());
        ComboBoxModel model = PackageView.createListView(projectInfo.getSourceGroup());
        if (model.getSize() > 0) {
            model.setSelectedItem(model.getElementAt(0));
        }//from   w w  w  .  ja  va  2  s  . c o  m
        packageCombo.setModel(model);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.FormPane.java

protected Vector<Object> getValues(final WorkbenchTemplateMappingItem wbtmi) {
    Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>();
    wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(wbtmis);/*from ww  w  .j  a  v a2 s.  co m*/
    int wbCol = -1;
    for (int c = 0; c < wbtmis.size(); c++) {
        if (wbtmis.get(c) == wbtmi) {
            wbCol = c;
            break;
        }
    }
    if (wbCol != -1) {
        if (workbenchPane.getSpreadSheet().getColumnModel().getColumn(wbCol)
                .getCellEditor() instanceof WorkbenchPaneSS.GridCellListEditor) {
            ComboBoxModel model = ((WorkbenchPaneSS.GridCellListEditor) workbenchPane.getSpreadSheet()
                    .getColumnModel().getColumn(wbCol).getCellEditor()).getList();
            Vector<Object> result = new Vector<Object>();
            for (int i = 0; i < model.getSize(); i++) {
                result.add(model.getElementAt(i));
            }
            return result;
        }
    }
    return null;
}

From source file:gdt.jgui.entity.query.JQueryPanel.java

private void setSelection(JComboBox<String> comboBox, String item$) {
    ComboBoxModel<String> model = comboBox.getModel();
    if (model != null) {
        int cnt = model.getSize();
        String[] sa = null;/*from  w  ww  .  ja  va  2s .c  om*/
        if (cnt > 0) {
            sa = new String[cnt];
            for (int i = 0; i < cnt; i++)
                if (item$.equals(model.getElementAt(i))) {
                    comboBox.setSelectedIndex(i);
                    return;
                }
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

/**
 * Sets the appropriate index in the combobox for the value
 * @param comboBox the combobox//  w  ww  .j  av  a2s .  co  m
 * @param data the data value
 */
protected static void setComboboxValue(final JComboBox comboBox, final Object data) {
    ComboBoxModel model = comboBox.getModel();

    for (int i = 0; i < comboBox.getItemCount(); i++) {
        Object item = model.getElementAt(i);
        if (item instanceof String) {
            if (((String) item).equals(data)) {
                comboBox.setSelectedIndex(i);
                break;
            }
        } else if (item.equals(data)) {
            comboBox.setSelectedIndex(i);
            break;
        }
    }

}