简体   繁体   中英

Custom JCombobox model with two toString methods

I have a pretty similar problem like this one Java ComboBox Different Value to Name

I have already changed the code, so I'll get a Employee -Object (i changed my classnames, since the classnames in the link above are Employee ).

In my case, I have already a toString() method, which I don't want to overwrite. (I need it somewhere else)

But I don't want to use this toString() method in my JCombobox . But it does automaticaly.

I don't want to return any strings! I need the objects.

Is there a way to say "take another toString() method, let's say toStringDifferent() " while creating the JCombobox?

this.comboEmployees = new JComboBox(new EmployeeComboboxModel(getEmployees())); 
// this will give me the toString-method's return-value of the Employee object. 
// But i want the toStringDifferent() method's result.

thanks!

In fact it is even considered good practice not to use toString .

comboEmployees.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList list,
                                               Object value,
                                               int index,
                                               boolean isSelected,
                                               boolean cellHasFocus) {
        Employee employee = (Employee)value;
        value = employee.toStringDifferent();
        return super.getListCellRendererComponent(list, value,
                index, isSelected, csellHasFocus);
    }
});

Use a ListCellRenderer . An example can be found int the Swing tutorial .

An alternative is to wrap your objects inside an object defining its own toString() method.

You need to create your JComboBox and implement your toString method.

Example:

public class        MyComboBox
    extends     JComboBox
{
  public String toString() {
    return "My toString";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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