Example usage for javax.swing DefaultComboBoxModel setSelectedItem

List of usage examples for javax.swing DefaultComboBoxModel setSelectedItem

Introduction

In this page you can find the example usage for javax.swing DefaultComboBoxModel setSelectedItem.

Prototype

public void setSelectedItem(Object anObject) 

Source Link

Document

Set the value of the selected item.

Usage

From source file:Main.java

public static void main(String[] args) {
    Object[] items = new Object[] { "Dog", "Cat", "Other" };
    DefaultComboBoxModel dcbm = new DefaultComboBoxModel(items);
    JComboBox comboBox = new JComboBox(dcbm);
    comboBox.setPreferredSize(new Dimension(200, 20));
    comboBox.addItemListener(e -> {/*  w ww  .  j a  v a 2 s.  c  o m*/
        Object selectedItem = comboBox.getSelectedItem();
        boolean editable = selectedItem instanceof String && ((String) selectedItem).equals("Other");
        comboBox.setEditable(editable);
    });
    comboBox.getEditor().addActionListener(e -> {
        Object newItem = comboBox.getEditor().getItem();
        DefaultComboBoxModel d = (DefaultComboBoxModel) comboBox.getModel();
        d.addElement(newItem);
        d.setSelectedItem(newItem);

    });

    JPanel content = new JPanel(new FlowLayout());
    content.add(new JLabel("Test:"));
    content.add(comboBox);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(content);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

public static void main(final String args[]) {
    final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();

    model.addElement("A");
    model.addElement("C");
    model.addElement("D");
    model.addElement("A");

    model.setSelectedItem("C");

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox<String> comboBox1 = new JComboBox<String>(model);
    comboBox1.setMaximumRowCount(5);//w ww  .ja v a2 s  .  c  o  m
    comboBox1.setEditable(true);
    frame.add(comboBox1, BorderLayout.NORTH);

    JList<String> jlist = new JList<String>(model);
    JScrollPane scrollPane = new JScrollPane(jlist);
    frame.add(scrollPane, BorderLayout.CENTER);

    JButton button = new JButton("Add");
    frame.add(button, BorderLayout.SOUTH);
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            model.addElement("a");
            model.insertElementAt("Z", 0);
        }
    };
    button.addActionListener(actionListener);

    frame.setSize(300, 200);
    frame.setVisible(true);
}

From source file:com.microsoft.azuretools.ijidea.ui.AppServiceChangeSettingsDialog.java

protected AppServiceChangeSettingsDialog(Project project, WebAppDetails wad) {
    super(project);

    setTitle("Change App Service Settings");

    setOKButtonText("Change");

    webApp = wad.webApp;//from ww  w  .j  a  v  a  2s  . co m
    textFieldWebappName.setText(wad.webApp.name());
    textFieldWebappName.setEnabled(false);

    DefaultComboBoxModel<WebContainer> wcModel = (DefaultComboBoxModel<WebContainer>) comboBoxWebContainer
            .getModel();
    if (wad.webApp.javaVersion() != JavaVersion.OFF) {
        wcModel.setSelectedItem(
                new WebContainer(wad.webApp.javaContainer() + " " + wad.webApp.javaContainerVersion()));
    }

    comboBoxSubscription.setEnabled(false);

    DefaultComboBoxModel<ResourceGroupAdapter> rgModel = (DefaultComboBoxModel<ResourceGroupAdapter>) comboBoxResourceGroup
            .getModel();
    rgModel.setSelectedItem(new ResourceGroupAdapter(wad.resourceGroup));
    for (Component c : panelResourceGroupUseExisting.getComponents()) {
        c.setEnabled(false);
    }

    for (Component c : panelResourceGroup.getComponents()) {
        c.setEnabled(false);
    }

    DefaultComboBoxModel<AppServicePlanAdapter> aspModel = (DefaultComboBoxModel<AppServicePlanAdapter>) comboBoxAppServicePlan
            .getModel();
    aspModel.setSelectedItem(new AppServicePlanAdapter(wad.appServicePlan));
    //comboBoxAppServicePlan.setEnabled(false);
    for (Component c : panelAppServiceUseExisting.getComponents()) {
        c.setEnabled(false);
    }

    for (Component c : panelAppServicePlan.getComponents()) {
        c.setEnabled(false);
    }
}

From source file:org.pentaho.reporting.designer.extensions.legacycharts.LegacyChartEditModel.java

private void populateExpressionSelectorModel(final DefaultComboBoxModel model, final Class resultType) {
    model.removeAllElements();//from   w w  w . ja  va  2  s .  c o  m
    if (resultType == null) {
        model.setSelectedItem(null);
        return;
    }

    final ExpressionMetaData[] allExpressionMetaDatas = ExpressionRegistry.getInstance()
            .getAllExpressionMetaDatas();
    Arrays.sort(allExpressionMetaDatas, new GroupedMetaDataComparator());
    for (int i = 0; i < allExpressionMetaDatas.length; i++) {
        final ExpressionMetaData data = allExpressionMetaDatas[i];
        if (data.isHidden()) {
            continue;
        }
        if (!WorkspaceSettings.getInstance().isVisible(data)) {
            continue;
        }
        if (StructureFunction.class.isAssignableFrom(data.getExpressionType())) {
            continue;
        }

        if (resultType.isAssignableFrom(data.getResultType())) {
            model.addElement(data);
        }
    }

    model.setSelectedItem(null);
}

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

/**
 * Select appropriate field value from combobox
 * @param switchFormatter// w  w w .ja  v  a  2  s  .c o m
 */
