简体   繁体   English

修改toString()方法JComboBox Swing

[英]Modify toString() method JComboBox Swing

I have a Proveedores class with ID, Name, Lastname and I want add this object into the combobox. 我有一个带有ID,Name,Lastname的Proveedores类,我希望将这个对象添加到组合框中。

      ListIterator listaNombre = listaProveedores.listIterator();
        listado = new Proveedores[listaProveedores.size()];
        int cont = 0;
        while (listaNombre.hasNext()) {
            prov = (Proveedores) listaNombre.next();
            listado[cont] = prov;
            cont++;
        }
this.vista.cArticuloFamilia.setModel(new javax.swing.DefaultComboBoxModel(listado));

With this code I add the differents objects into the combobox. 使用此代码,我将不同的对象添加到组合框中。 It works. 有用。 But now I want to override the toString method for show only Name attribute. 但是现在我想为show only Name属性覆盖toString方法。 Now combobox shows me the name class (Proveedores) and the ID. 现在,combobox向我展示了名称类(Proveedores)和ID。

entidades.Proveedores[idProveedores=1]

How can I override it to show the Proveedores Name? 如何覆盖它以显示Proveedores名称?

Thanks. 谢谢。

Use a custom ListCellRenderer to accomplish this. 使用自定义ListCellRenderer来完成此任务。

You shouldn't tailor toString() to produce GUI data for complex objects. 您不应该定制toString()来为复杂对象生成GUI数据。 It is meant for an internal data representation for the developers eyes, not the users. 它适用于开发人员眼睛的内部数据表示,而不是用户。

Java uses toString() to get the String representation of the Object by default it will return fully qualified classname @ followed by hashCode of the object. Java使用toString()来获取Object的String表示形式,默认情况下它将返回完全限定的classname @,后跟对象的hashCode。

Use ListCellRenderer to display Proveedores Name in the ComboBox. 使用ListCellRenderer在ComboBox中显示Proveedores Name。

Sample Code: 示例代码:

public static class ProveedoresRenderer extends DefaultListCellRenderer {
    public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) {
        Object item = value;

        // if the item to be rendered is Proveedores then display it's Name
        if( item instanceof Proveedores ) {
            item = ( ( Proveedores ) item ).getName();
        }
        return super.getListCellRendererComponent( list, item, index, isSelected, cellHasFocus);
    }
}

then set the ProveedoresRenderer to the JComboBox . 然后将ProveedoresRenderer设置为JComboBox

ListIterator listaNombre = listaProveedores.listIterator();
listado = new Proveedores[listaProveedores.size()];
int cont = 0;
while (listaNombre.hasNext()) {
    prov = (Proveedores) listaNombre.next();
    listado[cont] = prov;
    cont++;
}
this.vista.cArticuloFamilia.setModel(new javax.swing.DefaultComboBoxModel(listado));

// Set custom renderer to the combobox
this.vista.cArticuloFamilia.setRenderer( new ProveedoresRenderer() );

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

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