|
| 1 | +package com.temporaryteam.noticeditor.view; |
| 2 | + |
| 3 | +import javafx.animation.KeyFrame; |
| 4 | +import javafx.animation.Timeline; |
| 5 | +import javafx.animation.TranslateTransition; |
| 6 | +import javafx.event.ActionEvent; |
| 7 | +import javafx.scene.control.Label; |
| 8 | +import javafx.scene.layout.VBox; |
| 9 | +import javafx.util.Duration; |
| 10 | + |
| 11 | +/** |
| 12 | + * Simple notification. |
| 13 | + * @author aNNiMON |
| 14 | + */ |
| 15 | +public final class Notification { |
| 16 | + |
| 17 | + public static final Duration DURATION_SHORT = new Duration(2000); |
| 18 | + public static final Duration DURATION_LONG = new Duration(5000); |
| 19 | + private static final Duration TRANSITION_DURATION = new Duration(300); |
| 20 | + |
| 21 | + private static VBox notificationBox; |
| 22 | + private static Label notificationLabel; |
| 23 | + |
| 24 | + private static Timeline hideTimer; |
| 25 | + private static TranslateTransition transitionIn, transitionOut; |
| 26 | + |
| 27 | + public static void init(VBox vbox, Label label) { |
| 28 | + notificationBox = vbox; |
| 29 | + notificationLabel = label; |
| 30 | + |
| 31 | + transitionIn = new TranslateTransition(TRANSITION_DURATION, notificationBox); |
| 32 | + transitionIn.setToY(0); |
| 33 | + |
| 34 | + transitionOut = new TranslateTransition(TRANSITION_DURATION, notificationBox); |
| 35 | + transitionOut.setFromY(0); |
| 36 | + transitionOut.setOnFinished((e) -> notificationBox.setVisible(false)); |
| 37 | + } |
| 38 | + |
| 39 | + public static void show(String text) { |
| 40 | + show(text, DURATION_SHORT); |
| 41 | + } |
| 42 | + |
| 43 | + public static void show(String text, Duration duration) { |
| 44 | + if (hideTimer != null) { |
| 45 | + // show new notification while previous exists |
| 46 | + hideTimer.stop(); |
| 47 | + transitionOut.stop(); |
| 48 | + } |
| 49 | + notificationLabel.setText(text); |
| 50 | + hideTimer = new Timeline(new KeyFrame(duration.add(TRANSITION_DURATION))); |
| 51 | + hideTimer.setOnFinished(Notification::hide); |
| 52 | + hideTimer.playFromStart(); |
| 53 | + notificationBox.setVisible(true); |
| 54 | + |
| 55 | + transitionIn.setFromY(notificationBox.getHeight()); |
| 56 | + transitionIn.playFromStart(); |
| 57 | + } |
| 58 | + |
| 59 | + private static void hide(ActionEvent e) { |
| 60 | + if (hideTimer != null) { |
| 61 | + hideTimer.stop(); |
| 62 | + hideTimer = null; |
| 63 | + } |
| 64 | + transitionOut.setToY(notificationBox.getHeight()); |
| 65 | + transitionOut.playFromStart(); |
| 66 | + } |
| 67 | +} |
0 commit comments