私はこのクラスを取得しました
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; }
}
foo var の値を表示する JComboBox にいくつかの FooBar オブジェクトを配置したいと考えています。toString() をオーバーライドせずにそれを行うには、カスタム レンダラーを使用する必要があります。これら 2 つの 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);
}
}