Skip to content

Instantly share code, notes, and snippets.

@skrb skrb/LambdaTest.java
Created May 23, 2012

Embed
What would you like to do?
Lambda equation sample with JavaFX
import java.util.Map;
import java.util.LinkedHashMap;
import static java.lang.Math.*;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class LambdaTest extends Application {
public static final class MyMath {
private MyMath() {}
public static int combination(int n, int m) {
int ans = 1;
for (int i = n; i > n - m; i--) {
ans *= i;
}
for (int i = m; i > 0; i--) {
ans /= i;
}
return ans;
}
}
public static class Bezier {
private int n;
private double y1, y2;
public Bezier(int n, double y1, double y2) {
this.n = n;
this.y1 = y1;
this.y2 = y2;
}
public double calc(double t) {
t = this.trim(t);
double a = t;
double b = 1 - t;
double result = 0;
for (int i = 0; i <= n; i++) {
double y = getY(i);
result += MyMath.combination(n, i) * pow(a, i) * pow(b, n - i) * y;
}
return result;
}
public double calc(double t, double max) {
return calc(t) * max;
}
private double trim(double t) {
return t > 1
? 1
: t < 0
? 0
: t;
}
protected double getY(int i) {
return i == 0
? 0
: i < n / 2
? y1
: i == n
? 1
: y2;
}
}
private Map<Bezier, Rectangle> lines = new LinkedHashMap<Bezier, Rectangle>() {
{
Rectangle rect = new Rectangle(0, 0, 0, 0);
rect.setFill(Color.rgb(65, 63, 158));
this.put(new Bezier(3, 0.8, 0.75), rect);
rect = new Rectangle(0, 0, 0, 0);
rect.setFill(Color.rgb(65, 156, 152));
this.put(new Bezier(3, 0.5, 0.5), rect);
rect = new Rectangle(0, 0, 0, 0);
rect.setFill(Color.WHITE);
this.put(new Bezier(3, 0.2, 0.25), rect);
}
};
private double t;
private Scene scene;
private Timeline timeline;
@Override
public void start(Stage stage) {
stage.setTitle("Lambda Test");
Group root = new Group();
scene = new Scene(root, 1000, 640);
scene.setFill(Color.BLACK);
lines.forEach(
(k, v) -> {
v.setHeight(scene.getHeight());
root.getChildren().add(v);
}
);
stage.setScene(scene);
stage.show();
timeline = new Timeline(
new KeyFrame(new Duration(50), e -> { this.paintBezier(); })
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
public void paintBezier() {
lines.forEach(
(k, v) -> {
v.setWidth(k.calc(t) * scene.getWidth());
}
);
t += 0.005;
if (t > 1.2) {
timeline.stop();
}
}
public static void main(String[] args) {
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.