javafx - 清除javafx中的场景

标签 javafx javafx-8

我需要 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();

关于javafx - 清除javafx中的场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216396/

相关文章:

java - 如何使用java 10在maven中添加javafx依赖项

java - 将自定义 FXML 属性设置为自定义 javafx 组件的参数

java - 在 borderpane 中心加载新的 fxml

全屏时Javafx调整组件大小

java - Lombok javafx 属性

java - 在 TableView 中使用 PropertyValueFactory 中的值 - JavaFx

java - 在不使用按钮事件的情况下初始化 javafx 场景

3D 空间中的 JavaFX 2D 形状

滚动 Pane 内的 JavaFX 坐标

java - 是否可以将 JavaFX 的 PerspectiveTransform 与新的 Canvas 类一起使用?