Example usage for javax.swing.tree TreePath toString

List of usage examples for javax.swing.tree TreePath toString

Introduction

In this page you can find the example usage for javax.swing.tree TreePath toString.

Prototype

public String toString() 

Source Link

Document

Returns a string that displays and identifies this object's properties.

Usage

From source file:Main.java

public static void main(String[] args) {
    JTree tree = new JTree();
    Enumeration en = ((DefaultMutableTreeNode) tree.getModel().getRoot()).preorderEnumeration();
    while (en.hasMoreElements()) {
        TreePath path = new TreePath(((DefaultMutableTreeNode) en.nextElement()).getPath());
        String text = path.toString();
        System.out.println(text);
    }/*  w  w  w . j a  va2  s .c o  m*/
}

From source file:MainClass.java

public MainClass() {
    final JTree tree;
    final JTextField jtf;

    DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

    DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
    top.add(a);/*from w  w  w . j a  v  a  2  s  . c om*/
    DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
    a.add(a1);
    DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
    a.add(a2);

    DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
    top.add(b);
    DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
    b.add(b1);
    DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
    b.add(b2);
    DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
    b.add(b3);

    tree = new JTree(top);

    JScrollPane jsp = new JScrollPane(tree);

    add(jsp, BorderLayout.CENTER);

    jtf = new JTextField("", 20);
    add(jtf, BorderLayout.SOUTH);

    tree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
            if (tp != null)
                jtf.setText(tp.toString());
            else
                jtf.setText("");
        }
    });

}

From source file:com.pironet.tda.AbstractDumpParser.java

/**
 * strip the dump string from a given path
 *
 * @param path the treepath to check//from   www  .  j  av a 2 s. c o m
 * @return dump string, if proper tree path, null otherwise.
 */
protected String getDumpStringFromTreePath(TreePath path) {
    String[] elems = path.toString().split(",");
    if (elems.length > 1) {
        return (elems[elems.length - 1].substring(0, elems[elems.length - 1].lastIndexOf(']')).trim());
    } else {
        return null;
    }
}

From source file:edu.mbl.jif.datasetconvert.CheckboxTreeDimensions.java

/**
 * Initialize the tree.//from w w  w. j a v a2 s  .co  m
 *
 */
private JScrollPane getCheckboxTree() {
    if (this.checkboxTree == null) {
        this.checkboxTree = new CheckboxTree(getDimensionsTreeModel(sumMD));
        //this.checkboxTree.addKeyListener(new RefreshListener());

        System.out.println(this.checkboxTree.toString());

        this.checkboxTree.getCheckingModel().setCheckingMode(TreeCheckingModel.CheckingMode.PROPAGATE);
        this.checkboxTree.setRootVisible(true);
        this.checkboxTree.setEnabled(true);
        this.checkboxTree.expandAll();

        DefaultMutableTreeNode mn = (DefaultMutableTreeNode) this.checkboxTree.getModel().getRoot();
        //         mn = (DefaultMutableTreeNode) mn.getChildAt(2);
        //         mn = (DefaultMutableTreeNode) mn.getChildAt(2);

        //         System.out.println("row number: " + this.checkboxTree.getRowForPath(new TreePath(mn.getPath())));

        this.checkboxTree.addCheckingPath(new TreePath(mn.getPath()));

        this.checkboxTree.addTreeCheckingListener(new TreeCheckingListener() {
            public void valueChanged(TreeCheckingEvent e) {
                System.out.println("checking set changed, leading path: "
                        + ((TreeNode) e.getPath().getLastPathComponent()).toString());
                System.out.println("checking roots: ");
                TreePath[] cr = CheckboxTreeDimensions.this.checkboxTree.getCheckingRoots();
                for (TreePath path : cr) {
                    System.out.println(path.getLastPathComponent());
                }
                System.out.println("\nPaths: ");
                TreePath[] cp = CheckboxTreeDimensions.this.checkboxTree.getCheckingPaths();
                for (TreePath path : cp) {
                    System.out.println(path.toString());
                }
            }
        });
    }
    return new JScrollPane(this.checkboxTree);
}

From source file:edu.mbl.jif.datasetconvert.CheckboxTreeDimensions.java

