timer in Jframe restart

269 views Asked by At

Hi I have been struggling the last few days and can't seem to solve the problem I want to make a timer in a Jframe that will be reset and start again. I seem to get error the the timer has been canceled but can't how to solve this , any help will be appreciated. Here is my code

package cubebuddy;

import java.util.Timer;
import java.util.TimerTask;

public class One_timer extends javax.swing.JFrame {

    Timer timer= new Timer();
    String ms, s, m;

    public One_timer() {
        initComponents();
    }
     TimerTask  myTimerTask = new TimerTask() {            
        @Override
            public void run() {               
                ms = Timer_display_ms.getText();
                s = Timer_display_s.getText();
                m = Timer_display_m.getText();
                Long MS_timer = Long.valueOf(ms);
                Long S_timer = Long.valueOf(s);
                Long M_timer = Long.valueOf(m);
                if (ms.equals(Long.toString(99))) {
                    s = Long.toString(++S_timer);
                    Timer_display_s.setText(s);
                }
                if ("99".equals(Timer_display_ms.getText())) {
                    Timer_display_ms.setText("0");
                } else {
                    ms = Long.toString(++MS_timer);
                    Timer_display_ms.setText(ms);
                }
                if (s.equals(Long.toString(60))) {
                    m = Long.toString(++M_timer);
                    Timer_display_m.setText(m);
                    Timer_display_s.setText("0");
                }
            }

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

        OT_start_button = new javax.swing.JButton();
        Timer_display_ms = new javax.swing.JTextField();
        OT_stop_button = new javax.swing.JButton();
        Timer_display_s = new javax.swing.JTextField();
        Timer_display_m = new javax.swing.JTextField();
        OT_Reset_button = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(0, 153, 204));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        OT_start_button.setText("Start");
        OT_start_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OT_start_buttonActionPerformed(evt);
            }
        });

        Timer_display_ms.setEditable(false);
        Timer_display_ms.setBackground(new java.awt.Color(102, 102, 102));
        Timer_display_ms.setFont(new java.awt.Font("sansserif", 0, 48)); // NOI18N
        Timer_display_ms.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        Timer_display_ms.setText("0");
        Timer_display_ms.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Timer_display_msActionPerformed(evt);
            }
        });

        OT_stop_button.setText("Stop");
        OT_stop_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OT_stop_buttonActionPerformed(evt);
            }
        });

        Timer_display_s.setEditable(false);
        Timer_display_s.setBackground(new java.awt.Color(102, 102, 102));
        Timer_display_s.setFont(new java.awt.Font("sansserif", 0, 48)); // NOI18N
        Timer_display_s.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        Timer_display_s.setText("0");

        Timer_display_m.setEditable(false);
        Timer_display_m.setBackground(new java.awt.Color(102, 102, 102));
        Timer_display_m.setFont(new java.awt.Font("sansserif", 0, 48)); // NOI18N
        Timer_display_m.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        Timer_display_m.setText("0");

        OT_Reset_button.setText("Reset");
        OT_Reset_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OT_Reset_buttonActionPerformed(evt);
            }
        });

        jLabel1.setBackground(new java.awt.Color(0, 0, 0));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Min");

        jLabel2.setBackground(new java.awt.Color(0, 0, 0));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("sec");

        jLabel3.setBackground(new java.awt.Color(0, 0, 0));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Mil sec");

        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)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Timer_display_m, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(46, 46, 46)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(6, 6, 6)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(Timer_display_s, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(35, 35, 35)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(5, 5, 5)
                                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(Timer_display_ms, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(OT_stop_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(OT_Reset_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                                .addComponent(OT_start_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Timer_display_s)
                    .addComponent(Timer_display_ms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Timer_display_m, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(OT_start_button, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(OT_stop_button, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(OT_Reset_button, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26))
        );

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

    private void OT_start_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:      
        timer.schedule(myTimerTask, 0,1);     
    }                                               

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

    private void OT_Reset_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                                
        // TODO add your handling code here:
        m = "0";
        s = "0";
        ms = "0";
        Timer_display_ms.setText(ms);
        Timer_display_s.setText(s);
        Timer_display_m.setText(m);
    }                                               

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

    private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
        // 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(One_timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(One_timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(One_timer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(One_timer.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 One_timer().setVisible(true);
            }
        });     

    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton OT_Reset_button;
    private javax.swing.JButton OT_start_button;
    private javax.swing.JButton OT_stop_button;
    private javax.swing.JTextField Timer_display_m;
    private javax.swing.JTextField Timer_display_ms;
    private javax.swing.JTextField Timer_display_s;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration                   
}
1

There are 1 answers

0
BranchBacardi On

Not the most elegant solution but you could covert your timer task to a nested class and create a new timer and task each time you start the watch. I think ScheduledExecutorService is general easier to use than the Timers so you might take a look at it.

private void OT_start_buttonActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    timer = new Timer();
    MyTimerTask task = new MyTimerTask();
    timer.schedule(task, 0, 1);
}


private class MyTimerTask extends TimerTask {
    @Override
    public void run() {
        ms = Timer_display_ms.getText();
        s = Timer_display_s.getText();
        m = Timer_display_m.getText();
        Long MS_timer = Long.valueOf(ms);
        Long S_timer = Long.valueOf(s);
        Long M_timer = Long.valueOf(m);
        if (ms.equals(Long.toString(99))) {
            s = Long.toString(++S_timer);
            Timer_display_s.setText(s);
        }
        if ("99".equals(Timer_display_ms.getText())) {
            Timer_display_ms.setText("0");
        } else {
            ms = Long.toString(++MS_timer);
            Timer_display_ms.setText(ms);
        }
        if (s.equals(Long.toString(60))) {
            m = Long.toString(++M_timer);
            Timer_display_m.setText(m);
            Timer_display_s.setText("0");
        }
    }

};