Reputation: 1906
I am creating a product list screen where products are listed by their categories. I am sucessful in doing so and I have implemented a change listener which will print the selected tree item. But I only want to select the product not the categories. Here is my code that I have done so far.
Thing I want to know :- How to select only the product name from list and not the category name.
SessionFactory sessionFactory = null;
Session session = null;
TreeItem<String> CategoryrootItem = null;
TreeItem<String> dummyRoot = new TreeItem<>();
try {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
/*Select categories from database*/
List categoryList = session.createQuery("FROM Category").list();
for (Iterator iterator = categoryList.iterator(); iterator.hasNext();) {
Category category = (Category) iterator.next();
CategoryrootItem = new TreeItem<>(category.getCategory_Name());
Set productList = category.getProducts();
//access via new for-loop
for(Object object : productList) {
ProductHeader productHeader = (ProductHeader) object;
TreeItem<String> item = new TreeItem<>(productHeader.getProduct_Name());
CategoryrootItem.getChildren().add(item);
}
dummyRoot.getChildren().add(CategoryrootItem);
}
treeView.setRoot(dummyRoot);
treeView.setShowRoot(false);
session.getTransaction().commit();
} catch (Exception e) {
System.out
.println("populateSupplierList unable to create session : "
+ e.getMessage());
}
treeView.getSelectionModel().selectedItemProperty().addListener( new ChangeListener() {
public void changed(ObservableValue observable, Object oldValue,
Object newValue) {
TreeItem<String> selectedItem = (TreeItem<String>) newValue;
System.out.println("Selected Text : " + selectedItem.getValue());
}
});
The image gives the of the code. I want the product kaju
to be selected but not Dry fruits
category
Upvotes: 2
Views: 716
Reputation: 1906
I solved the problem through logical code. I searched whether a selected TableItem
has any children or not. If it has children items then it wont be selected, if it doesn't have child item, it will be selected.
Those TableItem
having child items is a category and those which doesn't have is a product.
Here is my code
TreeItem<String> selectedItem = (TreeItem<String>) newValue;
if(selectedItem.getChildren().isEmpty()){
System.out.println("Its a product");
}
else{
System.out.println("Its a category");
}
Upvotes: 2