Java – 如何使非String对象的JComboBox显示字符串名称?
我想让JComboBox
组件显示String
名称,而不是引用。 但是,我不知道是怎么做到的。
下面显示了我的代码:
public class Properties extends JPanel implements ItemListener { private static final long serialVersionUID = -8555733808183623384L; private static final Dimension SIZE = new Dimension(130, 80); private JComboBox tileCategory; public Properties() { tileCategory = new JComboBox(); tileCategory.setPreferredSize(SIZE); tileCategory.addItemListener(this); this.setLayout(new GridLayout(16, 1)); loadCategory(); } private void loadCategory() { //Obtains a HashMap of Strings from somewhere else. All of this is constant, so they //aren't modified at runtime. HashMap map = EditorConstants.getInstance().getCategoryList(); DefaultComboBoxModel model = (DefaultComboBoxModel) this.tileCategory.getModel(); for (int i = 0; i < map.size(); i++) { Category c = new Category(); c.name = map.get(i + 1); model.addElement(c); } this.add(tileCategory); } }
我唯一知道的是我将Category
类传递给了JComboBox
。 下面显示了Category
类:
public class Category { public String name; }
这就是它。
我唯一的目标是让Category.name
成员变量显示在JComboBox
下拉列表中,矩形在图片中标记。
谁能告诉我这是怎么做到的? 提前致谢。
JComboBox
使用ListCellRenderer
允许您自定义值的呈现方式。
请参阅提供自定义渲染器以获取更多详细信息
例如…
public class CategoryListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Category) { value = ((Category)value).name; } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates. } }
然后,您只需指定combobox的渲染
tileCategory.setRenderer(new CategoryListCellRenderer());
现在,话虽如此,这将阻止用户使用内置搜索function的combobox。
为此,请检查具有自定义渲染器的combobox以进行可能的解决方法。 这是由我们自己的camickr撰写的
最简单的方法是覆盖类的toString()
方法。 这不是一个非常强大的解决方案,但可以完成工作。
public class Category { public String name; @Override public String toString(){ return name; } }