JavaFX Canvas - 绘画后如何重绘画布?

时间:2015-07-18 06:12:29

标签: java swing canvas javafx

我编写了这段代码,可以在JavaFX Canvas上绘画。它工作正常,但我不知道如何重新绘制(如在Swing中)Canvas重新开始在新画布上绘画。 这是我的代码,非常感谢您的帮助! 马里奥

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);
  }
}

1 个答案:

答案 0 :(得分:1)

清除画布:

button.setOnAction(e ->
    gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()));
相关问题