更改甘特图渲染器的颜色

时间:2014-12-31 11:01:34

标签: java jfreechart

我想更改图表中渲染器的颜色。我正在使用JFreeChart 在同一行。我希望根据任务描述拥有不同的collors。 问题是我在一行中保持相同的颜色。

package testJFreeChart;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.CategoryItemEntity;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.IntervalCategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.CategoryItemRendererState;
import org.jfree.chart.renderer.category.GanttRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.GanttCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;
import org.jfree.ui.TextAnchor;

public class GanttDemo2 extends ApplicationFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static final TaskSeriesCollection model = new TaskSeriesCollection();

    public GanttDemo2(final String title) {

        super(title);

        final IntervalCategoryDataset dataset = createSampleDataset();

        // create the chart...
        final JFreeChart chart = ChartFactory.createGanttChart(
                "Diagramme de Gantt", // chart title
                "Processus", // domain axis label
                "temps(ms)", // range axis label
                dataset, // data
                true, // include legend
                true, // tooltips
                false // urls
        );
        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        DateAxis range = (DateAxis) plot.getRangeAxis();
        range.setDateFormatOverride(new SimpleDateFormat("SSS"));
        range.setMaximumDate(new Date(300));

        // add the chart to a panel...
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

        //GanttRenderer personnalisé..
        MyRenderer renderer = new MyRenderer(model);
        renderer.setBaseItemLabelGenerator(new CategoryItemLabelGenerator() {

            public String generateLabel(CategoryDataset dataSet, int series, int categories) {
                String label = "task";
                return label;
            }

            public String generateColumnLabel(CategoryDataset dataset, int categories) {
                //System.out.println(dataset.getColumnKey(categories).toString());
                return dataset.getColumnKey(categories).toString();
            }

            public String generateRowLabel(CategoryDataset dataset, int series) {
                return dataset.getRowKey(series).toString();
            }
        });

        renderer.setBaseItemLabelsVisible(true);
        renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_LEFT));

        plot.setRenderer(renderer);
        plot.setBackgroundPaint(Color.WHITE);

    }

    /** @see http://stackoverflow.com/questions/8938690 */
    private static class MyRenderer extends GanttRenderer {

        private static final int PASS = 2; // assumes two passes
        private final List<Color> clut = new ArrayList<Color>();
        private final TaskSeriesCollection model;
        private int row;
        private int col;
        private int index;

        public MyRenderer(TaskSeriesCollection model) {
            this.model = model;
        }

        @Override
        public Paint getItemPaint(int row, int col) {

            if (clut.isEmpty() || this.row != row || this.col != col) {
                initClut(row, col);
                this.row = row;
                this.col = col;
                index = 0;
            }
            int clutIndex = index++ / PASS;
            return clut.get(clutIndex);
        }

        private void initClut(int row, int col) {
            clut.clear();
            Color result = Color.cyan;

            TaskSeries series = (TaskSeries) model.getRowKeys().get(row);
            List<Task> tasks = series.getTasks(); // unchecked 

            int taskCount = tasks.get(col).getSubtaskCount();
            taskCount = Math.max(1, taskCount);

            System.out.println("---->" + taskCount);
            String description;

            for (int i = 0; i < taskCount; i++) {

       // if(taskCount!=1){
                //clut.remove(result);
                description = tasks.get(col).getSubtask(i).getDescription();

                System.out.println(description + "  " + i);
                if (description.equals("bloque")) {
                    result = Color.green;
                    clut.add(result);
                    System.out.println("yessssss");
                }
                if (description.equals("ES")) {
                    result = Color.yellow;
                    clut.add(result);
                }
                if (description.equals("Exec")) {
                    result = Color.blue;
                    clut.add(result);
                    System.out.println("NOOOOO");
                }

                //   }
                clut.add(result);
            }

        }

    }

    private IntervalCategoryDataset createSampleDataset() {

        final TaskSeries s1 = new TaskSeries("");

        final Task t = new Task("P0", new SimpleTimePeriod(30, 50));
        final Task st0 = new Task("Exec", new SimpleTimePeriod(10, 20));
        // Task st01 = new Task( "ES",new SimpleTimePeriod(30,60));
        t.addSubtask(st0);
  //   t.addSubtask(st01);

        s1.add(t);

        final Task t1 = new Task("P1", new SimpleTimePeriod(5, 10));

        final Task st11 = new Task("ES", new SimpleTimePeriod(10, 20));
        Task st12 = new Task("Exec", new SimpleTimePeriod(30, 60));
        t1.addSubtask(st11);
        t1.addSubtask(st12);
        s1.add(t1);

        final Task t3 = new Task("P2", new SimpleTimePeriod(0, 40));
        final Task st31 = new Task("bloque", new SimpleTimePeriod(5, 30));
        final Task st32 = new Task("Exec", new SimpleTimePeriod(50, 60));

        t3.addSubtask(st31);

        t3.addSubtask(st32);

        s1.add(t3);

        model.add(s1);

        return model;
    }

    public static void main(final String[] args) {

        final GanttDemo2 demo = new GanttDemo2("Gantt Chart Demo 2");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);

    }
}

