control.listaReporte.java Source code

Java tutorial

Introduction

Here is the source code for control.listaReporte.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 control;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author Jesus Ariel
 */
public class listaReporte extends javax.swing.JFrame {
    public boolean usuario = false; //tipo de usuario

    public listaReporte(boolean usuario) {
        this.usuario = usuario;
        initComponents();
        llena();
    }

    /**
     * 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() {

        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        pPrincipal = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        reportes = new javax.swing.JTable();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LISTA DE REPORTES");

        jButton1.setText("Crear Nuevo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Imprimir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        pPrincipal.setText("Pantalla Principal");
        pPrincipal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pPrincipalActionPerformed(evt);
            }
        });

        reportes.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

        }, new String[] { "Id Reporte", "Solicitante", "Proyecto", "Fecha de Prestamo", "Fecha de devolucion",
                "Fecha real", "prestador" }) {
            boolean[] canEdit = new boolean[] { false, false, false, false, false, true, true };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        jScrollPane1.setViewportView(reportes);

        jButton2.setText("Visualizar/Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(pPrincipal)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addGap(10, 10, 10)
                                                .addComponent(jButton1).addGap(72, 72, 72).addComponent(jButton2)
                                                .addGap(72, 72, 72).addComponent(jButton3))
                                        .addGroup(layout
                                                .createSequentialGroup().addComponent(jScrollPane1,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, 734, Short.MAX_VALUE)
                                                .addGap(14, 14, 14))))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(20, 20, 20).addComponent(pPrincipal)
                        .addGap(17, 17, 17)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(jButton3).addComponent(jButton2))
                        .addGap(9, 9, 9)));

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

    private void pPrincipalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pPrincipalActionPerformed
        entrar IE = new entrar();
        IE.setVisible(true);
        dispose();
    }//GEN-LAST:event_pPrincipalActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        nuevoReporte IE = new nuevoReporte(usuario);
        IE.setVisible(true);
        dispose();// TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int fila = reportes.getSelectedRow();
        Integer id = (Integer) reportes.getValueAt(fila, 0);
        System.out.println("Seleccionado : " + id);
        ModificaPrestamo mp = new ModificaPrestamo(id, usuario);
        mp.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        JFileChooser jf = new JFileChooser();
        int res = jf.showSaveDialog(this);
        if (res == JFileChooser.APPROVE_OPTION) {
            String path = jf.getSelectedFile() + ".pdf";
            System.out.println("Archivo " + path);
            try {
                if (this.generapdf(path)) {
                    JOptionPane.showMessageDialog(this, "Se ha almacenado el archivo ");
                } else {
                    JOptionPane.showMessageDialog(this, "No se ha almacenado el archivo ");
                }
            } catch (DocumentException ex) {
                Logger.getLogger(nuevoReporte.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(nuevoReporte.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @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(listaReporte.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(listaReporte.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(listaReporte.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(listaReporte.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton pPrincipal;
    private javax.swing.JTable reportes;
    // End of variables declaration//GEN-END:variables

    private void llena() {
        conectar conecta = new conectar();
        Connection con = conecta.conexion();
        String modo = null;
        String sql = "";
        if (usuario)
            sql = "select * from prestamo where prestador = 'usuario'";
        else
            sql = "select * from prestamo";
        ResultSet rs = conecta.consultar(sql, con);
        try {
            while (rs.next()) {
                Object[] fila = new Object[7];
                fila[0] = rs.getInt("idprestamo");
                fila[1] = rs.getString("solicitante");
                fila[2] = rs.getString("proyecto");
                fila[3] = rs.getDate("fprestamo");
                fila[4] = rs.getDate("fdevolucion");
                fila[5] = rs.getDate("freal");
                fila[6] = rs.getString("prestador");
                DefaultTableModel modelo = (DefaultTableModel) reportes.getModel();
                modelo.addRow(fila);
            }
        } catch (SQLException ex) {
            Logger.getLogger(listaReporte.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Object[][] getTableData(JTable table) {
        DefaultTableModel dtm = (DefaultTableModel) table.getModel();
        int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
        Object[][] tableData = new Object[nRow][nCol];
        for (int i = 0; i < nRow; i++)
            for (int j = 0; j < nCol; j++)
                tableData[i][j] = dtm.getValueAt(i, j);
        return tableData;
    }

    private boolean generapdf(String path) throws DocumentException, FileNotFoundException {
        boolean estado = false;
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        Paragraph paragraph1 = new Paragraph("Prestamos");
        document.add(paragraph1);
        Paragraph paragraph2 = new Paragraph("");
        paragraph2.setSpacingBefore(38f);
        document.add(paragraph2);
        PdfPTable table = new PdfPTable(7);
        table.addCell("Id reporte");
        table.addCell("Solicitante");
        table.addCell("Proyecto");
        table.addCell("Fecha prestamo");
        table.addCell("Fecha devolucion");
        table.addCell("Fecha real");
        table.addCell("prestador");
        Object[][] tabla = this.getTableData(reportes);
        for (Object[] o : tabla)
            for (Object e : o) {
                if (e != null)
                    table.addCell((String) e.toString());
                else
                    table.addCell("");
            }

        document.add(table);
        document.close();
        return true;
    }
}