Example usage for javax.swing JComboBox getModel

List of usage examples for javax.swing JComboBox getModel

Introduction

In this page you can find the example usage for javax.swing JComboBox getModel.

Prototype

public ComboBoxModel<E> getModel() 

Source Link

Document

Returns the data model currently used by the JComboBox.

Usage

From source file:org.smart.migrate.ui.UpdateRelatePKDialog.java

private void getParam(String key, JComboBox cbx) {
    cbx.getModel().setSelectedItem(preferences.get(key, null));
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private void initToolbar() {
    toolBar = new JToolBar();
    final JComboBox searchMode = new JComboBox(
            new String[] { "String contains search: ", "Regex search: ", "Query search: " });
    final SearchAction searchActionForward = new SearchAction(otrosApplication, SearchDirection.FORWARD);
    final SearchAction searchActionBackward = new SearchAction(otrosApplication, SearchDirection.REVERSE);
    searchFieldCbxModel = new DefaultComboBoxModel();
    searchField = new JXComboBox(searchFieldCbxModel);
    searchField.setEditable(true);/*w ww.j  a  va 2 s  .com*/
    AutoCompleteDecorator.decorate(searchField);
    searchField.setMinimumSize(new Dimension(150, 10));
    searchField.setPreferredSize(new Dimension(250, 10));
    searchField.setToolTipText(
            "<HTML>Enter text to search.<BR/>" + "Enter - search next,<BR/>Alt+Enter search previous,<BR/>"
                    + "Ctrl+Enter - mark all found</HTML>");
    final DelayedSwingInvoke delayedSearchResultUpdate = new DelayedSwingInvoke() {
        @Override
        protected void performActionHook() {
            JTextComponent editorComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
            int stringEnd = editorComponent.getSelectionStart();
            if (stringEnd < 0) {
                stringEnd = editorComponent.getText().length();
            }
            try {
                String selectedText = editorComponent.getText(0, stringEnd);
                if (StringUtils.isBlank(selectedText)) {
                    return;
                }
                OtrosJTextWithRulerScrollPane<JTextPane> logDetailWithRulerScrollPane = otrosApplication
                        .getSelectedLogViewPanel().getLogDetailWithRulerScrollPane();
                MessageUpdateUtils.highlightSearchResult(logDetailWithRulerScrollPane,
                        otrosApplication.getAllPluginables().getMessageColorizers());
                RulerBarHelper.scrollToFirstMarker(logDetailWithRulerScrollPane);
            } catch (BadLocationException e) {
                LOGGER.log(Level.SEVERE, "Can't update search highlight", e);
            }
        }
    };
    JTextComponent searchFieldTextComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
    searchFieldTextComponent.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
        @Override
        protected void documentChanged(DocumentEvent e) {
            delayedSearchResultUpdate.performAction();
        }
    });
    final MarkAllFoundAction markAllFoundAction = new MarkAllFoundAction(otrosApplication);
    final SearchModeValidatorDocumentListener searchValidatorDocumentListener = new SearchModeValidatorDocumentListener(
            (JTextField) searchField.getEditor().getEditorComponent(), observer, SearchMode.STRING_CONTAINS);
    SearchMode searchModeFromConfig = configuration.get(SearchMode.class, "gui.searchMode",
            SearchMode.STRING_CONTAINS);
    final String lastSearchString;
    int selectedSearchMode = 0;
    if (searchModeFromConfig.equals(SearchMode.STRING_CONTAINS)) {
        selectedSearchMode = 0;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_STRING, "");
    } else if (searchModeFromConfig.equals(SearchMode.REGEX)) {
        selectedSearchMode = 1;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_REGEX, "");
    } else if (searchModeFromConfig.equals(SearchMode.QUERY)) {
        selectedSearchMode = 2;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_QUERY, "");
    } else {
        LOGGER.warning("Unknown search mode " + searchModeFromConfig);
        lastSearchString = "";
    }
    Component editorComponent = searchField.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        final JTextField sfTf = (JTextField) editorComponent;
        sfTf.getDocument().addDocumentListener(searchValidatorDocumentListener);
        sfTf.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
            @Override
            protected void documentChanged(DocumentEvent e) {
                try {
                    int length = e.getDocument().getLength();
                    if (length > 0) {
                        searchResultColorizer.setSearchString(e.getDocument().getText(0, length));
                    }
                } catch (BadLocationException e1) {
                    LOGGER.log(Level.SEVERE, "Error: ", e1);
                }
            }
        });
        sfTf.addKeyListener(new SearchFieldKeyListener(searchActionForward, sfTf));
        sfTf.setText(lastSearchString);
    }
    searchMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SearchMode mode = null;
            boolean validationEnabled = false;
            String confKey = null;
            String lastSearch = ((JTextField) searchField.getEditor().getEditorComponent()).getText();
            if (searchMode.getSelectedIndex() == 0) {
                mode = SearchMode.STRING_CONTAINS;
                searchValidatorDocumentListener.setSearchMode(mode);
                validationEnabled = false;
                searchMode.setToolTipText("Checking if log message contains string (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_STRING;
            } else if (searchMode.getSelectedIndex() == 1) {
                mode = SearchMode.REGEX;
                validationEnabled = true;
                searchMode
                        .setToolTipText("Checking if log message matches regular expression (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_REGEX;
            } else if (searchMode.getSelectedIndex() == 2) {
                mode = SearchMode.QUERY;
                validationEnabled = true;
                String querySearchTooltip = "<HTML>" + //
                "Advance search using SQL-like quries (i.e. level>=warning && msg~=failed && thread==t1)<BR/>" + //
                "Valid operator for query search is ==, ~=, !=, LIKE, EXISTS, <, <=, >, >=, &&, ||, ! <BR/>" + //
                "See wiki for more info<BR/>" + //
                "</HTML>";
                searchMode.setToolTipText(querySearchTooltip);
                confKey = ConfKeys.SEARCH_LAST_QUERY;
            }
            searchValidatorDocumentListener.setSearchMode(mode);
            searchValidatorDocumentListener.setEnable(validationEnabled);
            searchActionForward.setSearchMode(mode);
            searchActionBackward.setSearchMode(mode);
            markAllFoundAction.setSearchMode(mode);
            configuration.setProperty("gui.searchMode", mode);
            searchResultColorizer.setSearchMode(mode);
            List<Object> list = configuration.getList(confKey);
            searchFieldCbxModel.removeAllElements();
            for (Object o : list) {
                searchFieldCbxModel.addElement(o);
            }
            searchField.setSelectedItem(lastSearch);
        }
    });
    searchMode.setSelectedIndex(selectedSearchMode);
    final JCheckBox markFound = new JCheckBox("Mark search result");
    markFound.setMnemonic(KeyEvent.VK_M);
    searchField.addKeyListener(markAllFoundAction);
    configuration.addConfigurationListener(markAllFoundAction);
    JButton markAllFoundButton = new JButton(markAllFoundAction);
    final JComboBox markColor = new JComboBox(MarkerColors.values());
    markFound.setSelected(configuration.getBoolean("gui.markFound", true));
    markFound.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean selected = markFound.isSelected();
            searchActionForward.setMarkFound(selected);
            searchActionBackward.setMarkFound(selected);
            configuration.setProperty("gui.markFound", markFound.isSelected());
        }
    });
    markColor.setRenderer(new MarkerColorsComboBoxRenderer());
    //      markColor.addActionListener(new ActionListener() {
    //
    //         @Override
    //         public void actionPerformed(ActionEvent e) {
    //            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
    //            searchActionForward.setMarkerColors(markerColors);
    //            searchActionBackward.setMarkerColors(markerColors);
    //            markAllFoundAction.setMarkerColors(markerColors);
    //            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
    //            otrosApplication.setSelectedMarkColors(markerColors);
    //         }
    //      });
    markColor.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
            searchActionForward.setMarkerColors(markerColors);
            searchActionBackward.setMarkerColors(markerColors);
            markAllFoundAction.setMarkerColors(markerColors);
            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
            otrosApplication.setSelectedMarkColors(markerColors);
        }
    });
    markColor.getModel()
            .setSelectedItem(configuration.get(MarkerColors.class, "gui.markColor", MarkerColors.Aqua));
    buttonSearch = new JButton(searchActionForward);
    buttonSearch.setMnemonic(KeyEvent.VK_N);
    JButton buttonSearchPrev = new JButton(searchActionBackward);
    buttonSearchPrev.setMnemonic(KeyEvent.VK_P);
    enableDisableComponetsForTabs.addComponet(buttonSearch);
    enableDisableComponetsForTabs.addComponet(buttonSearchPrev);
    enableDisableComponetsForTabs.addComponet(searchField);
    enableDisableComponetsForTabs.addComponet(markFound);
    enableDisableComponetsForTabs.addComponet(markAllFoundButton);
    enableDisableComponetsForTabs.addComponet(searchMode);
    enableDisableComponetsForTabs.addComponet(markColor);
    toolBar.add(searchMode);
    toolBar.add(searchField);
    toolBar.add(buttonSearch);
    toolBar.add(buttonSearchPrev);
    toolBar.add(markFound);
    toolBar.add(markAllFoundButton);
    toolBar.add(markColor);
    JButton nextMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.FORWARD));
    nextMarked.setToolTipText(nextMarked.getText());
    nextMarked.setText("");
    nextMarked.setMnemonic(KeyEvent.VK_E);
    enableDisableComponetsForTabs.addComponet(nextMarked);
    toolBar.add(nextMarked);
    JButton prevMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.BACKWARD));
    prevMarked.setToolTipText(prevMarked.getText());
    prevMarked.setText("");
    prevMarked.setMnemonic(KeyEvent.VK_R);
    enableDisableComponetsForTabs.addComponet(prevMarked);
    toolBar.add(prevMarked);
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.SEVERE)));
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.SEVERE)));
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

