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

Thursday 28 September 2017

javafx - NHS Spinner



Forked (http://codepen.io/csswizardry/pen/PjPXrg by Harry Roberts)


import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.RotateTransition;
import javafx.animation.SequentialTransition;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {

 @Override
 public void start(Stage stage) throws Exception {
  int radius = 20;
  Color fill = Color.WHITE;
  
  Circle center = new Circle(150, 150, radius, fill);
  Circle c1 = new Circle(150 - radius*2, 150 - radius*2, radius, fill);
  Circle c2 = new Circle(150 + radius*2, 150 + radius*2, radius, fill);
  Circle c3 = new Circle(150 - radius*2, 150 + radius*2, radius, fill);
  
  Group root = new Group(center, c1, c2, c3);
  
  RotateTransition rt = new RotateTransition(Duration.seconds(1.5), root);
  rt.setInterpolator(Interpolator.EASE_BOTH);
  rt.setFromAngle(-360*5);
  rt.setToAngle(-50);
  
  rt.setCycleCount(Animation.INDEFINITE);
  rt.setAutoReverse(true);
  rt.play();
  
  stage.setScene(new Scene(root, 300, 300, Color.web("#272727")));
  stage.show();
  stage.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.ESCAPE), () -> System.exit(0));
 }

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

}
styled using hilite.me

download code

javafx - Neon Button


import java.nio.file.Files;
import java.nio.file.Path;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.Bloom;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

 public static void main(String[] args) {
  launch(args);
 }
 
 @Override
 public void start(Stage stage) throws Exception {
  Path p = Files.createTempFile("prefix", "suffix");
  p.toFile().deleteOnExit();
  setUserAgentStylesheet(p.toUri().toURL().toString()); // remove default stylesheet
  
  Button b = new Button("Neon button");
  b.setEffect(new Bloom());
   
  VBox root = new VBox(20, b);
  root.setAlignment(Pos.CENTER);
  Scene scene = new Scene(root, 300, 300); 
  stage.setScene(scene);
  scene.getStylesheets().add("style.css");
  stage.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.ESCAPE), () -> System.exit(0));
  stage.show();
 }
}


.root {
 -fx-background-color: darkblue;
}

.button {
  -fx-font-size:2em;
 -fx-font-family: "Eras Medium ITC";
 -fx-padding:15px 20px;
 -fx-text-alignment: center;
 -fx-border-width: 2px; 
 -fx-border-color: cyan;
 -fx-text-fill:cyan;
 -fx-border-radius: 50%;
 -fx-padding:1em 2em 0.9em 2em;
}

.button:hover {
 -fx-border-color: derive(cyan, -20%);
 -fx-text-fill:derive(cyan, -20%);
}

styled using hilite.me

Tuesday 26 September 2017

particle explosion


import java.time.Duration;
import java.util.Random;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {

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

 @Override
 public void start(Stage stage) throws Exception {
  final int size = 400;
  final Rectangle[] rectangles = new Rectangle[size];
  final long[] delays = new long[size];
  final double[] angles = new double[size];
  final long duration = Duration.ofSeconds(3).toNanos();
  final Random random = new Random();

  for (int i = 0; i < size; i++) {
   rectangles[i] = new Rectangle(5, 5, Color.hsb(random.nextInt(360), 1, 1));
   delays[i] = (long) (Math.random()*duration);
   angles[i] = 2 * Math.PI * random.nextDouble();
  }
  stage.setScene(new Scene(new Pane(rectangles), 500, 500, Color.BLACK));
  stage.getScene().getAccelerators().put(new KeyCodeCombination(KeyCode.ESCAPE), () -> System.exit(0)); 
  stage.show();

  new AnimationTimer() {
   @Override
   public void handle(long now) {
    final double width = 0.5 * stage.getWidth();
    final double height = 0.5 * stage.getHeight();
    final double radius = Math.sqrt(2) * Math.max(width, height);

    for (int i = 0; i < size; i++) {
     Rectangle r = rectangles[i];
     double angle = angles[i];
     long t = (now - delays[i]) % duration;
     double d = t*radius/duration;
     
     r.setOpacity((duration - t)/(double)duration);
     r.setTranslateX(Math.cos(angle)*d + width);
     r.setTranslateY(Math.sin(angle)*d + height);
    }
   }
  }.start();
 }



}
styled using hilite.me

download code

Friday 8 September 2017

JavaFx - TextField with placeholder

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  TextField searchBox = new TextField();

  Text text = new Text("   Search");
  text.setStyle("-fx-fill:gray");
  text.visibleProperty().bind(searchBox.focusedProperty().not().and(searchBox.textProperty().isEmpty()));
  
  StackPane pane = new StackPane(text, searchBox);
  searchBox.setStyle("-fx-background-color:transparent;-fx-border-color:lightgray;-fx-border-radius:2%;");
  pane.setStyle("-fx-background-color:white;");
  pane.setAlignment(Pos.CENTER_LEFT);

javafx - RANDOM_CODE_1

i'm using this code to extract property - values from JavaFx's default css(es).

and that will be used as my javafx css refrence.



 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
package extras;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.osbcp.cssparser.CSSParser;
import com.osbcp.cssparser.PropertyValue;

