32

我想通过值而不是索引在 JComboBox 中设置选定的索引。怎么做?例子

public class ComboItem {

    private String value;
    private String label;

    public ComboItem(String value, String label) {
        this.value = value;
        this.label = label;
    }

    public String getValue() {
        return this.value;
    }

    public String getLabel() {
        return this.label;
    }

    @Override
    public String toString() {
        return label;
    }
}

JComboBox test = new JComboBox();
test.addItem(new ComboItem(0, "orange"));
test.addItem(new ComboItem(1, "pear"));
test.addItem(new ComboItem(2, "apple"));
test.addItem(new ComboItem(3, "banana"));
test.setSelectedItem("banana");

好的,我稍微修改了我的问题。我忘记了我的 JComboBox 中有一个自定义项目,这使它变得更加困难。我不能做 setSelectedItem 因为我在每个项目中都有一个 ComboItem。所以,我该怎么做呢?

4

10 回答 10

48

setSelectedItem("banana"). 您可以通过阅读javadoc自己找到它。

编辑:既然你改变了问题,我会改变我的答案。

如果要选择具有“香蕉”标签的项目,则有两种解决方案:

  1. 遍历项目以找到具有给定标签的项目(或项目的索引),然后调用setSelectedItem(theFoundItem)(or setSelectedIndex(theFoundIndex))
  2. 覆盖equalsandhashCodeComboItem使两个ComboItem具有相同名称的实例相等,并简单地使用setSelectedItem(new ComboItem(anyNumber, "banana"));
于 2011-11-30T14:22:42.053 回答
20

你应该使用模型

comboBox.getModel().setSelectedItem(object);
于 2014-11-17T11:13:28.730 回答
15
public static void setSelectedValue(JComboBox comboBox, int value)
    {
        ComboItem item;
        for (int i = 0; i < comboBox.getItemCount(); i++)
        {
            item = (ComboItem)comboBox.getItemAt(i);
            if (item.getValue().equalsIgnoreCase(value))
            {
                comboBox.setSelectedIndex(i);
                break;
            }
        }
    }

希望这有帮助:)

于 2012-03-21T05:50:41.667 回答
6

为什么不使用一个集合(可能是 HashMap 之类的 Map),并将其用作您自己的实现 ComboBoxModel 接口的组合框模型类的核心?然后,您可以通过键字符串而不是整数轻松访问组合框的项目。

例如...

import java.util.HashMap;
import java.util.Map;

import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;

public class MyComboModel<K, V>   implements ComboBoxModel {
   private Map<K, V> nucleus = new HashMap<K, V>();

   // ... any constructors that you want would go here

   public void put(K key, V value) {
      nucleus.put(key, value);
   }

   public V get(K key) {
      return nucleus.get(key);
   }

   @Override
   public void addListDataListener(ListDataListener arg0) {
      // TODO Auto-generated method stub

   }

   // ... plus all the other methods required by the interface
}
于 2011-11-30T14:23:35.933 回答
4

例如

在此处输入图像描述

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ComboboxExample {

    private JFrame frame = new JFrame("Test");
    private JComboBox comboBox = new JComboBox();

    public ComboboxExample() {
        createGui();
    }

    private void createGui() {
        comboBox.addItem("One");
        comboBox.addItem("Two");
        comboBox.addItem("Three");
        JButton button = new JButton("Show Selected");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
                javax.swing.SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        comboBox.requestFocus();
                        comboBox.requestFocusInWindow();
                    }
                });
            }
        });
        JButton button1 = new JButton("Append Items");
        button1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                appendCbItem();
            }
        });
        JButton button2 = new JButton("Reduce Items");
        button2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                reduceCbItem();
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(4, 1));
        frame.add(comboBox);
        frame.add(button);
        frame.add(button1);
        frame.add(button2);
        frame.setLocation(200, 200);
        frame.pack();
        frame.setVisible(true);
        selectFirstItem();
    }

    public void appendCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.addItem("Four");
                comboBox.addItem("Five");
                comboBox.addItem("Six");
                comboBox.setSelectedItem("Six");
                requestCbFocus();
            }
        });
    }

    public void reduceCbItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.removeItem("Four");
                comboBox.removeItem("Five");
                comboBox.removeItem("Six");
                selectFirstItem();
            }
        });
    }

    public void selectFirstItem() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.setSelectedIndex(0);
                requestCbFocus();
            }
        });
    }

    public void requestCbFocus() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                comboBox.requestFocus();
                comboBox.requestFocusInWindow();
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ComboboxExample comboboxExample = new ComboboxExample();
            }
        });
    }
}
于 2011-11-30T14:27:52.673 回答
3

http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object )

test.setSelectedItem("banana");

如 javadoc 中所述,有一些警告或潜在的意外行为。请务必阅读。

于 2011-11-30T14:25:16.057 回答
3

当组合框由某个类的构造函数填充时设置所选项目的正确方法(如@milosz 发布的那样):

combobox.getModel().setSelectedItem(new ClassName(parameter1, parameter2));

在您的情况下,代码将是:

test.getModel().setSelectedItem(new ComboItem(3, "banana"));
于 2016-05-16T16:05:15.267 回答
1

comboBox.updateUI()做完之后打电话comboBox.setSelectedItemor comboBox.setSelectedIndexorcomboModel.setSelectedItem

于 2015-04-07T14:32:33.227 回答
1
public boolean  preencherjTextCombox (){
       int x = Integer.parseInt(TableModelo.getModel().getValueAt(TableModelo.getSelectedRow(),0).toString());

       modeloobj = modelosDAO.pesquisar(x);
       Combmarcass.getModel().setSelectedItem(modeloobj.getMarca());  
       txtCodigo.setText(String.valueOf(modeloobj.getCodigo()));
       txtDescricao.setText(String.valueOf(modeloobj.getDescricao()));
       txtPotencia.setText(String.valueOf(modeloobj.getPotencia()));  

       return true;
   }
于 2016-06-01T23:11:56.920 回答
0

在我的情况下,构建类 Item(key, value) 作为组合框的项目

SanPhamDTO currentProd = prodDao.getDetailById(id);
Item item = new Item(currentProd.getCategory().getId(), 
currentProd.getCategory().getName());
cbdanhmuc.getModel().setSelectedItem(item)
于 2021-04-20T10:34:32.847 回答