public void getSelectedIndices() {
    //      channels = new int[]{0, 1, 2, 3, 4, 5, 6};
    //      slices = new int[]{0};
    //      frames = new int[]{0, 2};
    //      positions = new int[]{0};

    List listChannels = new ArrayList();
    List listSlices = new ArrayList();
    List listFrames = new ArrayList();
    List listPositions = new ArrayList();

    // Check if root "All" selected, if so, not need to go further
    TreePath[] cr = CheckboxTreeDimensions.this.checkboxTree.getCheckingRoots();
    for (TreePath path : cr) {
        System.out.println(path.getLastPathComponent());
    }//  ww  w  . j a  v a  2 s. c o  m
    System.out.println("\nPaths: ");
    TreePath[] cp = CheckboxTreeDimensions.this.checkboxTree.getCheckingPaths();
    for (TreePath path : cp) {
        //Object[] pathObjs = path.getPath();
        System.out.println(path.toString());
        if (path.getPathCount() == 3) {
            DefaultMutableTreeNode nodeDim = (DefaultMutableTreeNode) path.getPathComponent(1);
            String dimension = (String) nodeDim.getUserObject();
            DefaultMutableTreeNode nodeIndex = (DefaultMutableTreeNode) path.getPathComponent(2);
            Object uo = nodeIndex.getUserObject();
            if (dimension.equalsIgnoreCase("Channel")) {
                String chan = (String) nodeIndex.getUserObject();
                listChannels.add(chan);
            }
            if (dimension.equalsIgnoreCase("Z-Section")) {
                int index = (Integer) nodeIndex.getUserObject();
                listSlices.add(index);
            }
            if (dimension.equalsIgnoreCase("TimePoint")) {
                int index = (Integer) nodeIndex.getUserObject();
                listFrames.add(index);
            }
            if (dimension.equalsIgnoreCase("Position")) {
                int index = (Integer) nodeIndex.getUserObject();
                listPositions.add(index);
            }
        }
    }
    // sort the list
    Collections.sort(listChannels);
    Collections.sort(listSlices);
    Collections.sort(listFrames);
    Collections.sort(listPositions);

    System.out.println("\nChannels: ");
    Iterator<Object> it = listChannels.iterator();
    while (it.hasNext()) {
        Object obj = it.next();
        System.out.print("  " + obj);
    }
    // Change list of channel names to an array of channel indices
    System.out.println("\nChannel Indices: ");
    Iterator<Object> itc = listChannels.iterator();
    channels = new int[listChannels.size()];
    int c = 0;
    while (itc.hasNext()) {
        Object obj = itc.next();
        String channelName = (String) obj;
        int index = indexOfChannel(channelNamesOriginal, channelName, 0);
        channels[c] = index;
        c++;
        System.out.print("  " + channelName + " ::: " + index);
    }

    //      String[] strArray = {"abcd", "abdc", "bcda"};
    //for (String s : strArray)
    //    if (s.startsWith(searchTerm))
    //        System.out.println(s);
    // Swap startsWith for contains you wish to simply look for containment.

    System.out.println("\nSlices: ");
    it = listSlices.iterator();
    slices = new int[listSlices.size()];
    c = 0;
    while (it.hasNext()) {
        Object obj = it.next();
        int index = (Integer) obj;
        slices[c] = index;
        c++;
        System.out.print("  " + obj);
    }

    System.out.println("\nFrames: ");
    it = listFrames.iterator();
    frames = new int[listFrames.size()];
    c = 0;
    while (it.hasNext()) {
        Object obj = it.next();
        int index = (Integer) obj;
        frames[c] = index;
        c++;
        System.out.print("  " + obj);
    }

    System.out.println("\nPositions: ");
    it = listPositions.iterator();
    positions = new int[listPositions.size()];
    c = 0;
    while (it.hasNext()) {
        Object obj = it.next();
        int index = (Integer) obj;
        positions[c] = index;
        c++;
        System.out.print("  " + obj);
    }

    if (channels.length < 1) {
        promptForNoChoice("Channel");
    }
    System.out.println(Arrays.toString(channels));
    System.out.println(Arrays.toString(slices));
    System.out.println(Arrays.toString(frames));
    System.out.println(Arrays.toString(positions));
    //CheckboxTreeExample_1.this.checkboxTree.;
}

From source file:com.openbravo.pos.admin.RolesViewTree.java

