清除javafx中的场景

Clearing the scene in javafx

我需要 JavaFX 方面的帮助。我有一个程序可以在场景中用鼠标画线。当我按下清除按钮时,需要清除整个场景。但是这个程序只清除了最后绘制的线。

按下清除按钮时,应清除所有绘制的线条。现在,只有最后绘制的线被清除。

public class Test extends Application {

    private Line currentLine;
    private Group root;
    private ColorPicker colorPicker;
    private Button clearButton;
    private HBox buttons;
    private Scene scene;


    public void start(Stage primaryStage) {

        root = new Group();

        colorPicker = new ColorPicker(Color.WHITE);
        clearButton = new Button("Clear");
        clearButton.setOnAction(this::processActionButton);

        buttons = new HBox(colorPicker, clearButton);

        buttons.setSpacing(15);
        root.getChildren().addAll(buttons);

        scene = new Scene(root, 500, 300, Color.BLACK);
        scene.setOnMousePressed(this::processMousePress);
        scene.setOnMouseDragged(this::processMouseDrag);

        primaryStage.setTitle("Color Lines");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public void processMousePress(MouseEvent event) {
        currentLine = new Line(event.getX(), event.getY(), event.getX(),
                event.getY());
        currentLine.setStroke(colorPicker.getValue());
        currentLine.setStrokeWidth(3);
        root.getChildren().add(currentLine);
    }


    public void processMouseDrag(MouseEvent event) {
        currentLine.setEndX(event.getX());
        currentLine.setEndY(event.getY());

    }

    public void processActionButton(ActionEvent event) {

        root.getChildren().removeAll(currentLine);

    }

    public static void main(String[] args) {
        launch(args);
    }
}

您可以只为线路设置一个特殊组:

Group groupLines = new Group();

...

root.getChildren().add(groupLines);

向该组添加新行:

public void processMousePress(MouseEvent event) {
    ...
    groupLines.getChildren().add(currentLine);
}

并且只清理这组:

groupLines.getChildren().clear();