Search code examples
javajasper-reportsjfreechart

Jasper timeseries date axis : show monthly ticks but yearly tick labels


I want to show monthly ticks on a DateTime X-axis. I have achieved this using the below code.

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

Now I want to show tick labels only for a particular month (say Jan, labels for rest of the months will remain blank).

How can I possibly do this?


Solution

  • You can do the following:

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

    It's a little hacky, but at first sight I don't see other more elegant solutions.