Viruz Blog
¿Quieres reaccionar a este mensaje? Regístrate en el foro con unos pocos clics o inicia sesión para continuar.

Cronómetro 1.0

Ir abajo

Cronómetro 1.0 Empty Cronómetro 1.0

Mensaje  Admin (Viruz) Lun Ene 07, 2013 12:08 am

Buen día a todos amigos de Viruz Blog acabo de terminar un programa en java y quise compartirlo inmediatamente con ustedes, se trata de nada mas ni nada menos que de un cronómetro.

Para ello me apoye de un Thread (hilo) para llevar acabo las funcionas básicas de este, la actualización del cronometro al momento de pausar, continuar o detenerse por completo.

Imagen
[Tienes que estar registrado y conectado para ver esa imagen]
¿Como funciona el programa?

  1. Primero mediante un JFrameForm en el cual yo agregue 4 botones que harán las funciones de iniciar el cronómetro, pausarlo, reanudarlo y detenerlo por completo (este último también lo inicia desde 0) y tendrán sus respectivos eventos.
  2. A esta clase se realizará un Refactor a la variable de la etiqueta (JLabel) el cual ocuparemos en la clase de CronometroThread.
  3. En la clase CronometroThread se implementa la interfaz Runnable y se crea un objeto Thread para la cuestión del hilo que ocupará, dentro del método run() que se implementa tendremos 2 ciclos while() el cual tendrán de parámetros unas banderas(Boolean).
  4. La primera sirve para el botón iniciar en el cual al entrar al ciclo comienza un contador de segundos y manda a llamar al método actualizarThread(), en dicho método tuve que poner un if() para que al detener el cronómetro restablezca el contador a 0 junto con la etiqueta.
  5. El segundo ciclo while dentro del método run() es el encargado al botón pause esto es por si se activa la bandera el hilo entre en estado de espera wait().
Código

Clase Main

/**
*
* @author Viruz
*/
public class Main {
public static void main(String args[]) {
Cronometro c = new Cronometro();
c.setVisible(true);
c.setLocationRelativeTo(null);
}
}

Clase Cronometro

/**
*
* @author Viruz
*/
public class Cronometro extends javax.swing.JFrame {
CronometroThread cronometro;
Object source;

/**
* Creates new form Cronometro
*/
public Cronometro() {
initComponents();
cronometro = new CronometroThread(this);
}

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

jPanel1 = new javax.swing.JPanel();
start = new javax.swing.JButton();
pause = new javax.swing.JButton();
bcontinue = new javax.swing.JButton();
stop = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
display = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Viruz Blog: Cronometro");
setBackground(new java.awt.Color(255, 255, 255));

jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 0, 0), null));
jPanel1.setPreferredSize(new java.awt.Dimension(300, 45));

start.setText("Iniciar");
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
}
});
jPanel1.add(start);

pause.setText("Pause");
pause.setEnabled(false);
pause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseActionPerformed(evt);
}
});
jPanel1.add(pause);

bcontinue.setText("Continuar");
bcontinue.setEnabled(false);
bcontinue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bcontinueActionPerformed(evt);
}
});
jPanel1.add(bcontinue);

stop.setText("Detener");
stop.setEnabled(false);
stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopActionPerformed(evt);
}
});
jPanel1.add(stop);

getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jPanel2.setPreferredSize(new java.awt.Dimension(400, 130));
jPanel2.setLayout(new java.awt.BorderLayout());

display.setFont(new java.awt.Font("Times New Roman", 0, 50)); // NOI18N
display.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
display.setText("0 : 0 : 0");
jPanel2.add(display, java.awt.BorderLayout.CENTER);

getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

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

private void startActionPerformed(java.awt.event.ActionEvent evt) {
source = evt.getSource();
if (source == start) {
cronometro.createThread();
cronometro.setLive(true);
cronometro.setGo(true);
start.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
}

private void pauseActionPerformed(java.awt.event.ActionEvent evt) {
pause.setEnabled(false);
bcontinue.setEnabled(true);
cronometro.suspenderThread();
}

private void bcontinueActionPerformed(java.awt.event.ActionEvent evt) {
pause.setEnabled(true);
cronometro.continuarThread();
bcontinue.setEnabled(false);
}

private void stopActionPerformed(java.awt.event.ActionEvent evt) {
start.setEnabled(true);
stop.setEnabled(false);
pause.setEnabled(false);
cronometro.setLive(false);
cronometro.setGo(false);
cronometro.setSegundos(0);
}

// Variables declaration - do not modify
private javax.swing.JButton bcontinue;
private javax.swing.JLabel display;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JButton pause;
private javax.swing.JButton start;
private javax.swing.JButton stop;
// End of variables declaration

/**
* @return the display
*/
public javax.swing.JLabel getDisplay() {
return display;
}

/**
* @param display the display to set
*/
public void setDisplay(javax.swing.JLabel display) {
this.display = display;
}
}


Clase CronometroThread

/**
*
* @author Viruz
*/
public class CronometroThread implements Runnable {
private Thread hiloCronometro;
private boolean go,live;
private int segundos;
private Cronometro reloj;

public CronometroThread(Cronometro v) {
reloj = v;
}

public void run() {
try {
while (isLive()) {
synchronized(this) {
while (!isGo())
wait();
}
Thread.sleep(1000);
segundos++;
actualizarThread();
}
} catch (InterruptedException e) {}
}

public void createThread() {
hiloCronometro = new Thread(this);
hiloCronometro.start();
}

private void actualizarThread() {
if (isLive() == true) {
int hr= segundos/3600;
int min =(segundos-hr*3600)/60;
int seg = segundos-hr*3600-min*60;
reloj.getDisplay().setText(""+hr+" : "+min+" : "+seg);
} else {
segundos = 0;
reloj.getDisplay().setText("0 : 0 : 0");
}
}

public void suspenderThread() {
setGo(false);
}

public synchronized void continuarThread() {
setGo(true);
notify();
}

//********** MÉTODOS SET Y GET DE LAS VARIABLES DE TIPO BOOLEAN e INT ************
/**
* @return the live
*/
public boolean isLive() {
return live;
}

/**
* @param live the live to set
*/
public void setLive(boolean live) {
this.live = live;
}

/**
* @return the go
*/
public boolean isGo() {
return go;
}

/**
* @param go the go to set
*/
public void setGo(boolean go) {
this.go = go;
}

/**
* @return the segundos
*/
public int getSegundos() {
return segundos;
}

/**
* @param segundos the segundos to set
*/
public void setSegundos(int segundos) {
this.segundos = segundos;
System.out.println("Valor de SEgundos:" + this.segundos);
}
}


Vídeo



Descarga el código
Cronómetro
Autor: Viruz study
Enlace: Cronometro en Java
Admin (Viruz)
Admin (Viruz)
Admin

Mensajes : 148
Fecha de inscripción : 23/09/2012
Edad : 35
Localización : Desktop

https://viruz.foroactivo.mx

Volver arriba Ir abajo

Volver arriba


 
Permisos de este foro:
No puedes responder a temas en este foro.