Jasper时间序列日期轴:显示每月刻度,但每年刻度标签

时间:2016-02-19 15:19:37

标签: java jasper-reports jfreechart

我想在DateTime X轴上显示每月滴答。我使用下面的代码实现了这一点。

DateAxis dateAxis = (DateAxis)chart.getXYPlot().getDomainAxis();
DateTickUnit unit = new DateTickUnit(DateTickUnit.MONTH,1);
dateAxis.setTickUnit(unit);

现在我想只显示特定月份的刻度标签(比如Jan,其余月份的标签将保持空白)。

我怎么可能这样做?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

        DateFormat axisDateFormat = dateAxis.getDateFormatOverride();
        if (axisDateFormat == null) {
            axisDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
        }
        dateAxis.setDateFormatOverride(new SelectiveDateFormat(axisDateFormat, Calendar.MONTH, 0));

...

class SelectiveDateFormat extends DateFormat {
    private final DateFormat format;
    private final int dateField;
    private final int fieldValue;

    public SelectiveDateFormat(DateFormat format, int dateField, int fieldValue) {
        this.format = format;
        this.dateField = dateField;
        this.fieldValue = fieldValue;
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        Calendar calendar = Calendar.getInstance(format.getTimeZone());
        calendar.setTime(date);
        int value = calendar.get(dateField);
        if (value == fieldValue) {
            format.format(date, toAppendTo, fieldPosition);
        }
        return toAppendTo;
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        return format.parse(source, pos);
    }
}

这有点像黑客,但乍一看我没有看到其他更优雅的解决方案。