Java Code Examples for javax.swing.JComboBox.setSelectedItem()

The following are Jave code examples for showing how to use setSelectedItem() of the javax.swing.JComboBox class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: VASSAL-src   File: StringEnumConfigurer.java   Source Code and License Vote up 6 votes
public Component getControls() {
  if (panel == null) {
    panel = Box.createHorizontalBox();
    panel.add(new JLabel(name));
    box = new JComboBox(validValues);
    box.setMaximumSize(new Dimension(box.getMaximumSize().width,box.getPreferredSize().height));
    if (isValidValue(getValue())) {
      box.setSelectedItem(getValue());
    }
    else if (validValues.length > 0) {
      box.setSelectedIndex(0);
    }
    box.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        noUpdate = true;
        setValue(box.getSelectedItem());
        noUpdate = false;
      }
    });
    panel.add(box);
  }
  return panel;
}
 
Example 2
Project: incubator-netbeans   File: ConfigurationsComboModel.java   Source Code and License Vote up 6 votes
public void confirm(EventObject fe) {
    JTextField tf = (JTextField) fe.getSource();
    JComboBox combo = (JComboBox) tf.getParent();
    if (combo==null)
        return;
    if (fe instanceof FocusEvent) {
        combo.getEditor().getEditorComponent().removeFocusListener(this);
    } else {
        combo.getEditor().getEditorComponent().removeKeyListener(this);
    }
    Configuration config = configName==null ? 
            ConfigurationsManager.getDefault().duplicate(lastSelected, tf.getText(), tf.getText()):
            ConfigurationsManager.getDefault().create(tf.getText(), tf.getText());
    combo.setSelectedItem(config);
    combo.setEditable(false);
    currentActiveItem = null;
}
 
Example 3
Project: incubator-netbeans   File: ConfigurationsComboModel.java   Source Code and License Vote up 6 votes
private void confirm(EventObject fe) {
    JTextField tf = (JTextField) fe.getSource();
    JComboBox combo = (JComboBox) tf.getParent();
    if (combo==null)
        return;
    if (fe instanceof FocusEvent) {
        combo.getEditor().getEditorComponent().removeFocusListener(this);
    } else {
        combo.getEditor().getEditorComponent().removeKeyListener(this);
    }
    Configuration config = configName==null ? 
            ConfigurationsManager.getDefault().duplicate(lastSelected, tf.getText(), tf.getText()):
            ConfigurationsManager.getDefault().create(tf.getText(), tf.getText());
    combo.setSelectedItem(config);
    combo.setEditable(false);
}
 
Example 4
Project: OpenDA   File: Query.java   Source Code and License Vote up 6 votes
/** Create a choice menu.
 *  @param name The name used to identify the entry (when calling get).
 *  @param label The label to attach to the entry.
 *  @param values The list of possible choices.
 *  @param defaultChoice Default choice.
 *  @param editable True if an arbitrary choice can be entered, in addition
 *   to the choices in values.
 *  @param background The background color for the editable part.
 */
public void addChoice(
        String name,
        String label,
        String[] values,
        String defaultChoice,
        boolean editable,
        Color background) {
    JLabel lbl = new JLabel(label + ": ");
    lbl.setBackground(_background);
    JComboBox combobox = new JComboBox(values);
    combobox.setEditable(editable);
    // FIXME: Typical of Swing, the following does not set
    // the background color.  How does one set the background
    // color?
    combobox.setBackground(background);
    combobox.setSelectedItem(defaultChoice);
    _addPair(name, lbl, combobox, combobox);
    // Add the listener last so that there is no notification
    // of the first value.
    combobox.addItemListener(new QueryItemListener(name));
}
 
