JTree, always display all nodes in “edit mode”

2019-07-15 13:14发布

问题:

I'm displaying a tree of custom objects, and I've got custom custom CellTreeEditor and CellTreeRenderer set.

Now what I really want is to always display all objects as in "edit mode". Right now I have the CellTreeRenderer.getTreeCellRendererComponent() and CellTreeEditor.getTreeCellEditorComponent() implemented almost identically. This kind of works, but I still have to click a node to focus it before I can do any editing.

Is there any more sensible way of doing this, perhaps like saying no renderer should never be used, defaulting to my CellTreeEditor?

******UPDATE****

To clearify: What I have is a tree looking like this (and yes, it also looks like crap, but that's beside the point):

Right now, I accomplish this by having a renderer and an editor that returns identical components from getTreeCell[Renderer|Editor]Component().

If I click on the down-arrow on the ComboBox supplied by the renderer, it will flicker slighty as it opens the dropdown, but then be interrupted and replaced by my editor component. This means I have to click it again to open the dropdown. This is the behaviour I want to avoid.

回答1:

Expanding my comment: no, you don't want to have your editor shared across cells (nasty thingies start to happen) Instead, add a TreeCellListener which listens for changes in the lead (aka: focused) selection path and then explicitly start editing on that path

    final JXTree tree = new JXTree();
    tree.setEditable(true);
    tree.expandAll();
    TreeSelectionListener l = new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            final TreePath path = e.getNewLeadSelectionPath();
            if (path != null) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        tree.startEditingAtPath(path);
                    }
                });
            }
        }

    };
    tree.addTreeSelectionListener(l);

The trick to really make it work is the usual: wrap the custom reaction into an invokeLater to be sure the tree's internal update is complete



标签: java swing jtree