Interfaces.EstadisticaGui.java Source code

Java tutorial

Introduction

Here is the source code for Interfaces.EstadisticaGui.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaces;

import Modelos.Categoria;
import Modelos.Dato;
import Modelos.Gasto;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Paint;
import java.awt.Stroke;
import java.util.Iterator;
import javafx.scene.chart.CategoryAxis;
import javax.swing.JPanel;
import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartTheme;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarPainter;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author NicoOrcasitas
 */
public class EstadisticaGui extends javax.swing.JDialog {

    /**
     * Creates new form EstadisticaGui
     */

    public EstadisticaGui(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        dibujarGraficos();
    }

    private float[] calcularIngreso(Integer idCat, Integer anio) {
        float[] ingreso = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        LazyList<Dato> datosAero = Dato.where("categoria_id  = ? and ingreso_egreso =? ", idCat, "ingreso");
        Iterator<Dato> it = datosAero.iterator();
        Dato dato;
        Gasto gasto;
        while (it.hasNext()) {
            dato = it.next();
            LazyList<Gasto> gastos = dato.get(Gasto.class, "fecha < ? and fecha >  ?", anio + "-12-31",
                    anio + "-1-1");
            Iterator<Gasto> itG = gastos.iterator();
            while (itG.hasNext()) {
                gasto = itG.next();
                Integer mes = gasto.getDate("fecha").getMonth();
                ingreso[mes] += gasto.getFloat("monto");
            }

        }
        return ingreso;
    }

    public void abrirBase() {
        if (!Base.hasConnection()) {
            Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/gym", "root", "root");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        spinnerAnio = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        panelGrande = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Estadisticas de ingresos");
        setPreferredSize(new java.awt.Dimension(798, 462));

        spinnerAnio.setValue(2015);
        spinnerAnio.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spinnerAnioStateChanged(evt);
            }
        });

        jLabel1.setText("Ao");

        panelGrande.setLayout(new java.awt.GridLayout(0, 1));
        jScrollPane1.setViewportView(panelGrande);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addGap(36, 36, 36)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(spinnerAnio, javax.swing.GroupLayout.PREFERRED_SIZE, 141,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(592, Short.MAX_VALUE))
                .addComponent(jScrollPane1));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(spinnerAnio, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1))
                        .addGap(11, 11, 11)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)));

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void spinnerAnioStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerAnioStateChanged
        dibujarGraficos();
    }//GEN-LAST:event_spinnerAnioStateChanged

    private void dibujarGraficos() {
        this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        abrirBase();
        panelGrande.removeAll();
        Integer anio = (Integer) spinnerAnio.getValue();
        // Creamos y rellenamos el modelo de datos
        LazyList<Categoria> categorias = Categoria.findAll();
        Iterator<Categoria> it = categorias.iterator();
        while (it.hasNext()) {
            Categoria c = it.next();
            if (!c.getString("nombre").equals("COMPRAS")) {
                DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                float[] ingreso = calcularIngreso(c.getInteger("id"), anio);
                dataset.setValue(ingreso[0], c.getString("nombre"), "Enero");
                dataset.setValue(ingreso[1], c.getString("nombre"), "Febrero");
                dataset.setValue(ingreso[2], c.getString("nombre"), "Marzo");
                dataset.setValue(ingreso[3], c.getString("nombre"), "Abril");
                dataset.setValue(ingreso[4], c.getString("nombre"), "Mayo");
                dataset.setValue(ingreso[5], c.getString("nombre"), "Junio");
                dataset.setValue(ingreso[6], c.getString("nombre"), "Julio");
                dataset.setValue(ingreso[7], c.getString("nombre"), "Agosto");
                dataset.setValue(ingreso[8], c.getString("nombre"), "Septiembre");
                dataset.setValue(ingreso[9], c.getString("nombre"), "Octubre");
                dataset.setValue(ingreso[10], c.getString("nombre"), "Noviembre");
                dataset.setValue(ingreso[11], c.getString("nombre"), "Diciembre");
                JFreeChart chart = ChartFactory.createBarChart3D(
                        "Ingresos en la categoria " + c.getString("nombre"), "mes", "Pesos", dataset,
                        PlotOrientation.VERTICAL, true, true, false);
                // Creacin del panel con el grfico
                ChartPanel panelGrafico = new ChartPanel(chart);
                CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
                org.jfree.chart.axis.CategoryAxis categoryaxis = categoryplot.getDomainAxis();
                categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.2D));
                CategoryItemRenderer categoryitemrenderer = categoryplot.getRenderer();
                categoryitemrenderer.setBaseItemLabelsVisible(true);
                JPanel panelParaGrafico = new JPanel();
                panelParaGrafico.setLayout(new BorderLayout());
                panelGrande.add(panelParaGrafico);
                panelParaGrafico.add(panelGrafico);
            }
        }
        this.pack();
        this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EstadisticaGui.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EstadisticaGui.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EstadisticaGui.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EstadisticaGui.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EstadisticaGui dialog = new EstadisticaGui(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelGrande;
    private javax.swing.JSpinner spinnerAnio;
    // End of variables declaration//GEN-END:variables
}