0

I have a Treeview with menu content, which is working. I am just not sure how can I implement more root menu to add? Because this code only shows the "File" menu and all of submenus, but not the other roots.

-Also I would like to ask how could I make these submenus to act like links and create mouselisteners to them? Where is the right place to take the listeners?

The code is the following:

    TreeItem<String> treeItemRoot1 = new TreeItem<> ("File");
    TreeItem<String> treeItemRoot2 = new TreeItem<> ("Edit");
    TreeItem<String> treeItemRoot3 = new TreeItem<> ("View");
    TreeItem<String> treeItemRoot4 = new TreeItem<> ("Tools");
    TreeItem<String> treeItemRoot5 = new TreeItem<> ("Help");

    TreeItem<String> nodeItemA = new TreeItem<>("Item A");
    TreeItem<String> nodeItemB = new TreeItem<>("Item B");
    TreeItem<String> nodeItemC = new TreeItem<>("Item C");
    treeItemRoot1.getChildren().addAll(nodeItemA, nodeItemB, nodeItemC);


    TreeView<String> treeView = new TreeView<>(treeItemRoot1);

    StackPane.getChildren().add(treeView);
Mr.Fireman
  • 514
  • 1
  • 5
  • 16
  • 1
    Welcome to Stack Overflow. Your question as it stands is not very clear. Is "upload" really the word you mean here? Are you looking to create a menu bar, or a context menu? Please edit the question to clarify what you are looking to do. – James_D Mar 01 '15 at 15:09
  • Thank you James! I hope one day I'll be useful member of the page. I've edited as you mentioned, I hope now it is more understandable the way I composed the question! – Mr.Fireman Mar 01 '15 at 15:57

1 Answers1

1

The first part of your question is answered here: Set two root nodes for TreeView

For the second part, it depends on exactly what functionality you want. If you want to respond to a change in the selected item in the tree (this would include the user selecting either with the mouse or by using the keyboard), so can add a listener to the tree's selected item:

treeView.getSelectionModel().selectedItemProperty().addListener((obs, oldItem, newItem) -> {
    if (newItem == treeItemRoot1) {
        // "file" selected...
    } else if (newItem == treeItemRoot2) {
        // edit selected
    } // etc...
});

If you genuinely want a mouse listener, you need to add a listener to the cell. To do this, use a cell factory:

treeView.setCellFactory(tv -> {
    TreeCell<String> cell = new TreeCell<>();
    cell.textProperty().bind(cell.itemProperty());
    cell.setOnMousePressed(event -> {
        TreeItem<String> item = cell.getTreeItem();
        if (item == treeItemRoot1) {
            // "file" clicked...
        } else if (item == treeItemRoot2) {
            // etc...
        }
    }
    return cell ;
});

You can probably find ways to organize the code a little more cleanly, and avoid the big if-else construct in either case.

Community
  • 1
  • 1
James_D
  • 201,275
  • 16
  • 291
  • 322