我上了这门课
public class FooBar {
private String foo, bar;
public FooBar(String f, String b) { this.foo = f; this.bar = b; }
public String getFoo() { return this.foo; }
}
我想将一些 FooBar 对象放在一个 JComboBox 中,它将显示 foo var 的值。为了在不覆盖 toString() 的情况下做到这一点,我必须使用自定义渲染器。这两个 DefaultListCellRenderer 有什么区别?
public class MyCellRenderer1 extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
if(value != null && (value instanceof FooBar))
setText(((FooBar) value).getFoo());
else
setText(value.toString());
return this;
}
}
public class MyCellRenderer2 extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
Object item = value;
if(item != null && item instanceof FooBar))
item = ((FooBar)item).getFoo();
return super.getListCellRendererComponent(list, item,
index, isSelected, cellHasFocus);
}
}