Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

java - Changing the colors of Gantt renderer

I want to change the colors of the renderers in my chart. I'm using JFreeChart in the same line. I want to have different collors according to the task description. The problem is I keep having the same color in a line.

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

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It should be row 1 color blue; row 2 color yellow then blue; row 3 color green then blue.

The variation below seems to produce the desired result. Note that legend will not use the new colors unless you use the approach suggested here.

image

Console:

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

Code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...