[如何在JavaFX(JFoenix)中显示类似Android的Toast消息? [关闭]

问题描述 投票:-1回答:1
[我看到当我运行JFoenix演示时,可以在JavaFX中制作材料设计吐司消息。如何在自己的应用中实现呢? (我是JavaFX初学者)
javafx desktop-application toast jfoenix
1个回答
0
投票
以下是一个入门的小例子:Image sample

import javafx.animation.*; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.effect.DropShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; public class Main extends Application { public class Toast extends Label { private float displayTime = 0.90f; private float initialPositon =0; private float downBias = 10f;// the distance the label should sit below before appearing Interpolator interpolator = new Interpolator() { @Override protected double curve(double v) { //quadratic curve for upward motion return -4 * ( v - 0.5 ) * ( v - 0.5 ) +1; } }; public Toast(String msg){ super(); this.setText(msg); this.setOpacity(0);// starting it with zero because we dont want it to show up upoun adding it to the root this.setBackground(new Background(new BackgroundFill(Color.WHEAT, CornerRadii.EMPTY, Insets.EMPTY)));// some background cosmetics this.setAlignment(Pos.CENTER); } public void appear(){ this.setEffect(new DropShadow(20, Color.BLACK));// Shadow //creating animation in the Y axis Timeline timeline = new Timeline( new KeyFrame(Duration.seconds(this.displayTime), new KeyValue(this.translateYProperty(),this.initialPositon-this.getMinHeight()-20, interpolator)) ); FadeTransition fd = new FadeTransition(Duration.seconds(this.displayTime),this); fd.setCycleCount(1); fd.setFromValue(0); fd.setToValue(1.0); fd.setInterpolator(interpolator); fd.play(); timeline.play(); } public void setInitialPositon(float positon){ this.initialPositon = positon+downBias; this.setTranslateY(positon+downBias); } } @Override public void start(Stage primaryStage) throws Exception{ float sceneHeight = 230f; float sceneWidth =230f; Toast toast = new Toast("Hello World"); toast.setMinWidth(sceneWidth-40); toast.setMinHeight(30); toast.setInitialPositon(sceneHeight); toast.setTranslateX(sceneWidth/2-toast.getMinWidth()/2); Button showToast = new Button("show toast"); showToast.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { toast.appear(); } }); Pane root = new Pane(); root.getChildren().addAll(toast,showToast); Scene myscene =new Scene(root, sceneWidth, sceneWidth); primaryStage.setScene(myscene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }

不要忘记重构吐司类,以允许更灵活的术语内插器和其他修饰功能。
© www.soinside.com 2019 - 2024. All rights reserved.