问题描述
我编写了此代码,可以在JavaFX Canvas上进行绘制。 它可以正常工作,但我不知道如何重新绘制画布(例如在Swing中)以重新开始在新画布上绘画。 这是我的代码,非常感谢您的帮助! 马里奥
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楼
通过清除画布:
button.setOnAction(e ->
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()));