We have done some of this when coding button actions on JavaFX
package com.paint;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import java.io.IOException;
/**
* JavaFX App
*/
public class App extends Application {
private static Scene scene;
public static void main(String[] args) {
launch();
}
public void drawDot(int x, int y, Group group) {
Circle circle = new Circle();
circle.setCenterX(x);
circle.setCenterY(y);
circle.setRadius(5);
group.getChildren().add(circle);
}
@Override
public void start(Stage stage) throws IOException {
stage.setTitle("My Window");
// set up the canvas
Group root = new Group();
drawDot(10, 10, root);
scene = new Scene(root, 640, 480);
stage.setScene(scene);
stage.show();
}
}
Scene
The class Scence
has a .addEventFilter()
method. The MouseEvent
class has a few events. Let’s use MOUSE_CLICKED
.
The second argument in the addEventFilter
is new EventHandler<MouseEvent>() {}
, an anonymous inner class.
Anonymous method with a concise syntax: (e) -> {}
scene.addEventFilter(MouseEvent.MOUSE_CLICKED, (mouseEvent) -> {
int x = (int) mouseEvent.getX();
int y = (int) mouseEvent.getY();
System.out.println(x + " " + y);
drawDot(x, y, root);
});
Add a MOUSE_DRAGGED
event handler
clear
buttonImplement clearGroup(Group)
Do not set global variables. Create a Brush
class instead with instance variables for color and size.