我尝试在每次释放鼠标时创建一个Path类型的新对象并将其添加到ArrayList中,以便我以后可以使用它来允许创建具有不同颜色的许多路径,这将有所帮助在创建撤消/重做。 但是在事件处理程序中向ArrayList添加新元素似乎无法正常工作。
import java.util.ArrayList;
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.stage.Stage;
public class Source extends Application {
public static ArrayList<Path> paths = new ArrayList<>();
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
for(int i=0; i<paths.size(); i++)
root.getChildren().add(paths.get(i));
stage.setScene(scene);
stage.show();
}
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
Path path = new Path();
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED){
path.getElements().add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
}
else if(mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED){
path.getElements().add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
if(mouseEvent.getEventType() == mouseEvent.MOUSE_RELEASED){
paths.add(path);
}
}
};
}
答案 0 :(得分:0)
尝试以下方法,
public class Source extends Application {
public static ArrayList<Path> paths = new ArrayList<>();
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
for(int i=0; i<paths.size(); i++)
root.getChildren().add(paths.get(i));
stage.setScene(scene);
stage.show();
}
Path path = new Path();
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED){
path.getElements().add(new MoveTo(mouseEvent.getX(), mouseEvent.getY()));
}
else if(mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED){
path.getElements().add(new LineTo(mouseEvent.getX(), mouseEvent.getY()));
}
if(mouseEvent.getEventType() == mouseEvent.MOUSE_RELEASED){
paths.add(path);
}
}
};
}
希望这有帮助!
答案 1 :(得分:0)
public class Source extends Application {
public static ArrayList<Path> paths = new ArrayList<>();
public void start(Stage stage) {
Pane root = new Pane();
Scene scene = new Scene(root, 300, 250);
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
Path path = new Path();
paths.add(path);
path.getElements().add(new MoveTo(event.getX(),event.getY()));
scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
path.getElements().add(new LineTo(event.getX(),event.getY()));
}
});
root.getChildren().add(path);
}
});
stage.setScene(scene);
stage.show();
}
}
我已经弄清楚了。 :)