protected void updateValueFieldCombo(final DataObjSwitchFormatter switchFormatter) {
    if (switchFormatter == null || switchFormatter.getFieldName() == null) {
        return;
    }

    if (customEditor == null) {
        DefaultComboBoxModel cboModel = (DefaultComboBoxModel) valueFieldCbo.getModel();
        cboModel.setSelectedItem(tableInfo.getFieldByName(switchFormatter.getFieldName()));
    }
}

From source file:de.naoth.xabsleditor.graphpanel.AgentVisualizer.java

private void recreateAgentSelector(XABSLContext context) {
    DefaultComboBoxModel model = new DefaultComboBoxModel();

    model.addElement("(all)");
    for (String agent : context.getAgentMap().keySet()) {
        model.addElement(agent);//from  www.  j a  va  2 s  .  co  m
    }

    cbAgentSelector.setModel(model);

    if (lastSelectedAgentName != null) {
        model.setSelectedItem(lastSelectedAgentName);
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchTroopsFrame.java

private void addTroopsManuallyEvent() {
    HashMap<Integer, Tribe> tribes = DataHolder.getSingleton().getTribes();

    List<Tribe> tribesList = new LinkedList<>();
    for (Tribe t : tribes.values()) {
        tribesList.add(t);// w  w w .ja v  a  2 s .  com
    }
    Collections.sort(tribesList, Tribe.CASE_INSENSITIVE_ORDER);

    DefaultComboBoxModel model = new DefaultComboBoxModel(tribesList.toArray(new Tribe[tribesList.size()]));
    jTroopAddTribe.setModel(model);
    model.setSelectedItem(GlobalOptions.getSelectedProfile().getTribe());
    jTroopsAddDialog.setLocationRelativeTo(DSWorkbenchTroopsFrame.this);
    jTroopsAddDialog.setVisible(true);
}

From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java

private void fillSubscriptions() {
    //        try {
    List<Subscription> subscriptionList = AzureManagerImpl.getManager(project).getSubscriptionList();
    DefaultComboBoxModel subscriptionComboModel = new DefaultComboBoxModel(subscriptionList.toArray());
    subscriptionComboModel.setSelectedItem(null);
    subscriptionComboBox.setModel(subscriptionComboModel);
    if (!subscriptionList.isEmpty()) {
        subscriptionComboBox.setSelectedIndex(0);
    }/*  w  w w  .ja v a  2 s. c  om*/
    //        } catch (AzureCmdException e) {
    //            String msg = "An error occurred while trying to load the subscriptions list." + "\n" + String.format(message("webappExpMsg"), e.getMessage());
    //            PluginUtil.displayErrorDialogAndLog(message("errTtl"), msg, e);
    //        }
}

From source file:com.xue777hua.emails.frames.EmailCrawlerJFrame.java

/**
 * Creates new form EmailCrawlerJFrame/*  w  w w  . java 2s.c om*/
 */
public EmailCrawlerJFrame() {
    initComponents();
    DefaultComboBoxModel year1Model = new DefaultComboBoxModel();
    DefaultComboBoxModel year2Model = new DefaultComboBoxModel();
    int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    for (int i = currentYear; i >= 1823; i--) {
        year1Model.addElement(String.valueOf(i));
    }
    year1Model.setSelectedItem(String.valueOf(currentYear - 10));
    year2Model.addElement("Present");
    for (int i = currentYear - 1; i >= 1823; i--) {
        year2Model.addElement(String.valueOf(i));
    }
    fromDate.setModel(year1Model);
    toDate.setModel(year2Model);
}

From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java

private void fillResourceGroups(String valToSet) {
    try {//from   w ww.  j  a v  a2  s. com
        if (subscription != null) {
            final List<String> groupList = AzureManagerImpl.getManager(project)
                    .getResourceGroupNames(subscription.getId());
            DefaultComboBoxModel model = new DefaultComboBoxModel(groupList.toArray());
            model.insertElementAt(createResGrpLabel, 0);
            model.setSelectedItem(null);
            groupComboBox.setModel(model);
            if (!groupList.isEmpty()) {
                if (valToSet != null && !valToSet.isEmpty()) {
                    groupComboBox.setSelectedItem(valToSet);
                } else {
                    groupComboBox.setSelectedIndex(1);
                }
                // prepare list of App Service plans for selected subscription
                if (fillPlansAcrossSub != null && !fillPlansAcrossSub.isFinished()) {
                    fillPlansAcrossSub.cancel();
                }
                IDEHelper.ProjectDescriptor projectDescriptor = new IDEHelper.ProjectDescriptor(
                        project.getName(), project.getBasePath() == null ? "" : project.getBasePath());
                fillPlansAcrossSub = DefaultLoader.getIdeHelper().runInBackground(projectDescriptor,
                        "Loading service plans...", null, new CancellableTask() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSuccess() {
                            }

                            @Override
                            public void onError(@NotNull Throwable throwable) {
                            }

                            @Override
                            public synchronized void run(final CancellationHandle cancellationHandle)
                                    throws Throwable {
                                plansAcrossSub = new ArrayList<String>();
                                for (String groupName : groupList) {
                                    List<WebHostingPlanCache> plans = AzureManagerImpl.getManager(project)
                                            .getWebHostingPlans(subscription.getId(), groupName);
                                    for (WebHostingPlanCache plan : plans) {
                                        plansAcrossSub.add(plan.getName());
                                    }
                                }
                            }
                        });
            }
        }
    } catch (AzureCmdException e) {
        String msg = "An error occurred while loading the resource groups." + "\n"
                + String.format(message("webappExpMsg"), e.getMessage());
        PluginUtil.displayErrorDialogAndLog(message("errTtl"), msg, e);
    }
}