I have a treeview in which the cells must display different information according to the real implementation of the TreeItem's value.
My domain model looks like:
It seemed natural to me to split the behaviour of "how to display a Task in a cell" or "how to display a Group in a cell" in two different classes.
public abstract class ComponentTreeCell<T extends Component> extends TreeCell<T>
{
@Override
protected void updateItem(T item, boolean empty)
{
//Some common logic...
}
}
public class GroupTreeCell extends ComponentTreeCell<Group>
{
@Override
protected void updateItem(Group item, boolean empty)
{
super.updateItem(item, empty);
//Some group-specific-logic
}
}
public class TaskTreeCell extends ComponentTreeCell<Task>
{
@Override
protected void updateItem(Task item, boolean empty)
{
super.updateItem(item, empty);
//Some task-specific-logic
}
}
The following controller class contains a TreeView where I set the CellFactory.
public class Controller implements Initializable
{
@FXML
private TreeView<Component> treeview;
@Override
public void initialize(URL url, ResourceBundle bundle)
{
treeview.setCellFactory(new Callback<TreeView<Component>, TreeCell<Component>>()
{
@Override
public TreeCell<Component> call(TreeView<Component> arg0)
{
if(/* stuck */ instanceof Group)
{
return new GroupTreeCell();
}
else if(/* stuck */ instanceof Task)
{
return new TaskTreeCell();
}
else
{
return new DefaultTreeCell();
}
}
});
}
}
But here I get stuck at the moment to decide which kind of cell I have to return. Indeed I only have in parameter the related TreeView and not the related TreeItem !
It seems to me like a kind of weakness of JavaFX. Why JavaFX gives the full TreeView to the user when you only need to retrieve one TreeCell ??
Is there a way to do it in this manner or do I have to implement the 2 different behaviour in the same custom TreeCell implementation ?
public class ComponentTreeCell extends TreeCell<Component>
{
@Override
protected void updateItem(Component item, boolean empty)
{
//Some common logic...
if(item instanceof Group)
{
//Group-specific logic...
}
else if(item instanceof Task)
{
//Task-specific logic...
}
else
{
//Default logic...
}
}
}