Example usage for org.jfree.chart ChartUtilities saveChartAsJPEG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsJPEG

Introduction

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

Prototype

public static void saveChartAsJPEG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to a file in JPEG format.

Usage

From source file:de.dfki.owlsmx.gui.ShowResultVisualization.java

private void saveActionPerformed(java.awt.event.ActionEvent event) {//GEN-FIRST:event_saveActionPerformed
    try {//  www  .  j a  v a2 s  .co  m
        if (event.getSource().equals(save)) {
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                if (fc.getFileFilter().getClass().equals((new PNGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsPNG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsPNG(new File(fc.getSelectedFile().getAbsolutePath() + ".png"),
                                chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new JPGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsJPEG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsJPEG(
                                new File(fc.getSelectedFile().getAbsolutePath() + ".png"), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new PDFFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".pdf"))
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight, fc.getSelectedFile().getAbsolutePath());
                    else
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight,
                                fc.getSelectedFile().getAbsolutePath() + ".pdf");
                else if (fc.getFileFilter().getClass().equals((new EPSFilter()).getClass()))
                    printGraphics2DtoEPS(fc.getSelectedFile().getAbsolutePath());
            }
        }
    } catch (Exception e) {
        GUIState.displayWarning(e.getClass().toString(),
                "Couldn't save file " + fc.getSelectedFile().getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:se.lnu.cs.doris.metrics.SLOC.java

private void generateImage(ImageType type) throws Exception {
    if (this.m_mainDir == null) {
        throw new Exception("Base directory not set.");
    }/* www  . j  a  v  a 2  s.  c  o m*/

    XYSeries linesOfCodeTotal = new XYSeries("Total lines");
    XYSeries linesOfCode = new XYSeries("Lines of code");
    XYSeries linesOfComments = new XYSeries("Lines of comments");
    XYSeries baseLine = new XYSeries("index 100");

    for (File f : this.m_mainDir.listFiles()) {
        if (f.isDirectory() && !f.getName().contains(this.m_avoid)) {

            int commitNumber = Utilities.parseInt(f.getName());
            int slocd = 0;
            int slocmt = 0;
            int sloct = 0;

            for (File sd : f.listFiles()) {
                if (!sd.getName().toLowerCase().contains(this.m_avoid)) {
                    slocd += this.countLines(sd, false);
                    slocmt += this.countLines(sd, true);
                    sloct += slocd + slocmt;
                }
            }

            if (this.m_baseValueTotal < 0) {
                this.m_baseValueTotal = sloct;
                this.m_baseValueComments = slocmt;
                this.m_baseValueCode = slocd;

                sloct = 100;
                slocmt = 100;
                slocd = 100;
            } else {
                sloct = (int) ((double) sloct / (double) this.m_baseValueTotal * 100);
                slocmt = (int) ((double) slocmt / (double) this.m_baseValueComments * 100);
                slocd = (int) ((double) slocd / (double) this.m_baseValueCode * 100);
            }

            linesOfCodeTotal.add(commitNumber, sloct);
            linesOfCode.add(commitNumber, slocd);
            linesOfComments.add(commitNumber, slocmt);
            baseLine.add(commitNumber, 100);

        }
    }

    XYSeriesCollection collection = new XYSeriesCollection();

    collection.addSeries(linesOfCodeTotal);
    collection.addSeries(linesOfCode);
    collection.addSeries(linesOfComments);
    collection.addSeries(baseLine);

    JFreeChart chart = ChartFactory.createXYLineChart(
            "Source lines of code change for " + this.m_projectName + " \nBase value code: "
                    + this.m_baseValueCode + "\nBase value comments: " + this.m_baseValueComments,
            "Commit", "SLOC change %", collection, PlotOrientation.VERTICAL, true, true, false);

    XYPlot plot = chart.getXYPlot();

    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setTickUnit(new NumberTickUnit(2));

    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setTickUnit(new NumberTickUnit(10));

    switch (type) {
    case JPEG:
        ChartUtilities.saveChartAsJPEG(new File(this.m_mainDir.getAbsolutePath(), "sloc_chart.jpg"), chart,
                1000, 720);
        break;
    case PNG:
        ChartUtilities.saveChartAsPNG(new File(this.m_mainDir.getAbsolutePath(), "sloc_chart.png"), chart, 1000,
                720);
        break;
    default:
        break;
    }
}

From source file:entropy.plan.visualization.GanttVisualizer.java

/**
 * Build the plan agenda/*from w  w w  .  j a  v  a  2  s  .c om*/
 *
 * @param plan the plan to visualize
 * @return {@code true} if the generation succeeds
 */
@Override
public boolean buildVisualization(TimedReconfigurationPlan plan) {
    File parent = new File(out).getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) {
        Plan.logger.error("Unable to create '" + out + "'");
        return false;
    }
    final TaskSeriesCollection collection = new TaskSeriesCollection();
    TaskSeries ts = new TaskSeries("actions");
    for (Action action : plan) {
        Task t = new Task(action.toString(),
                new SimpleTimePeriod(action.getStartMoment(), action.getFinishMoment()));
        ts.add(t);
    }
    collection.add(ts);
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    final JFreeChart chart = ChartFactory.createGanttChart(null, // chart title
            "Actions", // domain axis label
            "Time", // range axis label
            collection, // data
            false, // include legend
            true, // tooltips
            false // urls
    );
    CategoryPlot plot = chart.getCategoryPlot();
    DateAxis da = (DateAxis) plot.getRangeAxis();
    SimpleDateFormat sdfmt = new SimpleDateFormat();
    sdfmt.applyPattern("S");
    da.setDateFormatOverride(sdfmt);
    ((GanttRenderer) plot.getRenderer()).setShadowVisible(false);
    int width = 500 + 10 * plan.getDuration();
    int height = 50 + 20 * plan.size();
    try {
        switch (fmt) {
        case png:
            ChartUtilities.saveChartAsPNG(new File(out), chart, width, height);
            break;
        case jpg:
            ChartUtilities.saveChartAsJPEG(new File(out), chart, width, height);
            break;
        }
    } catch (IOException e) {
        Plan.logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:sipl.recursos.Graficar.java

public void PrestamosY(int[][] values, int n, String direccion, String tiempo, String titulo) {
    try {//from www.j av a2  s.  c om
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int j = 0; j < n; j++) {
            dataset.addValue(values[j][1], "Cantidad de Prstamos", "" + values[j][0]);
        }
        JFreeChart chart = ChartFactory.createLineChart(titulo, tiempo, "Cantidad", dataset,
                PlotOrientation.VERTICAL, true, true, true);
        try {
            ChartUtilities.saveChartAsJPEG(new File(direccion), chart, 500, 500);
        } catch (IOException e) {
            System.out.println("Error al abrir el archivo");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:ch.zhaw.init.walj.projectmanagement.util.chart.LineChart.java

/**
  * creates a line chart with all booked and planned PMs
 *///  ww w . j  av a  2s  . c om
public void createChart() {

    // get dataset
    XYSeriesCollection dataset = null;
    try {
        dataset = (XYSeriesCollection) createDataset();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // create line chart
    JFreeChart xylineChart = ChartFactory.createXYLineChart("", "Month", "PM", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    // set color of chart
    XYPlot plot = xylineChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesPaint(0, new Color(0, 101, 166));
    renderer.setSeriesPaint(1, new Color(0, 62, 102));
    plot.setRenderer(renderer);

    // set size of the chart and save it as small JPEG for project overview
    int width = 600;
    int height = 400;
    File lineChart = new File(path + "EffortProject" + project.getID() + ".jpg");
    try {
        ChartUtilities.saveChartAsJPEG(lineChart, xylineChart, width, height);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // set size of the chart and save it as large JPEG for effort detail page
    width = 1200;
    height = 600;
    lineChart = new File(path + "/Charts/EffortProject" + project.getID() + "_large.jpg");
    try {
        ChartUtilities.saveChartAsJPEG(lineChart, xylineChart, width, height);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java

/**
 * A demonstration application showing how to create a simple time series chart.  This
 * example uses monthly data./*from  w  w w. j  ava2s. c  o  m*/
 *
 * @param title  the frame title.
 */
//    public TimeSeriesPlotter(final String title) {
//        
//        super(title);
//        final XYDataset dataset = createDataset();
//        final JFreeChart chart = createChart(dataset);
//        final ChartPanel chartPanel = new ChartPanel(chart);
//        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
//        chartPanel.setMouseZoomable(true, false);
//        
//        setContentPane(chartPanel);
//
//    }

//    public TimeSeriesPlotter(String title, ArrayList<Sensor> sensors)
//    {
//       super(title);
//        final XYDataset dataset = createDataset(sensors);
//        final JFreeChart chart = createChart(dataset);
//        final ChartPanel chartPanel = new ChartPanel(chart);
//        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
//        chartPanel.setMouseZoomable(true, false);
//        setContentPane(chartPanel);
//   }

public TimeSeriesPlotter_KMeans(String title, ArrayList<Cluster_KMeans> clusters, LocalDateTime from) {
    super(title);
    final XYDataset dataset = createDataset(clusters, from);
    final XYDataset dataset_cetroids = createDataset_centroids(clusters, from);
    final JFreeChart chart = createChart(dataset, dataset_cetroids, clusters);
    final ChartPanel chartPanel = new ChartPanel(chart);

    chartPanel.setPreferredSize(new java.awt.Dimension(2560, 1600));
    chartPanel.setMouseZoomable(true, false);
    setContentPane(chartPanel);

    try {
        ChartUtilities.saveChartAsJPEG(new File("./jpgs/" + title + ".jpg"), chart, 1920, 1200);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.indiana.htrc.visual.HTRCBarChartDrawer.java

@Override
public File draw() {

    System.out.println("draw bar!!!!!!!!!!!!!");

    DefaultCategoryDataset bar_dataset = new DefaultCategoryDataset();
    /*dataset.setValue(6, "Profit", "Jane");
    dataset.setValue(7, "Profit", "Tom");
    dataset.setValue(8, "Profit", "Jill");
    dataset.setValue(5, "Profit", "John");
    dataset.setValue(12, "Profit", "Fred");*/
    Set<String> key_set = input_map.keySet();
    Iterator<String> iter = key_set.iterator();

    while (iter.hasNext()) {
        String key = iter.next();
        int value = input_map.get(key);
        bar_dataset.setValue(value, dataset_label, key);
    }//from w w  w .  j  a  v a2 s  . c  om

    JFreeChart chart = null;
    if (is3D) {
        chart = ChartFactory.createBarChart3D(chart_name, x_axis_label, y_axis_label, bar_dataset,
                PlotOrientation.VERTICAL, true, true, false);
    } else {
        chart = ChartFactory.createBarChart(chart_name, x_axis_label, y_axis_label, bar_dataset,
                PlotOrientation.VERTICAL, true, true, false);
    }

    CategoryPlot p = chart.getCategoryPlot();
    /*  NumberAxis rangeAxis = (NumberAxis) p.getRangeAxis();
      rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());*/
    BarRenderer renderer = (BarRenderer) p.getRenderer();
    DecimalFormat decimalformat1 = new DecimalFormat("##");

    StandardCategoryItemLabelGenerator label_generator = new StandardCategoryItemLabelGenerator("{2}",
            decimalformat1);

    renderer.setItemLabelGenerator(label_generator);

    final ItemLabelPosition pos = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.CENTER_RIGHT,
            TextAnchor.CENTER_RIGHT, 0/* -Math.PI / 2.0*/
    );
    renderer.setPositiveItemLabelPosition(pos);
    final CategoryAxis domainAxis = p.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    renderer.setMaximumBarWidth(.15);
    renderer.setItemLabelsVisible(true);
    chart.getCategoryPlot().setRenderer(renderer);
    File img = new File("../webapps/HTRC-UI-AuditAnalyzer/images/" + System.currentTimeMillis() + ".jpg");

    try {
        ChartUtilities.saveChartAsJPEG(img, chart, 1400, 600);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
    return img;
}

From source file:grafix.principal.Comandos.java

static public void cmdSalvarJPEG() {
    ControleRegistro.alertaRegistro();/*  ww w.ja  v a  2s. c  o  m*/
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(Controle.getTela());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {
            ChartUtilities.saveChartAsJPEG(file, Controle.getJanelaAtiva().getPanelGraficos().getChart(),
                    Controle.getJanelaAtiva().getWidth(), Controle.getJanelaAtiva().getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:Balo.Main.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO dadd your handling code here:
    DefaultCategoryDataset barChart = new DefaultCategoryDataset();
    barChart.setValue(200, "Contribution Amount", "January");
    barChart.setValue(550, "Contribution Amount", "February");
    barChart.setValue(300, "Contribution Amount", "March");

    JFreeChart jbarChart = ChartFactory.createBarChart("Bar chart", "Monthly", "Contribution Amount", barChart,
            PlotOrientation.HORIZONTAL, true, true, true);
    CategoryPlot barchrt = (CategoryPlot) jbarChart.getPlot();
    barchrt.setRangeGridlinePaint(Color.BLUE);

    ChartPanel barPanel = new ChartPanel(jbarChart);
    barPanel.setPreferredSize(new Dimension(785, 440)); //size according to my window
    barPanel.setMouseWheelEnabled(true);
    JPanel jPanel = new JPanel();
    jPanel.add(barPanel);/*from  ww  w .j  av a 2s .  c  o  m*/

    String filename = "F:barchart.jpg";
    try {
        ChartUtilities.saveChartAsJPEG(new File(filename), jbarChart, 500, 300);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openmicroscopy.shoola.util.ui.graphutils.ChartObject.java

/**
 * Saves the chart as a <code>JPEG</code> or <code>PNG</code>.
 * //from   www .  j a  va 2 s .  c o m
 * @param file        The file where to save the chart.
 * @param savingType Indicates either to save as a 
 *                 <code>JPEG</code> or <code>PNG</code>
 */
public void saveAs(File file, int savingType) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file specified");
    try {
        switch (savingType) {
        case SAVE_AS_PNG:
            ChartUtilities.saveChartAsPNG(file, chart, WIDTH, HEIGHT);
            break;
        case SAVE_AS_JPEG:
            ChartUtilities.saveChartAsJPEG(file, chart, WIDTH, HEIGHT);
        }
    } catch (Exception e) {
        throw new Exception("Unable to save the file.", e);
    }
}