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

代码段如下:

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上的输出如下:

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

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

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

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

这意味着,它仅记住最后创建的按钮。我们如何使它分别记住所有按钮?

wwwshilei 回答:在HashSet迭代中动态创建javafx按钮。如何为每个按钮创建单独的actionEvent?

这是因为您正在覆盖范围内对全局对象的相同引用。

save = new Button("Save");

在范围内将其更改为自己的引用,并删除此代码其余部分上方的变量。

Button save = new Button("Save");
本文链接:https://www.f2er.com/2981404.html

大家都在问