Example 5
Project: incubator-netbeans   File: IssuePanel.java   Source Code and License Vote up 6 votes
private boolean selectInCombo(JComboBox combo, Object value, boolean forceInModel) {
    if (value == null) {
        return false;
    }
    if (!value.equals(combo.getSelectedItem())) {
        combo.setSelectedItem(value);
    } 
    if (forceInModel && !value.equals("") && !value.equals(combo.getSelectedItem())) { // NOI18N
        // Reload of server attributes is needed - workarounding it
        ComboBoxModel model = combo.getModel();
        if (model instanceof DefaultComboBoxModel) {
            ((DefaultComboBoxModel)model).insertElementAt(value, 0);
            combo.setSelectedIndex(0);
        }
    }
    return value.equals(combo.getSelectedItem());
}
 
Example 6
Project: incubator-netbeans   File: SearchPatternController.java   Source Code and License Vote up 5 votes
/**
 * Bind Match Type option to a combo box.
 *
 * @param comboBox Combo box to control and display the match type. The
 * model of the combo box can contain only items of type {@link MatchType}.
 * {@link MatchType#LITERAL} and {@link MatchType#REGEXP} are mandatory in
 * the model.
 *
 * @since api.search/1.11
 */
public void bindMatchTypeComboBox(@NonNull final JComboBox comboBox) {
    Parameters.notNull("comboBox", comboBox);                       //NOI18N

    boolean regexpFound = false, literalFound = false;
    for (int i = 0; i < comboBox.getItemCount(); i++) {
        if (comboBox.getItemAt(i) == MatchType.LITERAL) {
            literalFound = true;
        } else if (comboBox.getItemAt(i) == MatchType.REGEXP) {
            regexpFound = true;
        } else if (!(comboBox.getItemAt(i) instanceof MatchType)) {
            throw new IllegalArgumentException("Model of the combo "//NOI18N
                    + "box can contain only MatchType items");      //NOI18N
        }
    }
    if (!(regexpFound && literalFound)) {
        throw new IllegalArgumentException(
                "At least MatchType.LITERAL and MatchType.REGEXP " //NOI18N
                + "must be contained in the combo box model.");     //NOI18N
    }
    if (matchTypeComboBox != null) {
        throw new IllegalStateException(
                "Already bound with option MATCH_TYPE");            //NOI18N
    }
    this.matchTypeComboBox = comboBox;
    comboBox.setEditable(false);
    setMatchType(this.matchType); //update match type, check it is supported
    comboBox.setSelectedItem(matchType);
    comboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            setMatchType((MatchType) comboBox.getSelectedItem());
        }
    });
}
 
Example 7
Project: incubator-netbeans   File: FixDuplicateImportStmts.java   Source Code and License Vote up 5 votes
private JComboBox createComboBox(CandidateDescription[] choices, CandidateDescription defaultValue, Font font, FocusListener listener ) {
    JComboBox combo = new JComboBox(choices);
    combo.setSelectedItem(defaultValue);
    combo.getAccessibleContext().setAccessibleDescription(getBundleString("FixDupImportStmts_Combo_ACSD")); //NOI18N
    combo.getAccessibleContext().setAccessibleName(getBundleString("FixDupImportStmts_Combo_Name_ACSD")); //NOI18N
    combo.setOpaque(false);
    combo.setFont( font );
    combo.addFocusListener( listener );
    combo.setEnabled( choices.length > 1 );
    combo.setRenderer( new DelegatingRenderer(combo.getRenderer()));
    InputMap inputMap = combo.getInputMap( JComboBox.WHEN_FOCUSED );
    inputMap.put( KeyStroke.getKeyStroke( KeyEvent.VK_SPACE, 0), "showPopup" ); //NOI18N
    combo.getActionMap().put( "showPopup", new TogglePopupAction() ); //NOI18N
    return combo;
}
 
Example 8
Project: chipKIT-importer   File: SerialMonitorConfigPane.java   Source Code and License Vote up 5 votes
private JComboBox<String> createPortNameCombo() {
    final JComboBox <String> ret = new JComboBox<>( new SerialPortComboModel(model) );
    ret.addItemListener( (e) -> {            
        if ( e.getStateChange() == ItemEvent.SELECTED ) {
            model.setCurrentPortName( e.getItem().toString() );
        } else {
            model.setCurrentPortName( null );
        }
    });
    ret.setSelectedItem( model.getCurrentPortName() );
    return ret;
}
 