public class Toast {
    public static void main(String[] args) throws IOException, Exception  {

        Map<String, List<PropertyValue>> map = Stream.of(new File("folder containing css files").listFiles())
                .flatMap((File f) -> {
                    try {
                        return CSSParser.parse(new String(Files.readAllBytes(f.toPath()))).stream();
                    } catch (Exception e) {
                        System.out.println(f.getName()+"  "+e);
                    };
                    return Stream.empty();
                })
                .flatMap(r -> r.getPropertyValues().stream())
                .collect(Collectors.groupingBy(PropertyValue::getProperty));

        Map<String, TreeSet<String>> result = new HashMap<>();
        List<String> filterRegexes = new ArrayList<>();

        map.forEach((key, list) -> {
            TreeSet<String> list2 = 
                    list.stream()
                    .flatMap(p -> {
                        // split multi value values 
                        if(p.getValue().indexOf(')') < 0)
                            return Stream.of(p.getValue().split(","));

                        char[] chars = p.getValue().toCharArray();

                        ArrayList<String> str = new ArrayList<>();

                        int start = 0;
                        for (int end = 0; end < chars.length; end++) {
                            if(chars[end] == ',' && chars[end-1] != ')') {
                                boolean clean = true;
                                for (int k = start; k < end && clean; k++)
                                    clean = chars[k] != ')' && chars[k] != '(';

                                if(clean) {
                                    str.add(new String(chars, start, end - start));
                                    start = end + 1;
                                }
                            }
                        }
                        str.add(new String(chars, start, chars.length - start));

                        return str.stream();
                    })
                    .map(s -> s.replaceAll("\\s+", " ").trim())
                    .filter(s -> {
                        
                        //filter out similar looking values
                        
                        if(s.isEmpty())
                            return false;
                        
                        if(filterRegexes.stream().anyMatch(regex -> s.matches(regex)))
                            return false;
                        
                        String regex = s.replaceAll("\\d*\\.\\d+", Matcher.quoteReplacement("\\d*\\.\\d+"))
                                .replaceAll("\\d+", Matcher.quoteReplacement("\\d+"));
                        
                        filterRegexes.add(regex);
                        return true;
                        
                    })
                    .collect(Collectors.toCollection(TreeSet::new));

            result.put(key, list2);
        });
        
        System.out.println("DONE");
    }
}
styled using hilite.me

Thursday 7 September 2017

javafx - directional hover

(Inspired by)/(Copied from): https://codepen.io/manjitkarve/pen/Nvvjxv




  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
import java.util.Arrays;
import java.util.LinkedList;
import java.util.stream.Stream;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
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.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane grid = new GridPane();

        ObservableList<BackgroundFill> fills = FXCollections.observableList(new LinkedList<>());
        fills.addListener(new ListChangeListener<BackgroundFill>() {
            @Override
            public void onChanged(Change<? extends BackgroundFill> c) {
                grid.setBackground(new Background(c.getList().toArray(new BackgroundFill[0])));
            }
        });

        Label[] labels = Stream.iterate(1, i -> i + 1).limit(9)
                .map(i -> {
                    Label l = new Label(String.valueOf(i));
                    l.setMaxWidth(Double.MAX_VALUE);
                    l.setMaxHeight(Double.MAX_VALUE);
                    l.setAlignment(Pos.CENTER);

                    BackgroundFill fill;

                    if(i < 9) {
                        String pos = "to ";
                        if(i < 4) {
                            pos += "bottom ";
                            if(i == 1)
                                pos += "right ";
                            if(i == 3)
                                pos += "left ";
                        }
                        else if(i == 4)
                            pos += "right";
                        else if(i == 5)
                            pos += "left";
                        else {
                            pos += "top ";
                            if(i == 6)
                                pos += "right ";
                            if(i == 8)
                                pos += "left ";
                        }
                        fill = new BackgroundFill(Paint.valueOf("linear-gradient("+pos+", tomato 0%, transparent 70%)"), CornerRadii.EMPTY, Insets.EMPTY);
                    }
                    else 
                        fill = new BackgroundFill(Paint.valueOf("radial-gradient(center 50% 50%, radius 100%,  tomato 0%, transparent 110%)"), CornerRadii.EMPTY, Insets.EMPTY);

                    l.hoverProperty().addListener((pro, old, _new) -> {
                        if(_new)
                            fills.add(fill);
                        else
                            fills.remove(fill);
                    });

                    return l;
                }).toArray(Label[]::new);

        Label target = labels[8];
        target.setText("TARGET");

        grid.addRow(0, Arrays.copyOfRange(labels, 0, 3));
        grid.addRow(1, labels[3], target, labels[4]);
        grid.addRow(2, Arrays.copyOfRange(labels, 5, labels.length - 1));

        for (Label l : labels) {
            GridPane.setFillHeight(l, true);
            GridPane.setFillWidth(l, true);
            GridPane.setHgrow(l, Priority.ALWAYS);
            GridPane.setVgrow(l, Priority.ALWAYS);
            GridPane.setColumnSpan(l, 1);
            GridPane.setRowSpan(l, 1);
        };

        Scene scene = new Scene(grid, 300, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

styled using hilite.me



src download