Example usage for org.jfree.chart ChartRenderingInfo ChartRenderingInfo

List of usage examples for org.jfree.chart ChartRenderingInfo ChartRenderingInfo

Introduction

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

Prototype

public ChartRenderingInfo() 

Source Link

Document

Constructs a new ChartRenderingInfo structure that can be used to collect information about the dimensions of a rendered chart.

Usage

From source file:tl.lib.dataCollection.gui.TimeSeriesChart.java

public TimeSeriesChart(_CollectionGUIScenario scenario, String label, String description, String labelAxisY) {
    super(null);//from  ww  w .java 2 s  .  co  m
    this.sourceDescriptor = scenario.getSourceDescriptor();
    this.collection = new XYSeriesCollection();

    // ChartTheme currentTheme = new StandardChartTheme("JFree");
    ValueAxis timeAxis = new DateAxis("Time");
    timeAxis.setLowerMargin(0.02); // reduce the default margins
    timeAxis.setUpperMargin(0.02);
    NumberAxis valueAxis = new NumberAxis(labelAxisY);
    valueAxis.setAutoRangeIncludesZero(false); // override default

    XYToolTipGenerator toolTipGenerator = null;
    toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    // XYURLGenerator urlGenerator = new StandardXYURLGenerator();
    renderer.setBaseToolTipGenerator(toolTipGenerator);
    // renderer.setURLGenerator(urlGenerator);

    this.plot = new XYPlot(collection, timeAxis, valueAxis, renderer);

    this.chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    // currentTheme.apply(chart);

    renderingInfo = new ChartRenderingInfo();

    this.scenario = scenario;
    this.description = description;
    this.label = label;
    this.selected = new Vector<SourceId>();
    default_all = true;
    super.setChart(chart);
}

From source file:tl.lib.dataCollection.gui.NumXYChart.java

public NumXYChart(_CollectionGUIScenario scenario, String label, String description, String labelAxisY) {
    super(null);//from www . java 2s .c  o  m
    this.sourceDescriptor = scenario.getSourceDescriptor();
    this.collection = new XYSeriesCollection();

    // ChartTheme currentTheme = new StandardChartTheme("JFree");
    NumberAxis valueAxisX = new NumberAxis("Sample Number");
    valueAxisX.setAutoRangeIncludesZero(false); // override default
    NumberAxis valueAxisY = new NumberAxis(labelAxisY);
    valueAxisY.setAutoRangeIncludesZero(false); // override default

    XYToolTipGenerator toolTipGenerator = null;
    toolTipGenerator = new StandardXYToolTipGenerator();

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    // XYURLGenerator urlGenerator = new StandardXYURLGenerator();
    renderer.setBaseToolTipGenerator(toolTipGenerator);
    // renderer.setURLGenerator(urlGenerator);

    this.plot = new XYPlot(collection, valueAxisX, valueAxisY, renderer);

    this.chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    // currentTheme.apply(chart);

    renderingInfo = new ChartRenderingInfo();

    this.scenario = scenario;
    this.description = description;
    this.label = label;
    this.selected = new Vector<SourceId>();
    default_all = true;
    super.setChart(chart);
}

From source file:org.adempiere.webui.apps.graph.jfreegraph.ChartRendererServiceImpl.java

@Override
public boolean renderPerformanceGraph(Component parent, int chartWidth, int chartHeight,
        final GoalModel goalModel) {
    GraphBuilder builder = new GraphBuilder();
    builder.setMGoal(goalModel.goal);/*from w  ww .  j a  v  a2 s.  c  om*/
    builder.setXAxisLabel(goalModel.xAxisLabel);
    builder.setYAxisLabel(goalModel.yAxisLabel);
    builder.loadDataSet(goalModel.columnList);
    JFreeChart chart = builder.createChart(goalModel.chartType);
    ChartRenderingInfo info = new ChartRenderingInfo();
    chart.getPlot().setForegroundAlpha(0.6f);
    if (goalModel.zoomFactor > 0) {
        chartWidth = chartWidth * goalModel.zoomFactor / 100;
        chartHeight = chartHeight * goalModel.zoomFactor / 100;
    }
    if (!goalModel.showTitle) {
        chart.setTitle("");
    }
    BufferedImage bi = chart.createBufferedImage(chartWidth, chartHeight, BufferedImage.TRANSLUCENT, info);
    try {
        byte[] bytes = EncoderUtil.encode(bi, ImageFormat.PNG, true);

        AImage image = new AImage("", bytes);
        Imagemap myImage = new Imagemap();

        myImage.setContent(image);
        parent.appendChild(myImage);

        int count = 0;
        for (Iterator<?> it = info.getEntityCollection().getEntities().iterator(); it.hasNext();) {
            ChartEntity entity = (ChartEntity) it.next();

            String key = null;
            if (entity instanceof CategoryItemEntity) {
                Comparable<?> colKey = ((CategoryItemEntity) entity).getColumnKey();
                if (colKey != null) {
                    key = colKey.toString();
                }
            } else if (entity instanceof PieSectionEntity) {
                Comparable<?> sectionKey = ((PieSectionEntity) entity).getSectionKey();
                if (sectionKey != null) {
                    key = sectionKey.toString();
                }
            }
            if (key == null) {
                continue;
            }

            Area area = new Area();
            myImage.appendChild(area);
            area.setCoords(entity.getShapeCoords());
            area.setShape(entity.getShapeType());
            area.setTooltiptext(entity.getToolTipText());
            area.setId(count + "_WG_" + key);
            count++;
        }

        myImage.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
            public void onEvent(Event event) throws Exception {
                MouseEvent me = (MouseEvent) event;
                String areaId = me.getArea();
                if (areaId != null) {
                    List<GraphColumn> list = goalModel.columnList;
                    for (int i = 0; i < list.size(); i++) {
                        String s = "_WG_" + list.get(i).getLabel();
                        if (areaId.endsWith(s)) {
                            chartMouseClicked(goalModel.goal, list.get(i));
                            return;
                        }
                    }
                }
            }
        });
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        return false;
    }
    return true;
}

