[問題] Java fx 多個物件添加並點擊消除

看板java作者 (蒜蒜)時間3年前 (2020/06/18 01:26), 編輯推噓1(104)
留言5則, 3人參與, 3年前最新討論串1/1
※系統環境:NetBeans 8.2 ※狀況概述: 想要以for迴圈讓畫面出現30個circle,並以滑鼠點擊事件讓被點擊到的 消失,並且分數加一,最後得到分數。 但發現不能重複使用,想試著以陣列包起來再做添加,但反而無法做點擊 事件,也抓不到分數的值。 謝謝各位 ※程式碼: public class Test060511 extends Application { private int score = 0; @Override public void start(Stage primaryStage) { Group root = new Group(); Scene scene = new Scene(root, 800, 600); Text t = new Text(); for (int i = 0; i < 30; i++) { Circle circle=new Circle(15, Color.GOLD); circle.setCenterX(Math.random() * 800); circle.setCenterY(Math.random() * 600); root.getChildren().add(circle); circle.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { System.out.println("111"); root.getChildren().remove(circle); score++; t.setCache(true); t.setX(10.0); t.setY(30.0); t.setFill(Color.RED); t.setText("Score: " + score); t.setFont(Font.font(null, FontWeight.BOLD, 16)); root.getChildren().add(t); // System.out.println(score); } }); } primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } ※錯誤訊息: Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Children: duplicate children added: parent = Group@76bfa144[styleClass=root] ※補充說明: 新手上路請各位多包涵了._. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.214.183.185 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/java/M.1592414807.A.789.html

06/18 09:38, 3年前 , 1F
看error訊息說有重複加入同個child, circle看來每次都有new
06/18 09:38, 1F

06/18 09:39, 3年前 , 2F
所以推測是Text t在handle()中重複加入了.
06/18 09:39, 2F

06/18 09:51, 3年前 , 3F
是 text 重複 add 了沒錯, 剛改寫了一下,參考看看
06/18 09:51, 3F

06/18 09:51, 3年前 , 4F

06/18 12:20, 3年前 , 5F
超感謝救援!!!謝謝(,,・ω・,,)
06/18 12:20, 5F
文章代碼(AID): #1Uwb9NU9 (java)
文章代碼(AID): #1Uwb9NU9 (java)