我需要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);
}
}
答案 0 :(得分:1)
您可以只为行设置一个特殊组:
Group groupLines = new Group();
...
root.getChildren().add(groupLines);
在此群组中添加新行:
public void processMousePress(MouseEvent event) {
...
groupLines.getChildren().add(currentLine);
}
只清理这个群体:
groupLines.getChildren().clear();