Problem with Java timer

Asked

Viewed 384 times

5

Explanation:

I have a component JTextField that would be a regressive counter, but when I use the ActionListener in this way:

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

It works correctly, but when it calls 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);
}

He just prints it 299 repeatedly and the JTextField does not leave the 300.

How to solve this problem?

1 answer

4


Java parameters are always passed by value and not by reference. Then, when changing the variable value Tempo, you are changing the copy value of the argument and not the original value of tempoRedBGolem.

However, you could pass a mutable object by 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 goes 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);
}
  • Thank you @utluiz worked with the counter class, I’m using the transparent background on JtextFiel only when it changes the content it gets all scrambled as if it prints one number on top of the other, you know what ? I’m using the background thus: redBGolem.setBackground(new Color(1.0f,1.0f,1.0f,0f));

  • @alleen94 I’m not much of that part of GUI, but try calling the method repaint() component element or method revalidate() of the panel containing it.

Browser other questions tagged

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