public String buildPermissionsStr() {
    TreePath[] treePaths = uTree.getCheckingPaths();
    hasPermissions = false;//from w  w  w. ja  v  a2s .c om
    sent = new StringBuilder();
    sent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    sent.append("\n<!-- File generated by new Admin console -->");
    sent.append("\n\n <permissions>");
    if (treePaths != null) {
        for (TreePath path : treePaths) {
            // we know any paths not 3 are not a leaf node        
            if (path.getPathCount() == 3) {
                sent.append("\n\t<class name=\"" + classMap.get(path.toString()) + "\"/>");
                hasPermissions = true;
            }
        }
    }
    sent.append("\n </permissions>");
    return (sent.toString());
}

From source file:net.pms.newgui.SelectRenderers.java

/**
 * Create the GUI and show it./*  w  ww  .j a  va 2  s .c om*/
 */
public void showDialog() {
    if (!init) {
        // Initial call
        build();
        init = true;
    }
    SrvTree.validate();
    // Refresh setting if modified
    selectedRenderers = configuration.getSelectedRenderers();
    TreePath root = new TreePath(allRenderers);
    if (selectedRenderers.isEmpty() || (selectedRenderers.size() == 1 && selectedRenderers.get(0) == null)) {
        checkTreeManager.getSelectionModel().clearSelection();
    } else if (selectedRenderers.size() == 1 && selectedRenderers.get(0).equals(allRenderersTreeName)) {
        checkTreeManager.getSelectionModel().setSelectionPath(root);
    } else {
        if (root.getLastPathComponent() instanceof SearchableMutableTreeNode) {
            SearchableMutableTreeNode rootNode = (SearchableMutableTreeNode) root.getLastPathComponent();
            SearchableMutableTreeNode node = null;
            List<TreePath> selectedRenderersPath = new ArrayList<>(selectedRenderers.size());
            for (String selectedRenderer : selectedRenderers) {
                try {
                    node = rootNode.findInBranch(selectedRenderer, true);
                } catch (IllegalChildException e) {
                }
                if (node != null) {
                    selectedRenderersPath.add(new TreePath(node.getPath()));
                }
            }
            checkTreeManager.getSelectionModel().setSelectionPaths(
                    selectedRenderersPath.toArray(new TreePath[selectedRenderersPath.size()]));
        } else {
            LOGGER.error("Illegal node class in SelectRenderers.showDialog(): {}",
                    root.getLastPathComponent().getClass().getSimpleName());
        }
    }

    int selectRenderers = JOptionPane.showOptionDialog((Component) PMS.get().getFrame(), this,
            Messages.getString("GeneralTab.5"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
            null, null);

    if (selectRenderers == JOptionPane.OK_OPTION) {
        TreePath[] selected = checkTreeManager.getSelectionModel().getSelectionPaths();
        if (selected.length == 0) {
            if (configuration.setSelectedRenderers("")) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        } else if (selected.length == 1
                && selected[0].getLastPathComponent() instanceof SearchableMutableTreeNode
                && ((SearchableMutableTreeNode) selected[0].getLastPathComponent()).getNodeName()
                        .equals(allRenderers.getNodeName())) {
            if (configuration.setSelectedRenderers(allRenderersTreeName)) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        } else {
            List<String> selectedRenderers = new ArrayList<>();
            for (TreePath path : selected) {
                String rendererName = "";
                if (path.getPathComponent(0).equals(allRenderers)) {
                    for (int i = 1; i < path.getPathCount(); i++) {
                        if (path.getPathComponent(i) instanceof SearchableMutableTreeNode) {
                            if (!rendererName.isEmpty()) {
                                rendererName += " ";
                            }
                            rendererName += ((SearchableMutableTreeNode) path.getPathComponent(i))
                                    .getNodeName();
                        } else {
                            LOGGER.error("Invalid tree node component class {}",
                                    path.getPathComponent(i).getClass().getSimpleName());
                        }
                    }
                    if (!rendererName.isEmpty()) {
                        selectedRenderers.add(rendererName);
                    }
                } else {
                    LOGGER.warn("Invalid renderer treepath encountered: {}", path.toString());
                }
            }
            if (configuration.setSelectedRenderers(selectedRenderers)) {
                PMS.get().getFrame().setReloadable(true); // notify the user to restart the server
            }
        }
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenterTest.java

@Test
public final void testFavourites() {
    LOG.debug("*************************************************************************");
    LOG.debug("testFavourites");
    LOG.debug("*************************************************************************");
    // Set it up/*from  w w  w . j  a v a2 s .co  m*/
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    DepositTreeModel fileSystemModel = (DepositTreeModel) theFrame.treeFileSystem.getModel();
    DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) fileSystemModel.getRoot();
    FSOCollection coll = FSOCollection.create();
    FileSystemObject fso = (FileSystemObject) rootNode.getUserObject();
    coll.add(fso);
    if (fso.getFile() == null) {
        LOG.debug("Root Object (file null): " + fso.getDescription());
    } else {
        try {
            LOG.debug("Root Object (file not null): " + fso.getFile().getCanonicalPath());
        } catch (Exception ex) {
        }
    }
    for (int i = 0; i < rootNode.getChildCount(); i++) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) rootNode.getChildAt(i);
        fso = (FileSystemObject) node.getUserObject();
        if (fso.getFile() == null) {
            LOG.debug("Child " + i + " (file null): " + fso.getDescription());
        } else {
            try {
                LOG.debug("Child " + i + " (file not null): " + fso.getFile().getCanonicalPath());
            } catch (Exception ex) {
            }
        }
    }
    File settingsPathFile = new File(RESOURCES_SETTINGS_PATH);
    File favouritesPathFile = new File(FAVOURITES_PATH);
    assertTrue(favouritesPathFile.exists());
    FileSystemObject child = null;
    // Make sure the tree includes the path
    String fullPath = "";
    try {
        fullPath = settingsPathFile.getCanonicalPath();
    } catch (Exception ex) {
        fail();
    }
    String[] paths;
    String fileSeparator = System.getProperty("file.separator");
    if (fileSeparator.equals("\\")) {
        fullPath = fullPath.replaceAll("/", fileSeparator);
        paths = fullPath.split("[\\\\]");
    } else {
        fullPath = fullPath.replaceAll("[\\\\]", fileSeparator);
        paths = fullPath.split(fileSeparator);
    }
    String currentPath = "";
    String rootPath = paths[0] + fileSeparator;
    LOG.debug("Full Path: " + fullPath);
    LOG.debug("Root Path: " + rootPath);
    for (int i = 0; i < paths.length; i++) {
        LOG.debug("Path " + i + ": " + paths[i]);
    }
    for (int i = 0; i < paths.length; i++) {
        currentPath += paths[i] + fileSeparator;
        LOG.debug("Current Path: " + currentPath);
        child = coll.getFSOByFullPath(currentPath, true);
        if (child == null) {
            LOG.debug("Child is null (not found)");
        } else {
            if (child.getFile() == null) {
                LOG.debug("Child found, file is null");
            } else {
                LOG.debug("Child found, path " + child.getFullPath());
            }
        }
        depositPresenter.selectNode(child, ETreeType.FileSystemTree);
        TreePath currentTreePath = theFrame.treeFileSystem.getSelectionPath();
        LOG.debug("currentTreePath: " + currentTreePath.toString());
        depositPresenter.expandFileSystemTree(currentTreePath);
    }

    // Test the favourites
    // No favourites loaded - check that the menu is empty
    TreePath[] treePaths = null;
    depositPresenter.clearFavourites();
    assertFalse(depositPresenter.canStoreFavourites(treePaths));
    treePaths = theFrame.treeFileSystem.getSelectionPaths();
    assertTrue(depositPresenter.canStoreFavourites(treePaths));
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) theFrame.treeFileSystem
            .getLastSelectedPathComponent();
    fso = (FileSystemObject) node.getUserObject();
    JPopupMenu menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 1);
    JMenuItem item = (JMenuItem) menu.getSubElements()[0];
    String noFavouritesText = item.getText();
    assertFalse(noFavouritesText.equals(fso.getFullPath()));

    // Store a favourite & check that it is included in the menu
    depositPresenter.storeAsFavourite(node);
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    // Reset the screen & then check that the favourite is included in the
    // menu
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    // Delete the storage file & make sure that there are no menu items
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
    try {
        setUp();
    } catch (Exception ex) {
        fail();
    }
    menu = (JPopupMenu) theFrame.mnuFileFavourites.getSubElements()[0];
    assertTrue(menu.getSubElements().length == 1);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(noFavouritesText));

    // Check clearing
    depositPresenter.storeAsFavourite(node);
    assertTrue(menu.getSubElements().length == 2);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(fso.getFullPath()));
    depositPresenter.clearFavourites();
    assertTrue(theFrame.mnuFileFavourites.getSubElements().length == 1);
    item = (JMenuItem) menu.getSubElements()[0];
    assertTrue(item.getText().equals(noFavouritesText));

    // Check loading a directory
    fileSystemModel = (DepositTreeModel) theFrame.treeFileSystem.getModel();
    rootNode = (DefaultMutableTreeNode) fileSystemModel.getRoot();
    coll = FSOCollection.create();
    coll.add((FileSystemObject) rootNode.getUserObject());
    currentPath = rootPath;
    depositPresenter.loadPath(currentPath);
    DefaultMutableTreeNode newNode = (DefaultMutableTreeNode) theFrame.treeFileSystem
            .getLastSelectedPathComponent();
    FileSystemObject fsoNew = (FileSystemObject) newNode.getUserObject();
    assertTrue(fsoNew.getFullPath().equals(currentPath));
    currentPath = fso.getFullPath();
    depositPresenter.loadPath(currentPath);
    newNode = (DefaultMutableTreeNode) theFrame.treeFileSystem.getLastSelectedPathComponent();
    fsoNew = (FileSystemObject) newNode.getUserObject();
    assertTrue(fsoNew.getFullPath().equals(fso.getFullPath()));
    FileUtils.deleteFileOrDirectoryRecursive(FAVOURITES_PATH);
}

