2016-02-19 112 views
0

我想在DateTime X轴上显示每月刻度。我已经使用下面的代码实现了这一点。Jasper时间轴日期轴:显示每月刻度但显示年度刻度标签

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

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

我该如何做到这一点?

回答

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

这是一个小哈克,但乍一看我没有看到其他更优雅的解决方案。

+0

谢谢:)这工作得很好。 我刚刚对滴答的日期格式有问题,并使用下面的代码来修复它。 if(axisDateFormat == null)axisDateFormat = new SimpleDateFormat(“yyyy”); } – dnaik

+0

有没有办法对刻度标记进行条件格式化? – dnaik

+0

据我所见,JFreeChart不支持修改刻度笔划或从一个刻度到另一个刻度。如果这是你需要的,你可以考虑扩展JFreeChart。 – dada67