在JavaFX中的for循环中放置形状时出错



如果我只向Group scene2添加一个circle,程序执行良好。然而,当我将其添加到for-loop中时,第二阶段没有显示(错误(。我想设计应用程序的方式是,当用户在第一阶段按下按钮输入偶数时,第二阶段应该显示用户输入的圆圈数。

public static ArrayList<Integer> xaxis = new ArrayList<Integer>();
public static ArrayList<Integer> yaxis = new ArrayList<Integer>();
public static int x = 150, y = 200;
Scene scene, scene2;
@Override
public void start(Stage primaryStage) {
try {
Group root = new Group();
TextField text = new TextField();

Button button = new Button("Start");
button.setLayoutY(25);
root.getChildren().addAll(text,button);
scene = new Scene(root,400,200);

Group root2 = new Group();

button.setOnAction(e -> {
int a = Integer.parseInt(text.getText());
compute(a);
for(int i = 0; i < a; i++) {
root2.getChildren().add(getCircle(i));
}
scene2 =  new Scene(root2, 400, 400);
primaryStage.setScene(scene2);
});


primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}

我的计算方法和getCircle

public static void compute(int a) {
xaxis.add(x);
yaxis.add(y);
int b = a/2;

for(int i = 1; i < b; i++) {
x += 20;
xaxis.add(x);
yaxis.add(y);
}

y+=50;
x=140;

for(int i = 1; i < b; i++) {
x -= 20;
xaxis.add(x);
yaxis.add(y);
}

}
public Circle getCircle(int c) {
Circle circle = new Circle(xaxis.get(c), yaxis.get(c), 10);
return circle;
}

在java中,ArrayList中第一个元素的索引为零,而不是一。您需要更改方法compute()中的for循环。将您的compute()方法与下面的代码进行比较。

public static void compute(int a) {
xaxis.add(x);
yaxis.add(y);
int b = a/2;
for(int i = 0; i < b; i++) {
x += 20;
xaxis.add(x);
yaxis.add(y);
}
y+=50;
x=140;
for(int i = 0; i < b; i++) {
x -= 20;
xaxis.add(x);
yaxis.add(y);
}
}

EDIT
如果调试代码,您会发现由于for循环是从1(一(而不是0(零(开始的,因此xaxisyaxis包含的元素比所需的少一个。例如,如果在TextField中输入2(两(,则xaxisyaxis各包含一个元素。然后,在事件处理程序中,您尝试提取两个圆,但无法提取,因为xaxisyaxis只包含一个元素。因此,你得到的错误,即

线程中的异常"JavaFX应用程序线程";java.lang.IndexOutOfBoundsException:索引1超出长度1 的界限

在方法getCircle()中,您正在对ArrayList进行索引。

最新更新