Reputation: 2161
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!
Upvotes: 2
Views: 2828
Reputation: 691635
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.
Upvotes: 1
Reputation: 309
You need to create your JComboBox and implement your toString method.
Example:
public class MyComboBox
extends JComboBox
{
public String toString() {
return "My toString";
}
}
Upvotes: 0
Reputation: 109547
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);
}
});
Upvotes: 6