Example 9
Project: incubator-netbeans   File: EditLayoutSpacePanel.java   Source Code and License Vote up 5 votes
private static void initGapValues(EditableGap eg, JComboBox sizeCombo, JCheckBox resCheckBox) {
    if (eg != null) {
        String selected = null;
        String[] defaultNames = eg.getPaddingDisplayNames();
        if (eg.canHaveDefaultValue() && defaultNames != null) {
            sizeCombo.setModel(new DefaultComboBoxModel(defaultNames));
            if (eg.definedSize == LayoutConstants.NOT_EXPLICITLY_DEFINED) {
                LayoutConstants.PaddingType[] defaultTypes = eg.getPossiblePaddingTypes();
                if (eg.paddingType == null || defaultTypes == null || defaultTypes.length == 0) {
                    selected = defaultNames[0];
                } else {
                    for (int i=0; i < defaultTypes.length; i++) {
                        if (eg.paddingType == defaultTypes[i]) {
                            selected = defaultNames[i];
                            break;
                        }
                    }
                }
            }
        }
        if (selected == null) {
            selected = Integer.toString(eg.definedSize);
        }
        sizeCombo.setSelectedItem(selected);

        resCheckBox.setSelected(eg.resizing);
    } else {
        sizeCombo.setSelectedItem(NbBundle.getMessage(EditLayoutSpacePanel.class, "VALUE_NoEmptySpace")); // NOI18N
        sizeCombo.setEnabled(false);
        resCheckBox.setEnabled(false);
    }
}
 
Example 10
Project: Logisim   File: ComboOption.java   Source Code and License Vote up 5 votes
static void setSelected(JComboBox<?> combo, Object value) {
	for (int i = combo.getItemCount() - 1; i >= 0; i--) {
		ComboOption opt = (ComboOption) combo.getItemAt(i);
		if (opt.getValue().equals(value)) {
			combo.setSelectedItem(opt);
			return;
		}
	}
	combo.setSelectedItem(combo.getItemAt(0));
}
 
Example 11
Project: incubator-netbeans   File: RepositorySelectorBuilder.java   Source Code and License Vote up 5 votes
private void initializeCombo() {
    boolean hasExistingRepositories = (existingRepositories != null)
                                      && (existingRepositories.length != 0);
    boolean hasBugtrackingConnectors = (bugtrackingConnectors != null)
                                       && (bugtrackingConnectors.length != 0);

    if (!hasExistingRepositories && !hasBugtrackingConnectors) {
        throw new IllegalStateException("No data for the combo-box."); //NOI18N
    }

    String newConnectionFormatString
                = (bugtrackingConnectorDisplayFormat != null)
                  ? bugtrackingConnectorDisplayFormat
                  : NbBundle.getMessage(
                            ComboItemsRenderer.class,
                            "NewBugtrackingRepositoryConnection");  //NOI18N

    combo = new JComboBox(joinArrays(existingRepositories,
                                     createRepositoryInfos(bugtrackingConnectors)));
    combo.setRenderer(new ComboItemsRenderer(combo.getRenderer(),
                                             newConnectionFormatString));
    //combo.setEditable(false);

    if (repoToPreselect != null) {
        combo.setSelectedItem(repoToPreselect);
    }
    itemSelected(combo.getSelectedItem());
    combo.addItemListener(this);
    combo.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(RepositorySelectorBuilder.class, "RepositorySelectorBuilder.combo.accessibleDescription")); // NOI18N

    if (label != null) {
        bindLabelToCombo();
    }
}
 
Example 12
Project: OpenDA   File: VariationPerParameterTableController.java   Source Code and License Vote up 5 votes
public void populateTypeComboBox(JComboBox comboBox) {

		ArrayList<VariationFunctionContext> typeList;

		typeList = this.variationFunctionContextList;
		for (VariationFunctionContext context : typeList) {
			comboBox.addItem(context);
		}

		comboBox.setSelectedItem(this.defaultVariationFunctionContext);
	}
 
Example 13
Project: Logisim   File: PrefOption.java   Source Code and License Vote up 5 votes
static <Option> void setSelected(JComboBox<Option> combo, Object value) {
	for (int i = combo.getItemCount() - 1; i >= 0; i--) {
		PrefOption opt = (PrefOption) combo.getItemAt(i);
		if (opt.getValue().equals(value)) {
			combo.setSelectedItem(opt);
			return;
		}
	}
	combo.setSelectedItem(combo.getItemAt(0));
}
 
Example 14
Project: incubator-netbeans   File: ComboBoxUpdater.java   Source Code and License Vote up 5 votes
@Messages("HINT_inherited=Value is inherited from parent POM.")
    private void setComboValue(T value, T projectValue, JComboBox field) {
        if (!Utilities.compareObjects(value, projectValue)) {
            field.setSelectedItem(value != null ? value : field.getModel().getElementAt(0));
            component.setToolTipText(null);
            inherited = false;
            label.setFont(label.getFont().deriveFont(Font.BOLD));
        } else {
            field.setSelectedItem(projectValue != null ? projectValue : field.getModel().getElementAt(0));
//            field.setBackground(INHERITED);
            label.setFont(label.getFont().deriveFont(Font.PLAIN));
            component.setToolTipText(HINT_inherited());
            inherited = true;
      }
    }
 
Example 15
Project: incubator-netbeans   File: ColorComboBox.java   Source Code and License Vote up 5 votes
static void setColor (JComboBox<ColorValue> combo, Color color) {
    if (color == null) {
        combo.setSelectedIndex (content.length - 1);
    } else {
        combo.setSelectedItem (new ColorValue (color));
    }
}
 
Example 16
Project: incubator-netbeans   File: ConfigurationsComboModel.java   Source Code and License Vote up 5 votes
@Override
public void actionPerformed(ActionEvent ae) {
    JComboBox combo = (JComboBox) ae.getSource();
    combo.setEditable(true);
    combo.getEditor().getEditorComponent().addFocusListener(this);
    combo.getEditor().getEditorComponent().addKeyListener(this);
    combo.addPopupMenuListener(this);
    combo.setSelectedItem(configName == null ? lastSelected + "1" : configName);
}
 
Example 17
Project: incubator-netbeans   File: ConfigurationsComboModel.java   Source Code and License Vote up 5 votes
@Override
public void actionPerformed(ActionEvent ae) {
    JComboBox combo = (JComboBox) ae.getSource();
    combo.setEditable(true);
    JTextField editorComponent = (JTextField) combo.getEditor().getEditorComponent();
    editorComponent.addFocusListener(this);
    editorComponent.addKeyListener(this);
    combo.setSelectedItem(lastSelected);
    combo.addPopupMenuListener(this);
}
 
Example 18
Project: QN-ACTR-Release   File: DistributionsEditor.java   Source Code and License Vote up 4 votes
/**
 * Initialize this dialod's components and default dialog property
 */
