package test;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* @author fajar
*/
public class TestFollowMouse extends Application {
double width = 400;
double height = 400;
double startX;
double startY;
double endX;
double endY;
double toleransi;
boolean isRedraw = false;
GraphicsContext gc;
@Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
startX = 10;
startY = 10;
endX = 300;
endY = 20;
toleransi = 5;
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, (MouseEvent event) -> {
double x = event.getX();
double y = event.getY();
isRedraw = isAccessible(x, y);
});
canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, (MouseEvent event) -> {
processMouse(event.getX(), event.getY());
});
canvas.addEventHandler(MouseEvent.MOUSE_RELEASED, (MouseEvent event) -> {
isRedraw = false;
});
draw(gc);
root.getChildren().add(canvas);
primaryStage.setScene(new Scene(root, width, height));
primaryStage.show();
}
public void draw(GraphicsContext gc) {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, width);
gc.setStroke(Color.BLACK);
gc.strokeLine(startX, startY, endX, endY);
gc.setFill(Color.RED);
gc.fillOval(endX- toleransi/2, endY - toleransi/2, toleransi, toleransi);
}
public void processMouse(double x, double y) {
if (isRedraw) {
endX = x;
endY = y;
draw(gc);
}
}
boolean isAccessible(double x, double y) {
if (x <= (endX + toleransi) && x >= (endX - toleransi)) {
if (y <= (endY + toleransi) && y >= (endY - toleransi)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
launch(args);
}
}