繁体   English   中英

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

[英]Java - How to make JComboBox of non-String objects display String names?

伊姆古尔

我想让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);
    }
}

我唯一知道的是我将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.

    }

}

然后您只需将渲染指定到组合框

tileCategory.setRenderer(new CategoryListCellRenderer());

话虽如此,这将阻止用户使用内置于搜索功能的组合框。

为此,请检查带有自定义渲染器的组合框 ,以解决可能的问题。 这是由我们自己的camickr创作的

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

public class Category {
    public String name;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM