2014-11-07 167 views
9

我是JavaFX的新手,不知道是否有一些相當於Android Toast? 我已經看到類Notification,但它看起來不像只能在應用程序中顯示。我還發現我可以使用Timer併爲其着色Label,但如果有一些課程可以使用,我會更好!JavaFX中的相當於Android的吐司

謝謝!

回答

6

嘗試第三方ControlsFX Notifications or Notification Pane

「的NotificationPane控制可以讓你無需他們的直接輸入(可以與ControlsFX對話框API一樣)。該NotificationPane將動畫和退出的視圖通知你的東西的用戶」

toast1

通知「將在屏幕上的九個位置之一中向用戶顯示通知消息...經過一段時間後,通知將淡出。」

toast2

19

我知道它已經因爲你張貼此很長一段時間,但我剛纔提出JavaFX的一個機器人般的烤麪包的消息,所以我萬一有人需要這種代碼在這裏發佈。

import javafx.animation.KeyFrame; 
import javafx.animation.KeyValue; 
import javafx.animation.Timeline; 
import javafx.scene.Scene; 
import javafx.scene.layout.StackPane; 
import javafx.scene.paint.Color; 
import javafx.scene.text.Font; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 
import javafx.stage.StageStyle; 
import javafx.util.Duration; 

public final class Toast 
{ 
    public static void makeText(Stage ownerStage, String toastMsg, int toastDelay, int fadeInDelay, int fadeOutDelay) 
    { 
     Stage toastStage=new Stage(); 
     toastStage.initOwner(ownerStage); 
     toastStage.setResizable(false); 
     toastStage.initStyle(StageStyle.TRANSPARENT); 

     Text text = new Text(toastMsg); 
     text.setFont(Font.font("Verdana", 40)); 
     text.setFill(Color.RED); 

     StackPane root = new StackPane(text); 
     root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.2); -fx-padding: 50px;"); 
     root.setOpacity(0); 

     Scene scene = new Scene(root); 
     scene.setFill(Color.TRANSPARENT); 
     toastStage.setScene(scene); 
     toastStage.show(); 

     Timeline fadeInTimeline = new Timeline(); 
     KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(fadeInDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 1)); 
     fadeInTimeline.getKeyFrames().add(fadeInKey1); 
     fadeInTimeline.setOnFinished((ae) -> 
     { 
      new Thread(() -> { 
       try 
       { 
        Thread.sleep(toastDelay); 
       } 
       catch (InterruptedException e) 
       { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
        Timeline fadeOutTimeline = new Timeline(); 
        KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(fadeOutDelay), new KeyValue (toastStage.getScene().getRoot().opacityProperty(), 0)); 
        fadeOutTimeline.getKeyFrames().add(fadeOutKey1); 
        fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); 
        fadeOutTimeline.play(); 
      }).start(); 
     }); 
     fadeInTimeline.play(); 
    } 
} 

您可以從任何類舉杯消息與此代碼:

String toastMsg = "some text..."; 
int toastMsgTime = 3500; //3.5 seconds 
int fadeInTime = 500; //0.5 seconds 
int fadeOutTime= 500; //0.5 seconds 
Toast.makeText(primarystage, toastMsg, toastMsgTime, fadeInTime, fadeOutTime); 
+0

這像宣傳的那樣,所以從我+1。但我最終並不需要它;) – Christian 2016-08-02 11:59:03

+0

幹得好的人,這個答案應該有更多的投票。 – VAdaihiep 2017-07-28 04:09:14

+0

什麼是「primaryStage」? – 2017-11-01 18:58:45