2015-04-06 45 views
-2

我發現之前尋找類似的問題,這些解決方案無助於回答我的問題。動態添加圈子到Arraylist

我已經通過使用數組解決了這個問題,但使用ArrayList會更好。我創建了一個事件,檢查左鍵單擊以創建一個圓對象並將其添加到列表中。問題是,當我使用這個代碼時,沒有一個圓圈被添加到arrayList中,並且它沒有給出編譯錯誤。你如何從ArrayList向面板添加圓圈?

public class test extends Application { 
     static int index = 0; 
     @Override 
     public void start(Stage primaryStage) throws Exception { 
     Pane = pane = new Pane(); 
     ArrayList<Circle> circles = new ArrayList<Circle>(); 

     pane.setOnMouseClicked(e -> { 

      if (e.getButton() == MouseButton.PRIMARY) { 

       circles.add(new Circle(e.getX(), e.getY(), 5)); 
       circles.get(index).setStroke(Color.BLACK); 
       circles.get(index).setFill(Color.WHITE); 
       index++; 

      } 
     }); 

     pane.getChildren().addAll(circles); 

     Scene scene = new Scene(pane, 400, 400); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 

} 
+0

你有沒有打過電話'pane.getChildren()中的addAll(圓圈);'。在事件處理程序中 – MadProgrammer

+0

爲什麼你認爲圓沒有被添加到'ArrayList'?它似乎添加了圓圈就好了。 –

+0

@James_D當我點擊時它沒有出現在窗格中。 – Sankofa

回答

2

只需添加圈內窗格,以及數組列表中,當你創建:

pane.setOnMouseClicked(e -> { 

    if (e.getButton() == MouseButton.PRIMARY) { 

     Circle circle = new Circle(e.getX(), e.getY(), 5) ; 
     circles.add(circle); 
     pane.getChildren().add(circle); 
     circle.setStroke(Color.BLACK); 
     circle.setFill(Color.WHITE); 

     // not sure what index is for. Looks like it would always be 
     // equal to circles.size() 
     index++; 

    } 
});