Is there anyway to give a variable a value FOR A CERTAIN AMOUNT OF TIME (java)

So im writing a simple 2d javafx game and a thought just came into my head. Can i give a boolean (or any variable type for that matter) a value for a select amount of time.

If its possible ,how would it look like

2 answers

  • answered 2018-01-13 17:26 davidxxx

    Why not a TimeLine ?
    Suppose you want to change during about 2 seconds a String foo field for an object referenced by a myObject variable declared as MyObject.

    myObject.setTemporaryValueForFooField("special value");
    Timeline timeline = new Timeline(new KeyFrame(
            ae -> myObject.reuseOriginalValueForFooField()));;

    setTemporaryValueForFooField(String) makes a copy of the current value of the foo field in the current instance and assign to it the temporary value.
    reuseOriginalValueForFooField() reassigns the foo field with the original value as the duration is reached.

  • answered 2018-01-13 17:34 Elliott Frisch

    There are several ways to do this. You could use an AtomicBoolean, a Timer (a TimerTask) and a simple loop. Like,

    AtomicBoolean ab = new AtomicBoolean(true);
    Timer t = new Timer(); // <-- The Timer
    t.schedule(new TimerTask() {
        public void run() {
    }, TimeUnit.SECONDS.toMillis(5)); // <-- once in five seconds.
    while (ab.get()) { // <-- while the boolean is true
        System.out.println("It's true");
        try {
        } catch (InterruptedException e) {
    t.cancel(); // <-- don't forget to end the Timer.

    Which prints "It's true" ~ five times.