javaFX 在窗口的標題欄顯示當前時間,1秒更新一次時間

 例1:在窗口的標題欄顯示當前時間,1秒更新一次時間html

 1 import java.text.DateFormat;
 2 import java.text.SimpleDateFormat;
 3 import java.util.Date;
 4 
 5 import javafx.animation.KeyFrame;
 6 import javafx.animation.Timeline;
 7 import javafx.application.Application;
 8 import javafx.event.ActionEvent;
 9 import javafx.event.EventHandler;
10 import javafx.geometry.Insets;
11 import javafx.scene.Scene;
12 import javafx.scene.layout.GridPane;
13 import javafx.stage.Stage;
14 import javafx.util.Duration;
15 
16 public class Main extends Application {
17 
18     public static void main(String[] args) {
19         launch(args);
20     }
21     
22     @Override
23     public void start(Stage primaryStage) throws Exception {
24         // Create a pane to hold two players
25         GridPane pane = new GridPane();
26         pane.setStyle("-fx-border-color: green;");
27         pane.setPadding(new Insets(10, 10, 10, 10));
28         pane.setHgap(10);
29         pane.setVgap(10);
30         
31         // Date format
32         DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
33         
34         EventHandler<ActionEvent> eventHandler = e -> {
35             primaryStage.setTitle(df.format(new Date()));
36             System.out.println(df.format(new Date()));
37         };
38         
39         Timeline animation = new Timeline(new KeyFrame(Duration.millis(1000), eventHandler));
40         animation.setCycleCount(Timeline.INDEFINITE);
41         animation.play();
42         
43         // Create a scene
44         Scene scene = new Scene(pane, 400, 200);
45         primaryStage.setScene(scene);
46         primaryStage.setTitle("Starting");
47         primaryStage.setResizable(false);
48         primaryStage.show();
49     }
50 }

運行效果:java

 

 

關於lambda表達式:http://www.javashuo.com/article/p-biwqixyz-bx.htmlapp

例1中的第34~37行的代碼是lambda表達式的寫法(感受lambda表達式好難理解)。在這裏,其實就是將一個匿名內部類的引用賦給一個變量。ide

EventHandler<ActionEvent> eventHandler = e -> {
    primaryStage.setTitle(df.format(new Date()));
    System.out.println(df.format(new Date()));
};

以上代碼等同於:spa

EventHandler<ActionEvent> eventHandler = new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        primaryStage.setTitle(df.format(new Date()));
        System.out.println(df.format(new Date()));
    }
};

 

例1中的第34~39行的代碼能夠改寫成:code

Timeline animation = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        primaryStage.setTitle(df.format(new Date()));
        System.out.println(df.format(new Date()));
    }
}));
相關文章
相關標籤/搜索