Sunday, October 18, 2015

Illustrate JavaFX local coordinate system

Here is the code:

package sample;/**
 * Created by IDEA on 30/07/15.
 */

import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class TestCoordinates extends Application {
    private Pane root;
    private GridPane pane1;
    private GridPane pane2;
    private Rectangle r;
    private Line line;
    private Line xAxis1;
    private Line xAxis2;
    private Line xAxis3;
    private Line yAxis1;
    private Line yAxis2;
    private Line yAxis3;
    private Button btn;

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

    @Override
    public void init() {
        root = new Pane();
        pane1 = new GridPane();
        pane2 = new GridPane();
        pane1.setVgap(10);
        pane1.setHgap(10);
        // place holders
        pane1.add(new Label("PH"), 1, 1);
        pane1.add(new Label("PH"), 1, 2);
        pane1.add(new Label("PH"), 2, 1);
        pane1.add(pane2, 2, 2);
        r = new Rectangle(50, 50);
        r.setFill(Color.RED);
        pane2.add(r, 1, 1);
        line = new Line(0, 0, 50, 50);
        line.setStroke(Color.RED);
        pane2.add(line, 2, 2);
        btn = new Button("Draw axes");
        pane2.add(btn, 2, 3);
        xAxis1 = new Line(0, 0, 53, 0);
        yAxis1 = new Line(0, 0, 0, 53);
        root.getChildren().addAll(pane1, xAxis1, yAxis1);
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        btn.setOnAction(e -> drawAxes());
        primaryStage.show();
    }

    private void drawAxes() {
        Point2D origin2 = r.localToScene(0, 0);
        Point2D origin3 = line.localToScene(0, 0);
        root.getChildren().addAll(
          drawXAxis(origin2), drawYAxis(origin2),
          drawXAxis(origin3), drawYAxis(origin3)
        );
    }

    public Line drawXAxis(Point2D origin) {
        return new Line(origin.getX(), origin.getY(), origin.getX() + 53, origin.getY());
    }

    public Line drawYAxis(Point2D origin) {
        return new Line(origin.getX(), origin.getY(), origin.getX(), origin.getY() + 53);
    }
}

Click the button and you will see the local coordinate system appear.

0 comments: