Created
June 6, 2018 22:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Ticker { | |
public void tick(double progress); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It might be used something like...