I bound an observablelist with a Listview to perform my tasks on listview. type of listview and observablelist is a model that i defined in model layer.So i use cell factory to render a graphical node from my model objects. I should add an item to observablelist as user enter a text in a textField. My problem is when user enter a new text and i add items to observablelist some additional unexpectec items apear at listview. but if i add some items to observable list manualy out of event handler, list view works correctly. I think its because of some threading issues but i cant solve it.
here is a simple example that produce my problem:
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>
Entry.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>
Thanks in advances