Home > Enterprise >  How to restart the timer in JFrame Java?
How to restart the timer in JFrame Java?

Time:09-17

How can I restart the timer? I tried adding the variable of int i inside the reset button. How can I solve this problem?

Below are the codes of the Timer that I have created.

import javax.swing.Timer;
import java.awt.event.*;
/**
 *
 */
public class JFrame2 extends javax.swing.JFrame {
int score1=0;
int score2=0;
int i = 25;

    /**
     * Creates new form JFrame2
     */
    public JFrame2() {
        initComponents();
    }
Timer T = new Timer(1000, new ActionListener()
{
    public void actionPerformed(ActionEvent e){
    i--;
    if(i>=0){
        shotclock.setText("" i);
    }
}

});

  private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        T.start();
    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       T.stop();
    }                                        

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
int i = 25;                                         
        T.start();
    }               

CodePudding user response:

it didn't restart the timer back from the original starting time

int i = 25;     

That is because you created a new local variable.

You need to reset your original instance variable:

//int i = 25;     
i = 25;     
  • Related