Sunday 15 October 2017

Stacked Text



import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    public static final int size = 10;

    public void start(Stage stage) throws Exception {
        List<Color> colors = Stream.of(Color.class.getDeclaredFields())
                .filter(f -> f.getType() == Color.class && Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers()))
                .map(f -> {
                    try {
                        return (Color)f.get(null);
                    } catch (IllegalArgumentException | IllegalAccessException e) {}
                    return null;
                })
                .collect(Collectors.toList());

        Collections.shuffle(colors);

        Font font = Font.font("Berlin Sans FB Demi", 100);
        int[] pos = {0, 0};
        final int density = 5;
        Text[] texts = colors.stream().limit(size)
                .flatMap(color -> Stream.generate(() -> {
                    Text t = new Text("TEXT");
                    t.setFont(font);
                    t.setFill(color);
                    t.setX(pos[0]+=1);
                    t.setY(pos[1]+=1);
                    return t;
                }).limit(density))
                .toArray(Text[]::new);

        Group grp = new Group();
        for (int i = texts.length - 1; i >= density; i--) {
            grp.getChildren().add(texts[i]);
            if(i <= density) {
                texts[i].setFill(Color.WHITE);
                texts[i].setStroke(Color.BLACK);
            }
        };
        Text[] texts2 = Arrays.copyOfRange(texts, density+1, texts.length);
        texts = null;

        VBox root = new VBox(grp);
        root.setAlignment(Pos.CENTER);
        stage.setScene(new Scene(root, 500, 500));
        stage.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.ESCAPE), () -> System.exit(0));
        stage.show();

        new AnimationTimer() {

            @Override
            public void handle(long now) {
                Paint fill = texts2[texts2.length - 1].getFill();
                for (int i = texts2.length - 1; i >= 1 ; i--) {
                    texts2[i].setFill(texts2[i - 1].getFill());
                }
                texts2[0].setFill(fill);
            }
        }.start();
    }
}

No comments:

Post a Comment