@SuppressWarnings("unchecked")
private void initParameterValue(JComponent component, Object value, String paramName,
        List<Serializable> defaultValues) {
    if (value == null) {
        return;//from  w  w  w . j a  va 2s .c  o m
    }
    if (component instanceof JTextField) {
        ((JTextField) component).setText(value.toString());
    } else if (component instanceof JComboBox) {
        JComboBox combo = ((JComboBox) component);
        List<IdName> values = (List<IdName>) value;
        combo.removeAllItems();
        combo.addItem("-- " + I18NSupport.getString("parameter.value.select") + " --");
        for (int j = 0, len = values.size(); j < len; j++) {
            combo.addItem(values.get(j));
        }
        Object old = parametersValues.get(paramName);
        if (old != null) {
            combo.setSelectedItem(old);
        } else if ((defaultValues != null) && (defaultValues.size() > 0)) {
            Serializable id = defaultValues.get(0);
            if (id instanceof IdName) {
                id = ((IdName) id).getId();
            }
            combo.setSelectedItem(findIdName(combo.getModel(), id));
        }
    } else if (component instanceof ListSelectionPanel) {
        ListSelectionPanel lsp = (ListSelectionPanel) component;
        DefaultListModel model = new DefaultListModel();
        if (value != null) {
            List<IdName> values = (List<IdName>) value;
            for (int j = 0, len = values.size(); j < len; j++) {
                model.addElement(values.get(j));
            }
        }
        ArrayList srcList = new ArrayList(Arrays.asList(model.toArray()));

        Object old = parametersValues.get(paramName);
        Object[] selected = new Object[0];
        if (old != null) {
            selected = (Object[]) old;
        } else if ((defaultValues != null) && (defaultValues.size() > 0)) {
            selected = new Object[defaultValues.size()];
            for (int k = 0, len = selected.length; k < len; k++) {
                Serializable id = defaultValues.get(k);
                if (id instanceof IdName) {
                    id = ((IdName) id).getId();
                }
                IdName in = findIdName(srcList, id);
                selected[k] = in;
            }
        }
        List dstList = Arrays.asList(selected);

        if (!srcList.containsAll(dstList)) {
            dstList = new ArrayList();
            parametersValues.put(paramName, null);
        } else {
            srcList.removeAll(dstList);
        }
        if ((dstList.size() == 1) && ParameterUtil.NULL.equals(dstList.get(0))) {
            dstList = new ArrayList();
        }
        lsp.setLists(srcList, dstList);

    } else if (component instanceof ListAddPanel) {
        ListAddPanel lap = (ListAddPanel) component;
        DefaultListModel model = new DefaultListModel();
        if (value != null) {
            List<Object> values = (List<Object>) value;
            for (int j = 0, len = values.size(); j < len; j++) {
                model.addElement(values.get(j));
            }
        }
        ArrayList srcList = new ArrayList(Arrays.asList(model.toArray()));

        Object old = parametersValues.get(paramName);
        Object[] selected = new Object[0];
        if (old != null) {
            selected = (Object[]) old;
        } else if ((defaultValues != null) && (defaultValues.size() > 0)) {
            selected = new Object[defaultValues.size()];
            for (int k = 0, len = selected.length; k < len; k++) {
                Serializable id = defaultValues.get(k);
                if (id instanceof IdName) {
                    id = ((IdName) id).getId();
                }
                selected[k] = id;
            }
        }
        List dstList = Arrays.asList(selected);
        if (!srcList.containsAll(dstList)) {
            dstList = new ArrayList();
            parametersValues.put(paramName, null);
        } else {
            srcList.removeAll(dstList);
        }
        if ((dstList.size() == 1) && ParameterUtil.NULL.equals(dstList.get(0))) {
            dstList = new ArrayList();
        }

        lap.setElements(dstList);
    } else if (component instanceof JDateTimePicker) {
        ((JDateTimePicker) component).setDate((Date) value);
    } else if (component instanceof JXDatePicker) {
        ((JXDatePicker) component).setDate((Date) value);
    } else if (component instanceof JCheckBox) {
        ((JCheckBox) component).setSelected((Boolean) value);
    }
}

