-3

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

rashadbb
  • 31
  • 1
  • 6
  • This is C# but ought to give you some ideas. [How to reset an application variable daily](https://stackoverflow.com/questions/15246998/how-to-reset-an-application-variable-daily) – Brien Foss Jan 13 '18 at 17:24

2 Answers2

1

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(
        Duration.millis(2000),
        ae -> myObject.reuseOriginalValueForFooField()));
timeline.play();

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

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() {
    @Override
    public void run() {
        ab.set(false);
    }
}, TimeUnit.SECONDS.toMillis(5)); // <-- once in five seconds.
while (ab.get()) { // <-- while the boolean is true
    System.out.println("It's true");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
}
t.cancel(); // <-- don't forget to end the Timer.

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

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249