From source file:org.toobsframework.pres.chart.ChartBuilder.java

public String buildAsImage(ChartDefinition chartDef, IRequest componentRequest, int width, int height)
        throws ChartException {
    JFreeChart chart = this.build(chartDef, componentRequest);
    if (width <= 0) {
        chartDef.getChartWidth();//from w ww . j  a  v  a2s . c om
    }
    if (height <= 0) {
        chartDef.getChartHeight();
    }

    String genFileName = chartDef.getId() + "-" + new Date().getTime() + ".png";
    String imageOutputFileName = configuration.getUploadDir() + genFileName;
    try {
        File imageOutputFile = new File(imageOutputFileName);
        OutputStream os = null;
        ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo();
        try {
            os = new FileOutputStream(imageOutputFile);
            ChartUtilities.writeChartAsPNG(os, chart, width, height, chartRenderingInfo);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new ChartException(e);
    } catch (IOException e) {
        throw new ChartException(e);
    }

    return imageOutputFileName;
}

From source file:nextapp.echo.chart.webcontainer.sync.component.ChartDisplayPeer.java

private String getImageMap(Component comp) {
    StringBuffer sb = new StringBuffer();

    ChartDisplay chartDisplay = (ChartDisplay) comp;

    Extent ewidth = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_WIDTH);
    int width = ewidth != null ? ewidth.getValue() : ChartDisplayPeer.DEFAULT_WIDTH;

    Extent eheight = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_HEIGHT);
    int height = ewidth != null ? eheight.getValue() : ChartDisplayPeer.DEFAULT_HEIGHT;

    JFreeChart chart = chartDisplay.getChart();
    BufferedImage image;/* w  w  w . j av  a  2s .  c om*/
    ChartRenderingInfo info = new ChartRenderingInfo();
    synchronized (chart) {
        image = chart.createBufferedImage(width, height, info);
    }
    EntityCollection coll = info.getEntityCollection();
    //        debug("About to show entities");
    //        for (int i = 0; i < coll.getEntityCount(); i++) {
    //           debug("Entity: " + coll.getEntity(i).getShapeCoords());
    //           debug("Entity: " + coll.getEntity(i).getShapeType());
    //           debug("Entity: " + coll.getEntity(i).getToolTipText());
    //        }
    sb.append("[");
    for (int i = 0; i < coll.getEntityCount(); i++) {
        if (i > 0) {
            sb.append(", ");
        }
        sb.append("{ shapeType: '" + coll.getEntity(i).getShapeType() + "'");
        sb.append(", shapeCoords: '" + coll.getEntity(i).getShapeCoords() + "'");
        sb.append(", actionCommand: '" + chartDisplay.getActionCommands()[i] + "'");
        sb.append(", toolTipText: '" + coll.getEntity(i).getToolTipText() + "'}");

    }
    sb.append("]");

    return sb.toString();
}

From source file:ca.sqlpower.wabit.report.ChartRenderer.java