From source file:org.kepler.gui.popups.LibraryPopupListener.java

/**
 * Description of the Method//from   ww w  . java 2 s . co  m
 * 
 *@param e
 *            Description of the Parameter
 */
private void maybeShowPopup(MouseEvent e) {
    if (isDebugging)
        log.debug("maybeShowPopup(" + e.toString() + ")");
    if (e.isPopupTrigger() || _trigger) {
        _trigger = false;
        TreePath selPath = _aptree.getPathForLocation(e.getX(), e.getY());
        if (isDebugging)
            log.debug(selPath.toString());
        if ((selPath != null)) {

            if (isDebugging)
                log.debug(selPath.getLastPathComponent().getClass().getName());

            if (_isPathInsideKAR(selPath)) {
                handlePopupInsideKar(selPath, e);
            } else {
                handlePopupOutsideKar(selPath, e);

            }
        }
        // handle double clicks
    } else if (e.getClickCount() == 2) {
        TreePath selPath = _aptree.getPathForLocation(e.getX(), e.getY());
        if (isDebugging)
            log.debug(selPath.toString());
        if ((selPath != null)) {

            if (isDebugging)
                log.debug(selPath.getLastPathComponent().getClass().getName());

            if (_isPathInsideKAR(selPath)) {
                handlePopupInsideKar(selPath, e);
            } else {
                handleDoubleClickOutsideKar(selPath, e);
            }
        }
    }
}

From source file:org.kepler.gui.popups.OutlinePopupListener.java

/**
 * Description of the Method//from  ww  w .  j  av a  2 s.co m
 * 
 *@param e
 *            Description of the Parameter
 */
private void maybeShowPopup(MouseEvent e) {
    if (isDebugging)
        log.debug("maybeShowPopup(" + e.toString() + ")");
    if (e.isPopupTrigger() || _trigger) {
        _trigger = false;
        TreePath selPath = _aptree.getPathForLocation(e.getX(), e.getY());
        if (isDebugging)
            log.debug(selPath.toString());
        if ((selPath != null)) {

            // determine if this object is contained within a KAR
            // by checking all of the parent objects to see
            // if they are a KAREntityLibrary
            // do not check the object itself
            boolean inKAR = false;
            Object ob = null;
            for (int i = (selPath.getPathCount() - 2); i >= 0; i--) {
                ob = selPath.getPathComponent(i);
                if (ob instanceof KAREntityLibrary) {
                    inKAR = true;
                    break;
                }
            }

            ob = selPath.getLastPathComponent();
            if (isDebugging)
                log.debug(ob.getClass().getName());

            if (!inKAR) {
                handlePopupOutsideKar(selPath, e);
            }
        }
    }
}