gpt4 book ai didi

java - 在矩形网格内单击鼠标添加球体

转载 作者:行者123 更新时间:2023-12-02 12:01:38 25 4
gpt4 key购买 nike

每当我在矩形内单击时,我想添加一个球体。基本上,我使用矩形制作了这个 9X6 网格。附件是我的代码,我不知道要在 ActionEventHandler 中添加什么。

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);
}
});
}

如果我使用 scene.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) 这段代码,那么我可以在任何地方随机添加圆圈(或球体),甚至在网格线上单击。我只是想要为特定的矩形创建一个球体。

最佳答案

您可以将事件处理程序添加到各个 Rectangle 中,或者使用 MouseEventpickResult 属性来检查 >矩形被点击:

public static Rectangle getIntersectedRect(MouseEvent event) {
Node n = event.getPickResult().getIntersectedNode();
return (n instanceof Rectangle) ? (Rectangle) n : null;
}
scene.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
if(me.getButton().equals(MouseButton.PRIMARY)) {
Rectangle rect = getIntersectedRect(me);
if (rect != null) {
Circle circle = new Circle(rect.getX()+35, rect.getY()+35, 10, Color.BLUE);
addEventHandler(root, circle);
root.getChildren().add(circle);
}
}
});}

关于java - 在矩形网格内单击鼠标添加球体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47207893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com