下面是一个实用程序接口和类,可以轻松地获取组合框以使用不同的标签。这不是创建替换(如果外观和感觉发生更改,则冒着它看起来不合适的风险),而是使用默认值(无论可能是什么),而是将您自己的字符串作为标签文本交换,而不是在值对象中定义的字符串。ListCellRenderer
ListCellRenderer
toString()
public interface ToString {
public String toString(Object object);
}
public final class ToStringListCellRenderer implements ListCellRenderer {
private final ListCellRenderer originalRenderer;
private final ToString toString;
public ToStringListCellRenderer(final ListCellRenderer originalRenderer,
final ToString toString) {
this.originalRenderer = originalRenderer;
this.toString = toString;
}
public Component getListCellRendererComponent(final JList list,
final Object value, final int index, final boolean isSelected,
final boolean cellHasFocus) {
return originalRenderer.getListCellRendererComponent(list,
toString.toString(value), index, isSelected, cellHasFocus);
}
}
如您所见,从实现中获取自定义字符串,然后将其传递给原始字符串,而不是传入值对象本身。ToStringListCellRenderer
ToString
ListCellRenderer
若要使用此代码,请执行类似如下操作:
// Create your combo box as normal, passing in the array of values.
final JComboBox combo = new JComboBox(values);
final ToString toString = new ToString() {
public String toString(final Object object) {
final YourValue value = (YourValue) object;
// Of course you'd make your own label text below.
return "custom label text " + value.toString();
}
};
combo.setRenderer(new ToStringListCellRenderer(
combo.getRenderer(), toString)));
除了使用它来创建自定义标签之外,如果创建基于系统区域设置创建字符串的实现,则可以轻松地将组合框国际化,而无需更改值对象中的任何内容。ToString