Saturday, 11 November 2017

Image Carousel

my flavor of : DisplaySelf
 https://github.com/shemnon/javafx-gradle/blob/master/samples/Ensemble8/src/samples/java/ensemble/samples/graphics/displayshelf/DisplayShelf.java




package pagination;

import java.io.File;
import java.net.URI;
import java.util.stream.Stream;

import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.effect.Reflection;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;

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

 @Override
 public void start(Stage stage) throws Exception {
  HostServices hs = getHostServices();
  String folder = hs.resolveURI(hs.getDocumentBase(), "imgs/animals/");

  int[] index = {0};

  Unit[] images = 
    Stream.of(new File(new URI(folder).getPath()).list())
    .map(name -> hs.resolveURI(folder, name))
    .map(url -> new Unit(url, index[0]++))
    .toArray(Unit[]::new);

  Group container = new Group();
  container.setStyle("-fx-background-color:derive(black, 20%)");
  container.getChildren().addAll(images);

  Slider slider = new Slider(0, images.length - 1, 0);
  slider.setMajorTickUnit(1);
  slider.setMinorTickCount(0);
  slider.setBlockIncrement(1);
  slider.setSnapToTicks(true);
  
  container.getChildren().add(slider);

  Scene scene = new Scene(container, 1000, 400, true);
  scene.setFill(Color.rgb(33,33,33));

  stage.setScene(scene);
  stage.getScene().setCamera(new PerspectiveCamera());
  stage.setResizable(false);
  stage.initStyle(StageStyle.UNDECORATED);
  stage.show();

  slider.translateXProperty().bind(stage.widthProperty().divide(2).subtract(slider.widthProperty().divide(2)));
  slider.setTranslateY(10);

  // FxTransformer.sliders(new DoubleProperty[] {x, z, rotation}, new String[] {"x", "z", "rotation"}, stage, -360, 360).show();
  // new FxTransformer(images, IntStream.range(0, images.length).mapToObj(i -> "images["+i+"]").toArray(String[]::new), stage, -500, 1000).show();

  slider.valueProperty().addListener((p, o, n) -> {
   if(n.doubleValue() == n.intValue())
    Stream.of(images).forEach(u -> u.update(n.intValue(), stage.getWidth(), stage.getHeight()));
  });

  container.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
   if(e.getTarget() instanceof Unit)
    slider.setValue(((Unit)e.getTarget()).index);
  });
  
  Button close = new Button("X");
  close.setOnAction(e -> System.exit(0));
  close.getStyleClass().clear();
  close.setStyle("-fx-text-fill:white;-fx-font-size:15;-fx-font-weight:bold;-fx-font-family:'Comic Sans MS';");

  container.getChildren().add(close);
  close.translateXProperty().bind(stage.widthProperty().subtract(15));

  slider.setValue(5);
 }

 private static class Unit extends ImageView {
  final static Reflection reflection = new Reflection();
  final static Point3D  rotationAxis = new Point3D(0, 90, 1);

  static {
   reflection.setFraction(0.5);
  }

  final int index;
  final Rotate rotate = new Rotate(0, rotationAxis);
  final TranslateTransition transition = new TranslateTransition(Duration.millis(300), this);

  public Unit(String imageUrl, int index) {
   super(imageUrl);
   setEffect(reflection);
   setUserData(index);

   this.index = index;
   getTransforms().add(rotate);
  }
  public void update(int currentIndex, double width, double height) {
   int ef = index - currentIndex;
   double middle = width / 2 - 100;
   boolean b = ef < 0;

   setTranslateY(height/2 - getImage().getHeight()/2);
   double x,z, theta, pivot;

   if(ef == 0) {
    z = -300;
    x = middle;
    theta = 0;
    pivot = b ? 200 : 0;
   }
   else {
    x = middle + ef * 82 + (b ? -147 : 147);
    z = -78.588;
    pivot = b ? 200 : 0 ;
    theta = b ? 46 : -46;
   }
   rotate.setPivotX(pivot);
   rotate.setAngle(theta);

   transition.pause();
   transition.setToX(x);
   transition.setToZ(z);
   transition.play();
  }

 }

}
styled using hilite.me

download code

Thursday, 9 November 2017

Floating Boxes




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.Random;

