看板 java 關於我們 聯絡資訊
※系統環境: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
LZN: 看error訊息說有重複加入同個child, circle看來每次都有new 06/18 09:38
LZN: 所以推測是Text t在handle()中重複加入了. 06/18 09:39
swallowcc: 是 text 重複 add 了沒錯, 剛改寫了一下,參考看看 06/18 09:51
swallowcc: https://pastebin.com/DRyJNi89 06/18 09:51
qq0802qq: 超感謝救援!!!謝謝(,,・ω・,,) 06/18 12:20