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
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
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.
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.