我需要在单击按钮时显示一些文本。已将按钮arraylist添加到vbox,在Platform.runLater()方法中调用vbox到gridpane和setOnAction,如图所示。 代码:
private ArrayList<Button> btnar;
private VBox vb;
private Button downloadbtn;
@FXML
private ScrollPane displayscroll;
private GridPane gridpane;
public HomeUI_2Controller() {
Platform.runLater(new Runnable() {
@Override
public void run() {
gridpane = new GridPane();
displayscroll.setContent(gridpane);
btnar = new ArrayList<>();
for (int i = 0; i < filelist2.size(); i++) {
downloadbtn = new Button("Download");
btnar.add(downloadbtn);
}
int imageCol = 0;
int imageRow = 0;
for (int i = 0; i < filelist2.size(); i++) {
System.out.println(filelist2.get(i).getName());
image = new Image(filelist2.get(i).toURI().toString());
pic = new ImageView();
pic.setFitWidth(130);
pic.setFitHeight(130);
pic.setImage(image);
vb = new VBox();
vb.getChildren().addAll(pic, (Button) btnar.get(i));
gridpane.add(vb, imageCol, imageRow);
GridPane.setMargin(pic, new Insets(2, 2, 2, 2));
imageCol++;
// To check if all the 3 images of a row are completed
if (imageCol > 2) {
// Reset Column
imageCol = 0;
// Next Row
imageRow++;
}
}
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
System.out.println("sssss");
}
});
}
});
}
答案 0 :(得分:1)
只有你的上一个&#34;下载&#34;按钮应该被触发。因为您只是将onAction事件处理程序添加到最后一个。
您在这里不需要Paltform.runLater()
。
如果只能循环一次,则不应构建相同的多循环。
尽量保持变量的范围尽可能窄。换句话说,不要定义全局变量,并将其作为占位符使用。这使得代码更容易出错并且难以维护。
测试这个重构的代码:
private ArrayList<Button> btnar;
private VBox vb;
@FXML
private ScrollPane displayscroll;
private GridPane gridpane;
public HomeUI_2Controller() {
gridpane = new GridPane();
displayscroll.setContent(gridpane);
btnar = new ArrayList<>();
int imageCol = 0;
int imageRow = 0;
for (int i = 0; i < filelist2.size(); i++) {
Button downloadbtn = new Button("Download");
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
System.out.println("You are requested to download the file " + filelist2.get(i).getName());
}
});
btnar.add(downloadbtn);
System.out.println(filelist2.get(i).getName());
image = new Image(filelist2.get(i).toURI().toString());
ImageView pic = new ImageView();
pic.setFitWidth(130);
pic.setFitHeight(130);
pic.setImage(image);
vb = new VBox();
vb.getChildren().addAll(pic, downloadbtn);
gridpane.add(vb, imageCol, imageRow);
GridPane.setMargin(pic, new Insets(2, 2, 2, 2));
imageCol++;
// To check if all the 3 images of a row are completed
if (imageCol > 2) {
// Reset Column
imageCol = 0;
// Next Row
imageRow++;
}
}
}