简体   繁体   English

如何将JComboBox与Class值一起使用

[英]how use JComboBox with Class value

I have made this: 我做了这个:

private JComboBox vehicleType = new JComboBox();
DefaultComboBoxModel<Class> dcbm = new DefaultComboBoxModel<Class>( 
        new Class[] {Truck.class, Trailer.class, RoadTractor.class, SemiTrailer.class, Van.class, Car.class})
{
    @Override
    public String getSelectedItem() {
        return ((Class<?>)super.getSelectedItem()).getSimpleName();
    }

};

And I have obtained this: 我已经获得了:

在此处输入图片说明

How you can see, the selected item show his simple class name, but in the list... doesn't. 如您所见,所选项目显示其简单的类名,但在列表中却没有。 How I can make this? 我该怎么做?

JComboBox uses the toString() method to get the label, you can override the behavior by implementing a ListCellRenderer . JComboBox使用toString()方法获取标签,您可以通过实现ListCellRenderer来覆盖行为。

vehicleType.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if(value != null) {
            setText(((Class)value).getSimpleName());
        }
        return this;
    }
});

Also if you use this method you should remove the override of getSelectedItem() in your model as it will interfere with the renderer. 另外,如果使用此方法,则应在模型中删除getSelectedItem()的覆盖,因为这会影响渲染器。

When filling the comboBox, by default, the toString() method of all elements is called. 填充comboBox时,默认情况下,将调用所有元素的toString()方法。 The toString() method of Class returns the full class Name as explained here . toString()类方法返回的解释类的全名在这里 In the getSelectedItem() method, you call getSimpleName() which of course returns the simple name of the class. getSelectedItem()方法中,调用getSimpleName() ,该getSimpleName()当然会返回该类的简单名称。

To solve your Problem, you need to create a custom list cell renderer , and overwrite getListCellRendererComponent . 要解决您的问题,您需要创建一个自定义列表单元格渲染器 ,并覆盖getListCellRendererComponent

您需要创建一个自定义ListCellRenderer

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

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