Return names of selected items from a checkboxTree

Asked

Viewed 119 times

1

How can I check which items are selected from a checkboxTree ?

I have already searched and I know that this code returns the last selected:

DefaultMutableTreeNode node = (DefaultMutableTreeNode) checkboxTree1.getLastSelectedPathComponent();

Is there any way to know the nodes names of the selected checkboxes?

inserir a descrição da imagem aqui

In this case something that returns me "Colors, blue , red".

1 answer

1

The node has a method getUserObject that returns the object referring to the current node (e.g., if you fed the tree with the string "red" just convert the Object for a String):

String color = (String) node.getUserObject();

To search all selected paths you can use:

TreePath[] paths = checkboxTree1.getSelectionPaths();

In turn each TreePath also has the method getLastPathComponent():

if (paths != null) {
    for (TreePath path : paths) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        System.out.println(node.getUserObject());
    }
}

If you also want relatives (I do not know if this is the case) can still use the method getPath that returns a Object[] with all elements from the root.

  • When referring to all selected paths, you are referring to the selected items ?

  • Path implies everything (from the root). For example, the path of "blue" would be JTree -> colors -> blue, the lastPathComponentthat way would be blue.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.