Example usage for org.jfree.chart.title TextTitle TextTitle

List of usage examples for org.jfree.chart.title TextTitle TextTitle

Introduction

In this page you can find the example usage for org.jfree.chart.title TextTitle TextTitle.

Prototype

public TextTitle(String text, Font font, Paint paint, RectangleEdge position,
        HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, RectangleInsets padding) 

Source Link

Document

Creates a new title.

Usage

From source file:it.cnr.istc.iloc.gui.TimelinesChart.java

@Override
public void currentNode(Solver.Node n) {
    final CombinedDomainXYPlot combined_plot = new CombinedDomainXYPlot(new DateAxis("Time"));
    combined_plot.setGap(3.0);/*  w  ww  .j ava 2s  .c  om*/
    combined_plot.setOrientation(PlotOrientation.VERTICAL);

    Set<Type> c_types = new HashSet<>();
    LinkedList<Type> queue = new LinkedList<>();
    queue.addAll(solver.getTypes());
    while (!queue.isEmpty()) {
        Type c_type = queue.pollFirst();
        if (!c_types.contains(c_type)) {
            c_types.add(c_type);
            queue.addAll(c_type.getTypes());
        }
    }
    for (Type type : c_types) {
        if (visualizers.containsKey(type.getClass())) {
            for (XYPlot plot : visualizers.get(type.getClass()).getPlots(type)) {
                TextTitle title = new TextTitle(type.name, new Font("SansSerif", Font.PLAIN, 11), Color.BLACK,
                        RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM,
                        new RectangleInsets(4, 4, 4, 4));
                XYTitleAnnotation titleAnn = new XYTitleAnnotation(0.01, 1, title, RectangleAnchor.TOP_LEFT);
                plot.addAnnotation(titleAnn);
                combined_plot.add(plot, 1);
            }
        }
    }
    setChart(new JFreeChart("", new Font("SansSerif", Font.BOLD, 14), combined_plot, false));
    setBorder(BorderFactory.createEtchedBorder());
}

From source file:piramide.interaction.reasoner.FuzzyReasonerWizardFacade.java

@Override
public void generateMembershipFunctionGraph(boolean isInput, boolean isDevices, String variableName,
        RegionDistributionInfo[] linguisticTerms, OutputStream destination, int width, int height,
        Geolocation geo, DecayFunctions decayFunction, Calendar when) {
    BufferedImage img;//from  w ww  . j ava 2s .c o m
    if (variableName == null) {
        img = createErrorMessagesImage("Error generating graph: variableName not provided");
    } else if (linguisticTerms == null) {
        img = createErrorMessagesImage("Error generating graph: linguisticTerms not provided");
    } else if (isInput && isDevices && !isValidDeviceVariableName(variableName)) {
        img = createErrorMessagesImage("Error generating graph: invalid device variable name: " + variableName);
    } else if (isInput && !isDevices && !isValidUserVariableName(variableName)) {
        img = createErrorMessagesImage("Error generating graph: invalid user variable name: " + variableName);
    } else {
        try {
            final WarningStore warningStore = new WarningStore();
            final net.sourceforge.jFuzzyLogic.rule.Variable variable = processVariable(isInput, isDevices,
                    variableName, linguisticTerms, geo, decayFunction, when, warningStore);

            final JFreeChart theChart = variable.chart(false);

            final String[] messages = warningStore.getMessages();
            if (messages.length > 0) {
                final Font font = TextTitle.DEFAULT_FONT;
                final Font bigBold = new Font(font.getName(), Font.BOLD, font.getSize() + 2);
                final Font bold = new Font(font.getName(), Font.BOLD, font.getSize());

                theChart.addSubtitle(new TextTitle("WARNINGS:", bigBold, Color.RED, Title.DEFAULT_POSITION,
                        Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT,
                        Title.DEFAULT_PADDING));
                for (String message : messages)
                    theChart.addSubtitle(new TextTitle(message, bold, Color.RED, Title.DEFAULT_POSITION,
                            Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT,
                            Title.DEFAULT_PADDING));
            }
            img = theChart.createBufferedImage(width, height);

        } catch (FuzzyReasonerException e) {
            e.printStackTrace();
            img = createErrorMessagesImage("Error generating graph: " + e.getMessage());
        }
    }

    try {
        final ImageEncoder myEncoder = ImageEncoderFactory.newInstance("png");
        myEncoder.encode(img, destination);
        destination.flush();
        destination.close();
    } catch (IOException e) {
        // Cry
        e.printStackTrace();
        return;
    }
}

