[英]Custom JCombobox model with two toString methods
I have a pretty similar problem like this one Java ComboBox Different Value to Name 我有一个非常类似的问题,就像这个Java ComboBox不同的值名称
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
). 我已经更改了代码,因此我将获得一个Employee
-Object(我更改了我的类名,因为上面链接中的类名是Employee
)。
In my case, I have already a toString()
method, which I don't want to overwrite. 在我的情况下,我已经有一个toString()
方法,我不想覆盖它。 (I need it somewhere else) (我需要它在其他地方)
But I don't want to use this toString()
method in my JCombobox
. 但我不想在我的JCombobox
使用这个toString()
方法。 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? 有没有办法说“另一个toString()
方法,让我们说创建JCombobox时toStringDifferent()
”?
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
. 实际上,甚至不使用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
. 使用ListCellRenderer
。 An example can be found int the Swing tutorial . 可以在Swing教程中找到一个示例。
An alternative is to wrap your objects inside an object defining its own toString()
method. 另一种方法是将对象包装在定义自己的toString()
方法的对象中。
You need to create your JComboBox and implement your toString method. 您需要创建JComboBox并实现toString方法。
Example: 例:
public class MyComboBox
extends JComboBox
{
public String toString() {
return "My toString";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.