sdasdadas
sdasdadas

Reputation: 25096

How do I set a JTree to always display using its cell editors?

I have a JTree

JTree tree = new JTree();
tree.setCellRenderer(// ...);
tree.setCellEditor(// ...);
tree.setEditable(true);

that uses its cell renderer to display its cells; if the cells are clicked, then they use the cell editor to display. Is there a way I can only display using the cell editor?

  1. I have tried to just remove the renderer. This doesn't work because the JTree resorts to its default cell renderer.
  2. This is similar to this question, however, that question doesn't seem to contain an answer pertinent to my specific question.

Upvotes: 1

Views: 163

Answers (2)

RudolphEst
RudolphEst

Reputation: 1250

The problem with cell editors and renderers is that one GUI component is supposed to be re-used to draw every one of the elements in the list (renderer) and only a single line can be edited at a time (editor). If you break that single GUI component rule, Swing GUIs can behave awkwardly, slowly or even completely break.

In other words, using an editing component (like a dropdiwn) for the cell renderer you will run into problems, because the same JComboBox should be used for each of your list's elements. If you create a different renderer object for each tree element, you'll run into memory problems and other unusual behavior

If you really want to use a dropdown for the renderer, you can do it by implementing a TreeCellRenderer yourself that returns a unique JComboBox instance when public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) is called.

Upvotes: 0

JohnnyO
JohnnyO

Reputation: 3068

The easiest thing to do would be to create a TreeCellRenderer that returns the associated TreeCellEditor component.

Try something like this:

        tree.setCellRenderer(new TreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(
                JTree tree, Object value, 
                boolean selected, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            return tree.getCellEditor().getTreeCellEditorComponent(tree, value, 
                                                      selected, expanded, leaf, row);
        }

    });

Upvotes: 1

Related Questions