From source file:com.manydesigns.portofino.chart.Chart1DGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultPieDataset dataset = new DefaultPieDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);/* w  w w .j a  v a2s .c o m*/
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper key = new ComparableWrapper((Comparable) current[0]);
        dataset.setValue(key, (Number) current[1]);
        if (current.length > 2) {
            key.setLabel(current[2].toString());
        }
    }

    JFreeChart chart = createChart(chartDefinition, dataset);

    chart.setAntiAlias(isAntiAlias());

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(isBorderVisible());

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    PiePlot plot = (PiePlot) chart.getPlot();

    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        PieURLGenerator urlGenerator = new ChartPieUrlGenerator(urlExpression);
        plot.setURLGenerator(urlGenerator);
    } else {
        plot.setURLGenerator(null);
    }

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // hongliangpan add
    // :?{0}  {1}  {2} ? ,???
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})",
            NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
    // {0}={1}({2})
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
    // ?(0.0-1.0)
    // plot.setForegroundAlpha(1.0f);
    // imposta la distanza delle etichette dal plot
    plot.setLabelGap(0.03);
    // plot.setLabelGenerator(new MyPieSectionLabelGenerator());

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));

    plot.setCircular(true);

    plot.setBaseSectionOutlinePaint(Color.BLACK);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);
    // ?
    plot.setForegroundAlpha(1.0f);
    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, getHeight(), Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.linecharts.LineChart.java

