miércoles, 7 de mayo de 2014

Unidad 4 Ejercicio 4

Hacer un programa que visualice dos campos de texto (JtextField). En el primer campo se puede teclear un valor numérico en euros, que será convertido a pesetas en el segundo campo. Si el valor se teclea en el segundo campo, se convertirá a euros en el primero.
Emplear la clase DecimalFormat para establecer la salida a dos decimales:

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

import java.text.DecimalFormat;
import javax.swing.JOptionPane;

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

    /**
     * Creates new form Conversion
     */
    public Conversion() {
        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);
        setTitle("Conversor Euros <-> Pesetas");

        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()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtEuros, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2)
                    .addComponent(txtPesetas, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtEuros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPesetas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(198, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                      

    private void txtPesetasActionPerformed(java.awt.event.ActionEvent evt) {                                          
       convAEuros();
    }                                        

    private void txtEurosActionPerformed(java.awt.event.ActionEvent evt) {                                        
    
    }                                      

    private void txtEurosKeyReleased(java.awt.event.KeyEvent evt) {                                    
      convAPesetas();
    }                                  

    private void txtPesetasKeyReleased(java.awt.event.KeyEvent evt) {                                      
       convAEuros();
    }                                    

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

    private void convAPesetas() {
     double pesetas,euros;
     DecimalFormat formato = new DecimalFormat("######.##");
     if (!txtEuros.getText().equals(""))
        try {
            euros = Double.parseDouble(txtEuros.getText());
            pesetas=euros*166.386;
            txtPesetas.setText(formato.format(pesetas));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "Los datos introducidos no se pueden convertir a moneda", "Error en la conversión", JOptionPane.ERROR_MESSAGE);
            txtEuros.setText("");
            txtEuros.requestFocus();
        }
    
    
    
    }

    private void convAEuros() {
      double pesetas,euros;
      DecimalFormat formato = new DecimalFormat("######.##");
        try {
            pesetas = Double.parseDouble(txtPesetas.getText());
            euros=pesetas/166.386;
            txtEuros.setText(String.valueOf(formato.format(euros)));
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "Los datos introducidos no se pueden convertir a moneda", "Error en la conversión", JOptionPane.ERROR_MESSAGE);
            txtPesetas.setText("");
            txtPesetas.requestFocus();
        }
    
    }
}

No hay comentarios: