Skip to content

Instantly share code, notes, and snippets.

@stnwtr
Last active April 25, 2019 18:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stnwtr/fd808d54ede12f99efa042964c441a54 to your computer and use it in GitHub Desktop.
Save stnwtr/fd808d54ede12f99efa042964c441a54 to your computer and use it in GitHub Desktop.
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
public class AnimatedTitle {
public interface Animation {
String animate(String title);
static Animation marquee() {
return title -> {
if (title == null || title.length() < 2)
return title;
else
return title.substring(1) + title.charAt(0);
};
}
static Animation empty() {
return title -> title;
}
}
private final Stage stage;
private final String title;
private final Animation animation;
private final long period;
private final Timer timer;
public AnimatedTitle(Stage stage, String title, Animation animation, long period) {
if (stage == null)
throw new IllegalArgumentException("Stage cannot be null");
this.stage = stage;
this.title = title == null ? "" : title;
this.animation = animation == null ? Animation.empty() : animation;
this.period = period <= 0 ? 256 : period;
this.timer = new Timer(true);
stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, windowEvent -> timer.cancel());
}
public void start() {
stage.setTitle(title);
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
stage.setTitle(animation.animate(stage.getTitle()));
});
}
}, 0, period);
}
public void stop() {
timer.cancel();
}
public void reset() {
stop();
stage.setTitle(title);
}
public String getOriginalTitle() {
return title;
}
public String getCurrentTitle() {
return stage.getTitle();
}
}
@pascalklassen
Copy link

Die Klasse gefällt mir aber ich würde tatsächlich den null check simpel halten dann erstellst du nicht jedes Mal ein Optional Objekt

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