JavaFX z Arią - powrót do strony głównej

JavaFX: najprostszy zegar cyfrowy (sposób 2)

Klasa Listing14c_02a

Ściągnij klasę Listing14c_02a

package rozdzial14c;

import javafx.animation.AnimationTimer;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Label;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class Listing14c_02a extends Label {

    private final StringProperty tp;

    private final DigitalTimer timer;

    public Listing14c_02a() {
        super();
        tp = this.textProperty();
        timer = new DigitalTimer();
        timer.start();
    }

    class DigitalTimer extends AnimationTimer {
        @Override
        public void handle(long now) {
            LocalTime lt = LocalTime.now();
            String text = lt.format(DateTimeFormatter.
                    ofLocalizedTime(FormatStyle.MEDIUM));
            tp.set(text);
        }
    }

    public DigitalTimer getTimer() {
        return timer;
    }
}
Klasa Listing14c_02b

Ściągnij klasę Listing14c_02b

package rozdzial14c;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
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;

public class Listing14c_02b 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)));

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {

        try {
            StackPane root = new StackPane();
            Listing14c_02a aclock = new Listing14c_02a();
            aclock.setFont(CLOCK_FONT);
            aclock.setTextFill(Color.GREEN);
            root.setBackground(CLOCK_BACKGROUND);
            root.getChildren().add(aclock);
            Scene scene = new Scene(root,200,50);
            stage.setScene(scene);
            stage.setTitle("Zegar Cyfrowy");
            stage.setOnCloseRequest(event -> {
                Listing14c_02a.DigitalTimer acat = aclock.getTimer();
                acat.stop();
                Platform.exit();
            });
            stage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Po uruchomieniu klasy Listing14c_02b otrzymujemy (Rys. 14_02).

Zegar cyfrowy
Rys. 14_2. Zegar cyfrowy