每当我在Rectangle中单击时,我想添加一个Sphere。基本上,我使用Rectangles.Attached制作了这个9X6网格是我的代码,我不知道在ActionEventHandler中添加什么。
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
如果我使用public void Settings(ActionEvent event) throws Exception
{
Stage primaryStage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/application/Settings.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
@FXML
ObservableList<Integer> comboList = FXCollections.observableArrayList(3,4,5,6,7,8);
ObservableList<String> gridList = FXCollections.observableArrayList("9 X 6","15 X 10");
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
combo.setItems(comboList);
gridb.setItems(gridList);
}
public void Grid() throws Exception {
Stage primaryStage=new Stage();
//AnchorPane root = new AnchorPane();
Group root = new Group();
Scene scene = new Scene(root);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
Rectangle r = null;
for(int i=0;i<9;i++) {
for(int j=0;j<6;j++) {
r = new Rectangle(70*j,70*i,70,70);
r.setStroke(Color.BLUE);
root.getChildren().add(r);
}
}
scene.setRoot(root);
primaryStage.show();
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
if(me.getButton().equals(MouseButton.PRIMARY)) {
Circle circle = new Circle(me.getX(), me.getY(), 10, Color.BLUE);
addEventHandler(root, circle);
root.getChildren().add(circle);
}
});}
private void addEventHandler(Group parent, Node node) {
// TODO Auto-generated method stub
node.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
if(me.getButton().equals(MouseButton.SECONDARY)) {
parent.getChildren().remove(node);
}
});
}
这段代码,那么即使在网格线上,我也可以随意添加Circles(或Spheres)。我只想为一个特定的矩形设置一个Sphere。
答案 0 :(得分:1)
您可以向个人Rectangle
添加事件处理程序,也可以使用pickResult
的{{1}}属性进行检查,如果点击了MouseEvent
:
Rectangle
public static Rectangle getIntersectedRect(MouseEvent event) {
Node n = event.getPickResult().getIntersectedNode();
return (n instanceof Rectangle) ? (Rectangle) n : null;
}