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:techtonic.Onview.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {
    try {// ww w.  j  a  va  2 s  . c o m
        ChartUtilities.saveChartAsJPEG(new File(defaultDirectory, fileName + "." + fileFormat), chart, 800,
                600);
        statusBar.setForeground(Color.blue);
        statusBar.setText("File Saved");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Problem saving this file");
        statusBar.setForeground(Color.red);
        statusBar.setText("File not saved");
    }

}

From source file:techtonic.Techtonic.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
    try {/*from www  . j a v  a  2  s .c  o  m*/
        ChartUtilities.saveChartAsJPEG(new File(defaultDirectory, fileName + "." + fileFormat), chart, 800,
                600);
        statusBar.setForeground(Color.blue);
        statusBar.setText("File Saved");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Problem saving this file");
        statusBar.setForeground(Color.red);
        statusBar.setText("File not saved");
    }

}

From source file:ctPrincipal.Principal.java

public void criaGrafico() throws IOException {
    CategoryDataset cds = _grafico.createDataset();
    String titulo = "Mdia Linha de varredura ";
    String eixoy = "Valores";
    String txt_legenda = "Pixels";
    boolean legenda = true;
    boolean tooltips = true;
    boolean urls = true;
    JFreeChart graf = ChartFactory.createLineChart(titulo, txt_legenda, eixoy, cds, PlotOrientation.VERTICAL,
            true, true, true);/* www  .j  a  v a 2 s .  co  m*/
    ChartPanel myChartPanel = new ChartPanel(graf, true);
    myChartPanel.setSize(jPanel1.getWidth(), jPanel1.getHeight());
    myChartPanel.setVisible(true);
    File lineChart = new File("OutputImg/grafico.jpeg");
    ChartUtilities.saveChartAsJPEG(lineChart, graf, 256, 256);
    jLImgC.setIcon(new ImageIcon(lineChart.getAbsolutePath()));
}

From source file:skoa.helpers.Graficos.java

/*********************************************************************************************************
 * FUNCIONES PARA CREAR LOS GRFICOS DE LA CONSULTA C! MANIPULANDO LOS DATOS OBTENIDOS DE LAS CONSULTAS.*
 *********************************************************************************************************/
private void maxMinMed() {
    //En este tipo de consultas, sacamos la DG del fichero original de datos, para ponerla en la graf.
    String dg = nombresFicheros.get(0);
    //dg=dg.substring(dg.indexOf("-")+7,dg.indexOf(".txt")); //Saca la DG del nombre del fich.
    if (dg.indexOf("D") > 0 && dg.indexOf(" ") < 0) { //Si es el resultado final de una consulta D.
        dg = dg.substring(dg.indexOf(".txt") - 13, dg.indexOf(".txt")); //Saca la DG del nombre del fich.
    } else { //Si son resultados de una consulta D.
        //As, buscando a partir de .txt da igual el tipo de consulta que sea, que se saca igual.
        dg = dg.substring(dg.indexOf(" ") - 6, dg.indexOf(".txt")); //Saca la DG del nombre del fich.
    }//from  www.j  a v a  2  s . co  m
    //---------------------------------------------
    crearEstadisticas(); //Crea el fichero estadisticas.txt donde se encuentra el FECHA MAX MIN y MED en este orden
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades.add(unidad);
    nombresDGs.add("Max"); //Reusamos esta variable. Nos referimos al nombre de cada una de las barras que se ven.
    nombresDGs.add("Min");
    nombresDGs.add("Med");
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset = obtenerSerieBarras2(vectorOrdenUnidades);
    String unidad = "";
    for (int i = 0; i < vectorOrdenUnidades.size(); i++)
        unidad = unidad + vectorOrdenUnidades.elementAt(i) + ", ";
    unidad = unidad.substring(0, unidad.length() - 2); //Quita el ultimo espacio y la ultima coma.
    if (unidad.indexOf("C") >= 0)
        unidad = "C";
    dg = dg.replaceAll("-", "/");
    JFreeChart grafica = ChartFactory.createBarChart("Valores medidos de las direcciones de grupo", "Fechas", //titulo eje x
            "Mediciones (" + unidad + ") de " + dg, dataset, PlotOrientation.VERTICAL, true, //leyenda
            true, false);
    if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estn vacas es porque no hay resultados para ese intervalo.
        fechaInicial = " ? ";
        fechaFinal = " ? ";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    CategoryPlot plot = grafica.getCategoryPlot();
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 9)); //Letra de las fechas ms pequea
    //Esconder las sombras de las barras del barchart.
    CategoryPlot categoryPlot = (CategoryPlot) grafica.getPlot();
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false);
    categoryPlot.setRenderer(renderer);
    //-------------------------------------------------
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "MaxMinMedSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "MaxMinMedBig.jpg"), grafica, 900, 600);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart." + e);
    }
}

From source file:skoa.helpers.Graficos.java

/*********************************************************************************************************
 * FUNCIONES PARA CREAR LOS GRFICOS DE LA CONSULTA D! MANIPULANDO LOS DATOS OBTENIDOS DE LAS CONSULTAS.*
 *********************************************************************************************************/