import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.PathTransition;
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

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

    final Random random = new Random();
    final int orbitalCounts = 15;

    @Override
    public void start(Stage stage) throws Exception {
        Group root = new Group();

        for (int i = 0; i < 25; i++)
            unit(root);

        CheckBox cb = new CheckBox("show path");
        root.getChildren().add(0, cb);
        cb.setOnAction(e -> {
            Color color = cb.isSelected() ? Color.BLACK : Color.TRANSPARENT;
            root.getChildren().stream()
            .filter(n -> n instanceof Circle)
            .forEach(c -> ((Circle) c).setStroke(color));
        });

        Scene scene = new Scene(root, 500, 500, true);
        scene.setCamera(new PerspectiveCamera(false));
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    private void unit(Group root) {
        Circle c = new Circle(250, 250, 100 + random.nextInt(150), null);
        c.setStroke(Color.BLACK);
        c.setRotate(random.nextInt(360));
        c.setRotationAxis(new Point3D(random.nextInt(360), random.nextInt(360), random.nextInt(360)));
        c.setStroke(Color.TRANSPARENT);
        c.setStrokeWidth(0.2);

        int size = 10 + random.nextInt(10);
        Box box = new Box(size, size, size);
        box.setMaterial(new PhongMaterial(Color.hsb(random.nextInt(360), 0.5, 1)));
        box.setRotate(random.nextInt(360));
        box.setRotationAxis(new Point3D(random.nextInt(360), random.nextInt(360), random.nextInt(360)));

        PathTransition pt = new PathTransition(Duration.seconds(5), c, box);
        RotateTransition rt = new RotateTransition(Duration.seconds(2), box);
        rt.setToAngle(360 + box.getRotate());

        pt.setDelay(Duration.millis(random.nextInt(1000)));
        pt.setCycleCount(Animation.INDEFINITE);
        rt.setCycleCount(Animation.INDEFINITE);
        pt.setInterpolator(Interpolator.LINEAR);
        rt.setInterpolator(Interpolator.LINEAR);
        rt.play();
        pt.play();

        root.getChildren().addAll(box, c);
    }
}
styled using hilite.me

Tuesday, 7 November 2017

Bouncing Circles


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
import java.util.Arrays;
import java.util.Random;
import java.util.function.DoubleSupplier;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }
    final Color fill = new Color(1, 1, 1, 00.05);
    double width, height;
    Circle[] circles = new Circle[0];
    double[][] moveBy = new double[0][2];
    double[] radiusDivs = new double[0];

    @Override
    public void start(Stage stage) throws Exception {
        Random random = new Random();
        Pane pane = new Pane();

        pane.setStyle("-fx-background-color:derive(black, 30%);");

        Scene scene = new Scene(new BorderPane(pane), 300, 300);
        stage.setScene(scene);
        stage.show();

        DoubleSupplier randomFraction = () -> (random.nextBoolean() ? 1 : -1) * random.nextDouble();

        InvalidationListener resizeListener = e -> {
            double oldW = width;
            double oldH = height;

            width = stage.getWidth();
            height = stage.getHeight();

            double min = Math.min(width, height);
            double max = Math.max(width, height);
            int size = (int) Math.sqrt(max);
            int sizePrev = circles.length;
            circles = sizePrev == size ? circles : Arrays.copyOf(circles, size);
            radiusDivs = sizePrev == size ? radiusDivs : Arrays.copyOf(radiusDivs, size);
            moveBy = sizePrev == size ? moveBy : Arrays.copyOf(moveBy, size);

            if (sizePrev < size) {
                for (int i = sizePrev; i < size; i++) {
                    Circle c = circles[i] = new Circle(5, fill);
                    c.getStyleClass().add("circles");

                    double r = radiusDivs[i] = 0.5 + random.nextDouble();
                    c.setRadius((min / 10) * radiusDivs[i]);
                    c.setCenterX(r + random.nextInt((int) (width - r)));
                    c.setCenterY(r + random.nextInt((int) (height - r)));

                    moveBy[i] = new double[] { randomFraction.getAsDouble(), randomFraction.getAsDouble() };
                }
            }
            int limit = sizePrev > size ? size : sizePrev;
            for (int i = 0; i < limit; i++) {
                Circle c = circles[i];

                c.setRadius((min / 10) * radiusDivs[i]);
                c.setCenterX(width * (c.getCenterX() / oldW));
                c.setCenterY(height * (c.getCenterY() / oldH));
            }
            pane.getChildren().setAll(circles);
        };

        stage.widthProperty().addListener(resizeListener);
        stage.heightProperty().addListener(resizeListener);
        resizeListener.invalidated(null);

        new AnimationTimer() {

            @Override
            public void handle(long now) {
                for (int i = 0; i < circles.length; i++) {
                    Circle c = circles[i];
                    double x = c.getCenterX();
                    double y = c.getCenterY();
                    double r = c.getRadius();

                    if (x - r < 0)
                        moveBy[i][0] = random.nextDouble();
                    else if (x + r > width)
                        moveBy[i][0] = -1 * random.nextDouble();
                    if (y - r < 0)
                        moveBy[i][1] = random.nextDouble();
                    else if (y + r > height)
                        moveBy[i][1] = -1 * random.nextDouble();

                    c.setCenterX(x + moveBy[i][0]);
                    c.setCenterY(y + moveBy[i][1]);
                }
            }
        }.start();
    }
}

styled using hilite.me

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();
    }
}

