Text labels inside jfree Gantt chart bars

repto picture repto · Jul 3, 2012 · Viewed 7.2k times · Source

I have a simple Gantt chart here, that consists of a number of Tasks just like that:

TaskSeries s1 = new TaskSeries("Planned Tasks");
Task newTask = new Task("Task" +
String.valueOf(taskIndex),
new
SimpleTimePeriod(currentTime,
currentTime +
(int) distributionTime)
);
s1.add(newTask) 
final TaskSeriesCollection collection = new TaskSeriesCollection();
collection.add(s1);

JFreeChart chart = ChartFactory.createGanttChart(
"Distribution ", 
"Task", 
"Time", 
collection, 
true, 
true, 
false 
);

Is there a way to write something INSIDE each bar, representing a task? For example, if the task is made up of a two subtasks, is it possible to mark them with labels, so their names would be seen on a plot? Thanks in advance!

Answer

GrahamA picture GrahamA · Jul 3, 2012

To add a a lable inside each item set the setBaseItemLabelGenerator in this case I'm using a IntervalCategoryItemLabelGenerator but you can implement you own by extending CategoryItemLabelGenerator.

Use this code:

CategoryPlot plot = (CategoryPlot) chart.getPlot();
CategoryItemRenderer renderer = plot.getRenderer();
renderer.setBaseItemLabelGenerator( new IntervalCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelPaint(Color.BLACK);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE6, TextAnchor.BOTTOM_CENTER));

You shold then get this: b

Ganttt Chart with BaseItemLabelGenerator

To customise the lables implement CategoryItemLabelGenerator

renderer.setBaseItemLabelGenerator( new CategoryItemLabelGenerator(){

    @Override
    public String generateRowLabel(CategoryDataset dataset, int row) {
        return "Your Row Text  " + row;
    }

    @Override
    public String generateColumnLabel(CategoryDataset dataset, int column) {
        return "Your Column Text  " + column;
    }

    @Override
    public String generateLabel(CategoryDataset dataset, int row, int column) {
        return "Your Label Text  " + row + "," + column;
    }


});

In this example generateLabel controls the lable in the bar, CategoryDataset, row and column can be used to determine which bar you are labelling

enter image description here