private void difPorc() {
    //Aplicarle la frmula a los valores de las dos direcciones, obteniendo un slo fichero.
    aplicarFormula(1); //Se le aplica con porcentajes.
    //En este tipo de consultas, buscamos el tipo que es y la unidad, para que se vean.
    String tipo = unidad.substring(0, unidad.indexOf("\t"));
    unidad = unidad.substring(unidad.indexOf("\t") + 1);
    if (unidad.indexOf("C") >= 0)
        unidad = "C";
    TimeSeries serie = obtenerSerieEvolucion2(); //Reutilizamos este cdigo.
    TimeSeriesCollection dataset = new TimeSeriesCollection(serie); //Slo se obtiene una curva.
    JFreeChart grafica = ChartFactory.createTimeSeriesChart("Valores medidos de las direcciones de grupo", //titulo
            "Fechas", //titulo eje x
            "Mediciones en " + tipo + " " + "(" + unidad + ")", //titulo eje y
            dataset, //dataset
            true, //leyenda
            true, //tooltips
            false); //configure chart to generate URLs?

    //Dar color a cada categoria
    grafica.setBackgroundPaint(Color.WHITE); //Color del fondo del grfico
    if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estn vacas es porque no hay resultados para ese intervalo.
        fechaInicial = " ? ";
        fechaFinal = " ? ";
    }/*from w  w  w. j a v  a2  s.  c o  m*/
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasBig.jpg"), grafica, 900, 600);
    } catch (IOException e1) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:skoa.helpers.Graficos.java

private void difAbs() {
    //Aplicarle la frmula a los valores de las dos direcciones, obteniendo un slo fichero.
    aplicarFormula(2); //Se le aplica con porcentajes.
    String tipo = unidad.substring(0, unidad.indexOf("\t"));
    if (tipo.contentEquals("ABS"))
        tipo = "DIF";
    unidad = unidad.substring(unidad.indexOf("\t") + 1);
    if (unidad.indexOf("C") >= 0)
        unidad = "C";
    TimeSeries serie = obtenerSerieEvolucion2(); //Reutilizamos este cdigo.
    TimeSeriesCollection dataset = new TimeSeriesCollection(serie); //Slo se obtiene una curva.
    JFreeChart grafica = ChartFactory.createTimeSeriesChart("Valores medidos de las direcciones de grupo", //titulo
            "Fechas", //titulo eje x
            "Mediciones en " + tipo + " " + "(" + unidad + ")", //titulo eje y
            dataset, //dataset
            true, //leyenda
            true, //tooltips
            false); //configure chart to generate URLs?
    //Dar color a cada categoria
    grafica.setBackgroundPaint(Color.WHITE); //Color del fondo del grafico
    if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estan vacas es porque no hay resultados para ese intervalo.
        fechaInicial = " ? ";
        fechaFinal = " ? ";
    }/*from  w w w.  j  a  va  2s .  c  o m*/
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "DiferenciasBig.jpg"), grafica, 900, 600);
    } catch (IOException e1) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:org.nuclos.client.ui.collect.Chart.java

private void actionCommandSave() {
    try {//from ww w . ja  va  2s. c  o m
        JFileChooser fileChooser = new JFileChooser();
        FileFilter filter = new FileNameExtensionFilter(
                SpringLocaleDelegate.getInstance().getMessage("filenameextensionfilter.1", "Bildformate")
                        + " (*.svg, *.png, *.jpg, *.jpeg)",
                "svg", "png", "jpg", "jpeg"); // @todo i18n
        fileChooser.addChoosableFileFilter(filter);

        int option = fileChooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            String filename = fileChooser.getSelectedFile().getPath();
            if (fileChooser.getSelectedFile().getName().lastIndexOf(".") == -1) {
                filename = filename + ".png";
            }

            if (filename.toLowerCase().endsWith(".png"))
                ChartUtilities.saveChartAsPNG(new File(filename), getChartPanel().getChart(),
                        getChartPanel().getWidth(), getChartPanel().getHeight());
            else if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".jpeg"))
                ChartUtilities.saveChartAsJPEG(new File(filename), getChartPanel().getChart(),
                        getChartPanel().getWidth(), getChartPanel().getHeight());
            else if (filename.toLowerCase().endsWith(".svg")) {
                // Get a DOMImplementation and create an XML document
                DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
                Document document = domImpl.createDocument(null, "svg", null);

                // Create an instance of the SVG Generator
                SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                // draw the chart in the SVG generator
                JFreeChart chart = getChartPanel().getChart();
                chart.draw(svgGenerator, getChartPanel().getBounds());

                // Write svg file
                OutputStream outputStream = new FileOutputStream(filename);
                Writer out = new OutputStreamWriter(outputStream, "UTF-8");
                svgGenerator.stream(out, true /* use css */);
                outputStream.flush();
                outputStream.close();
            }
        }
    } catch (Exception e) {
        throw new NuclosFatalException(e.getMessage());
    }
}