这就是我实现UniqueValue的方式
public class UniqueValue implements Comparable<UniqueValue> {
private final String uniqueId;
private final String value;
public UniqueValue(String uniqueId, String value) {
this.uniqueId = uniqueId;
this.value = value;
}
@Override
public int compareTo(UniqueValue o) {
return uniqueId.compareTo(o.uniqueId);
}
@Override
public int hashCode() {
return uniqueId.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof UniqueValue) {
return uniqueId.equals(((UniqueValue)obj).uniqueId);
}
return false;
}
@Override
public String toString() {
return value;
}
}
你可以使用这个类来处理我在问题中提到的唯一性问题。
更新
但是,由于 JFreeChart 使用toString() 方法为类别创建标签。所以UniqueValue 中的toString() 实现可能很奇怪。所以这是另一个尝试。
一、生成器接口
public interface CategoryLabelGenerator {
public String generate(Comparable<?> category);
}
然后我为CategoryAxis创建一个子类
public class CategoryLabelCustomizableCategoryAxis extends CategoryAxis {
private static final long serialVersionUID = 1L;
private CategoryLabelGenerator labelGenerator;
public CategoryLabelCustomizableCategoryAxis(String label) {
super(label);
}
public void setCategoryLabelGenerator(CategoryLabelGenerator generator) {
this.labelGenerator = generator;
}
@Override
protected TextBlock createLabel(Comparable category, float width,
RectangleEdge edge, Graphics2D g2) {
if (generator == null) {
return super.createLabel(category, width, edge, g2);
}
return TextUtilities.createTextBlock(
labelGenerator.generate(category), // generate label for category on the fly
getTickLabelFont(category), getTickLabelPaint(category), width,
getMaximumCategoryLabelLines(), new G2TextMeasurer(g2));
}
}
示例:
JFreeChart chart = makeChart();
CategoryPlot plot = chart.getCategoryPlot();
CategoryAxis axis = new CategoryLabelCustomizableCategoryAxis();
axis.setCategoryLabelGenerator(new MyCategoryLabelGenerator());
plot.setDomainAxis(axis);
这就是我自定义类别标签的方式。 (至少对于使用CategoryAxis 作为域轴的图表..)