Reputation: 163
I wrote this code where it is possible to paint on a JavaFX Canvas. It works fine but I don't know how to repaint (like in Swing) the Canvas to start again painting on a new canvas. Here is my code and thanks a lot for your help! Mario
public class Main extends Application {
private static final int WIDTH = 600;
private static final int HEIGTH = 400;
@Override
public void start(Stage primaryStage) {
//handling the canvas
final Canvas canvas = new Canvas(WIDTH, HEIGTH);
final GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.AQUA);
gc.fill();
//Painting with MouseDragged Event
canvas.setOnMouseDragged(event -> gc.fillOval(event.getX(), event.getY(), 25, 25));
//User a ColorPicke for Color of Painting
ColorPicker cp = new ColorPicker();
cp.setOnAction(e -> gc.setFill(cp.getValue()));
//Layout
BorderPane root = new BorderPane();
HBox hb = new HBox(30);
Button button = new Button("Clear all");
button.setOnAction(e ->
/*how to repaint the canvas*/
System.out.println("How to repaint???"));
hb.getChildren().addAll(cp, button);
hb.setPrefHeight(200);
hb.setAlignment(Pos.CENTER);
root.setCenter(canvas);
root.setBottom(hb);
final Scene scene = new Scene(root);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 0
Views: 7822
Reputation: 3099
By clearing the canvas :
button.setOnAction(e ->
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()));
Upvotes: 2