Wednesday, March 7, 2012

JavaFX 2.0: Create Path dynamically



package javafx_path;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.stage.Stage;

/**
 *
 * @web java-buddy.blogspot.com
 */
public class JavaFX_Path extends Application {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        Group root = new Group();
        Scene scene = new Scene(root, 400, 300, Color.WHITE);
        
        
        final Path path = new Path();
        path.setStrokeWidth(1);
        path.setStroke(Color.BLACK);
        
        //Mouse button pressed - clear path and start from the current X, Y.
        scene.onMousePressedProperty().set(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                path.getElements().clear();
                path.getElements().add(new MoveTo(event.getX(), event.getY()));
            }
        });

        //Mouse dragged - add current point.
        scene.onMouseDraggedProperty().set(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                path.getElements().add(new LineTo(event.getX(), event.getY()));
            }
        });
                
        //Mouse button released,  finish path.
        scene.onMouseReleasedProperty().set(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {

            }
        });

        root.getChildren().add(path);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
}


No comments:

Post a Comment