下面列出了怎么用javax.swing.DefaultComboBoxModel的API类实例代码及写法,或者点击链接到github查看源代码。
/** Creates new form AmazonWizardComponent */
public AmazonWizardComponent(AmazonWizardPanel panel, AmazonInstance ai) {
this.panel = panel;
initComponents();
initRegions();
jRegionComboBox.setModel(new DefaultComboBoxModel(regions.toArray()));
setName(NbBundle.getBundle(AmazonWizardComponent.class).getString("LBL_Name")); // NOI18N
if (ai != null) {
accessKey.setText(ai.getKeyId());
secret.setText(ai.getKey());
accessKey.setEditable(false);
secret.setEditable(false);
jRegionComboBox.setEnabled(false);
jRegionComboBox.setSelectedItem(AmazonRegion.findRegion(ai.getRegionURL()));
}
accessKey.getDocument().addDocumentListener(this);
secret.getDocument().addDocumentListener(this);
}
private void updateStatisticsComboBox() {
String newName = Statistic.GRANULARITY_MAXIMUM.getName(gui.getGranularity());
@SuppressWarnings("unchecked")
DefaultComboBoxModel<Object> model = (DefaultComboBoxModel<Object>) ((JComboBox<Object>) statsPanel
.getComponent(1)).getModel();
boolean reselect = false;
if (model.getSelectedItem() == model.getElementAt(4)) {
reselect = true;
}
model.removeElementAt(4);
model.insertElementAt(newName, 4);
if (reselect) {
model.setSelectedItem(newName);
}
}
/**
* Creates a panel containing a combo-box that allows the user to select
* one stroke from a list of available strokes.
*
* @param current the current stroke sample.
* @param available an array of 'available' stroke samples.
*/
public StrokeChooserPanel(StrokeSample current, StrokeSample[] available) {
setLayout(new BorderLayout());
// we've changed the behaviour here to populate the combo box
// with Stroke objects directly - ideally we'd change the signature
// of the constructor too...maybe later.
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (int i = 0; i < available.length; i++) {
model.addElement(available[i].getStroke());
}
this.selector = new JComboBox(model);
this.selector.setSelectedItem(current.getStroke());
this.selector.setRenderer(new StrokeSample(null));
add(this.selector);
// Changes due to focus problems!! DZ
this.selector.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent evt) {
getSelector().transferFocus();
}
});
}
/**
* Add a link on primary and dependent JComboBoxes by property name.
* When selection changes on primary use propertyName to get a Collection and fill dependent JComboBox with it
* @param primary JComboBox when selection changes
* @param dependent JComboBox that are filled with collection
* @param propertyName the property name for get the collection from primary selected item
* @param addNull if true, add a null as first combobox item
*/
@SuppressWarnings("rawtypes")
public static void link(final JComboBox primary, final JComboBox dependent, final String propertyName,
final boolean addNull) {
primary.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = primary.getSelectedItem();
if (selected != null) {
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(selected);
if (wrapper.isWritableProperty(propertyName)) {
Collection collection = (Collection) wrapper.getPropertyValue(propertyName);
Vector<Object> vector = new Vector<Object>(collection);
if (addNull) vector.add(0, null);
DefaultComboBoxModel model = new DefaultComboBoxModel(vector);
dependent.setModel(model);
}
else {
log.error("Can't write on propety '" + propertyName + "' of class: '" + selected.getClass() + "'");
}
}
}
});
}
/**
* Obtains a list of clases of type Doc allowed to the user
* @return a DefaultComboModel with names of classes of Docs
*/
private DefaultComboBoxModel getComboModelDoc()
{
Vector VObjects=new Vector();
try {
DriverGeneric Session=MainWin.getSession();
PDObjDefs Obj = new PDObjDefs(Session);
Cursor CursorId = Obj.getListDocs();
Record Res=Session.NextRec(CursorId);
while (Res!=null)
{
Attribute Attr=Res.getAttr(PDObjDefs.fNAME);
VObjects.add(Attr.getValue());
Res=Session.NextRec(CursorId);
}
Session.CloseCursor(CursorId);
} catch (PDException ex)
{
MainWin.Message(ex.getLocalizedMessage());
}
return(new DefaultComboBoxModel(VObjects));
}
private java.util.List<PlatformKey> updatePlatformsList() {
final java.util.List<PlatformKey> platformList = new ArrayList<PlatformKey>();
final SpecificationVersion targetLevel = new SpecificationVersion("1.8");
final SourceLevelQuery.Profile targetProfile = SourceLevelQuery.Profile.COMPACT1;
if (targetLevel != null && targetProfile != null) {
for (J2SERuntimePlatformProvider rpt : project.getLookup().lookupAll(J2SERuntimePlatformProvider.class)) {
for (JavaPlatform jp : rpt.getPlatformType(targetLevel, targetProfile)) {
platformList.add(PlatformKey.create(jp));
}
}
Collections.sort(platformList);
}
platformList.add(0, PlatformKey.createDefault());
final DefaultComboBoxModel<PlatformKey> model = new DefaultComboBoxModel<PlatformKey>(platformList.toArray(new PlatformKey[0]));
comboBoxRuntimePlatform.setModel(model);
return platformList;
}
/** Populate function combo box. */
private void populateFunctionComboBox() {
if (functionComboBox != null) {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("");
// Sort function names alphabetically
List<String> functionNameList = new ArrayList<>(functionNameMap.keySet());
java.util.Collections.sort(functionNameList);
for (String name : functionNameList) {
model.addElement(name);
}
functionComboBox.setModel(model);
}
}
protected void onShow() {
List<OculusSession> recentSessions = ServiceLocator.getInstance(SessionController.class).listRecentSessions();
if(!lastSessions.equals(recentSessions)) {
lastSessions = recentSessions;
DefaultComboBoxModel<OculusSession> model = ((DefaultComboBoxModel<OculusSession>) serviceUri.getModel());
model.removeAllElements();
for(OculusSession hau: ServiceLocator.getInstance(SessionController.class).listRecentSessions()) {
model.addElement(hau);
}
}
if(username.getText().isEmpty()) {
username.requestFocusInWindow();
}
else {
password.requestFocusInWindow();
}
}
private ComboBoxModel getListObjFold()
{
Vector VObjects=new Vector();
try {
DriverGeneric Session=MainWin.getSession();
PDObjDefs Obj = new PDObjDefs(Session);
Cursor CursorId = Obj.getListFold();
Record Res=Session.NextRec(CursorId);
while (Res!=null)
{
Attribute Attr=Res.getAttr(PDObjDefs.fNAME);
VObjects.add(Attr.getValue());
Res=Session.NextRec(CursorId);
}
Session.CloseCursor(CursorId);
} catch (PDException ex)
{
MainWin.Message("Error"+ex.getLocalizedMessage());
}
return(new DefaultComboBoxModel(VObjects));
}
public Component getTableCellEditorComponent(JTable table, Object obj, boolean isSelected, int row, int col) {
comboBox = new JComboBox();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
fireEditingStopped();
}
});
DefaultComboBoxModel rootModel = new DefaultComboBoxModel();
SchemaObject o = (SchemaObject)table.getModel().getValueAt(row, SCHEMA_COL);
if( !(o.toString().equals(startString))) {
String[] root = o.getRootElements();
if(root != null && root.length >0) {
for(int i=0; i < root.length; i++)
rootModel.addElement(root[i]);
}
}
comboBox.setModel(rootModel);
return comboBox;
}
private void enableInsertionPoint() {
if (ipModel == null) {
ipModel = insertionPointComboBox.getModel();
}
Object[] values;
Object toSelect = insertionPointComboBox.getSelectedItem();
if (sortMembersAlphaCheckBox.isSelected()) {
if (toSelect == ipModel.getElementAt(0) || toSelect == ipModel.getElementAt(1)) {
toSelect = ipModel.getElementAt(2);
}
values = new Object[] {ipModel.getElementAt(2), ipModel.getElementAt(3)};
} else {
if (toSelect == ipModel.getElementAt(2)) {
toSelect = ipModel.getElementAt(0);
}
values = new Object[] {ipModel.getElementAt(0), ipModel.getElementAt(1), ipModel.getElementAt(3)};
}
insertionPointComboBox.setModel(new DefaultComboBoxModel(values));
insertionPointComboBox.setSelectedItem(toSelect);
}
public VMInstance selectDestination() {
JPanel panel = new JPanel();
panel.add(new JLabel("Please make a selection:"));
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (ExternalComponentInstance n : dm.getComponentInstances().onlyExternals()) {
model.addElement(n);
}
JComboBox comboBox = new JComboBox(model);
panel.add(comboBox);
int result = JOptionPane.showConfirmDialog(null, panel, "Destination", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
switch (result) {
case JOptionPane.OK_OPTION:
return ((VMInstance) comboBox.getSelectedItem());
}
return null;
}
RepositoryConnection getSelectedRCIntern() {
String urlString;
try {
urlString = getUrlString();
}
catch (InterruptedException ex) {
// should not happen
Subversion.LOG.log(Level.SEVERE, null, ex);
return null;
}
DefaultComboBoxModel dcbm = (DefaultComboBoxModel) repositoryPanel.urlComboBox.getModel();
int idx = dcbm.getIndexOf(urlString);
if(idx > -1) {
return (RepositoryConnection) dcbm.getElementAt(idx);
}
return getEditedRC();
}
private void refreshFormWidgetsCombo() {
JSONObject form4Name = Utilities.getForm4Name(currentSelectedFormName, currentSelectedSectionObject);
JSONArray formItems = Utilities.getFormItems(form4Name);
int length = formItems.length();
if (length == 0) {
_loadedWidgetsCombo.setModel(new DefaultComboBoxModel<String>());
return;
}
String[] names = new String[length];
for( int i = 0; i < length; i++ ) {
JSONObject jsonObject = formItems.getJSONObject(i);
if (jsonObject.has(Utilities.TAG_KEY)) {
names[i] = jsonObject.getString(Utilities.TAG_KEY).trim();
} else if (jsonObject.has(Utilities.TAG_VALUE)) {
names[i] = jsonObject.getString(Utilities.TAG_VALUE).trim();
}
}
_loadedWidgetsCombo.setModel(new DefaultComboBoxModel<String>(names));
}
public DefaultComboBoxModel<String> setUpJobCBModel() {
List<String> jobs = JobType.getList();
jobs.remove(POLITICIAN);
Collections.sort(jobs);
DefaultComboBoxModel<String> m = new DefaultComboBoxModel<String>();
Iterator<String> j = jobs.iterator();
while (j.hasNext()) {
String s = j.next();
m.addElement(s);
}
return m;
}
private void createPositionModel(final JComboBox positionsCombo,
final FileObject[] files,
final LayerItemPresenter parent) {
DefaultComboBoxModel<Position> newModel = new DefaultComboBoxModel<>();
LayerItemPresenter previous = null;
for (FileObject file : files) {
if (file.getNameExt().endsWith(LayerUtil.HIDDEN)) {
continue;
}
LayerItemPresenter current = new LayerItemPresenter(
file,
parent.getFileObject());
newModel.addElement(createPosition(previous, current));
previous = current;
}
newModel.addElement(createPosition(previous, null));
positionsCombo.setModel(newModel);
checkValidity();
}
public static ComboBoxModel<String> getPageSizeModel(Scanner scanner) {
DefaultComboBoxModel<String> pageSizeModel = new DefaultComboBoxModel<String>();
HashMap<String, StringOption> stringOptions = scanner.getStringOptions();
StringOption stringOption = stringOptions.get(EPSON_NAME_SCAN_AREA);
if (stringOption == null) {
return null;
}
Constraints constraints = stringOption.getConstraints();
List<String> values = constraints.getStringList();
for (String value : values) {
pageSizeModel.addElement(value);
}
if (values.size() > 0) {
return pageSizeModel;
} else {
return null;
}
}
public void setSelectedType(PkmType type) {
String toSelect = null;
if (type != null) {
if (shouldRebuild) {
refill();
}
toSelect = WordUtils.capitalizeFully(type.toString());
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) getModel();
if (model.getIndexOf(toSelect) == -1) {
shouldRebuild = true;
insertItemAt(toSelect, 0);
} else {
shouldRebuild = false;
}
}
setSelectedItem(toSelect);
}
@Override
public void actionPerformed(final ActionEvent e) {
if (availableGames.isEmpty()) {
JOptionPane.showMessageDialog(
parent, "No available games", "No available games", JOptionPane.ERROR_MESSAGE);
return;
}
final DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
final JComboBox<String> combo = new JComboBox<>(model);
model.addElement("");
model.addAll(availableGames);
final int selectedOption =
JOptionPane.showConfirmDialog(
parent, combo, "Change Game To: ", JOptionPane.OK_CANCEL_OPTION);
if (selectedOption != JOptionPane.OK_OPTION) {
return;
}
final String name = (String) combo.getSelectedItem();
if (name == null || name.length() <= 1) {
return;
}
serverStartupRemote.changeServerGameTo(name);
}
public void run() {
// build the allowed values
String allowedRegEx = jcb.getActionCommand();
DefaultComboBoxModel dcbm = new DefaultComboBoxModel();
Pattern p = Pattern.compile(allowedRegEx);
Set<String> keys = data.keySet();
//String pushPrefix = null;
for (String k : keys) {
Matcher test = p.matcher(k);
if (test.matches()) {
dcbm.addElement(data.get(k));
}
}
jcb.setModel(dcbm);
jcb.setSelectedItem(value);
}
RangeEditorDialog(Window window, Model model) {
super(window, "New Range Mask",
ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP, "rangeEditor");
this.model = model;
container = PropertyContainer.createObjectBacked(this.model);
getJDialog().setResizable(false);
rasterModel = new DefaultComboBoxModel(this.model.rasterNames);
setContent(createUI());
}
/**
* Sets the current {@link PlotConfiguration} for this dialog.
*
* @param plotConfig
*/
private void setPlotConfiguration(PlotConfiguration plotConfig) {
if (plotConfig == null) {
throw new IllegalArgumentException("plotConfig must not be null!");
}
this.plotConfig = plotConfig;
Vector<RangeAxisConfig> rangeConfigsVector = new Vector<RangeAxisConfig>();
for (RangeAxisConfig config : this.plotConfig.getRangeAxisConfigs()) {
rangeConfigsVector.add(config);
}
rangeAxisSelectionCombobox.setModel(new DefaultComboBoxModel<>(rangeConfigsVector));
}
public JreFormImpl(Bindings bindings, JFileChooser fc) {
_jdkPreferenceCombo.setModel(new DefaultComboBoxModel(new String[] {
Messages.getString("jdkPreference.jre.only"),
Messages.getString("jdkPreference.prefer.jre"),
Messages.getString("jdkPreference.prefer.jdk"),
Messages.getString("jdkPreference.jdk.only")}));
_runtimeBitsCombo.setModel(new DefaultComboBoxModel(new String[] {
Messages.getString("runtimeBits.64"),
Messages.getString("runtimeBits.64And32"),
Messages.getString("runtimeBits.32And64"),
Messages.getString("runtimeBits.32")}));
bindings.add("jre.path", _jrePathField)
.add("jre.bundledJre64Bit", _bundledJre64BitCheck)
.add("jre.bundledJreAsFallback", _bundledJreAsFallbackCheck)
.add("jre.minVersion", _jreMinField)
.add("jre.maxVersion", _jreMaxField)
.add("jre.jdkPreferenceIndex", _jdkPreferenceCombo, Jre.DEFAULT_JDK_PREFERENCE_INDEX)
.add("jre.runtimeBitsIndex", _runtimeBitsCombo, Jre.DEFAULT_JDK_PREFERENCE_INDEX)
.add("jre.initialHeapSize", _initialHeapSizeField)
.add("jre.initialHeapPercent", _initialHeapPercentField)
.add("jre.maxHeapSize", _maxHeapSizeField)
.add("jre.maxHeapPercent", _maxHeapPercentField)
.add("jre.options", _jvmOptionsTextArea);
_varCombo.setModel(new DefaultComboBoxModel(new String[] {
"EXEDIR", "EXEFILE", "PWD", "OLDPWD", "JREHOMEDIR",
"HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE",
"HKEY_USERS", "HKEY_CURRENT_CONFIG" }));
_varCombo.addActionListener(new VarComboActionListener());
_varCombo.setSelectedIndex(0);
_propertyButton.addActionListener(new PropertyActionListener());
_optionButton.addActionListener(new OptionActionListener());
_envPropertyButton.addActionListener(new EnvPropertyActionListener(_envVarField));
_envOptionButton.addActionListener(new EnvOptionActionListener(_envVarField));
}
public static JComboBox<MagicCollection> createComboboxCollection()
{
DefaultComboBoxModel<MagicCollection> model = new DefaultComboBoxModel<>();
JComboBox<MagicCollection> combo = new JComboBox<>(model);
try {
MTGControler.getInstance().getEnabled(MTGDao.class).listCollections().stream().forEach(model::addElement);
combo.setRenderer(new MagicCollectionIconListRenderer());
return combo;
} catch (Exception e) {
logger.error(e);
return combo;
}
}
private synchronized void initLibraries() {
if (libsInitialized) {
return;
}
springLibs.clear();
RequestProcessor.getDefault().submit(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
final List<String> items = new ArrayList<>();
for (Library library : LibraryManager.getDefault().getLibraries()) {
if (SpringUtilities.isSpringLibrary(library)) {
items.add(library.getDisplayName());
springLibs.add(new SpringLibrary(library));
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cbSpringVersion.setModel(new DefaultComboBoxModel(items.toArray(new String[items.size()])));
int selectedIndex = cbSpringVersion.getSelectedIndex();
if (selectedIndex < springLibs.size()) {
springLibrary = springLibs.get(selectedIndex);
libsInitialized = true;
repaint();
fireChange();
}
}
});
LOG.log(Level.FINEST, "Time spent in {0} initLibraries = {1} ms",
new Object[]{this.getClass().getName(), System.currentTimeMillis() - startTime});
}
});
}
private JComboBox<ImageSizePresets> getSizePresetsCombo(MouseListener aListener) {
cboPresets.setModel(new DefaultComboBoxModel<>(ImageSizePresets.values()));
cboPresets.getModel().setSelectedItem(CONFIG.getPreferredImageSize());
cboPresets.setToolTipText(getTooltip());
cboPresets.addMouseListener(aListener);
return cboPresets;
}
/**
* Creates new form ScatterGraphDialog
*/
public ScatterGraphDialog(java.awt.Frame parent, boolean modal, ScatterGraphApp graph) {
super(parent, modal);
this.graph = graph;
initComponents();
interpolationSchemeField.setModel(new DefaultComboBoxModel<InterpolationScheme>(ScatterGraph2DRenderer.supportedInterpolationScheme.toArray(new InterpolationScheme[0])));
if (graph != null) {
interpolationSchemeField.setSelectedItem(graph.getInterpolationScheme());
}
}
private void refreshBranchFilterModel () {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(ALL_BRANCHES_FILTER);
for (Map.Entry<String, GitBranch> e : info.getBranches().entrySet()) {
GitBranch b = e.getValue();
if (b.getName() != GitBranch.NO_BRANCH) {
model.addElement(b);
if (currentBranchFilter instanceof GitBranch && b.getName().equals(((GitBranch) currentBranchFilter).getName())) {
currentBranchFilter = b;
}
}
}
cmbBranch.setModel(model);
cmbBranch.setSelectedItem(currentBranchFilter);
}
private void loadChromeEmulators() {
chromeEmulatorList.setModel(
new DefaultComboBoxModel(
ChromeEmulators.getEmulatorsList().toArray()));
if (chromeEmulatorList.getItemCount() == 0) {
chromeEmulator.setEnabled(false);
chromeEmulator.setToolTipText("Not Supported");
}
}
public ComboParameter(JComboBox combo, String parameter, String encoding) {
super(parameter, encoding);
this.combo = combo;
combo.setModel(new DefaultComboBoxModel());
combo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
fireStateChanged();
}
});
original = (ParameterValue) combo.getSelectedItem();
}