e.pkg3.pkg6a.acertijo.acertijo.java Source code

Java tutorial

Introduction

Here is the source code for e.pkg3.pkg6a.acertijo.acertijo.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 e.pkg3.pkg6a.acertijo;

import java.util.Calendar;
import java.util.Random;
import javax.swing.JOptionPane;
import org.apache.commons.lang3.time.DurationFormatUtils;

/**
 *
 * @author Manuel Caamaque
 */
public class acertijo extends javax.swing.JFrame {
    int numero_Aleatorio;
    int contador = 0;
    Calendar inicio;
    Random rnd;

    /**
     * Creates new form acertijo
     */
    public acertijo() {
        initComponents();
        rnd = new Random();
        numero_Aleatorio = rnd.nextInt(100) + 1;
        System.out.println("" + numero_Aleatorio);
        inicio = Calendar.getInstance();

    }

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

        texto = new javax.swing.JTextField();
        boton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        area = new javax.swing.JTextArea();
        boton_Otro = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        boton.setText("Comprobar Nmero");
        boton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botonActionPerformed(evt);
            }
        });

        area.setEditable(false);
        area.setColumns(20);
        area.setLineWrap(true);
        area.setRows(5);
        area.setWrapStyleWord(true);
        jScrollPane1.setViewportView(area);

        boton_Otro.setText("Generar Otro Numero");
        boton_Otro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton_OtroActionPerformed(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().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(texto, javax.swing.GroupLayout.PREFERRED_SIZE, 60,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(boton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(boton_Otro).addGap(0, 23, Short.MAX_VALUE)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(texto, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(boton).addComponent(boton_Otro))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

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

    private void botonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonActionPerformed
        int numero_Usuario = 0;
        try {
            numero_Usuario = Integer.valueOf(texto.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "Introduce un Numero");
            e.printStackTrace();
            contador++;
        }

        int resta = numero_Aleatorio - numero_Usuario;

        if (resta < 0) {
            area.setText("El numero es menor que " + numero_Usuario);
        }
        if (resta > 0) {
            area.setText("El numero es mayor que " + numero_Usuario);
        }
        contador++;
        if (resta == 0) {
            Calendar fin = Calendar.getInstance();
            String formato = "HH:mm:ss";
            long inicioMilis = (inicio.get(Calendar.HOUR) * 3600000L) + (inicio.get(Calendar.MINUTE) * 60000L)
                    + (inicio.get(Calendar.SECOND) * 1000L);
            long finalMilis = (fin.get(Calendar.HOUR) * 3600000L) + (fin.get(Calendar.MINUTE) * 60000L)
                    + (fin.get(Calendar.SECOND) * 1000L);
            String duracion = DurationFormatUtils.formatPeriod(inicioMilis, finalMilis, formato);

            area.setText("El numero es Correcto!\n");
            area.append("Acertado en " + contador + " intentos\n");
            area.append("Acertado en " + duracion);
            contador = 0;
            boton.setEnabled(false);
            texto.setEnabled(false);
        }

    }//GEN-LAST:event_botonActionPerformed

    private void boton_OtroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_OtroActionPerformed
        numero_Aleatorio = rnd.nextInt(100) + 1;
        System.out.println("" + numero_Aleatorio);
        inicio = Calendar.getInstance();
        boton.setEnabled(true);
        texto.setEnabled(true);
    }//GEN-LAST:event_boton_OtroActionPerformed

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea area;
    private javax.swing.JButton boton;
    private javax.swing.JButton boton_Otro;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField texto;
    // End of variables declaration//GEN-END:variables
}