protected void initComponents() {
	// Sets default title, close operation and dimensions
	this.setTitle("Editing Distribution...");
	int width = 320, height = 600;

	// Centers this dialog on the screen
	if (recursive) {
		this.centerWindowWithOffset(width, height, 50, 50);
	} else {
		this.centerWindow(width, height);
	}

	// Creates a main panel and adds margins to it
	JPanel mainpanel = new JPanel(new BorderLayout());
	mainpanel.setLayout(new BorderLayout());
	mainpanel.add(Box.createVerticalStrut(BORDERSIZE), BorderLayout.NORTH);
	mainpanel.add(Box.createVerticalStrut(BORDERSIZE), BorderLayout.SOUTH);
	mainpanel.add(Box.createHorizontalStrut(BORDERSIZE), BorderLayout.WEST);
	mainpanel.add(Box.createHorizontalStrut(BORDERSIZE), BorderLayout.EAST);
	this.getContentPane().add(mainpanel, BorderLayout.CENTER);

	// Creates a subpanel that holds scrolledpanel and distr_panel and adds it to mainpanel
	JPanel subpanel = new JPanel(new BorderLayout());
	mainpanel.add(subpanel, BorderLayout.CENTER);
	JPanel distr_panel = new JPanel(new BorderLayout());
	subpanel.add(distr_panel, BorderLayout.NORTH);

	// Creates scrolledpanel that holds param_panel and mean_c_panel
	scrolledPanel = new JPanel(new GridLayout(2, 1));
	subpanel.add(new JScrollPane(scrolledPanel), BorderLayout.CENTER);
	scrolledPanel.add(param_panel);
	scrolledPanel.add(mean_c_panel);
	mean_c_panel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.gray));

	// Adds bottom_panel to contentpane
	JPanel bottom_panel = new JPanel(new FlowLayout());
	this.getContentPane().add((bottom_panel), BorderLayout.SOUTH);

	// Adds Okay button to bottom_panel
	JButton okaybutton = new JButton(okayAction);
	bottom_panel.add(okaybutton);

	// Adds Cancel button to bottom_panel
	JButton cancelbutton = new JButton(cancelAction);
	bottom_panel.add(cancelbutton);

	// Adds distribution chooser
	distr_panel.add(new JLabel("Selected Distribution: "), BorderLayout.WEST);

	Set<String> distributionNameSet;
	if (recursive) {
		distributionNameSet = allowedNestedDistributions.keySet();
	} else {
		distributionNameSet = distributions.keySet();

	}

	Object[] distributionNames = distributionNameSet.toArray();
	Arrays.sort(distributionNames); // Sorts alphabetically distribution names
	choser = new JComboBox(distributionNames);
	choser.setToolTipText("Choose distribution type");
	// Select correct distribution
	if (current != null) {
		choser.setSelectedItem(current.getName());
		refreshView();
	}
	choser.addItemListener(change_listener);
	distr_panel.add(choser, BorderLayout.CENTER);

	// Adds image viewer with a couple of borders
	JPanel image_panel = new JPanel(new BorderLayout());
	distr_panel.add(image_panel, BorderLayout.SOUTH);
	image_panel.add(Box.createVerticalStrut(BORDERSIZE / 2), BorderLayout.NORTH);
	image_panel.add(Box.createVerticalStrut(BORDERSIZE / 2), BorderLayout.SOUTH);
	image_panel.add(iconpanel, BorderLayout.CENTER);
}
 
