|
| 1 | +import javafx.animation.KeyFrame; |
| 2 | +import javafx.animation.KeyValue; |
| 3 | +import javafx.animation.Timeline; |
| 4 | +import javafx.scene.Scene; |
| 5 | +import javafx.scene.layout.StackPane; |
| 6 | +import javafx.scene.paint.Color; |
| 7 | +import javafx.scene.text.Font; |
| 8 | +import javafx.scene.text.Text; |
| 9 | +import javafx.stage.Stage; |
| 10 | +import javafx.stage.StageStyle; |
| 11 | +import javafx.util.Duration; |
| 12 | + |
| 13 | +public final class Toast { |
| 14 | + public static void makeText(Stage ownerStage, String toastMsg, int toastDelay, int fadeInDelay, int fadeOutDelay) { |
| 15 | + Stage toastStage=new Stage(); |
| 16 | + toastStage.initOwner(ownerStage); |
| 17 | + toastStage.setResizable(false); |
| 18 | + toastStage.initStyle(StageStyle.TRANSPARENT); |
| 19 | + |
| 20 | + Text text = new Text(toastMsg); |
| 21 | + text.setFont(Font.font("Verdana", 40)); |
| 22 | + text.setFill(Color.RED); |
| 23 | + |
| 24 | + StackPane root = new StackPane(text); |
| 25 | + root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.2); -fx-padding: 50px;"); |
| 26 | + root.setOpacity(0); |
| 27 | + |
| 28 | + Scene scene = new Scene(root); |
| 29 | + scene.setFill(Color.TRANSPARENT); |
| 30 | + toastStage.setScene(scene); |
| 31 | + toastStage.show(); |
| 32 | + |
| 33 | + Timeline fadeInTimeline = new Timeline(); |
| 34 | + KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(fadeInDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 1)); |
| 35 | + fadeInTimeline.getKeyFrames().add(fadeInKey1); |
| 36 | + fadeInTimeline.setOnFinished((ae) -> { |
| 37 | + new Thread(() -> { |
| 38 | + try { |
| 39 | + Thread.sleep(toastDelay); |
| 40 | + } |
| 41 | + catch (InterruptedException e){ |
| 42 | + // TODO Auto-generated catch block |
| 43 | + e.printStackTrace(); |
| 44 | + } |
| 45 | + Timeline fadeOutTimeline = new Timeline(); |
| 46 | + KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(fadeOutDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 0)); |
| 47 | + fadeOutTimeline.getKeyFrames().add(fadeOutKey1); |
| 48 | + fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); |
| 49 | + fadeOutTimeline.play(); |
| 50 | + }).start(); |
| 51 | + }); |
| 52 | + fadeInTimeline.play(); |
| 53 | + } |
| 54 | +} |
0 commit comments