Tree is extending TreeGrid, so it has basically the same data model. However since Tree has only one column, it is a bit more permissive. With TreeGrid you get easily in trouble with different properties of the objects, that are mutually incompatible.
With Tree you can use common abstract supertype as a workaround, something like this example:
@Route(value = "mixed-tree", layout = MainLayout.class)
public class MixedTree extends Div {
public MixedTree() {
setSizeFull();
Library library = new Library();
Tree<TreeObject> tree = new Tree<>(TreeObject::getName);
tree.setItems(library.getAuthors(), library::getBooks);
tree.setHeight(“500px”);
tree.setHtmlProvider(item -> {
String content = “”;
if (item instanceof Author) {
content = “Author: <b>” + item.getName() + “</b>”;
} else if (item instanceof Book) {
Book book = (Book) item;
content = “Book: <i>” + book.getName() + “</i><br>” + "pages: "
+ book.getPages();
}
return content;
});
add(tree);
}
public class Library {
List<Book> books = new ArrayList<>();
Random rand = new Random();
public Library() {
for (int i = 1; i < 5; i++) {
Author author = new Author();
author.setName("Author " + i);
for (int j = 1; j < 5; j++) {
Book book = new Book(rand.nextInt(100, 200), author);
book.setName("Book " + j);
books.add(book);
}
}
}
public List<TreeObject> getAuthors() {
return books.stream().map(book -> book.getAuthor()).distinct()
.collect(Collectors.toList());
}
public List<TreeObject> getBooks(TreeObject author) {
return books.stream()
.filter(book -> book.getAuthor().equals(author))
.collect(Collectors.toList());
}
}
public abstract class TreeObject {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Author extends TreeObject {
}
public class Book extends TreeObject {
private int pages;
private Author author;
public Book(int pages, Author author) {
setPages(pages);
setAuthor(author);
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
}