在JavaFx 8 listview单元格中的自定义控件fxml
问题描述:
我有一个由几个Label控件组成的自定义控件:日期,标题,文本等。控件有fxml文件和控制器。我想用这个控件作为ListView的一个单元格。我创建了一个自定义的ListCell在JavaFx 8 listview单元格中的自定义控件fxml
public class NoteTextCell extends ListCell<Note>{
//....
protected void updateItem(Note note, boolean isEmpty){
if(isEmpty|| note == null){
//....
}
else {
FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/note.fxml"));
Node node = loader.load();
setGraphic(node);
}
}
}
但我不知道它是做正确的方式。我的应用程序中的ListView可能有成千上万的项目。在我对每个单元更新的理解中,它必须在创建图形节点之前加载fxml,进行解析和其他操作。有没有更好的方法来解决这个问题?
答
装入FXML每个单元一次,只是将其配置为您在updateItem(...)
方法需要:
public class NoteTextCell extends ListCell<Note>{
private final Node graphic ;
private final NoteController controller ;
public NoteTextCell() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/note.fxml"));
graphic = loader.load();
controller = loader.getController();
}
@Override
protected void updateItem(Note note, boolean isEmpty){
if(isEmpty|| note == null){
setGraphic(null);
}
else {
// configure based on note:
controller.setText(...);
controller.setXXX(...);
setGraphic(graphic);
}
}
}
在这里,我假设FXML文件声明控制器类NoteController
和你定义的方法其中您需要为特定的Note
配置UI。
这样,FXML仅为每个创建的单元格加载一次(不管列表中有多少项目,它可能不会超过20个),并且更新它的(相对有效的)方法是当用户滚动或单元格以其他方式重用时根据需要调用。