vista.Director.ListaProfesores.java Source code

Java tutorial

Introduction

Here is the source code for vista.Director.ListaProfesores.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 vista.Director;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import control.ControladorInstructor;
import java.awt.BorderLayout;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Calendar;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;
import vista.Formulario.Formulario;

/**
 *
 * @author master
 */
public class ListaProfesores extends javax.swing.JFrame {

    /**
     * Creates new form ListaProfesores
     */
    private ControladorInstructor ctrlI;

    public ListaProfesores() {
        initComponents();
        ((JPanel) getContentPane()).setOpaque(false);
        ImageIcon imagen = new ImageIcon(this.getClass().getResource("/imagenes/fondos/fondoAdmInstructores.png"));
        JLabel fondo = new JLabel();
        fondo.setIcon(imagen);
        getLayeredPane().add(fondo, JLayeredPane.FRAME_CONTENT_LAYER);
        fondo.setBounds(0, 0, imagen.getIconWidth(), imagen.getIconHeight());
        this.add(fondo, BorderLayout.CENTER);
        this.setSize(fondo.getWidth(), fondo.getHeight());
        this.setResizable(false);
        this.setTitle("Profesores Registrados");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        ctrlI = new ControladorInstructor();
    }

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

        jScrollPane1 = new javax.swing.JScrollPane();
        tabProfesor = new javax.swing.JTable();
        btnEliminar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }

            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        tabProfesor.setBackground(new java.awt.Color(51, 51, 255));
        tabProfesor.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        tabProfesor.setForeground(new java.awt.Color(153, 255, 255));
        tabProfesor.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

        }, new String[] { "Title 1", "Title 2", "Title 3", "Title 4" }));
        tabProfesor.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabProfesorMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabProfesor);

        btnEliminar.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btnEliminar.setForeground(new java.awt.Color(153, 255, 255));
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/eliminar.png"))); // NOI18N
        btnEliminar.setText("BORRAR");
        btnEliminar.setBorder(null);
        btnEliminar.setBorderPainted(false);
        btnEliminar.setContentAreaFilled(false);
        btnEliminar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnEliminar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnEliminarMouseEntered(evt);
            }
        });
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnEditar.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btnEditar.setForeground(new java.awt.Color(153, 255, 255));
        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/editar.png"))); // NOI18N
        btnEditar.setText("EDITAR");
        btnEditar.setBorder(null);
        btnEditar.setBorderPainted(false);
        btnEditar.setContentAreaFilled(false);
        btnEditar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnEditar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnEditarMouseEntered(evt);
            }
        });
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnSalir.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btnSalir.setForeground(new java.awt.Color(153, 255, 255));
        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/cancelar_7.png"))); // NOI18N
        btnSalir.setText("SALIR");
        btnSalir.setBorder(null);
        btnSalir.setBorderPainted(false);
        btnSalir.setContentAreaFilled(false);
        btnSalir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnSalir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnSalirMouseEntered(evt);
            }
        });
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnImprimir.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btnImprimir.setForeground(new java.awt.Color(153, 255, 255));
        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/botones/imprimir.png"))); // NOI18N
        btnImprimir.setText("IMPRIMIR");
        btnImprimir.setBorder(null);
        btnImprimir.setBorderPainted(false);
        btnImprimir.setContentAreaFilled(false);
        btnImprimir.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnImprimir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnImprimirMouseEntered(evt);
            }
        });
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(102, 255, 204));
        jLabel1.setText("MAESTROS REGISTRADOS");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 531,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btnEditar).addComponent(btnEliminar)
                                .addComponent(btnImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 99,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 76,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                .addGroup(layout.createSequentialGroup().addGap(204, 204, 204).addComponent(jLabel1)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEditar).addGap(26, 26, 26).addComponent(btnEliminar).addGap(38, 38, 38)
                        .addComponent(btnImprimir).addGap(30, 30, 30).addComponent(btnSalir).addGap(104, 104, 104))
                .addGroup(
                        layout.createSequentialGroup().addContainerGap().addComponent(jLabel1).addGap(12, 12, 12)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 261,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(42, Short.MAX_VALUE)));

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

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        actualizarTabla();

        this.btnEditar.setEnabled(false);
        this.btnEliminar.setEnabled(false);
        this.tabProfesor.setShowHorizontalLines(false);
        this.tabProfesor.setShowVerticalLines(false);
    }//GEN-LAST:event_formWindowOpened

    private void tabProfesorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabProfesorMouseClicked
        btnEditar.setEnabled(true);
        btnEliminar.setEnabled(true);
        btnImprimir.setEnabled(true);
    }//GEN-LAST:event_tabProfesorMouseClicked

    private void btnEditarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarMouseEntered
        this.btnEditar.setToolTipText("Editar datos personales");
    }//GEN-LAST:event_btnEditarMouseEntered

    private void btnEliminarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEliminarMouseEntered
        this.btnEliminar.setToolTipText("Eliminar Instructor");
    }//GEN-LAST:event_btnEliminarMouseEntered

    private void btnImprimirMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnImprimirMouseEntered
        this.btnImprimir.setToolTipText("Imprimir lista de Instructores");
    }//GEN-LAST:event_btnImprimirMouseEntered

    private void btnSalirMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSalirMouseEntered
        this.btnSalir.setToolTipText("Volver a Menu");
    }//GEN-LAST:event_btnSalirMouseEntered

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        String ci = String.valueOf(tabProfesor.getValueAt(tabProfesor.getSelectedRow(), 3));
        int auxCI = Integer.parseInt(ci);
        ctrlI.eliminarInstructor(auxCI);
        actualizarTabla();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        Formulario f = new Formulario("Editar", "Instructor");
        int fila = this.tabProfesor.getSelectedRow();
        String datos[] = new String[5];
        datos[0] = this.tabProfesor.getValueAt(fila, 1).toString();
        datos[1] = this.tabProfesor.getValueAt(fila, 2).toString();
        datos[2] = this.tabProfesor.getValueAt(fila, 3).toString();
        datos[3] = this.tabProfesor.getValueAt(fila, 4).toString();
        datos[4] = this.tabProfesor.getValueAt(fila, 5).toString();
        f.enviarDatos(datos);
        f.setVisible(true);
    }//GEN-LAST:event_btnEditarActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        actualizarTabla();
    }//GEN-LAST:event_formWindowActivated

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        try {
            prepararImpresion();
        } catch (DocumentException ex) {
            System.out.println(ex);
        }
    }//GEN-LAST:event_btnImprimirActionPerformed

    public void prepararImpresion() throws DocumentException {
        String ARCHIVO = "/home/master/Documentos/prueba.pdf";
        int numFilas = tabProfesor.getRowCount();
        Document document = new Document();
        Font fuenteTitulo = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        try {
            PdfWriter.getInstance(document, new FileOutputStream(ARCHIVO));
            document.open();
            Paragraph parrafo = new Paragraph();
            Chunk titulo = new Chunk("Lista de Instructores Registrados", fuenteTitulo);
            parrafo.add(titulo);
            parrafo.setAlignment(Element.ALIGN_CENTER);

            agregarSaltoLinea(parrafo, 3);

            document.add(parrafo);

            Paragraph fecha = new Paragraph();
            String fechaHoy = obtenerFechaActual();
            Chunk datoFecha = new Chunk(fechaHoy);
            fecha.add(datoFecha);
            fecha.setAlignment(Element.ALIGN_RIGHT);

            agregarSaltoLinea(fecha, 3);
            document.add(fecha);

            PdfPTable tabla = new PdfPTable(3);
            tabla.setWidthPercentage(70);

            PdfPCell cell1 = new PdfPCell(new Phrase("Nombre"));
            cell1.setBackgroundColor(BaseColor.YELLOW);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cell2 = new PdfPCell(new Phrase("Apellido"));
            cell2.setBackgroundColor(BaseColor.YELLOW);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cell3 = new PdfPCell(new Phrase("CI"));
            cell3.setBackgroundColor(BaseColor.YELLOW);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);

            tabla.addCell(cell1);
            tabla.addCell(cell2);
            tabla.addCell(cell3);

            for (int i = 0; i < numFilas; i++) {
                Object obj1 = obtenerDato(tabProfesor, i, 1);
                Object obj2 = obtenerDato(tabProfesor, i, 2);
                Object obj3 = obtenerDato(tabProfesor, i, 3);

                String valor1 = obj1.toString();
                String valor2 = obj2.toString();
                String valor3 = obj3.toString();

                tabla.addCell(valor1);
                tabla.addCell(valor2);
                tabla.addCell(valor3);
            }
            document.add(tabla);
            document.close();

        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        }
    }

    public String obtenerFechaActual() {
        Calendar fecha = Calendar.getInstance();
        String fecha_actual = "Fecha: " + fecha.get(Calendar.DATE) + "/" + (fecha.get(Calendar.MONTH) + 1) + "/"
                + fecha.get(Calendar.YEAR);
        return fecha_actual;
    }

    public Object obtenerDato(JTable tabla, int fila, int columna) {
        return tabProfesor.getModel().getValueAt(fila, columna);
    }

    public void agregarSaltoLinea(Paragraph parrafo, int numero) {
        for (int c = 0; c < numero; c++) {
            parrafo.add(new Paragraph(" "));
        }
    }

    public void actualizarTabla() {
        String columnas[] = { "#", "Nombre", "Apellido", "CI", "Semestre", "Celular" };
        Object[][] info = ctrlI.darInformacionInstructores();
        DefaultTableModel nuevaTabla = new DefaultTableModel(info, columnas) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }

        };
        tabProfesor.setModel(nuevaTabla);
    }

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListaProfesores().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabProfesor;
    // End of variables declaration//GEN-END:variables
}