gpt4 book ai didi

java - 在 HashSet 迭代上动态创建 javafx 按钮。如何为每个按钮创建单独的actionEvent?

转载 作者:行者123 更新时间:2023-12-02 09:13:51 25 4
gpt4 key购买 nike

代码片段如下:

HashSet<String> listView = StringOperations.printListView(ReadPDFFile2.map2);

Iterator<String> it = listView.iterator();
while(it.hasNext()) {
i++;
String word = it.next();

Label lbl = new Label(word);
save = new Button("Save");
save.setId(word);
save.setOnAction(e ->{
System.out.println("clicked.. to save: "+ save.getId());
saveWords(save.getId());
});

root.getChildren().addAll(lbl, save);

}


public void saveWords(String word) {

if(fileType.equals("Word")) {

String s = word + ", "+ fileNameIV;
System.out.println("saving "+s+" in PDFHashSet for now");
savedDOCXWords.add(s);

}
else {
String s = word + ", "+ fileNameIV;
System.out.println("saving "+s+" in PDFHashSet for now");
savedPDFWords.add(s);
}
}

UI 上的输出如下:

enter image description here

这是正确的,但是当我单击这些按钮中的任何一个时,控制台中的输出如下:

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

clicked.. to save: cancelreaderthread
saving cancelreaderthread, in PDFHashSet for now

这意味着,它只记住最后创建的按钮。我们怎样才能让它单独记住所有按钮呢?

最佳答案

这是因为您正在覆盖对您的作用域的全局对象的相同引用。

save = new Button("Save");

将其更改为作用域中自己的引用,并删除此代码其余部分上方的该变量。

Button save = new Button("Save");

关于java - 在 HashSet 迭代上动态创建 javafx 按钮。如何为每个按钮创建单独的actionEvent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59167727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com