gpt4 book ai didi

java - 这两个DefaultListCellRenderer有什么区别?

转载 作者:行者123 更新时间:2023-11-30 03:53:03 24 4
gpt4 key购买 nike

我上了这门课

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);
}
}

最佳答案

区别在于……嗯……代码。以及他们所做的事情。但说真的,主要的实际区别是第二个调用 super 方法。此方法将执行基本的设置操作,例如根据 isSelected 标志设置边框和背景颜色等。

我通常总是建议调用super方法来执行此设置并确保列表的外观和风格一致。

但是,第二种情况的使用模式可能有点困惑,因为 item 引用的是对象或其字符串表示形式。我个人更喜欢这样写:

public class MyCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object item,
int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, item,
index, isSelected, cellHasFocus);
if (item != null && (item instanceof FooBar))
{
FooBar fooBar = (FooBar)item;
String foo = fooBar.getFoo();
setText(foo);
}
return this;
}
}

但这可能只是一个偏好问题。

关于java - 这两个DefaultListCellRenderer有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com