我有一个非常类似的问题,比如这个Java ComboBox Different Value to Name
我已经更改了代码,所以我将获得一个Employee-Object (我更改了我的类名,因为上面链接中的类名是Employee)。
在我的例子中,我已经有了一个toString()方法,我不想重写它。(我需要在其他地方使用它)
但是我不想在我的JCombobox中使用这个toString()方法。但它是自动的。
我不想返回任何字符串!我需要这些东西。
有没有办法在创建JCombobox时说“采用另一个toString()方法,比方说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.谢谢!
发布于 2012-11-20 03:29:01
事实上,不使用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);
}
});发布于 2012-11-20 03:30:17
使用ListCellRenderer。可以在int the Swing tutorial中找到一个示例。
另一种方法是将对象包装在定义自己的toString()方法的对象中。
发布于 2012-11-20 03:29:25
您需要创建JComboBox并实现toString方法。
示例:
public class MyComboBox
extends JComboBox
{
public String toString() {
return "My toString";
}
}https://stackoverflow.com/questions/13460555
复制相似问题