public boolean renderReportContent(Graphics2D g, double width, double height, double scaleFactor, int pageIndex,
        boolean printing, SPVariableResolver variablesContext) {

    if (printing) {
        // If we're printing a streaming query, we have to
        // print whatever's displayed.
        if (this.chartCache == null || (this.chartCache != null && !this.chartCache.getQuery().isStreaming())) {
            refresh(false);//from   w ww . ja v a  2  s  .  com
        }
    } else if (needsRefresh || this.chartCache == null) {
        // No chart loaded. Doing a refresh will trigger a new 
        // redraw later on.
        refresh();
        return false;
    }

    JFreeChart jFreeChart = null;
    try {
        jFreeChart = ChartSwingUtil.createChartFromQuery(chartCache);
        if (jFreeChart == null) {
            g.drawString("Loading...", 0, g.getFontMetrics().getHeight());
            return false;
        }

        Rectangle2D area = new Rectangle2D.Double(0, 0, width, height);

        // first pass establishes rendering info but draws nothing
        ChartRenderingInfo info = new ChartRenderingInfo();
        Graphics2D dummyGraphics = (Graphics2D) g.create(0, 0, 0, 0);
        jFreeChart.draw(dummyGraphics, area, info);
        dummyGraphics.dispose();

        // now for real
        Rectangle2D plotArea = info.getPlotInfo().getDataArea();
        ChartGradientPainter.paintChartGradient(g, area, (int) plotArea.getMaxY());
        jFreeChart.draw(g, area);

    } catch (Exception e) {
        logger.error("Error while rendering chart", e);
        g.drawString("Could not render chart: " + e.getMessage(), 0, g.getFontMetrics().getHeight());
    }
    return false;
}

From source file:edu.jhuapl.graphs.jfreechart.JFreeChartBaseSource.java

/**
 * {@inheritDoc}/*from ww  w.ja v a  2 s.  c  om*/
 */
@Override
public RenderedGraph renderGraph(int width, int height, Encoding encoding) throws GraphException {
    if (!isInitialized()) {
        throw new GraphException("Not Initialized");
    }

    ImageEncoder encoder = getEncoder(encoding);
    ChartRenderingInfo info = new ChartRenderingInfo();
    byte[] data;
    try {
        data = encoder.encode(renderImage(width, height, info));
    } catch (IOException e) {
        throw new GraphException("Image encoding failed", e);
    }

    return new JFreeChartRenderedGraph(info, data, encoding);
}

From source file:org.toobsframework.pres.chart.controller.ChartHandler.java

/**
 * //  w w w.j a v  a 2 s  .  co  m
 * Retrieves the URL path to use for lookup and delegates to
 * <code>getViewNameForUrlPath</code>.
 * 
 * @throws Exception Exception fetching or rendering component.
 * @see #getViewNameForUrlPath
 * 
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response,
        UrlDispatchInfo dispatchInfo) throws Exception {

    String chartId = dispatchInfo.getResourceId();
    if (log.isDebugEnabled()) {
        log.debug("Rendering chart '" + chartId + "' for lookup path: " + dispatchInfo.getOriginalPath());
    }

    IRequest componentRequest = this.setupComponentRequest(dispatchInfo, request, response, true);

    Date startTime = null;
    if (log.isDebugEnabled()) {
        startTime = new Date();
    }

    JFreeChart chart = null;
    int height = 400;
    int width = 600;
    ChartDefinition chartDef = null;
    if (null != chartId && !chartId.equals("")) {
        try {
            request.setAttribute("chartId", chartId);
            chartDef = this.chartManager.getChartDefinition(chartId);
        } catch (ChartNotFoundException cnfe) {
            log.warn("Chart " + chartId + " not found.");
            throw cnfe;
        }
        try {

            chart = chartBuilder.build(chartDef, componentRequest);
            width = chartDef.getChartWidth();
            height = chartDef.getChartHeight();

        } catch (ChartException e) {
            Throwable t = e.rootCause();
            log.info("Root cause " + t.getClass().getName() + " " + t.getMessage());
            throw e;
        } catch (Exception e) {
            throw e;
        } finally {
            this.componentRequestManager.unset();
        }

    } else {
        throw new Exception("No chartId specified");
    }

    //Write out to the response.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "max-age=0, must-revalidate"); // HTTP 1.1
    ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo();
    if (chartDef.doImageWithMap()) {
        response.setContentType("text/html; charset=UTF-8");
        String genFileName = chartDef.getId() + "-" + new Date().getTime() + ".png";
        String imageOutputFileName = configuration.getUploadDir() + genFileName;
        File imageOutputFile = new File(imageOutputFileName);
        OutputStream os = null;
        try {
            os = new FileOutputStream(imageOutputFile);
            ChartUtilities.writeChartAsPNG(os, chart, width, height, chartRenderingInfo);
        } finally {
            if (os != null) {
                os.close();
            }
        }
        PrintWriter writer = response.getWriter();
        StringBuffer sb = new StringBuffer();

        // TODO BUGBUG Chart location needs to fixed
        sb.append("<img id=\"chart-").append(chartDef.getId()).append("\" src=\"")
                .append(/*Configuration.getInstance().getMainContext() +*/ "/upload/" + genFileName)
                .append("\" ismap=\"ismap\" usemap=\"#").append(chartDef.getId()).append("Map\" />");
        URLTagFragmentGenerator urlGenerator;
        if (chartDef.getUrlFragmentBean() != null) {
            urlGenerator = (URLTagFragmentGenerator) beanFactory.getBean(chartDef.getUrlFragmentBean());
        } else {
            urlGenerator = new StandardURLTagFragmentGenerator();
        }
        sb.append(ImageMapUtilities.getImageMap(chartDef.getId() + "Map", chartRenderingInfo, null,
                urlGenerator));
        writer.print(sb.toString());
        writer.flush();

    } else {
        response.setContentType("image/png");

        ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height, chartRenderingInfo);

    }

    if (log.isDebugEnabled()) {
        Date endTime = new Date();
        log.debug("Time [" + chartId + "] - " + (endTime.getTime() - startTime.getTime()));
    }
    return null;

}