From source file:storybook.model.EntityUtil.java

@SuppressWarnings("unchecked")
public static void fillAutoCombo(MainFrame mainFrame, AutoCompleteComboBox autoCombo,
        AbstractEntityHandler entityHandler, String text, String methodName) {
    try {//  w ww  . j  a v  a 2 s  .co m
        JComboBox combo = autoCombo.getJComboBox();
        combo.removeAllItems();
        BookModel model = mainFrame.getBookModel();
        Session session = model.beginTransaction();
        SbGenericDAOImpl<?, ?> dao = entityHandler.createDAO();
        dao.setSession(session);
        Method m = dao.getClass().getMethod(methodName, (Class<?>[]) null);
        List<Object> items = (List<Object>) m.invoke(dao);
        model.commit();
        for (Object item : items) {
            if (item == null || ((item instanceof String) && (((String) item).isEmpty()))) {
                continue;
            }
            combo.addItem(item);
        }
        combo.addItem("");
        combo.getModel().setSelectedItem(text);
        combo.revalidate();
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        SbApp.error("EntityUtil.copyEntityProperties()", e);
    }
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Checks whether an input (query or connect string) is already in its
 * associated combo box. If not, the new information is added to the combo
 * list//from w  w w.  j  a va 2s .  c  om
 * 
 * @param combo
 *          JComboBox which has a list of the query statements or connect
 *          strings.
 */
private void checkForNewString(JComboBox combo) {
    // String newString, foundString;
    Object newValue;
    int checkDups, matchAt;
    boolean match;
    // boolean newCommented, foundCommented;

    // newCommented = foundCommented = false;
    matchAt = -1;

    if (combo == querySelection) {
        newValue = new Query(queryText.getText(), whichModeValue());
        // newString = queryText.getText();
        // newString = newString.replace('\n', ' ');
    } else {
        // newString = (String)combo.getEditor().getItem();
        newValue = combo.getEditor().getItem();
    }

    // if (newString.startsWith(COMMENT_PREFIX)) {
    // newCommented = true;
    // newString = newString.substring(2);
    // }

    // if (newString.trim().length() > 0) {
    if (newValue.toString().length() > 0) {
        match = false;
        for (checkDups = 0; checkDups < combo.getItemCount() && !match; ++checkDups) {
            // if (combo == querySelection) {
            // foundString = ((Query)combo.getItemAt(checkDups)).getSQL();
            // } else {
            // foundString = ((String)combo.getItemAt(checkDups));
            // }

            // if (foundString.startsWith(COMMENT_PREFIX)) {
            // foundString = foundString.substring(2);
            // foundCommented = true;
            // } else {
            // foundCommented = false;
            // }

            // if (newString.equals(foundString)) {
            if (newValue.equals(combo.getItemAt(checkDups))) {
                match = true;
                if (combo == querySelection) {
                    ((Query) combo.getItemAt(checkDups)).setMode(whichModeValue());
                }
                combo.setSelectedIndex(checkDups);
                matchAt = checkDups;
            }
        }

        // if (newCommented) {
        // newString = COMMENT_PREFIX + newString;
        // }

        if (!match) {
            addToCombo(combo, newValue);
            if (combo == querySelection) {
                // addToCombo(combo, new Query(newString, whichModeValue()));
                combo.setSelectedIndex(combo.getModel().getSize() - 1);
                matchAt = combo.getSelectedIndex();
            }
        }
        // if (foundCommented != newCommented) {
        // if (combo == querySelection) {
        // replaceInCombo(combo, matchAt,
        // new Query(newString, whichModeValue()));
        // } else {
        // replaceInCombo(combo, matchAt, newString);
        // }
        // }
        if (combo == querySelection) {
            if (((Query) newValue).isCommented() != ((Query) combo.getSelectedItem()).isCommented()) {
                replaceInCombo(combo, matchAt, newValue);
            }
        }
    }
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Adds a new object in the combo box/*from  w  w w . j  a  v a 2s  . c  om*/
 * 
 * @param combo
 *          The JComboBox
 * @param newData
 *          The Object that is to be added
 */
private void addToCombo(JComboBox combo, Object newData) {
    ((DefaultComboBoxModel) combo.getModel()).addElement(newData);
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Replaces an existing object with a new one
 * //  w  ww .j a  v a2 s  .co m
 * @param combo
 *          The JComboBox
 * @param position
 *          The int value of the positon where the
 *          repalcement occurs
 * @param newData
 *          The new Object that is to be inserted in the combobox
 */
private void replaceInCombo(JComboBox combo, int position, Object newData) {
    ((DefaultComboBoxModel) combo.getModel()).removeElementAt(position);
    ((DefaultComboBoxModel) combo.getModel()).insertElementAt(newData, position);
    combo.setSelectedIndex(position);
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Writes all the queries in the query selection (or connection URLS) combobox
 * to the supplied file in a print formatted representation.
 * /*from   w w w  . jav  a  2  s  .  c  o  m*/
 * @param combo
 *          The JComboBox - it can be the combobox that contains
 *          all the queries or the combobox with the URLs
 * @param fileName
 *          The fileName to be written to contain the queries or the
 *          connect URLs
 */
private void writeOutCombo(JComboBox combo, String fileName) {
    PrintWriter out;

    if (combo != null) {
        out = null;
        try {
            out = new PrintWriter(new FileWriter(fileName));
            for (int i = 0; i < combo.getModel().getSize(); ++i) {
                if (combo == querySelection) {
                    out.println(((Query) combo.getModel().getElementAt(i)).getSql() + "["
                            + ((Query) combo.getModel().getElementAt(i)).getMode());
                } else {
                    out.println((String) combo.getModel().getElementAt(i));
                }
            }
        } catch (Exception any) {
            LOGGER.error("Failed to write out the content of the combobox", any);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception any) {
                    LOGGER.error("Failed to close the combobox output file", any);
                }
            }
        }
    }
}