Saturday, 30 September 2017

javafx - Form Element _001



Practiced  (http://codepen.io/kaezarrex/pen/EmzVLM by David)



import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Duration;

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

 final Font DEFAULT_FONT = Font.font("Candara", 15);

 @Override
 public void start(Stage stage) throws Exception {
  VBox root = new VBox(20, new InputField("First Name"), new InputField("Last Name"), new CustomButton("Submit"));
  root.setAlignment(Pos.CENTER);
  root.setStyle("-fx-background-color:white");

  Scene scene = new Scene(root, 300, 300, Color.WHITE);
  stage.setScene(scene);
  stage.show();
  scene.getAccelerators().put(new KeyCodeCombination(KeyCode.ESCAPE), () -> System.exit(0));
  scene.getStylesheets().add("style.css");
 }

 class CustomButton extends HBox {
  Button btn;
  public CustomButton(String name) {
   setAlignment(Pos.CENTER);

   btn = new Button(name);
   getChildren().add(btn);

   btn.getStyleClass().clear();
   btn.getStyleClass().add("button-2");
   btn.setFont(DEFAULT_FONT);
   animations();
  }
  private void animations() {
   SimpleIntegerProperty lineLength = new SimpleIntegerProperty(0);
   lineLength.addListener((p, o, n) -> {
    String color = "linear-gradient(to right, red "+n+"%, gray "+(n.doubleValue()+1)+"%, gray 100%)";
    btn.setStyle("-fx-border-color:"+color);
   });

   Timeline tl = new Timeline(
     new KeyFrame(Duration.ZERO, new KeyValue(lineLength, 0, Interpolator.EASE_OUT)),
     new KeyFrame(Duration.millis(600), new KeyValue(lineLength, 100, Interpolator.EASE_OUT))
     );
   
   btn.hoverProperty().addListener((p, o, n) -> {
    if(n)
     tl.playFromStart();
    else {
     tl.stop();
     btn.setStyle("-fx-border-color:gray");
    }
   });
  }
 }

 class InputField extends Group {
  final TextField field;
  final Label label;

  public InputField(String name) {
   field = new TextField();
   label = new Label(name);

   field.setFont(DEFAULT_FONT);
   label.setFont(DEFAULT_FONT);

   label.getStyleClass().clear();
   field.getStyleClass().clear();

   getStyleClass().add("input-field");
   field.getStyleClass().add("text-field-2");
   label.getStyleClass().add("label-2");

   getChildren().addAll(label, field);
   animations();
  }

  private void animations() {
   TranslateTransition translateField = new TranslateTransition(Duration.millis(300), field);
   TranslateTransition translateLabel = new TranslateTransition(Duration.millis(300), label);
   ScaleTransition scaleLabel = new ScaleTransition(Duration.millis(300), label);

   SimpleIntegerProperty lineLength = new SimpleIntegerProperty(0);
   lineLength.addListener((p, o, n) -> {
    String color = "linear-gradient(to right, red "+n+"%, gray "+(n.doubleValue()+1)+"%, gray 100%)";
    label.setStyle("-fx-text-fill:"+color);
    field.setStyle("-fx-border-color:"+color);
   });

   Timeline tl = new Timeline(
     new KeyFrame(Duration.ZERO, new KeyValue(lineLength, 0, Interpolator.EASE_OUT)),
     new KeyFrame(Duration.millis(600), new KeyValue(lineLength, 100, Interpolator.EASE_OUT))
     );

   ParallelTransition pt = new ParallelTransition(translateField, scaleLabel, translateLabel);

   Runnable focused = () -> {
    pt.pause();
    translateField.setToY(17);
    scaleLabel.setToY(0.6);
    scaleLabel.setToX(0.6);
    translateLabel.setToX(-10);
    pt.playFromStart();
    tl.playFromStart();
    pt.setOnFinished(e -> {});
   };

   Runnable focuslost = () ->{
    if(field.isFocused())
     return;

    pt.pause();
    translateField.setToY(0);
    scaleLabel.setToY(1);
    scaleLabel.setToX(1);
    translateLabel.setToX(0);
    pt.playFromStart();
    tl.stop();
    pt.setOnFinished(e -> {
     label.setStyle("-fx-text-fill:gray");
     field.setStyle("-fx-border-color:gray");
    });
   };
   
   ChangeListener<Boolean> cl =  (p, o, n) -> {
    if(n)
     focused.run();
    else
     focuslost.run();
   };
    
   hoverProperty().addListener(cl);
   field.focusedProperty().addListener(cl);
  }
 }
}



.input-field .text-field-2 {
 -fx-border-width:0 0 2 0;
 -fx-border-color:gray;
 -fx-padding:2;
}

.button-2 {
 -fx-padding: 0.3em 1.4em 0.3em 1.4em;
 -fx-border-width:2;
 -fx-border-color:gray; 
}