automata.gui.IngresoAutomata.java Source code

Java tutorial

Introduction

Here is the source code for automata.gui.IngresoAutomata.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 automata.gui;

import automata.clas.Estado;
import automata.clas.Transicion;
import automata.util.HibernateUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Alejandro
 */
public class IngresoAutomata extends javax.swing.JFrame {

    /**
     * Creates new form IngresoAutomata
     */
    public IngresoAutomata() {
        initComponents();
        cbTransiciones.setVisible(false);
        jLabel4.setVisible(false);
    }

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

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtEstado = new javax.swing.JTextField();
        txtTransicion = new javax.swing.JTextField();
        btnEstado = new javax.swing.JButton();
        btnTransicion = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbTransiciones = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        rbInicial = new javax.swing.JRadioButton();
        rbNormal = new javax.swing.JRadioButton();
        rbFinal = new javax.swing.JRadioButton();
        cbTransiciones = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Estado:");

        jLabel2.setText("Transicion:");

        txtTransicion.setEnabled(false);

        btnEstado.setText("Crear estado");
        btnEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEstadoActionPerformed(evt);
            }
        });

        btnTransicion.setText("Asignar Transicion");
        btnTransicion.setEnabled(false);
        btnTransicion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTransicionActionPerformed(evt);
            }
        });

        btnGuardar.setText("Guardar estado");
        btnGuardar.setEnabled(false);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

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

        }, new String[] { "Estado", "Transicion" }) {
            boolean[] canEdit = new boolean[] { false, false };

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

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setText("Ingreso de Estado y Transiciones");

        rbInicial.setSelected(true);
        rbInicial.setText("Estado Inicial");
        rbInicial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbInicialActionPerformed(evt);
            }
        });

        rbNormal.setText("Estado Normal");
        rbNormal.setEnabled(false);
        rbNormal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbNormalActionPerformed(evt);
            }
        });

        rbFinal.setText("Estado Final");
        rbFinal.setEnabled(false);
        rbFinal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbFinalActionPerformed(evt);
            }
        });

        jLabel4.setText("Transiciones Anteriores:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                        layout.createSequentialGroup()
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3).addGap(76, 76, 76))
                .addGroup(layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addGap(10, 10, 10).addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout
                                        .createSequentialGroup().addGap(19, 19, 19)
                                        .addGroup(layout
                                                .createParallelGroup(
                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(
                                                        javax.swing.GroupLayout.Alignment.TRAILING, layout
                                                                .createSequentialGroup()
                                                                .addGroup(layout.createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addComponent(jLabel1).addComponent(
                                                                                jLabel2))
                                                                .addGap(99, 99, 99))
                                                .addGroup(
                                                        layout.createSequentialGroup().addComponent(jLabel4)
                                                                .addPreferredGap(
                                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                        Short.MAX_VALUE)))
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,
                                                        false)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addGroup(layout.createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING, false)
                                                                .addComponent(txtEstado).addComponent(txtTransicion,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 136,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                                        .addGap(27, 27, 27)
                                                        .addGroup(layout
                                                                .createParallelGroup(
                                                                        javax.swing.GroupLayout.Alignment.TRAILING)
                                                                .addComponent(btnEstado)
                                                                .addComponent(btnTransicion)))
                                                .addGroup(layout.createSequentialGroup().addGap(33, 33, 33)
                                                        .addComponent(rbFinal)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                Short.MAX_VALUE)
                                                        .addComponent(rbNormal))
                                                .addComponent(cbTransiciones,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(layout.createSequentialGroup().addComponent(btnGuardar)
                                                .addGap(292, 292, 292).addComponent(btnSalir))
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(rbInicial)))
                        .addContainerGap(128, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(17, 17, 17).addComponent(jLabel3).addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnEstado))
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(txtTransicion, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btnTransicion))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(cbTransiciones, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(rbInicial).addComponent(rbNormal).addComponent(rbFinal))
                        .addGap(43, 43, 43)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnGuardar).addComponent(btnSalir))
                        .addGap(36, 36, 36)));

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

    private void btnEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEstadoActionPerformed
        try {
            if (txtEstado.getText().length() <= 0) {
                throw new IllegalArgumentException("No se permite campos vacios");
            } else {
                miEstado = new Estado(txtEstado.getText());
                txtTransicion.setEnabled(true);
                btnTransicion.setEnabled(true);
                txtTransicion.requestFocus();
            }
        } catch (IllegalArgumentException e) {
            txtEstado.requestFocus();
            JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
        }
    }//GEN-LAST:event_btnEstadoActionPerformed

    private void btnTransicionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTransicionActionPerformed
        try {
            if (txtTransicion.getText().length() <= 0) {
                throw new IllegalArgumentException("No se permite campos vacios");
            } else {
                Transicion transicion = new Transicion(txtTransicion.getText());
                transicions.add(transicion);
                Insert_Table_Content();
                btnGuardar.setEnabled(true);
            }
        } catch (IllegalArgumentException e) {
            txtTransicion.requestFocus();
            JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
        }
    }//GEN-LAST:event_btnTransicionActionPerformed

    private void Insert_Table_Content() {
        Object[] row = { txtEstado.getText(), txtTransicion.getText() };
        DefaultTableModel model = (DefaultTableModel) tbTransiciones.getModel();
        model.addRow(row);
    }

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        try {
            session.close();
        } catch (HibernateException he) {
            JOptionPane.showMessageDialog(null, "Error: " + he.getMessage());
        } finally {
            System.exit(0);
        }
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            miEstado.setTransicions(transicions);
            if (rbInicial.isSelected() == true) {
                jLabel4.setVisible(true);
                rbInicial.setSelected(false);
                rbInicial.setEnabled(false);
                rbNormal.setEnabled(true);
                rbNormal.setSelected(true);
                rbFinal.setEnabled(true);
                miEstado.setInicial(true);
            } else if (rbNormal.isSelected() == true) {
                miEstado.setNormal(true);
            } else {
                miEstado.setFinal_(true);
            }
            session.persist(miEstado);
            transaction.commit();
            transicions.clear();
            //Vacial texto de los jtext;
            txtEstado.setText(null);
            txtTransicion.setText(null);
            txtTransicion.setEnabled(false);
            //Eliminar contenido de la tabla;
            DefaultTableModel model = (DefaultTableModel) tbTransiciones.getModel();
            model.getDataVector().removeAllElements();
            model.fireTableDataChanged();
            //Desabilitar el boton de guardar
            btnGuardar.setEnabled(false);

            if (cbTransiciones.isVisible() == true) {
                Update_Estado();
            }
            cbTransiciones.setVisible(true);
            if (rbFinal.isSelected() == true) {
                BuscaAutomata resolver = new BuscaAutomata();
                resolver.getSession(session);
                resolver.setVisible(true);
                this.setVisible(false);
            }

            Carga_Box();
        } catch (HibernateException he) {
            JOptionPane.showMessageDialog(null, "Hibernate Error: " + he.getMessage());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error al guardar: " + e.getMessage());
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void Update_Estado() {
        try {
            Transaction transaction = session.beginTransaction();
            Query query = session.createQuery(
                    "from Transicion t where t.idTransicion = " + cbTransiciones.getSelectedItem().toString());
            Transicion transicion = (Transicion) query.list().get(0);
            session.update(transicion);
            transicion.setIdEstadoSiguiente(miEstado.getIdEstado());
            transaction.commit();
        } catch (HibernateException he) {
            JOptionPane.showMessageDialog(null, "Erro update: " + he.getMessage());
        }
    }

    private void Carga_Box() {
        Query q = session.createQuery("from Transicion");
        List resultList = q.list();
        for (Object o : resultList) {
            Transicion transicion = (Transicion) o;
            cbTransiciones.addItem(transicion.getIdTransicion());
        }
    }

    private void rbInicialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbInicialActionPerformed
        rbNormal.setSelected(false);
        rbFinal.setSelected(false);
    }//GEN-LAST:event_rbInicialActionPerformed

    private void rbNormalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbNormalActionPerformed
        rbFinal.setSelected(false);
    }//GEN-LAST:event_rbNormalActionPerformed

    private void rbFinalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbFinalActionPerformed
        rbNormal.setSelected(false);
    }//GEN-LAST:event_rbFinalActionPerformed

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEstado;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton btnTransicion;
    private javax.swing.JComboBox cbTransiciones;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbFinal;
    private javax.swing.JRadioButton rbInicial;
    private javax.swing.JRadioButton rbNormal;
    private javax.swing.JTable tbTransiciones;
    private javax.swing.JTextField txtEstado;
    private javax.swing.JTextField txtTransicion;
    // End of variables declaration//GEN-END:variables
    private Estado miEstado;
    private Transaction miTransicion;
    private Set transicions = new HashSet(0);
    static Session session;
}