Java - 如何使非String对象的JComboBox显示字符串名称?

tom*_*101 0 java string swing object jcombobox

Imgur

我想使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<Category> tileCategory;

    public Properties() {
        tileCategory = new JComboBox<Category>();
        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<Integer, String> map = EditorConstants.getInstance().getCategoryList();

        DefaultComboBoxModel<Category> model = (DefaultComboBoxModel<Category>) 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我唯一知道的就是我把Category课程传给了JComboBox.下面显示了这个Category类:

public class Category {
    public String name;
}
Run Code Online (Sandbox Code Playgroud)

这就是它.

我唯一的目标是让Category.name成员变量显示在JComboBox下拉列表中,矩形在图片中标记.

谁能告诉我这是怎么做到的?提前致谢.

Mad*_*mer 7

A JComboBox使用a 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.

    }

}
Run Code Online (Sandbox Code Playgroud)

然后,您只需指定组合框的渲染

tileCategory.setRenderer(new CategoryListCellRenderer());
Run Code Online (Sandbox Code Playgroud)

现在,已经说过,这将阻止用户使用内置搜索功能的组合框.

为此,请检查具有自定义渲染器的组合框以进行可能的解决方法.这是由我们自己的camickr撰写的


Bal*_*des 5

最简单的方法是覆盖toString()类的方法。这不是一个非常强大的解决方案,但可以完成工作。

public class Category {
    public String name;

    @Override
    public String toString(){
        return name;
    }
}
Run Code Online (Sandbox Code Playgroud)