From source file:org.orbeon.oxf.processor.serializer.legacy.JFreeChartSerializer.java

protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config,
        OutputStream outputStream) {
    try {//from w w  w . j a v  a  2  s.  c  om
        ChartConfig chartConfig = readCacheInputAsObject(pipelineContext, getInputByName(INPUT_CHART),
                new CacheableInputReader<ChartConfig>() {
                    public ChartConfig read(org.orbeon.oxf.pipeline.api.PipelineContext context,
                            org.orbeon.oxf.processor.ProcessorInput input) {
                        return createChartConfig(context, input);
                    }
                });
        Document data = readInputAsDOM4J(pipelineContext, (input != null) ? input : getInputByName(INPUT_DATA));

        Dataset ds;
        if (chartConfig.getType() == ChartConfig.PIE_TYPE || chartConfig.getType() == ChartConfig.PIE3D_TYPE)
            ds = createPieDataset(chartConfig, data);
        else if (chartConfig.getType() == ChartConfig.XY_LINE_TYPE)
            ds = createXYDataset(chartConfig, data);
        else if (chartConfig.getType() == ChartConfig.TIME_SERIES_TYPE)
            ds = createTimeSeriesDataset(chartConfig, data);
        else
            ds = createDataset(chartConfig, data);
        JFreeChart chart = drawChart(chartConfig, ds);
        ChartRenderingInfo info = new ChartRenderingInfo();
        ChartUtilities.writeChartAsPNG(outputStream, chart, chartConfig.getxSize(), chartConfig.getySize(),
                info, true, 5);
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:nextapp.echo.chart.webcontainer.service.ChartImageService.java

public void service(Connection conn) throws IOException {
    try {//from   w w w .  j ava2  s . c o  m
        UserInstance userInstance = (UserInstance) conn.getUserInstance();
        if (userInstance == null) {
            serviceBadRequest(conn, "No container available.");
            return;
        }

        HttpServletRequest request = conn.getRequest();
        String chartId = request.getParameter("chartId");
        ChartDisplay chartDisplay = (ChartDisplay) userInstance.getApplicationInstance()
                .getComponentByRenderId(chartId);
        synchronized (chartDisplay) {
            if (chartDisplay == null || !chartDisplay.isRenderVisible()) {
                throw new IllegalArgumentException("Invalid chart id.");
            }

            Extent ewidth = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_WIDTH);
            int width = ewidth != null ? ewidth.getValue() : ChartDisplayPeer.DEFAULT_WIDTH;

            Extent eheight = (Extent) chartDisplay.getRenderProperty(ChartDisplay.PROPERTY_HEIGHT);
            int height = ewidth != null ? eheight.getValue() : ChartDisplayPeer.DEFAULT_HEIGHT;

            JFreeChart chart = chartDisplay.getChart();
            BufferedImage image;
            ChartRenderingInfo info = new ChartRenderingInfo();
            synchronized (chart) {
                image = chart.createBufferedImage(width, height, info);
            }
            //                EntityCollection coll = info.getEntityCollection();
            //                debug("About to show entities");
            //                for (int i = 0; i < coll.getEntityCount(); i++) {
            //                   debug("Entity: " + coll.getEntity(i).getShapeCoords());
            //                   debug("Entity: " + coll.getEntity(i).getShapeType());
            //                   debug("Entity: " + coll.getEntity(i).getToolTipText());
            //                }

            PngEncoder encoder = new PngEncoder(image, true, null, 3);
            conn.setContentType(ContentType.IMAGE_PNG);
            OutputStream out = conn.getOutputStream();
            encoder.encode(out);
        }
    } catch (IOException ex) {
        // Internet Explorer appears to enjoy making half-hearted requests for images, wherein it resets the connection
        // leaving us with an IOException.  This exception is silently eaten.
        ex.printStackTrace();
    }
}