JAVA - Swing-free timer with MVC

Asked

Viewed 198 times

-1

I’m studying java and I saw myself in a situation that I don’t know how to solve... I have a timer where I intend to do it following the rules of MVC, but I can’t update Jlabel when I separate the code Timer from View.

I believe I have to use Threads. It has an easier way that is with swing.Timer however, I would like to separate the logic of the interface so I can use the same model in java android when I make the mobile version.

When I click the 'start' button the application hangs.

Simple GUI with two buttons

package source;
import source.Pomodoro;

public class GUI extends javax.swing.JFrame {
    private Pomodoro pomodoro;
public GUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lbContadorTempo = new javax.swing.JLabel();
        btIniciar = new javax.swing.JButton();
        btZerar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        lbContadorTempo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lbContadorTempo.setText("00:00:00");
        getContentPane().add(lbContadorTempo);

        btIniciar.setText("Iniciar");
        btIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIniciarActionPerformed(evt);
            }
        });
        getContentPane().add(btIniciar);

        btZerar.setText("Zerar");
        btZerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btZerarActionPerformed(evt);
            }
        });
        getContentPane().add(btZerar);

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

    private void btIniciarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        pomodoro = new Pomodoro();

        pomodoro.iniciar();        
        lbContadorTempo.setText(pomodoro.getTempo()); // altera o JLabel

    }                                         

    private void btZerarActionPerformed(java.awt.event.ActionEvent evt) {                                        


    }                                       

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton btIniciar;
    private javax.swing.JButton btZerar;
    private javax.swing.JLabel lbContadorTempo;
    // End of variables declaration                   
}

Model

   package source;


import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Pomodoro {
    private Timer tm;
    private int tempo = 5; // segundos
    private boolean ligado = false;


    public Pomodoro() {

    }
    public void iniciar() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
          public void run() {
            tempo++;
           System.out.println(tempo);
          }
        }, 1000, 1000);

    }
    public void setTempo(int tempo) {
        tempo++;

    }
    public String getTempo() {
        return String.format("%02d", tempo);

    }

}

2 answers

1


import javax.swing.*;

public class GUI extends javax.swing.JFrame{
    private Pomodoro pomodoro;
    boolean cronometroIniciar = true;
    Thread t = null;

public GUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lbContadorTempo = new javax.swing.JLabel();
        btIniciar = new javax.swing.JButton();
        btParar = new javax.swing.JButton();
        btZerar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.LINE_AXIS));

        lbContadorTempo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        lbContadorTempo.setText("00:00:00");
        getContentPane().add(lbContadorTempo);

        btIniciar.setText("Iniciar");
        btIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIniciarActionPerformed(evt);
            }
        });
        getContentPane().add(btIniciar);

        btParar.setText("Parar");
        btParar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPararActionPerformed(evt);
            }
        });
        getContentPane().add(btParar);

        btZerar.setText("Zerar");
        btZerar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btZerarActionPerformed(evt);
            }
        });
        getContentPane().add(btZerar);

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

    private void btIniciarActionPerformed(java.awt.event.ActionEvent evt) { 
        cronometroIniciar = true;   
        pomodoro = new Pomodoro();
        pomodoro.iniciar();  
        t = new Thread(() ->{
        while(cronometroIniciar){ //status true quando aperta o botão iniciar
            lbContadorTempo.setText(pomodoro.getTempo()); // altera o JLabel
        }
        });
        t.start();
    }  

    private void btPararActionPerformed(java.awt.event.ActionEvent evt) {  
        System.out.println("Parar");
        cronometroIniciar = false;
        pomodoro = new Pomodoro();
        pomodoro.parar(); 
        t.interrupt();
    }

    private void btZerarActionPerformed(java.awt.event.ActionEvent evt) {                                        


    } 



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

    // Variables declaration - do not modify                     
    private javax.swing.JButton btIniciar;
    private javax.swing.JButton btParar;
    private javax.swing.JButton btZerar;
    private javax.swing.JLabel lbContadorTempo;
    // End of variables declaration                   
}
import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class Pomodoro {
    private Timer tm = new Timer();
    private int tempo = 5; // segundos
    private static boolean ligado = true;

    public Pomodoro() {

    }

    public void iniciar() {
        ligado = true;
        tm.scheduleAtFixedRate(new TimerTask() {
          public void run() {             
                if(ligado) {
                    tempo++;
                    System.out.println(tempo);    
                } else {
                   tm.cancel();
                   tm.purge();
                }

          }
        }, 1000, 1000);
    }

    public void parar() {
        System.out.println("parouuuu");
        ligado  = false;
    }

    public void setTempo(int tempo) {
        tempo++;

    }
    public String getTempo() {
        return String.format("%02d", tempo);

    }

}

0

    private void btIniciarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        pomodoro = new Pomodoro();
        pomodoro.iniciar();  
        Thread t = new Thread(() ->{
        while(true){ //status true quando aperta o botão iniciar
            lbContadorTempo.setText(pomodoro.getTempo()); // altera o JLabel
        }
        });
        t.start();
    }  
  • Vlw solved more problem and I think this will help a lot of people, but how do I stop the execution? I’m trying to stop the thread with the Interrupt() method but it’s not working

Browser other questions tagged

You are not signed in. Login or sign up in order to post.