Example 19
Project: jmt   File: ParametricAnalysisPanel.java   Source Code and License Vote up 4 votes
public void initGui() {
	enabler = new JCheckBox("Enable What-If analysis");
	enabler.setToolTipText("Enable or disable What-If analysis");
	enablerPanel = new JPanel(new BorderLayout());
	enablerPanel.add(enabler, BorderLayout.WEST);
	upperPanel = new JPanel(new BorderLayout());
	chooserPanel = new JPanel();
	tb = new TitledBorder("Parameter selection for the control of repeated executions");
	chooserPanel.setBorder(tb);
	chooser = new JComboBox(parameters);
	chooser.setPreferredSize(DIM_BUTTON_L);
	chooser.setToolTipText("Choose the what-if analysis to be performed");
	chooserPanel.add(chooser, BorderLayout.NORTH);
	JLabel description = new JLabel(PARAMETRIC_ANALYSIS_DESCRIPTION);
	JLabel Warning = new JLabel (HTML_START + HTML_FONT_TITLE + "WARNING: "+ HTML_FONT_TIT_END + HTML_FONT_NORM
			+ "Enabling What-If analysis will disable all statistical outputs." + HTML_FONT_NOR_END + HTML_END);
	JPanel northPanel = new JPanel(new BorderLayout());
	northPanel.setBorder(new EmptyBorder(0, 0, 15, 0));
	northPanel.add(description, "Center");
	northPanel.add(Warning, "South");
	northPanel.add(enablerPanel, "East");
	upperPanel.add(northPanel, BorderLayout.NORTH);
	upperPanel.add(chooserPanel, BorderLayout.SOUTH);
	this.setLayout(new BorderLayout());
	this.setBorder(new EmptyBorder(20, 20, 20, 20));
	chooser.removeAllItems();
	ParametricAnalysisChecker pac = new ParametricAnalysisChecker(cd, sd, simd);
	if (!pac.canBeEnabled()) {
		enabler.setEnabled(false);
		parameterOptionPanel = createPanel(null);
		simd.setParametricAnalysisModel(null);
		simd.setParametricAnalysisEnabled(false);
	} else {
		enabler.setEnabled(true);
		enabler.setSelected(simd.isParametricAnalysisEnabled());
		ParametricAnalysisDefinition pad = simd.getParametricAnalysisModel();
		parameters = pac.getRunnableParametricAnalysis();
		for (String parameter : parameters) {
			chooser.addItem(parameter);
		}
		String temp = parameters[0];
		if (pad == null) {
			pad = ParametricAnalysisModelFactory.createParametricAnalysisModel(temp, cd, sd, simd);
			simd.setParametricAnalysisModel(pad);
		} else {
			int code = pad.checkCorrectness(true); //check correctness of the PAD and if it is possible corrects it
			if (code != 2) {
				chooser.setSelectedItem(pad.getType());
			} else { //the old type of parametric analysis is no more available
				pad = ParametricAnalysisModelFactory.createParametricAnalysisModel(temp, cd, sd, simd);
				simd.setParametricAnalysisModel(pad);
			}
		}
		parameterOptionPanel = createPanel(pad);
	}
	parameterOptionPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
	this.add(upperPanel, BorderLayout.NORTH);
	this.add(parameterOptionPanel, BorderLayout.CENTER);
	this.setEnabled(enabler.isSelected());
}
 
Example 20
Project: gate-core   File: FeaturesSchemaEditor.java   Source Code and License Vote up 4 votes
protected void prepareCombo(JComboBox combo, int row, int column){
  Feature feature = featureList.get(row);
  DefaultComboBoxModel comboModel = (DefaultComboBoxModel)combo.getModel(); 
  comboModel.removeAllElements();
  switch(column){
    case NAME_COL:
      List<String> fNames = new ArrayList<String>();
      if(schema != null && schema.getFeatureSchemaSet() != null){
        Iterator<FeatureSchema> fSchemaIter = schema.getFeatureSchemaSet().iterator();
        while(fSchemaIter.hasNext())
          fNames.add(fSchemaIter.next().getFeatureName());
      }
      if(!fNames.contains(feature.name))fNames.add(feature.name);
      Collections.sort(fNames);
      for(Iterator<String> nameIter = fNames.iterator(); 
          nameIter.hasNext(); 
          comboModel.addElement(nameIter.next()));
      combo.getEditor().getEditorComponent().setBackground(defaultBackground);          
      combo.setSelectedItem(feature.name);
      break;
    case VALUE_COL:
      List<Object> fValues = new ArrayList<Object>();
      if(feature.isSchemaFeature()){
        Set<Object> permValues = schema.getFeatureSchema(feature.name).
          getPermittedValues();
        if(permValues != null) fValues.addAll(permValues);
      }
      if(!fValues.contains(feature.value)) fValues.add(feature.value);
      Collections.sort(fValues, defaultComparator);
      for(Iterator<Object> valIter = fValues.iterator(); 
          valIter.hasNext(); 
          comboModel.addElement(valIter.next()));
      combo.getEditor().getEditorComponent().setBackground(feature.isCorrect() ?
          defaultBackground :
          (feature.isRequired() ? REQUIRED_WRONG : OPTIONAL_WRONG));
      combo.setSelectedItem(feature.value);
      break;
    default: ;
  }
  
}