Java Fx TreeTableView different Context Menu items

2.1k views Asked by At

I'm using TreeTableView , and I want to change the menu items that are associated to the context menu according to the data inside the selected row.

Suppose that I'm having a table with a structure like:


visitors


visitor 1

visitor 2

visitor 3

Chatters


chatter1

chatter2


Here in this table we can metaphorically say that we have two root nodes which are "Visitors" and "Chatters". Now, I want to have two context menus with different options. A context menu for visitors that we can say have one item which is "Invite to Chat" and another context menu that handles chatters and have different options like : "kick" , "ban" and so on. My problem is how can I achieve this scenario? Where should I use these context menus? Should I use them with cells, rows or the table?

1

There are 1 answers

3
James_D On BEST ANSWER

Use a custom row factory and configure the context menu in the updateItem(...) method.

Assuming you have a

TreeTableView<MyDataType> treeTable = ... ;

you would do something like

treeTable.setRowFactory(ttv -> {
    ContextMenu contextMenu = new ContextMenu();
    MenuItem inviteMenuItem = new MenuItem("Invite to Chat");
    // ...
    MenuItem banMenuItem = new MenuItem("Ban");
    // ...
    TreeTableRow<MyDataType> row = new TreeTableRow<MyDataType>() {
        @Override
        public void updateItem(MyDataType item, boolean empty) {
            super.updateItem(item, empty);
            if (empty) {
                setContextMenu(null);
            } else {
                // configure context menu with appropriate menu items, 
                // depending on value of item
                setContextMenu(contextMenu);
            }
        }
    };
    inviteMenuItem.setOnAction(evt -> {
        MyDataType item = row.getItem();
        // do something with item...
    });
    // event handlers for other menu items...
    return row ;
});

Caveat: this is not tested as you didn't provide an MCVE for me to test against, but it should give you the general idea. This will show the appropriate context menu for the row on which the user clicks (with the appropriate trigger for a context menu, e.g. right-click); this is independent of which item is selected.