Jframe重启时的计时器

时间:2015-06-09 17:23:22

标签: java swing timer jframe restart

您好我过去几天一直在努力,似乎无法解决问题我想在Jframe中制作一个可以重置并重新启动的计时器。我似乎得到错误,计时器已被取消,但不能如何解决这个,任何帮助将不胜感激。 这是我的代码

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 个答案:

答案 0 :(得分:0)

不是最优雅的解决方案,但您可以将计时器任务转换为嵌套类,并在每次启动监视时创建新的计时器和任务。我认为ScheduledExecutorService通常比计时器更容易使用,因此您可以查看它。

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");
        }
    }

};