【发布时间】:2020-09-20 22:28:03
【问题描述】:
我想使用 java 在 lopp 中创建多个具有不同名称的按钮变量,我该怎么做才能自动获取此代码?
GridPane button_grid = new GridPane();
Button sound_button = new Button("Lire livre N°");
Button sound_button2 = new Button("Lire livre N°1");
Button sound_button3 = new Button("Lire livre N°2");
Button sound_button4 = new Button("Lire livre N°3");
Button sound_button5 = new Button("Lire livre N°4");
Button sound_button6 = new Button("Lire livre N°5");
Button sound_button7 = new Button("Lire livre N°6");
Button sound_button8 = new Button("Lire livre N°7");
Button sound_button9 = new Button("Lire livre N°8");
Button sound_button10 = new Button("Lire livre N°9");
button_grid.add(sound_button, 1,1);
button_grid.add(sound_button2, 2,1);
button_grid.add(sound_button3, 3,1);
button_grid.add(sound_button4, 4,1);
button_grid.add(sound_button5, 5,1);
button_grid.add(sound_button6, 6,1);
button_grid.add(sound_button7, 7,1);
button_grid.add(sound_button8, 8,1);
button_grid.add(sound_button9, 9,1);
button_grid.add(sound_button10,10,1);
我的目标是将一个 gridPane 插入一个 scrollPane 到一个 VBox 中,这是我的代码
public class controller {
ScrollPane scrollPane = new ScrollPane();
GridPane button_grid = new GridPane();
@FXML private VBox vbox;
public void initialize() {
Button sound_button = new Button("Lire livre N°1");
Button sound_button2 = new Button("Lire livre N°2");
button_grid.add(sound_button, 1,1);
button_grid.add(sound_button, 2,1);//<================the ERROR is Here
scrollPane.setContent(button_grid);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
vbox.getChildren().add(scrollPane);
}
不幸的是,我收到该代码错误:儿童:添加了重复的儿童。 正确执行此操作的唯一方法是使用不同的按钮变量名称 sound_button & sound_button2 等...插入 button_grid。 如何在循环中使用不同的按钮变量名?
最好的问候
【问题讨论】:
-
只需编写一个
for循环,它会创建一个新按钮并在每次迭代时将其添加到网格窗格中。至少表明你这样做的尝试。 -
int r; for (r = 1; r
-
将代码放在问题中,而不是在评论中。您不能动态更改变量的名称。这样做没有任何意义,因为一旦退出循环,变量就会超出范围,所以它们的名称完全不重要。为什么不在循环的每次迭代中使用相同的变量名?如果您以后需要访问它们(绝对没有理由这样做),请将它们放在列表或数组中。
标签: loops variables button javafx dynamic