Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created June 6, 2018 22:35
Show Gist options
  • Save RustyKnight/343e563060919c58978ba97bd3bc426d to your computer and use it in GitHub Desktop.
Save RustyKnight/343e563060919c58978ba97bd3bc426d to your computer and use it in GitHub Desktop.
A simple wrapper around a Swing `Timer` that provides `Duration` based animation that also provides pause/resume functionality
public class Animator {
private Instant startTime;
private Duration totalRunTime = Duration.ZERO;
private Duration runTime;
private Timer timer;
private List<Ticker> tickers;
public Animator(Duration duration) {
tickers = new ArrayList<>(25);
this.runTime = duration;
timer = new Timer(5, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Duration runningTime = getDuration();
if (runningTime.compareTo(getRunTime()) > 0) {
stop();
reset();
runningTime = getRunTime();
}
double progress = runningTime.toMillis() / (double) runTime.toMillis();
if (progress >= 1.0) {
progress = 1.0d;
stop();
reset();
}
for (Ticker ticker : tickers) {
ticker.tick(progress);
}
}
});
}
public void addTicker(Ticker ticker) {
tickers.add(ticker);
}
public void removeTicker(Ticker ticker) {
tickers.remove(ticker);
}
public Duration getRunTime() {
return runTime;
}
public void start() {
startTime = Instant.now();
timer.start();
}
public void stop() {
timer.stop();
if (startTime != null) {
Duration runTime = Duration.between(startTime, Instant.now());
totalRunTime = totalRunTime.plus(runTime);
}
startTime = null;
}
public void pause() {
stop();
}
public void resume() {
start();
}
public void reset() {
stop();
totalRunTime = Duration.ZERO;
}
public boolean isRunning() {
return startTime != null;
}
public Duration getDuration() {
Duration currentDuration = Duration.ZERO;
currentDuration = currentDuration.plus(totalRunTime);
if (isRunning()) {
Duration runTime = Duration.between(startTime, Instant.now());
currentDuration = currentDuration.plus(runTime);
}
return currentDuration;
}
}
public interface Ticker {
public void tick(double progress);
}
@RustyKnight
Copy link
Author

It might be used something like...

Animator animator = new Animator(Duration.ofSeconds(5));
animator.addTicker(new Ticker() {
    @Override
    public void tick(double progress) {
        // Perform required animation
    }
});
animator.start();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment