所以,我正在开展一个小型夜校项目,我们正在“操纵”一个现有的圈子。通过单击按钮 4 (btn4),我需要向 StackPane 添加一些(数量并不重要)同心圆。 我将它们添加到列表中并试图使其工作,但我就是做不到。除了那个按钮之外,一切正常。
在 btn4 操作中:尝试将所有代码都放在 for 循环、foreach 中,但 add() 方法不接受 setFill ,因此我将 setOnAction() 之外的所有内容放入列表中
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
HBox hb1 = new HBox(20);
hb1.setAlignment(Pos.CENTER);
hb1.setStyle("-fx-background-color:darkgrey;");
Button btn1 = new Button("+");
Button btn2 = new Button("-");
Button btn3 = new Button("Change color");
Button btn4 = new Button("Add concentric circles");
hb1.getChildren().addAll(btn1, btn2, btn3, btn4);
StackPane sp = new StackPane();
sp.setStyle("-fx-background-color:lightblue;");
Circle circle = new Circle(75);
circle.setFill(RED);
sp.getChildren().add(circle);
BorderPane bp = new BorderPane();
bp.setBottom(hb1);
bp.setCenter(sp);
btn1.setOnAction(e -> {
circle.setRadius(circle.getRadius() + 10);
});
btn2.setOnAction(e -> {
circle.setRadius(circle.getRadius() - 10);
});
btn3.setOnAction(e -> {
circle.setFill(Color.color(Math.random(), Math.random(), Math.random(), 1));
});
ArrayList <Circle> moreCircles = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
new Circle(circle.getRadius() - (i * 5)).setFill(Color.color(Math.random(), Math.random(), Math.random(), 1));
}
btn4.setOnAction(e -> {
for(Circle c : moreCircles) {
sp.getChildren().add(c);
}
});
Scene scene = new Scene(bp, 500, 350);
primaryStage.setTitle("Game with circles");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我想让这些新的同心圆比现有的稍小一些。为了一次添加它们,我当然希望它们可见,所以我添加了一些颜色。
感谢@anthony yaghi为我解决了这个小问题
按钮操作需要如下所示,上面的数组可以进行一些删除:
btn4.setOnAction(e -> {
for (int i = 1; i <= 10; i++) {
sp.getChildren().add(new Circle(circle.getRadius() - (i*5), Color.color(Math.random(), Math.random(), Math.random(), 1)));
}
});
最佳答案
首先,创建数组列表之后的 for 循环是没有用的。您正在创建新的圆圈并且对它们不执行任何操作,我猜您正在尝试将其添加到列表中,但如果您查看可用的构造函数,则无法执行“new Circle(...)”然后 .setFill您可以看到有一个圆形对象采用半径和颜色进行填充,因此您可以这样做:
new Circle(circle.getRadius() - (i*5), Color.color(Math.random(), Math.random(), Math.random(), 1));
此外,如果您只想在当前圆内添加 n 个圆,而不关心稍后会发生什么(如果主圆变大或变小),那么您不需要将其添加到列表中并跟踪他们只需将它们直接添加到 StackPane 中即可。
/*
ArrayList<Circle> moreCircles = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
new Circle(circle.getRadius() - (i * 5)).setFill(Color.color(Math.random(), Math.random(), Math.random(), 1));
}
*/
btn4.setOnAction(e -> {
for (int i = 1; i <= 10; i++) {
sp.getChildren().add(new Circle(circle.getRadius() - (i*5), Color.color(Math.random(), Math.random(), Math.random(), 1)));
}
});
关于java - 将对象添加到列表并将这些列表对象添加到带有按钮的 Pane ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789457/