0

我用 Listview 绑定了一个 observablelist 以在 listview 上执行我的任务。listview 和 observablelist 的类型是我在模型层中定义的模型。所以我使用单元工厂从我的模型对象中渲染图形节点。当用户在 textField 中输入文本时,我应该向 observablelist 添加一个项目。我的问题是当用户输入新文本并且我将项目添加到 observablelist 时,listview 中会出现一些额外的意外项目。但是如果我从事件处理程序中手动将一些项目添加到可观察列表中,则列表视图可以正常工作。我认为这是因为一些线程问题,但我无法解决它。

这是一个产生我的问题的简单示例:

FXMLDocumentController.java:

public class FXMLDocumentController implements Initializable {
@FXML
ListView<String> list;
ObservableList<String> ol;

@FXML
TextField text;

@Override
public void initialize(URL url, ResourceBundle rb) {
    ol = FXCollections.observableArrayList();
    list.setItems(ol);
    list.setCellFactory((ListView<String> param) -> {
        ListCell<String> lc = new ListCell<String>(){
            @Override
            protected void updateItem(String item, boolean empty){
                super.updateItem(item, empty);
                if(!empty){
                    System.out.println("HI");
                    Parent root = null;
                    try {
                        root = FXMLLoader.load(getClass().getResource("Entry.fxml"));
                    } catch (IOException ex) {
                    }
                    ((Label)(root.lookup("#label"))).setText(item);
                    setGraphic(root);
                }
            }
        };
        return lc;
    });
    text.setOnAction((ActionEvent event) -> {
        ol.add(text.getText());
        text.clear();
    });
}    
}

FXMLDoument.fxml:

<AnchorPane id="AnchorPane" prefHeight="511.0" prefWidth="420.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="testapp.FXMLDocumentController">
<children>
  <ListView fx:id="list" layoutX="68.0" layoutY="14.0" prefHeight="391.0" prefWidth="284.0" />
  <TextField fx:id="text" layoutX="110.0" layoutY="419.0" />
</children>
</AnchorPane>

入口.fxml:

<AnchorPane id="AnchorPane" prefHeight="50.0" prefWidth="250.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="label" layoutX="70.0" layoutY="18.0" prefHeight="15.0" prefWidth="178.0" AnchorPane.rightAnchor="49.0" />
</children>
</AnchorPane>

提前感谢

4

0 回答 0