Editing in a JTree

Hi!
I would to edit on a JTree but my program doesn't work properly, the problem is that I don't know how many clicks I need to catch and assign a new name to the selected node. What I would like to do is with a double click to change the name of this node. I have also a pb with the track that I am exploring: the compiler jdk1.3 doesn't recognize CellEditor. If someone has already have this pb or can help me, thank you by advance.
Maheva

IconeNodeModification nodeModification = new IconeNodeModification();
tree.setCellEditor(nodeModification);
public class IconeNodeModification extends DefaultCellEditor {
public boolean isCellEditable(EventObject evt) {
if (evt instanceof MouseEvent) {
MouseEvent e = (MouseEvent)evt;
int cpt = e.getClickCount();
if (cpt == 2) {
return true
return false;
}

Similar Messages

  • JTREE request edit mode for one node

    hello,
    my jtree is editable
    tree.setEditable(true); // double click on a node and it goes in "edit mode"
    I would like to set a specific node into "edit mode" (just like when you create a new folder in windows - new folder appears in edit mode - you just have to type the name of the folder)
    //set the node selected
    setSelectionPath(new TreePath(newfolder.getPath()));
    // set the node in edit mode - does not exist ???
    setEdit((new TreePath(newfolder.getPath())); ????
    Second question:
    how can I avoid a specific node from being editable ?
    // set all the nodes editable !!
    tree.setEditable(true);
    thanks a lot !

    polo777 wrote:
    I would like to set a specific node into "edit mode" (just like when you create a new folder in windows - new folder appears in edit mode - you just have to type the name of the folder)[JTree.startEditingAtPath|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTree.html#startEditingAtPath(javax.swing.tree.TreePath)].
    how can I avoid a specific node from being editable ?Override [JTree.isPathEditable|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JTree.html#isPathEditable(javax.swing.tree.TreePath)].

  • Dynamic update of text from JTree manipulation

    Hi I working on an application that uses both a JTree and text view at the same time.
    What I want to do is everytime a node is added/edited/removed from the JTree the text for that node is dynamically updated in the tree view.
    At the moment what I do is everytime something is edited in the JTree the whole text is re-written. This is causing the program to slow down for large files.
    What I have thought of doing is producing the text for only the edited node, however this may affect others node, for example if a child node is added the parent node needs a closing tag.
    Is there anyway I could possibly do this?
    An alternative I had thought of was, because it is the syntax highlighting that is taking the time. I thought I could produce the full text for the edited tree then compare it to the pre-editted text. Then only sytax highlight the difference and add it to the text view. Would this be possible?
    Cheers Alex

    On 04 Apr 2007 in macromedia.dreamweaver.appdev, DrBlanston
    wrote:
    > I am trying to figure out a way to update certain fields
    on my ASP
    > pages based on input from different fields. For
    instance, I am
    > writing a program with an SQL 2005 database underneath.
    This
    > program takes data from fields that the user will input
    and needs to
    > update another field with a calculated result, then
    update the
    > database.
    >
    > Example,
    >
    > TaxRateField * SquareFootage = BilledAmount
    > (where all three of these fields are in the table)
    >
    > When a new record page is there for the end user, I want
    them to be
    > able to select a rate code (which has a
    factor/multiplyer associated
    > with it), then enter the Square footage, and have the
    > BilledAmount field automatically calculated. So when
    they hit the
    > submit button, all three values are inserted into the
    database.
    >
    > Any suggestions?
    Just enter the rate and the square footage; do the
    calculation when you
    pull the data from the database. In general, you don't want
    information stored in a database which depends on other
    information (ie
    calculated fields). The prime example is calculating an age
    when you
    get Date of Birth information.
    Joe Makowiec
    http://makowiec.net/
    Email:
    http://makowiec.net/contact.php

  • JTree ignores the return value from shouldYieldFocus

    I have a JTree component with my own custom DefaultTreeCellEditor which in turn uses my custom JTextField as an editor.
    I have attached the InputVerifier to the JFieldText and when user is editing node my code inside shouldYieldFocus method of InputVerifier that returns false if the node text does not match my criteria.
    I have noticed that when I click on any other JTree node (different then what I am editing now) the JTree removes my JTextField editor despite of the �false� value that I return from shouldYieldFocus.
    How can I force JTree to stay in editor until the text entered passes my validation criteria?
    Thanks in advance.
    JD

    store return value in tag class property and then use bean:setProperty, bean:getProperty.

  • JTree's

    I was wondering how to make ONLY the parent nodes editable and the leaf nodes not editable in a JTree.
    e.g. Imaging a list of courses where each course has a list of students.
    I would like to be able to edit the course names but not the student names.
    Any ideas?
    I have tried overriding setPathEditable(TreePath path), but this does not seem to work.

    Look at this - it should help.
    http://forum.java.sun.com/thread.jspa?tstart=0&forumID=57&threadID=190140&trange=15
    rykk

  • How to add a TreeNode using a path?

    When I doing my project, I get stuck on a portion of my GUI Coding.
    My code provide a path such as
    /Home/fsloke
    /Home/fsloke/directory1
    /Home/WorkHard
    /Home/WorkSmart
    /Home/WorkSmart/Dreamincode
    Currently my tree constructed as below:
    Home
    + fsloke
    ---+directory1
    + WorkHard
    + WorkSmart
    ---+ Dreamincode
    May I know how can I add a childNode called "TryHard" under WorkHard?
    Generally the path give is "/Home/WorkHard/TryHard".
    Don't worried I will split it to
    TreeNode Head ="Home"
    parentPath ="/Home/WorkHard";
    childNode name = "TryHard";
    Any clue?
    I search in net. All give me the solution when the user click on the tree Node. Then the code use , getSelectedPath() function.
    In my case my user not click on the Tree...
    Any advise and direction...
    Thanx...
    I like the DynamicTreeDemo coding from this website http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

    you can use this method:
    addChildTo("WorkHard","TryHard");
    public void addChildTo(String parentObject, String child){
             TreePath parentPath = getTreePath(parentObject);
             if(parentPath != null){
                 DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
                 treeModel.insertNodeInto(new DefaultMutableTreeNode(child), parent, parent.getChildCount());
    private TreePath getTreePath(String userObject) {
             java.util.Enumeration nodes = ( (DefaultMutableTreeNode) treeModel.getRoot()).
             preorderEnumeration();
             while (nodes.hasMoreElements()) {
                  DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement();
                  if (node.getUserObject().equals(userObject)){
                       return new TreePath(node.getPath());
             return null;
    }if you are using new DefaultMutableTreeNode("WorkHard"); , then the object name(WorkHard) should be unique , otherwise create node with your own object. Or alter the method what ever you need..
    edit:
    creation of jtree like
    DefaultMutableTreeNode top =
                new DefaultMutableTreeNode("The Java Series");
            createNodes(top);
            treeModel = new DefaultTreeModel(top);
            tree = new JTree(treeModel);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);ref:http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TreeDemoProject/src/components/TreeDemo.java
    Edited by: david_david on Mar 19, 2008 10:15 AM

  • TreeCellEditor using a JFileChooser

    Hey,
    I have a problem with a JTree. In my tree I'd like some nodes to be editable
    (others not) in a way, that if someone tripple-clicks the cells, a JFileChooser pops up. I implemented it like, the cell editor starts a JFileChooser and returns a JTextField containing the filepath resulting from the JFileChooser.
    My problem is, that I always have to confirm the JTextField again after I already chose the file via JFileChooser. I'd like the JTextField to simply accept the file and stop any editing process on that cell. Unfortunately a call to stopCellEditing() - even tree.stopEditing() didn't work. Is there a possibility to have the JTextField confirmed or is there another way to use the JFileChooser for cell editing in a JTree?
    The TreeCellEditor is derrived from DefaultTreeCellEditor. LeafFileChooser extends Node, my class for nodes. My problem mainly is in this method:
    class TestSettingsCellEditor extends DefaultTreeCellEditor {
         private JTextField tf;
         private String szFcTermination;
         private Component comSelected;
         public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
              cancelCellEditing();
              Node node = (Node) value;
              if(node instanceof LeafComboBox){
              }else if(node instanceof LeafFileChooser){
                   JFileChooser fc = FileIO.getFileChooser(".xml");
                   tf = new JTextField(20);
                   tf.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             stopCellEditing();
                   File file = fc.getSelectedFile();
                   if((file == null)
                             || (!file.getAbsolutePath().endsWith(".xml"))
                             || (!file.exists())){
                        tf.setText("N/A");
                   }else{
                        tf.setText(file.getAbsolutePath());
                   this.stopCellEditing();  // XXX
    // XXX doesn't work - the cell displays a JTextField that needs additionally be confirmed!?
                   this.comSelected = tf;
                   return tf;
              return null;          
         public Object getCellEditorValue() {
              if(comSelected.equals(this.box)){
              }else if(comSelected.equals(this.tf)){
                   return tf.getText();
              return null;
         public boolean isCellEditable(EventObject anEvent) {
              if(anEvent instanceof MouseEvent){
                   return (((MouseEvent)anEvent).getClickCount() > 2);
              }else{
                   return true; // XXX actually, should this be false?
    // in the tree model (extends TreeModel) the value will be accepted as follows:
         public void valueForPathChanged(TreePath path, Object newValue) {
              Node node = (Node) path.getLastPathComponent();
              if(node instanceof LeafComboBox){
              }else if(node instanceof LeafFileChooser){
                   String sz = newValue.toString();
                   node.setContent(sz);
              }

    hi
    i seem to be having a problem opening the selected file using the following code.
    the selected file needs to be opened on a new frame.
    please help.
    if (cmd.equals("Open.."))
                                       fc.addChoosableFileFilter(new ImageFilter());
         int returnVal = fc.showOpenDialog(Proj.this);
         // Determine which button was clicked to close the dialog
         switch ( returnVal) {
         case JFileChooser.APPROVE_OPTION:
              {                              File fl = fc.getSelectedFile();
              //String file =("test.gif");
              ImageIcon icon = new ImageIcon(f1);
              JLabel label = new JLabel();
              label.setIcon( new ImageIcon(icon) );
              Frame1 frame = new Frame1(TITLE,drawPanel);          frame.setVisible(true);
              deskTop.add(frame);
              drawPanel.add(label);
         // Approve (Open or Save) was clicked
    break;
         case JFileChooser.CANCEL_OPTION:
    // Cancel or the close-dialog icon was clicked
    break;
    // case JFileChooser.ERROR_OPTION:
    // The selection process did not complete successfully
    // break;
                             }

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • Problem with JTree custom renderer when editing

    I have a JTree which uses a custom renderer to display my own icons for different types of nodes. The problem I am having is when I setEditable to true and then attept to edit a node the icon switches back to the default icon, as soon as I am done editing it goes back.
    What I am doing wrong?

    Here is my rendererer
    public class DeviceTreeRenderer extends DefaultTreeCellRenderer implements GuiConstants {
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
          JLabel returnValue = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
          if (value != null) {
             returnValue.setToolTipText(value.toString());
          if (value instanceof Device) {
             returnValue.setIcon(TREE_DEVICE);
             if (!((Device)value).isAlive()) {
                returnValue.setEnabled(false);
          else if (value instanceof GuiPanelGroup) {
             if (expanded) {
                returnValue.setIcon(TREE_PANEL_GROUP_OPEN);
             else {
                returnValue.setIcon(TREE_PANEL_GROUP_CLOSED);
          else if (value instanceof GuiPanel && ((GuiPanel)value).isDirty()) {
             returnValue.setIcon(TREE_PANEL_DIRTY);
          return returnValue;
    }Here is my editor:
    public class WwpJTreeCellEditor extends DefaultTreeCellEditor implements GuiConstants {
          private WwpJTree tree;
           * Creates a new WwpJTreeCellEditor.
           * @param tree The WwpJTree to associate with this editor.
          public WwpJTreeCellEditor(WwpJTree tree) {
             super(tree, (DefaultTreeCellRenderer)tree.getCellRenderer());
             this.tree = tree;
           * Overrides the default isCellEditable so that we check the isEditable() method
           * of the WwpJTreeNodes.
           * @param e An EventObject.
          public boolean isCellEditable(EventObject e) {
             boolean returnValue = super.isCellEditable(e);
             if (returnValue) {
                WwpJTreeNode node = this.tree.getSelectedNode();
                if (node == null || !node.isEditable() || node.isDragging()) {
                   returnValue = false;
             return returnValue;
       }In my JTree I make these calls:
    super.setCellRenderer(new DeviceTreeRenderer());
    super.setCellEditor(new WwpJTreeCellEditor(this));
    super.setEditable(true);

  • Icon was changed to default icon when editting a node on JTree

    I have a tree with icon on nodes. However, when I edit the node, the icon is changed to default icon.
    I don't known how to write the treeCellEditor to fix that one.
    The following is my code:
    package description.ui;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.ToolTipManager;
    import javax.swing.WindowConstants;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class Tree extends javax.swing.JPanel {
         private JTree tree;
         private JScrollPane jScrollPane1;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              frame.getContentPane().add(new Tree());
              frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
              frame.pack();
              frame.show();
         public Tree() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   BorderLayout thisLayout = new BorderLayout();
                   this.setLayout(thisLayout);
                   setPreferredSize(new Dimension(400, 300));
                    jScrollPane1 = new JScrollPane();
                    this.add(jScrollPane1, BorderLayout.CENTER);
                        DefaultMutableTreeNode rootNode = createNode();
                        tree = new JTree(rootNode);
                        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                        jScrollPane1.setViewportView(tree);
                        ToolTipManager.sharedInstance().registerComponent(tree);
                        MyCellRenderer cellRenderer = new MyCellRenderer();
                        tree.setCellRenderer(cellRenderer);
                        tree.setEditable(true);
                        tree.setCellEditor(new DefaultTreeCellEditor(tree, cellRenderer));
                        //tree.setCellEditor(new MyCellEditor(tree, cellRenderer));
              } catch (Exception e) {
                   e.printStackTrace();
         private void btRemoveActionPerformed(ActionEvent evt) {
             TreePath path = tree.getSelectionPath();
             DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
             ((DefaultTreeModel)tree.getModel()).removeNodeFromParent(selectedNode);
         private DefaultMutableTreeNode createNode() {
             DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Doc");
             DefaultMutableTreeNode ch1 = createChuongNode(rootNode, "Ch1");
             DefaultMutableTreeNode ch2 = createChuongNode(rootNode, "Ch2");
             createTextLeafNode(ch1, "title");
             return rootNode;
         private DefaultMutableTreeNode createChuongNode(DefaultMutableTreeNode parent, String name) {
             DefaultMutableTreeNode node = new DefaultMutableTreeNode(new ChapterNodeData(name));
             parent.add(node);
             return node;
         private DefaultMutableTreeNode createTextLeafNode(DefaultMutableTreeNode parent, String name) {
             DefaultMutableTreeNode node = new DefaultMutableTreeNode(new TitleNodeData(name));
             parent.add(node);
             return node;
          private class MyCellRenderer extends DefaultTreeCellRenderer {
                 ImageIcon titleIcon;
                 ImageIcon chapterIcon;
                 public MyCellRenderer() {
                     titleIcon = new ImageIcon(getClass().getClassLoader()
                            .getResource("description/ui/icons/Text16.gif"));
                     chapterIcon = new ImageIcon(getClass().getClassLoader()
                            .getResource("description/ui/icons/Element16.gif"));
                 public Component getTreeCellRendererComponent(
                                     JTree tree,
                                     Object value,
                                     boolean sel,
                                     boolean expanded,
                                     boolean leaf,
                                     int row,
                                     boolean hasFocus) {
                     super.getTreeCellRendererComponent(
                                     tree, value, sel,
                                     expanded, leaf, row,
                                     hasFocus);
                     if (isChapterNode(value)) {
                         setIcon(chapterIcon);
                         setToolTipText("chapter");
                     } else if (isTextLeafNode(value)) {
                         setIcon(titleIcon);
                         setToolTipText("title");
                     return this;
                 protected boolean isChapterNode(Object node) {
                     return ((DefaultMutableTreeNode)node).getUserObject() instanceof ChapterNodeData;
                 protected boolean isTextLeafNode(Object node) {
                     return ((DefaultMutableTreeNode)node).getUserObject() instanceof TitleNodeData;
          private class MyCellEditor extends DefaultTreeCellEditor {
                 ImageIcon titleIcon;
                 ImageIcon chapterIcon;
              public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
                  super(tree, renderer);
                  titleIcon = new ImageIcon(getClass().getClassLoader()
                         .getResource("description/ui/icons/Text16.gif"));
                  titleIcon = new ImageIcon(getClass().getClassLoader()
                         .getResource("description/ui/icons/Element16.gif"));
              public Component getTreeCellEditorComponent(
                           JTree tree,
                           Object value,
                           boolean isSelected,
                           boolean expanded,
                           boolean leaf,
                           int row) {
                  super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                  return this.editingComponent;
          abstract class NodeData{
              String name;
              public NodeData(String name) {
                  this.name = name;
              public String getName() {
                  return name;
              public void setName(String name) {
                  this.name = name;
              public String toString() {
                  return name;
          class ChapterNodeData extends NodeData {
              public ChapterNodeData(String s) {
                  super(s);
          class TitleNodeData extends NodeData {
              public TitleNodeData(String attr) {
                  super(attr);
    }

    Arungeeth wrote:
    I know the name of the node... but i cant able to find that nodeHere is some sample code for searching and selecting a node:
        TreeModel model = jtemp.getModel();
        if (model != null) {
            Object root = model.getRoot();
            search(model, root, "Peter");//search for the name 'Peter'
            System.out.println(jtemp.getSelectionPath().getLastPathComponent());
        } else {
            System.out.println("Tree is empty.");
    private void search(TreeModel model, Object o, String argSearch) {
        int cc;
        cc = model.getChildCount(o);
        for (int i = 0; i < cc; i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode) model.getChild(o, i);
            if (model.isLeaf(child)) {
                TreeNode[] ar = child.getPath();
                String currentValue = Arrays.toString(ar);
                if (currentValue.contains(argSearch)) {
                    jtemp.setSelectionPath(new TreePath(ar));
            } else {
                search(model, child, argSearch);
    }

  • Selectively editing nodes in a JTree

    I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

    Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
    So tell us which methods you found to be likely candidates.
    db

  • Is there possible to edit JTree cell but not by double click?

    Hi,
    I looked for few hours to solve that problem but couldnt find a good solution. I have JTree component a simple model, when I click on some button I would like to add a new item to my model and immidiately display editor in JTree's cell when new item was added to enter its custom unique name. Does an one know how to fire edit mode for cell?
    thanx and regards
    Adam

    The discussion in this thread from last week should get you started.
    [How can I add a node with with a user-chosen name to JTree in one action|http://forums.sun.com/thread.jspa?threadID=5325551]
    db

  • JTree: How to make few nodes editable

    I have a JTree which displays some complex expression.
    I want to make few nodes of the JTree editable and specify JCombobox as an editor. How can I do this?
    Any help or pointer?
    Thanks in advance
    Sachin

    I want to make few nodes of the JTree editablei'm not sure how you can do this - there is JTree.setPathEditable(boolean) but this means you'd have to subclass JTree ?
    you might be able to make a cell editor that returns some value to indicate a particular cell isn't editable, or failing that return a read-only component but I've not tried this..
    and specify JCombobox as an editor.this may help:
    http://www.cs.cf.ac.uk/Dave/HCI/HCI_Handout_CALLER/node156.html
    asjf

  • How to do SelectAll() when during JTree node edit?

    This question's been asked a few times but the answers haven't been very clear ( or the code that was posted was broken, etc. )
    I have a JTree -- when the user edits a node, I want to initially select all the text in the .that node.
    Does anyone have a SIMPLE, COMPLETE extension of a DefaultTreeCellEditor which does this? If so, please post. -- No fancy bells or whistles.
    Thanks much.

    ...well, there is a very easy, but not clean way to do it:
             * Configures the editor.  Passed onto the <code>realEditor</code>.
            public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
                DefaultTreeCellEditor.EditorContainer comp= (EditorContainer) super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                JTextField textField= (JTextField) comp.getComponent(0);
                textField.setSelectionStart(0);
                textField.setSelectionEnd(textField.getText().length());
                return comp;
            }This will work if you click the node twice and wait to call the editor, however most users will start editing a TreeNode by clicking multiplely on the node - as the Editor is a normal TextField, it will lose it's selection when being clicked upon. If this is a problem for you, just overwrite DefaultTreeCellEditor.DefaultTextField's processMouseEvent(MouseEvent) method and decide whether the click should remove the selection or not.
    I guess if you ask for a piece of code which will keep the text selected you have something special in mind to do with the editor, so sample code wouldn't do you much good here. Get back to me if you have trouble intercepting the mouse event.

  • JTree stop cell editing on lost focus and scrollPathToVIsible behavior

    how can you make a Jtree that uses a DefaultTreeCellEditor stop editing when it loses focus to a component other than the
    cell editor's DefaultTextField component ?
    i had to use a custom TreeCellEditor and attach my focus listener to the DefaultTextField object and attach it also to the JTree object
              DefaultTreeCellEditor celEditor = new DefaultTreeCellEditor(containerTree,renderer)
                   @Override
                   public Component getTreeCellEditorComponent(JTree tree, Object value,
                                     boolean isSelected,
                             boolean expanded,
                             boolean leaf, int row) {
                        Component comp = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
                        boolean found= false;
                        for(FocusListener f:editingComponent.getFocusListeners())
                             if(focusListener.equals(f))
                                  found=true;
                                  break;
                        if(!found)
                             editingComponent.addFocusListener(focusListener);
                        return comp;
    myTree.addFocusListener(focusListener);in JTable there's a property that you switch on/off which does exactly that, is there anything alike for JTree ?
    one more thing,after adding a new TreeNode to the JTree,i'm calling scrollPathToVisible(<path to the new node>),but for all the nodes i add except the first, the user object is not displayed,am i missing something? here's my code
              ActionListener actionListener = new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        DefaultTreeModel model = (DefaultTreeModel)containerTree.getModel();
                        int nodeCount=containerTree.getModel().getChildCount(root);
                        if(ae.getSource().equals(menuAdd))
                             DefaultMutableTreeNode newNode=new DefaultMutableTreeNode();
                             if(currentNode>0 && currentNode+1<nodeCount)
                                  model.insertNodeInto(newNode, root, currentNode+1);
                                  newNode.setUserObject("container #"+(currentNode+1));
                             else
                                  model.insertNodeInto(newNode, root, root.getChildCount());
                                  newNode.setUserObject("container #"+nodeCount);
                             TreePath path = new TreePath(newNode.getPath());
                                            // only works properly for 1st node,for the rest i have to
                                            // click on the new node to get the proper display
                             containerTree.scrollPathToVisible(path);
                        else if(nodeCount>=0 && currentNode!=0)
                             model.removeNodeFromParent((DefaultMutableTreeNode)model.getChild(root, currentNode-1));
              };

    i solved the second issue by selecting the new node and starting to edit it

Maybe you are looking for

  • How to change draw dashed line with arrowhead (not straight)?

    Hi friends, The following code sinept draws an arrowed line from a given point to the other point. I want to know how it can changed to be dashed line as well? I would appreciate it if anybody help me for doing such changes. Thanks in advance, Reza_m

  • Will apple replace my ipod touch since the headphone jack no longer works properly?

    It is still under warranty and there was no damage to it from anyone. The headphone jack is faulty and it is a hardware problem not user damage

  • Unable to see my bills online for 2 months now

    Hi I had BT broadband, Vision and a new phoneline installed back in September. When I placed the order online I chose online billing (which I am now massively regretting!) Since everything was succesfully installed I have been unable to see my online

  • Viewing gallery on older Mac

    My brother and sister-in-law have an older iMac, probably running an earlier version of OS X and iPhoto. We published a web gallery of some of our photos, but they were having trouble accessing it. Are there system requirements for viewing the photo

  • Mac Pro 3,1 (Early 2008, 10.6) Slow startup, no chime

    Hello all. Purchased this one from a friend of mine bc my own Mac Pro (we both bought them at the same time, back in Feb., 2008) had issues with video card and bad memory sticks. So this Mac Pro was his, he barely used it and since i want to continue