TextField in JTree

Hi,
I'm using a treeCellEditor to edit a jtree with textfields. It's works but I don't know how to make the cursor disappear in the textfield when I type on ENTER :
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent evt) {
if (evt.getKeyChar() == '\n') {
System.out.println("enter typed on the textfield");
// I make the action I want
// I'd like to make the cell editing stop
--> I don't know what to do <--
Thanks

I thougth JTree provides a textfield for cell editing by default when you call jTree.setEditable(true) ???
The default cell editor disappears when you type enter. So you might have read away the ENTER key with e.consume() in some KeyListener for jTree.
Besides, to catch the ENTER key you must write
if (e.getKeyCode() == KeyEvent.VK_ENTER) ...

Similar Messages

  • How to add a name to Jtree froma textfield

    HiAll
    I havea Jtree f_viewtree
    I have a dialog box which contains a textfield and gets a name of group to be added in the Jtree and also a add button. when the add button is clicked
    the name should added it to the Jtree.
    I know there s method called setText(text)
    String text = grouptext.getText();
    f_viewTree.setText(text);
    does anybody knows how this works????????

    I would suggest tha you read the tutorial section on handling trees, in particular on the relationship between JTree and its TreeModel.That makes 2 of us. I already gave the OP that advice 1 week ago when the same question was asked:
    http://forum.java.sun.com/thread.jspa?threadID=5299814
    To the OP, quit multi-posting and wasting our time. You have not made any effort to post your SSCCE showing what you are attempting to do. We have no idea what your problem is. The code from the tutorial shows you how to do this. The code we post would not be any different.

  • How to set Jtree Nodes' name into TextField??

    Dear Sir:
    I have following code to select any file's name then put into TextField,
    see:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    public class JTreeSplitChooseDemo extends JPanel implements ActionListener{
        JFileChooser fc;
        JButton openButton, saveButton;
        JTextField jtf;
      public JTreeSplitChooseDemo() {
        final JTree tree;
        final JTextField jtf;
        JPanel jp= new JPanel();
        setPreferredSize(new Dimension(500,350));
        jp.setPreferredSize(new Dimension(500,300));
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
        DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
        top.add(a);
        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);
        jsp.setPreferredSize(new Dimension(500,300));
        tree.setPreferredSize(new Dimension(500,300));
        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("");
      public JPanel JTreeText() {
             JPanel jp= new JPanel();
             JPanel jpanel= new JPanel();
             setPreferredSize(new Dimension(400,350));
             jp.setPreferredSize(new Dimension(400,300));
             JScrollPane jsp = new JScrollPane(jp);
             jsp.setPreferredSize(new Dimension(400,300));
             jpanel.add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             fc = new JFileChooser();
             openButton = new JButton("Open a File...",new ImageIcon("images/hui.gif"));
             openButton.addActionListener(this);
             JPanel buttonPanel = new JPanel(); //use FlowLayout
             buttonPanel.add(openButton);
             //jp.add(buttonPanel, BorderLayout.PAGE_START);
             jp.add(buttonPanel, BorderLayout.NORTH);
             jp.add(jtf, BorderLayout.CENTER);
             return jpanel;
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JTreeSplitChooseDemo(), new BorderLayout().WEST);
        frame.getContentPane().add(new JTreeSplitChooseDemo().JTreeText(), new BorderLayout().CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 350);
        frame.setVisible(true);
    @Override
    public void actionPerformed(ActionEvent e) {
         //Handle open button action.
        if (e.getSource() == openButton) {
          int returnVal = fc.showOpenDialog(JTreeSplitChooseDemo.this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
             jtf.setText(file.getName());
          } else {
             jtf.add("Open command cancelled by user.", null);
    }For example, If i choose file : C:\temp\ftp\TestMyFile.txt
    after I press open button, then choose it, then, the file name TestMyFile.txt will be displayed in the textFiled.
    My problem is that I hope to choose any node in the JTree on the left Panel, then when I choose it, this JNode I selected will be displayed its name in the TextField.
    Not file, I need choose JNode,
    ie, B1 under B node, or A1 under A node, then B1 will be displayed in jtf.
    How to do this one??
    Can Guru throw some light??
    Thanks
    sunny

    Thanks, camickr.
    My fault not to explain detail.
    Actually I mean that I will use a dialog box(very much look like a file choose) that is something like a file chooser then I can browse over JTree first for any node then I can choose or select a node in this JTree, after select this node, its name is populated into text field. My one is I will use a JTree browser (something like that) to get a tree node.
    ie, this showOpenDialog will browse over JTree, not File system.
    I did not want to click on the node then this node name is populated into textField.
    the sample (http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html) shows that when I select a node, then its name was populated to a destination.

  • How to rename node in JTree?(URGENT)

    Hi,all:
    I am facing a renaming problem in JTree. After I rename, the node still remain the old name, Could anybody tell me why and how to solve it?
    The piece of code is as follow:
    JTextField textField = new JTextField();
    newDndTree.setCellEditor(new MyCellEditor(newDndTree,textField));
    newDndTree.setEditable(true);
    class MyCellEditor extends DefaultCellEditor {
    private JTree tree;
    public MyCellEditor(JTree tree, JTextField text) {
    super(text);
    this.tree = tree;
    public boolean isCellEditable(EventObject e) {
    boolean rv = false; // return value
    if(e instanceof MouseEvent) {
    MouseEvent me = (MouseEvent)e;
    if(me.getClickCount() == 3) {
    TreePath path =
    tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) // root node
    return false;
    DefaultMutableTreeNode node =
    (DefaultMutableTreeNode) path.getLastPathComponent();
    Object hitObject=path.getLastPathComponent();
    if(hitObject instanceof TreeNode)
    return (((TreeNode)hitObject).isLeaf());
    return (false);

    Hi,all:
    My problem is it doesn't rename the node, the node remain the old name.
    My piece of code as follow:
    //Set Cell Editor
    newDndTree.setCellEditor(new MyCellEditor());
    //inner class MyCellEditor
    class MyCellEditor extends DefaultCellEditor {   
    public MyCellEditor() {     
    super(new JTextField());
    public boolean isCellEditable(EventObject e) {     
    if(e instanceof MouseEvent) {     
    MouseEvent me = (MouseEvent)e;     
    if(me.getClickCount() == 3) {      
    JTree tree = (JTree)me.getSource();     
    TreePath path = tree.getPathForLocation(me.getX(), me.getY());     
    if(path.getPathCount() == 1) {        
    //System.out.println("Root");     
    return false; // root node     
    DefaultMutableTreeNode node =     
    (DefaultMutableTreeNode) path.getLastPathComponent();     
    Object hitObject=path.getLastPathComponent();     
    if(hitObject instanceof TreeNode) {        
    TreeNode t = (TreeNode)hitObject;     
    boolean b = t.isLeaf();     
    if (b) {          
    //System.out.println("Leaf");     
    return (((TreeNode)hitObject).isLeaf());     
    //else System.out.println("Not Leaf");     
    // System.out.println("Exit");
    return false;
    }

  • 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.

  • Similar to JTree

    Hi!
    I need your expertise advice for this problem.
    I am trying to write something which has the same concept as JTree.
    But instead of showing the child nodes names only i want to show the contents under the link.
    But i am not sure how to write that. Any advice?
    e.g
    +XYZ Company Ltd
    +Macdonalds'
    -ABC Company
    Name: <TextField>
    Address:<textfield>
    Email:<email>
    +Techie Pte Ltd
    +123Happy Ltd

    This is an extension to what StanislavL did. It's ugly as...a bad habit...but shows what to do:
    --A
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class TreeNodeEx {
        JScrollPane scroll;
        JTree tree;
        public TreeNodeEx()  throws Exception {
            final JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyModel2TreeAdapter oAdapter = new MyModel2TreeAdapter(new MyModel());
            tree = new JTree(oAdapter);
            tree.setRootVisible(false);
            tree.setShowsRootHandles(true);
            tree.setCellRenderer(new MyCellRenderer());
            scroll = new JScrollPane(tree);
            frame.getContentPane().add(scroll);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) throws Exception {
            new TreeNodeEx();
    class MyCellRenderer implements TreeCellRenderer {
        LineBorder m_oLineBorder = new LineBorder(Color.gray);
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                      boolean sel,
                                                      boolean expanded,
                                                      boolean leaf, int row,
                                                      boolean hasFocus) {
            if (leaf) {
                JPanel p = new JPanel(new GridLayout(3, 2));
                p.setOpaque(false);
                p.setBorder(m_oLineBorder);
                p.add(new JLabel("Name:"));
                p.add(new JTextField(((MyNode.MyNodeEx)value).Name));
                p.add(new JLabel("Address:"));
                p.add(new JTextField(((MyNode.MyNodeEx)value).Address));
                p.add(new JLabel("email:"));
                p.add(new JTextField(((MyNode.MyNodeEx)value).Email));
                return p;
            return new JLabel(value.toString());
    Custom data model.
    class MyModel {
        ArrayList nodes;
        public MyModel() {
            nodes = new ArrayList();
            nodes.add(new MyNode("Apple", "One Infinite Loop", "[email protected]"));
            nodes.add(new MyNode("Microsoft", "One Microsoft Way", "[email protected]"));
            nodes.add(new MyNode("Sun", "Someplace Cupertino", "[email protected]"));
    class MyNode {
        MyNodeEx nodeEx;
        public MyNode(String Name, String Address, String Email) {
            nodeEx = new MyNodeEx(Name, Address, Email);
        class MyNodeEx {
            String Name, Address, Email;
            public MyNodeEx(String Name, String Address, String Email) {
                this.Name = Name;
                this.Address = Address;
                this.Email = Email;
        public String toString() {
            return nodeEx.Name;
    This class "adapts" our custom data model to
    something JTree can use.
    class MyModel2TreeAdapter implements TreeModel {
        MyModel model;
        public MyModel2TreeAdapter(MyModel model) {
            setRoot(model);
        public void setRoot(MyModel model) {
            this.model = model;
        public Object getChild(Object parent, int index) {
            return (parent instanceof MyNode) ? ((MyNode)parent).nodeEx :
                (parent instanceof MyNode.MyNodeEx) ? null : model.nodes.get(index);
        public int getChildCount(Object parent)  {
            return (parent instanceof MyNode) ? 1 :
                (parent instanceof MyNode.MyNodeEx) ? 0 : model.nodes.size();
        public int getIndexOfChild(Object parent, Object child) {
            return (parent instanceof MyNode) ? 0 :
                (parent instanceof MyNode.MyNodeEx) ? -1 : model.nodes.indexOf(child);
        public Object getRoot() {
            return model;
        public boolean isLeaf(Object node) {
            return (node instanceof MyNode.MyNodeEx);
        public void addTreeModelListener(TreeModelListener l) {
        public void removeTreeModelListener(TreeModelListener l) {
        public void valueForPathChanged(TreePath path, Object newValue) {
    }

  • Jtree startEditingAtPath cannot work

    I want my JTree to be always automatically goes into editing mode everytime a node is selected. I have add a treeselectionlistener that will initiate startEditingAtPath everytime the tree selection changed. However, the celleditor just won't show.
    Here is my code:
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.LinkedList;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class MyTreePane extends JScrollPane implements TreeSelectionListener{
         private JTree tree;
         private DefaultTreeModel treeModel;
         private DefaultMutableTreeNode rootNode;
        public MyTreePane() {
            super();
            setPreferredSize(new Dimension(950,330));
            setMinimumSize(new Dimension(950,330));
            setSize(new Dimension(950,330));
            revalidate();
            rootNode = new DefaultMutableTreeNode("Root");
            treeModel = new DefaultTreeModel(rootNode);
            tree = new JTree(treeModel);
            tree.setBackground(Color.lightGray);
            MyCellRenderer renderer = new MyCellRenderer();
             tree.setCellRenderer(renderer);
             tree.setCellEditor(new MyCellEditor(tree,renderer));
            tree.setEditable(true);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(true);
            tree.setRootVisible(false);
              tree.setDragEnabled(false);
              setViewportView(tree);
              DefaultMutableTreeNode firstNode = new DefaultMutableTreeNode("Good");
              treeModel.insertNodeInto(firstNode, rootNode, 0);
              tree.scrollPathToVisible(new TreePath(firstNode.getPath()));
              tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              tree.addTreeSelectionListener(this);
              tree.setSelectionPath(new TreePath(firstNode.getPath()));
        public void insertNewRowAfter(int index){
              DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
              treeModel.insertNodeInto(newNode, rootNode, index+1);
              tree.scrollPathToVisible(new TreePath(newNode.getPath()));
              tree.setSelectionPath(new TreePath(newNode.getPath()));
        //listener to selection change event
        public void valueChanged(TreeSelectionEvent e){
             DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                  tree.getLastSelectedPathComponent();
             if (node == null)
                  return;
             tree.startEditingAtPath(new TreePath(node.getPath()));
    class MyCellRenderer extends DefaultTreeCellRenderer{
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
                // Get background color based on selected state
              JLabel renderer =(JLabel) super.getTreeCellRendererComponent(tree,
                        value,selected,expanded,leaf,row,hasFocus);
              Color background = (selected ? Color.yellow : Color.white);
              renderer.setOpaque(true);
              renderer.setBackground(background);
             renderer.setMinimumSize(new Dimension(950,(int)renderer.getMinimumSize().getHeight()));
             renderer.setPreferredSize(new Dimension(950,(int)renderer.getPreferredSize().getHeight()));
              renderer.setText(value.toString());
             return renderer;
    class MyCellEditor extends DefaultTreeCellEditor{
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer){
              super(tree,renderer);
         public MyCellEditor(JTree tree, DefaultTreeCellRenderer renderer, TreeCellEditor editor){
              super(tree,renderer,editor);
         public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected,
                   boolean expanded, boolean leaf, int row){
              Component c = super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              Component editor = realEditor.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
              SwingUtilities.updateComponentTreeUI(c);
              if (editor instanceof JTextField)
                   //widen the textfield for the editor
                   ((JTextField)editor).setColumns(85);
                   ((JTextField)editor).setText(value.toString());
                   //((JTextField)test).selectAll();
              return c;
       

    Use path from the event.
    public void valueChanged(TreeSelectionEvent e){
             tree.startEditingAtPath(e.getPath());
    }Regards,
    Stas

  • Is it possible to add a JComponent as a JTree node? If yes then please help

    I am writing a java program in which I want to make my tree nodes editable by adding textfields, comboboxes, radiobuttons as nodes to the tree. So if anyone has any soluition please help!!!

    "Search Forums"
    has a wealth of information, and should be your first action when seeking a solution
    here's the results of searching, keywords: JTree JTextField
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=Jtree+JTextfield&subCat=&site=dev&dftab=&chooseCat=javaall&col=developer-forums
    plenty of the hits will have sample code you should be able to modify for your own needs

  • MyTextField in JTree???

    hi,
    i have written my own textfield, with many features like attributes for the characters and format rules. now i want to display some of the textfields in a tree-structure like the one of JTree. how can i tell a JTree that a node is my textfield???
    when i put the textfield in the tree or a node as a UserObject, the treenode is the string that i get when i call System.out.println(new JTextField().paramString()). i get the same result, when i put the TextField into the constructor of DefaultMutableTreeNode, what i take for the nodes (maybe there is something better ... tell me when). i also tried to write my own node, but then i have the problem, that i cannot overwrite the getParent() method. i created the node like this:
    class myNode extends JTextField implements MutableTreeNode {
    i have to write a lot of methods when i make this. one is getParent(). but both, JTextField and MutableTreeNode, have that method and both have different return types. and i can't overwrite the one of JTextField, that return a Component.
    so tell me, how would you solve my problem?
    p.s. i run the JDK 1.4.0 beta 3 build 65 and it's not important if your solution is Swing or AWT or both.
    THANKS :)

    javax.swing.DefaultCellEditor is a default cell editor for trees and tables. It can take an initialization parameter of a JTextField. This means you dont have to write any code to implement tree nodes or editors, you just pass in your own editor and utilize the DefaultCellEditor functionality.
    Just set the editor of the tree...
    tree.setCellEditor(new DefaulCellEditor(new MyTextField()));
    -jonathan

  • Key Listening without a textfield or similar

    Ok, I want to let the program call a method when a key is pressed, but so for I have only been able to do this when i added a KeyListener to an object like a textfield.
    You can imagine this is a little bit annoying. I want something that listens to my Keys without some field. A panel was quite hard to implement and then I read something about ProcessKeyEvent and if you want this to work you have to do SOMETHING with enableEvent(), but I have no idea what. Can anybody tell me plz or give me another solution to this problem.

    I think JComponents can listen for KeyEvents (as a previous post explains, there should at least be some component available to listen for the events)
    The code below works for my JTree based component.
    tree.addKeyListener( new HierarchyTreeKeyListener(this) );Where the listener class looks like...
         class HierarchyTreeKeyListener extends KeyAdapter{
              HierarchyTree tree;
              public HierarchyTreeKeyListener(CTree treeIn){
                   tree = treeIn;
              public void keyTyped(KeyEvent kt){
                   //get a handle on the selected node. This will be the root for the search
                   DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                   //System.out.println("selected node: "+selectedNode);
                   char key = Character.toLowerCase(kt.getKeyChar());
                   boolean found = false;
                        DefaultMutableTreeNode queryNode = (DefaultMutableTreeNode)tree.charSearch(key, selectedNode);
                        if( queryNode != null ){
                             expandPath( queryNode );
              }//end of method
         }//end of class HierarchyTreeKeyListener

  • Help with JTree and JPanel (or JFrame)

    Hi! I've an application that has JLabel, JTextField, JTree and JScrollPane.
    The problem is that when I add the tree to the scrollpane and then add it to the frame (or panel), the tree is not displayed. The labels and textfields are there, but the tree is not. But, if I don't use the scroll, just add the tree, then the tree is visible.
    Why is this happening?
    Hope u can help me!

    Please, helpppppppppppp!!!!!!!!!!!!!!!!!!!!!!!
    :)

  • Editing JPanel of TreeNode in JTree

    Hi all,
    I am badly stuck with one issue.
    I have a Jtree, some of the node of Jtree contains panel, panels also has some components JtextField and JLabels.
    Tree is generating properly. Node containing Panel shows all the
    components (TextField and Labels).
    The only problem is I am not able to edit the Textbox of JPanel.
    Pls help me out.

    Override the getToolTipLocation(MouseEvent e) method in your JTree to display the tooltip in the desired location(directly over the tree node).
    Try this piece of code. I've used it in my application and it works!
    public Point getToolTipLocation(MouseEvent event)
    Point location = null;
         Point point = event.getPoint();
         TreePath path = getPathForLocation(point.x, point.y);
         if (path != null && isTextVisible(path) == false)
              TreeCellRenderer renderer = getCellRenderer();
              java.awt.Component c =
                   renderer.getTreeCellRendererComponent(
                   this,path.getLastPathComponent(),false,
                   false,false,0,false);
              if (c instanceof JLabel)
                   JLabel label = (JLabel)c;
                   int icon = label.getIcon() == null
                        ? 0 : label.getIcon().getIconWidth();
                   Rectangle cellBounds = getPathBounds(path);
                   location = new Point(cellBounds.x icon label.getIconTextGap(), cellBounds.y);
              return location;
    private boolean isTextVisible(TreePath path)
         Rectangle cellBounds = this.getPathBounds(path);
         Rectangle visibleRect = this.getVisibleRect();
         if ((visibleRect.width - cellBounds.x) < cellBounds.width)
              return false;
         return true;
    }

  • JTree - Highlighting a different node dynamically

    Hello All,
    I am using a JTree to display a tree hierarchy. I have a situation, in which, the Tree window should update in the sense, point to a different node ( A different node has to be selected) based on user input.
    Say the tree has root and then 3 children
    root
    - A
    - - B
    - - C
    - D
    - E
    Each hyphen indicates a level, now when the user types B in the text box I need to update the currently selected node as B, and when he types E it should update to E Automatically. I googled online in general, and also saw that the action listeners are based on some action performed on the tree... but is there any function that can be trigged externally to update the tree selected data?
    Also It will be great if there is a way in which my TreeSelectionListener event is not triggered during this change.
    Regards,
    Sirish

    you can add key listener to your text field. Then invoke the method valueForPathChanged() of tree model. For example see small piece of code
    final JTree tree = new JTree();
    textField.addKeyListener(new KeyAdapter(){
                public void keyReleased(KeyEvent e) {
                    TreePath path = tree.getSelectionPath();
                    if(path == null) return;
                    tree.getModel().valueForPathChanged(path, textField.getText());
            });

  • Creating JTree by JTable Data

    Hi,
    I want to create JTree for the data in JTable, Is it possible. Thanks

    This question is a repeat of your last posting:
    http://forum.java.sun.com/thread.jspa?threadID=648759&tstart=0
    and you still haven't followed the advice given there. Quit cluttering the forum with the same question
    I will first explain what I want. I wanna 3 structures: TextField,JButton, and JTable.The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists has an example that is identical to this except that it uses a JList instead of a JTable. However, the concept is the same.
    .

  • JTree Selection problem. Plz help...

    Hi All,
    I hv designed a JTree with DefaultMutableTreeNode. And i hv added TreeSelectionListener to it. When i select the nodes of the tree i hv to display the RootNode name of the tree in a label. I'm able to achieve it using
    DefaultMutableTreeNode node =(DefaultMutableTreeNode) mBalanceInfoTree.getLastSelectedPathComponent();
    TextField.setText(node.getParent());
    the problem is when i click on the RootNode it is displaying as "RootNode" but not the node name.
    Can anyone help me on this.
    Thanks in advance
    ss

    Hi Frank,
    Atlast i made it to work.
    TreePath tp = mBalanceInfoTree.getSelectionPath();
    StringTokenizer st = new StringTokenizer(tp.toString(), ",");
    String bal_Grp[] = new String[st.countTokens()];
    int count = 0;
    while (st.hasMoreElements()) {
    bal_Grp[count] = st.nextToken();
    count++;
    Thanks for your replies..
    N correct me if there is any wrong in this approach.
    Cheers
    SS

Maybe you are looking for

  • HT3024 iBook G4 WiFi reception after hard-drive swap

    I just replaced the hard drive in my iBook G4 with a larger one. Everything works fine except that the WiFi only works in close proximity to our Airport Extreme Router. Our other 2 current Macs and our 2 iPhones continue to have good WiFi connections

  • Report Writer Adding New GL Account

    Hi experts, I would like to add new GL Account in the existing report in Report Writer. I do Do have following information to make changes, but I don't know where I could add new Gl Account. Library = ZRU Report Group = ZBS2 Report Name = ZBS-0002 Pl

  • Hp 2840 scan, Mac os-x V10.7

    My HP Color Laserjet 2840 worked perfectly for years when connected to a PC running XP.  I recently converted to a MacBook Pro running OS X V10.7.  The print function works fine but the HP Director icon is nowhere to be found so to select a Scan func

  • Make references in the NW Developer Studio

    Hello Andreas, When I talked about "in the workspace needs to reference " i meant that you need to add these DCs - BRMS FAÇADE; ENGFACADE/tc/bl/logging/api; JEE Engine Façade - as a dependency to your (dummy) DC. To do this, you need to open the Deve

  • Moving itunes from external hard-drive to another and using another comput

    Hi, This has probably been posted before but i couldn't find it. My itunes works on another computer, with the library (Edit->Preferences->Itunes location as g:\itunes), this includes the xml files for the library. I've now got a new laptop and exter