javaFX 在窗口的标题栏显示当前时间,1秒更新一次时间
例1:在窗口的标题栏显示当前时间,1秒更新一次时间
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 }
运行效果:
关于lambda表达式:https://www.cnblogs.com/franson-2016/p/5593080.html
例1中的第34~37行的代码是lambda表达式的写法(感觉lambda表达式好难理解)。在这里,其实就是将一个匿名内部类的引用赋给一个变量。
EventHandler<ActionEvent> eventHandler = e -> { primaryStage.setTitle(df.format(new Date())); System.out.println(df.format(new Date())); };
以上代码等同于:
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行的代码可以改写成:
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())); } }));