1 个答案:

答案 0 :(得分:2)

应该是第1行蓝色;第2行颜色为黄色然后为蓝色;第3行颜色为绿色,然后为蓝色

以下变化似乎产生了预期的结果。请注意,除非您使用建议的here方法,否则图例不会使用新颜色。

image

控制台:

----> 1
exec: 0
blue
----> 2
ES: 0
yellow
exec: 1
blue
----> 2
bloque: 0
green
exec: 1
blue

代码:

package chart;

import java.awt.Color;
import java.awt.Paint;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.GanttRenderer;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class GanttDemo2 extends ApplicationFrame {

    private static final long serialVersionUID = 1L;
    public static final TaskSeriesCollection model = new TaskSeriesCollection();

    public GanttDemo2(final String title) {
        super(title);
        final IntervalCategoryDataset dataset = createSampleDataset();
        // create the chart...
        final JFreeChart chart = ChartFactory.createGanttChart(
                "Diagramme de Gantt", // chart title
                "Processus", // domain axis label
                "temps(ms)", // range axis label
                dataset, // data
                false, // include legend
                true, // tooltips
                false // urls
        );
        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        DateAxis range = (DateAxis) plot.getRangeAxis();
        range.setDateFormatOverride(new SimpleDateFormat("SSS"));
        range.setMaximumDate(new Date(100));

        // add the chart to a panel...
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

        //GanttRenderer personnalisé..
        MyRenderer renderer = new MyRenderer(model);
        plot.setRenderer(renderer);
        plot.setBackgroundPaint(Color.WHITE);
    }

    /**
     * @see https://stackoverflow.com/questions/8938690
     */
    private static class MyRenderer extends GanttRenderer {

        private static final int PASS = 2; // assumes two passes
        private final List<Color> clut = new ArrayList<>();
        private final TaskSeriesCollection model;
        private int row;
        private int col;
        private int index;

        public MyRenderer(TaskSeriesCollection model) {
            this.model = model;
        }

        @Override
        public Paint getItemPaint(int row, int col) {

            if (clut.isEmpty() || this.row != row || this.col != col) {
                initClut(row, col);
                this.row = row;
                this.col = col;
                index = 0;
            }
            int clutIndex = index++ / PASS;
            return clut.get(clutIndex);
        }

        private void initClut(int row, int col) {
            clut.clear();

            TaskSeries series = (TaskSeries) model.getRowKeys().get(row);
            List<Task> tasks = series.getTasks(); // unchecked 

            int taskCount = tasks.get(col).getSubtaskCount();
            taskCount = Math.max(1, taskCount);

            System.out.println("----> " + taskCount);
            String description;

            for (int i = 0; i < taskCount; i++) {
                description = tasks.get(col).getSubtask(i).getDescription();

                System.out.println(description + ": " + i);
                if (description.equals("bloque")) {
                    clut.add(Color.green);
                    System.out.println("green");
                }
                if (description.equals("ES")) {
                    clut.add(Color.yellow);
                    System.out.println("yellow");
                }
                if (description.equals("exec")) {
                    clut.add(Color.blue);
                    System.out.println("blue");
                }
            }
        }
    }

    private IntervalCategoryDataset createSampleDataset() {
        final TaskSeries s1 = new TaskSeries("");
        final Task t0 = new Task("P0", new SimpleTimePeriod(30, 50));
        final Task st0 = new Task("exec", new SimpleTimePeriod(10, 20));
        // Task st01 = new Task( "ES",new SimpleTimePeriod(30,60));
        t0.addSubtask(st0);
        //   t.addSubtask(st01);
        s1.add(t0);

        final Task t1 = new Task("P1", new SimpleTimePeriod(5, 10));
        final Task st11 = new Task("ES", new SimpleTimePeriod(10, 20));
        Task st12 = new Task("exec", new SimpleTimePeriod(30, 60));
        t1.addSubtask(st11);
        t1.addSubtask(st12);
        s1.add(t1);

        final Task t2 = new Task("P2", new SimpleTimePeriod(0, 40));
        final Task st31 = new Task("bloque", new SimpleTimePeriod(5, 30));
        final Task st32 = new Task("exec", new SimpleTimePeriod(50, 60));
        t2.addSubtask(st31);
        t2.addSubtask(st32);
        s1.add(t2);

        model.add(s1);
        return model;
    }

    public static void main(final String[] args) {
        final GanttDemo2 demo = new GanttDemo2("Gantt Chart Demo 2");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);
    }
}