viernes, 2 de mayo de 2014

Pasando de Euros a Pesetas al cambiar pulsaciones sin DocumentListener

En lugar de usar DocumentListener como en la entrada anterior para gestionar los cambios de letras en un cuadro de texto, en esta ocasión se emplea KeyReleased para detectar los cambios acaecidos en el contenido de los cuadros de texto:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package explicaciones;

import javax.swing.JOptionPane;

/**
*
* @author juan
*/
public class ventanaboton2 extends javax.swing.JFrame {


    /**
     * Creates new form ventanaboton2
     */
    public ventanaboton2() {
        initComponents();
    }

    /**
     * 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">
    private void initComponents() {

        txtEuros = new javax.swing.JTextField();
        txtPesetas = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtEuros.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtEurosActionPerformed(evt);
            }
        });
        txtEuros.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtEurosKeyReleased(evt);
            }
        });

        txtPesetas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPesetasActionPerformed(evt);
            }
        });
        txtPesetas.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesetasKeyReleased(evt);
            }
        });

        jLabel1.setText("Euros:");

        jLabel2.setText("Pesetas:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addComponent(txtEuros, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(45, 45, 45)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(txtPesetas, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(134, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addComponent(txtEuros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(58, 58, 58)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(txtPesetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(110, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>
   private void actualizarEuros()
    {
        Double pesetas,euros;
         if (!txtPesetas.getText().equals(""))
        try {
            pesetas = Double.parseDouble(txtPesetas.getText());
            euros=pesetas /166.386;
          
            txtEuros.setText(String.valueOf(euros));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Solo se admiten números","Error en la introducción de datos",JOptionPane.ERROR_MESSAGE);
            txtPesetas.setText("");
            txtPesetas.requestFocus();
        }
         else txtEuros.setText("");
          
       
   
   
   
    }
   
    private void actualizarPesetas(){
    Double pesetas,euros;
      
        if (!txtEuros.getText().equals(""))
        try {
            euros = Double.parseDouble(txtEuros.getText());
            pesetas=euros*166.386;
            txtPesetas.setText(String.valueOf(pesetas));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "solo se admiten números");
            txtEuros.setText("");
            txtEuros.requestFocus();
        }
       
           
       
        else txtPesetas.setText("");
       
    }
    private void txtEurosActionPerformed(java.awt.event.ActionEvent evt) {
       actualizarPesetas();     // TODO add your handling code here:
    }

    private void txtEurosKeyReleased(java.awt.event.KeyEvent evt) {
    actualizarPesetas();        // TODO add your handling code here:
    }

    private void txtPesetasActionPerformed(java.awt.event.ActionEvent evt) {
    actualizarEuros();        // TODO add your handling code here:
    }

    private void txtPesetasKeyReleased(java.awt.event.KeyEvent evt) {
    actualizarEuros();        // TODO add your handling code here:
    }

    /**
     * @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(ventanaboton2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ventanaboton2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ventanaboton2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ventanaboton2.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 ventanaboton2().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField txtEuros;
    private javax.swing.JTextField txtPesetas;
    // End of variables declaration
}