JavaFX: najprostszy zegar cyfrowy (sposób 1)
Najprostszy zegar cyfrowy można stworzyć na bazie etykietki Label
albo tekstu Tekst
. Ja wybrałam etykietkę Label
.
Klasa Listing14c_01
Ściągnij klasę Listing14c_01
package rozdzial14c; import javafx.animation.*; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Stage; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; public class Listing14c_01 extends Application { private static final Font CLOCK_FONT = Font.font("Arial", FontWeight.BOLD, 20); private static final Background CLOCK_BACKGROUND = new Background(new BackgroundFill(Color.HONEYDEW, CornerRadii.EMPTY, new Insets(0, 0, 0, 0))); private Label label; private AnimationTimer timer; public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { try { StackPane root = new StackPane(); label = new Label(); label.setFont(CLOCK_FONT); label.setTextFill(Color.GREEN); root.setBackground(CLOCK_BACKGROUND); root.getChildren().add(label); Scene scene = new Scene(root, 200, 50); stage.setScene(scene); stage.setTitle("Zegar Cyfrowy"); stage.setOnCloseRequest(event -> { timer.stop(); Platform.exit(); }); timer = new DigiTimer(); timer.start(); stage.show(); } catch (Exception e) { e.printStackTrace(); } } private class DigiTimer extends AnimationTimer { @Override public void handle(long now) { LocalTime lt = LocalTime.now(); String text = lt.format(DateTimeFormatter. ofLocalizedTime(FormatStyle.MEDIUM)); label.textProperty().set(text); } } }
Po uruchomieniu klasy zobaczymy (Rys. 14_01):