Problem with timer in Java

5

Explanation:

I have a JTextField component that would be a countdown timer, but when I use ActionListener this way:

 public static ActionListener alredBGolem = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      redBGolem.setText(String.valueOf(tempoRedBGolem));
      tempoRedBGolem--;
  }
};

It works correctly, but when calling a function:

public static JTextField redBGolem = new JTextField();
private static int tempoRedBGolem = 300;
private static Timer timerRedBGolem = new Timer(1000, alredBGolem);


 public static ActionListener alredBGolem = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      count(redBGolem,timerRedBGolem,tempoRedBGolem,1);
  }
};
public static void count(JTextField Field, Timer cTimer, int Tempo, int Type){
    Field.setText(String.valueOf(Tempo));
    Tempo--;
    System.out.println(Tempo);
}

It only prints 299 repeatedly and JTextField does not exit 300 .

How do I solve this problem?

    
asked by anonymous 18.02.2014 / 18:05

1 answer

4

Parameters in Java are always passed by value, not by reference. So by changing the value of the Tempo variable, you are changing the copy value of the argument and not the original value of tempoRedBGolem .

However, you could pass a changeable object parameter and change a property of that object.

public class Contador {
    private int i = 0;
    public Contador(int i) { this.i = i; }
    public void count() {  i--; } 
    public int get() { return i; }
}

And then your code looks like this:

public static JTextField redBGolem = new JTextField();
private static Contador tempoRedBGolem = new Contador(300); 
private static Timer timerRedBGolem = new Timer(1000, alredBGolem);

public static ActionListener alredBGolem = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
      count(redBGolem,timerRedBGolem,tempoRedBGolem,1);
  }
};

public static void count(JTextField Field, Timer cTimer, Contador Tempo, int Type){
    Field.setText(String.valueOf(Tempo.get()));
    Tempo.count();
    System.out.println(Tempo.get());
}

Another option would be to change the static value directly:

public static void count(JTextField Field, Timer cTimer, int Type){
    Field.setText(String.valueOf(tempoRedBGolem));
    tempoRedBGolem--;
    System.out.println(tempoRedBGolem);
}
    
18.02.2014 / 18:15