public JFreeChart createChart() {

    logger.debug("IN");
    CategoryPlot plot = new CategoryPlot();

    NumberAxis rangeAxis = new NumberAxis("Kpi Values");
    rangeAxis.setLabelFont(new Font("Arial", Font.PLAIN, 12));
    Color colorLabel = Color.decode("#000000");
    rangeAxis.setLabelPaint(colorLabel);
    rangeAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
    rangeAxis.setTickLabelPaint(colorLabel);
    plot.setRangeAxis(rangeAxis);//from  w  ww  . ja v  a2s.  c om

    CategoryAxis domainAxis = new CategoryAxis();
    domainAxis.setLabelFont(new Font("Arial", Font.PLAIN, 10));
    domainAxis.setLabelPaint(colorLabel);
    domainAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
    domainAxis.setTickLabelPaint(colorLabel);
    plot.setDomainAxis(domainAxis);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeGridlinesVisible(true);
    plot.setDomainGridlinesVisible(true);

    //I create a line renderer 
    MyStandardCategoryItemLabelGenerator generator = null;

    LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
    lineRenderer.setShapesFilled(true);
    lineRenderer.setBaseItemLabelGenerator(generator);
    lineRenderer.setBaseItemLabelFont(new Font("Arial", Font.PLAIN, 12));
    lineRenderer.setBaseItemLabelPaint(colorLabel);
    lineRenderer.setBaseItemLabelsVisible(true);

    DefaultCategoryDataset datasetLine = (DefaultCategoryDataset) datasetMap.getDatasets().get("line");

    for (Iterator iterator = datasetLine.getRowKeys().iterator(); iterator.hasNext();) {
        String serName = (String) iterator.next();
        String labelName = "";
        int index = -1;
        index = datasetLine.getRowIndex(serName);

        Color color = Color.decode("#990200");
        lineRenderer.setSeriesPaint(index, color);
    }

    plot.setDataset(0, datasetLine);
    plot.setRenderer(0, lineRenderer);

    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    JFreeChart chart = new JFreeChart(plot);
    logger.debug("Chart created");
    TextTitle title = new TextTitle(name, new Font("Arial", Font.BOLD, 16), Color.decode("#990200"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.setTitle(title);
    TextTitle subTitle = new TextTitle(subName, new Font("Arial", Font.PLAIN, 12), Color.decode("#000000"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.addSubtitle(subTitle);
    TextTitle subTitle2 = new TextTitle(subName, new Font("Arial", Font.PLAIN, 8), Color.decode("#FFFFFF"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.addSubtitle(subTitle2);
    chart.removeLegend();

    chart.setBackgroundPaint(Color.white);
    logger.debug("OUT");
    return chart;
}

From source file:org.n52.server.io.render.DiagramRenderer.java

/**
 * <pre>//from  ww  w  . j  a  v  a2s . c o m
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 *
 * .
 *
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());
    dateAxis.setTimeZone(end.getTimeZone());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) { // dashed
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:it.eng.spagobi.engines.kpi.bo.charttypes.trendcharts.LineChart.java

public JFreeChart createChart() {

    logger.debug("IN");
    CategoryPlot plot = new CategoryPlot();
    IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
    String rangeAxisName = msgBuilder.getMessage("sbi.kpi.rangeAxisName");
    NumberAxis rangeAxis = new NumberAxis(rangeAxisName);
    rangeAxis.setLabelFont(new Font("Arial", Font.PLAIN, 12));
    Color colorLabel = Color.decode("#000000");
    rangeAxis.setLabelPaint(colorLabel);
    rangeAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
    rangeAxis.setTickLabelPaint(colorLabel);
    plot.setRangeAxis(rangeAxis);/* ww  w. jav a 2 s  .  c o  m*/

    CategoryAxis domainAxis = new CategoryAxis();
    domainAxis.setLabelFont(new Font("Arial", Font.PLAIN, 10));
    domainAxis.setLabelPaint(colorLabel);
    domainAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
    domainAxis.setTickLabelPaint(colorLabel);
    plot.setDomainAxis(domainAxis);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeGridlinesVisible(true);
    plot.setDomainGridlinesVisible(true);

    //I create a line renderer 
    MyStandardCategoryItemLabelGenerator generator = null;

    LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
    lineRenderer.setShapesFilled(true);
    lineRenderer.setBaseItemLabelGenerator(generator);
    lineRenderer.setBaseItemLabelFont(new Font("Arial", Font.PLAIN, 12));
    lineRenderer.setBaseItemLabelPaint(colorLabel);
    lineRenderer.setBaseItemLabelsVisible(true);

    DefaultCategoryDataset datasetLine = (DefaultCategoryDataset) datasetMap.getDatasets().get("line");

    for (Iterator iterator = datasetLine.getRowKeys().iterator(); iterator.hasNext();) {
        String serName = (String) iterator.next();
        String labelName = "";
        int index = -1;
        index = datasetLine.getRowIndex(serName);

        Color color = Color.decode("#990200");
        lineRenderer.setSeriesPaint(index, color);
    }

    plot.setDataset(0, datasetLine);
    plot.setRenderer(0, lineRenderer);

    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    JFreeChart chart = new JFreeChart(plot);
    logger.debug("Chart created");
    TextTitle title = new TextTitle(name, new Font("Arial", Font.BOLD, 16), Color.decode("#990200"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.setTitle(title);
    TextTitle subTitle = new TextTitle(subName, new Font("Arial", Font.PLAIN, 12), Color.decode("#000000"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.addSubtitle(subTitle);
    TextTitle subTitle2 = new TextTitle(subName, new Font("Arial", Font.PLAIN, 8), Color.decode("#FFFFFF"),
            RectangleEdge.TOP, HorizontalAlignment.CENTER, VerticalAlignment.TOP, RectangleInsets.ZERO_INSETS);
    chart.addSubtitle(subTitle2);
    chart.removeLegend();

    chart.setBackgroundPaint(Color.white);
    logger.debug("OUT");
    return chart;
}

From source file:org.n52.server.sos.render.DiagramRenderer.java

/**
 * <pre>/*from   w  w w  .  j  ava  2s  .c  om*/
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 * 
 * .
 * 
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin 
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) {
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:com.manydesigns.portofino.chart.Chart2DGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);//from ww w  .  j  ava 2 s .c  om
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper x = new ComparableWrapper((Comparable) current[0]);
        ComparableWrapper y = new ComparableWrapper((Comparable) current[1]);
        if (current.length > 3) {
            x.setLabel(current[3].toString());
        }
        if (current.length > 4) {
            y.setLabel(current[4].toString());
        }
        dataset.setValue((Number) current[2], x, y);
    }

    PlotOrientation plotOrientation = PlotOrientation.HORIZONTAL;
    if (chartDefinition.getActualOrientation() == ChartDefinition.Orientation.VERTICAL) {
        plotOrientation = PlotOrientation.VERTICAL;
    }

    JFreeChart chart = createChart(chartDefinition, dataset, plotOrientation);

    chart.setAntiAlias(antiAlias);

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(borderVisible);

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryItemRenderer renderer = plot.getRenderer();
    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        CategoryURLGenerator urlGenerator = new ChartBarUrlGenerator(chartDefinition.getUrlExpression());
        renderer.setBaseItemURLGenerator(urlGenerator);
    } else {
        renderer.setBaseItemURLGenerator(null);
    }
    renderer.setBaseOutlinePaint(Color.BLACK);

    // ///////////////
    if (renderer instanceof BarRenderer) {
        BarRenderer barRenderer = (BarRenderer) renderer;

        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());
    }
    // ///////////////

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // plot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} = {1} ({2})"));

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.GRAY);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    // Category axis
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setAxisLinePaint(Color.BLACK);
    categoryAxis.setLabelFont(axisFont);
    categoryAxis.setAxisLineVisible(true);

    // impostiamo la rotazione dell'etichetta
    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
        CategoryLabelPosition pos = new CategoryLabelPosition(RectangleAnchor.TOP_LEFT,
                TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 4.0,
                CategoryLabelWidthType.CATEGORY, 100);
        CategoryLabelPositions positions = new CategoryLabelPositions(pos, pos, pos, pos);
        categoryAxis.setCategoryLabelPositions(positions);
        categoryAxis.setMaximumCategoryLabelWidthRatio(6.0f);
        height = 333;
    } else {
        categoryAxis.setMaximumCategoryLabelWidthRatio(0.4f);

        // recuperiamo 8 pixel a sinistra
        plot.setInsets(new RectangleInsets(4.0, 0.0, 4.0, 8.0));

        height = 74;

        // contiamo gli elementi nel dataset
        height += 23 * dataset.getColumnCount();

        height += 57;
    }

    Axis rangeAxis = plot.getRangeAxis();
    rangeAxis.setAxisLinePaint(Color.BLACK);
    rangeAxis.setLabelFont(axisFont);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);
    // ?
    plot.setForegroundAlpha(1.0f);
    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, height, Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:com.manydesigns.portofino.chart.ChartStackedBarGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);/*from   w  ww.  j  av  a 2  s .c  o  m*/
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper x = new ComparableWrapper((Comparable) current[0]);
        ComparableWrapper y = new ComparableWrapper((Comparable) current[1]);
        if (current.length > 3) {
            x.setLabel(current[3].toString());
        }
        if (current.length > 4) {
            y.setLabel(current[4].toString());
        }
        dataset.setValue((Number) current[2], x, y);
    }

    PlotOrientation plotOrientation = PlotOrientation.HORIZONTAL;
    if (chartDefinition.getActualOrientation() == ChartDefinition.Orientation.VERTICAL) {
        plotOrientation = PlotOrientation.VERTICAL;
    }

    JFreeChart chart = createChart(chartDefinition, dataset, plotOrientation);

    chart.setAntiAlias(antiAlias);

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(borderVisible);

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryItemRenderer renderer = plot.getRenderer();
    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        CategoryURLGenerator urlGenerator = new ChartBarUrlGenerator(chartDefinition.getUrlExpression());
        renderer.setBaseItemURLGenerator(urlGenerator);
    } else {
        renderer.setBaseItemURLGenerator(null);
    }
    renderer.setBaseOutlinePaint(Color.BLACK);

    // ///////////////
    if (renderer instanceof BarRenderer) {
        BarRenderer barRenderer = (BarRenderer) renderer;

        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        // ?
        barRenderer.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.06);
    }
    if (renderer instanceof StackedBarRenderer3D || renderer instanceof StackedBarRenderer) {
        BarRenderer barRenderer = (BarRenderer) renderer;
        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        // ? setSeriesItemLabelGenerator
        barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.06);
        // ?????
        ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                TextAnchor.BASELINE_LEFT, TextAnchor.HALF_ASCENT_LEFT, -1.57D);
        // ??labelposition
        barRenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
        barRenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);

        barRenderer.setItemLabelsVisible(true);
        barRenderer.setItemMargin(10);
    }

    // ///////////////

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // plot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} = {1} ({2})"));

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.GRAY);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    // Category axis
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setAxisLinePaint(Color.BLACK);
    categoryAxis.setLabelFont(axisFont);
    categoryAxis.setAxisLineVisible(true);

    // impostiamo la rotazione dell'etichetta
    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
        CategoryLabelPosition pos = new CategoryLabelPosition(RectangleAnchor.TOP_LEFT,
                TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 4.0,
                CategoryLabelWidthType.CATEGORY, 100);
        CategoryLabelPositions positions = new CategoryLabelPositions(pos, pos, pos, pos);
        categoryAxis.setCategoryLabelPositions(positions);
        categoryAxis.setMaximumCategoryLabelWidthRatio(6.0f);
        height = 333;
    } else {
        categoryAxis.setMaximumCategoryLabelWidthRatio(0.4f);

        // recuperiamo 8 pixel a sinistra
        plot.setInsets(new RectangleInsets(4.0, 0.0, 4.0, 8.0));

        height = 74;

        // contiamo gli elementi nel dataset
        height += 23 * dataset.getColumnCount();

        height += 57;
    }

    Axis rangeAxis = plot.getRangeAxis();
    rangeAxis.setAxisLinePaint(Color.BLACK);
    rangeAxis.setLabelFont(axisFont);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);

    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, height, Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:com.manydesigns.portofino.chart.ChartBarGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);//w w w  .  ja v a 2  s .  com
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper x = new ComparableWrapper((Comparable) current[0]);
        ComparableWrapper y = new ComparableWrapper((Comparable) current[1]);
        if (current.length > 3) {
            x.setLabel(current[3].toString());
        }
        if (current.length > 4) {
            y.setLabel(current[4].toString());
        }
        dataset.setValue((Number) current[2], x, y);
    }

    PlotOrientation plotOrientation = PlotOrientation.HORIZONTAL;
    if (chartDefinition.getActualOrientation() == ChartDefinition.Orientation.VERTICAL) {
        plotOrientation = PlotOrientation.VERTICAL;
    }

    JFreeChart chart = createChart(chartDefinition, dataset, plotOrientation);

    chart.setAntiAlias(antiAlias);

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(borderVisible);

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryItemRenderer renderer = plot.getRenderer();
    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        CategoryURLGenerator urlGenerator = new ChartBarUrlGenerator(chartDefinition.getUrlExpression());
        renderer.setBaseItemURLGenerator(urlGenerator);
    } else {
        renderer.setBaseItemURLGenerator(null);
    }
    renderer.setBaseOutlinePaint(Color.BLACK);

    // ///////////////
    if (renderer instanceof BarRenderer || renderer instanceof BarRenderer3D) {
        BarRenderer barRenderer = (BarRenderer) renderer;

        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barRenderer.setBaseItemLabelsVisible(true);
        // ? setSeriesItemLabelGenerator
        barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.05);
        // ?????
        // ??90,??/3.14
        ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                TextAnchor.BASELINE_LEFT, TextAnchor.HALF_ASCENT_LEFT, -1.57D);
        // ??labelposition
        // barRenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
        // barRenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);

        barRenderer.setItemLabelsVisible(true);

        // ?
        barRenderer.setBaseOutlinePaint(Color.BLACK);
        // ???
        barRenderer.setDrawBarOutline(true);

        // ???
        barRenderer.setItemMargin(0.0);

        // ?
        barRenderer.setIncludeBaseInRange(true);
        barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barRenderer.setBaseItemLabelsVisible(true);
        // ?
        plot.setForegroundAlpha(1.0f);
    }

    // ///////////////

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // plot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} = {1} ({2})"));

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.GRAY);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    // Category axis
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setAxisLinePaint(Color.BLACK);
    categoryAxis.setLabelFont(axisFont);
    categoryAxis.setAxisLineVisible(true);

    // impostiamo la rotazione dell'etichetta
    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
        CategoryLabelPosition pos = new CategoryLabelPosition(RectangleAnchor.TOP_LEFT,
                TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 4.0,
                CategoryLabelWidthType.CATEGORY, 100);
        CategoryLabelPositions positions = new CategoryLabelPositions(pos, pos, pos, pos);
        categoryAxis.setCategoryLabelPositions(positions);
        categoryAxis.setMaximumCategoryLabelWidthRatio(6.0f);
        height = 333;
    } else {
        categoryAxis.setMaximumCategoryLabelWidthRatio(0.4f);

        // recuperiamo 8 pixel a sinistra
        plot.setInsets(new RectangleInsets(4.0, 0.0, 4.0, 8.0));

        height = 74;

        // contiamo gli elementi nel dataset
        height += 23 * dataset.getColumnCount();

        height += 57;
    }

    Axis rangeAxis = plot.getRangeAxis();
    rangeAxis.setAxisLinePaint(Color.BLACK);
    rangeAxis.setLabelFont(axisFont);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);

    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, height, Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}