Firing a delayed TreeSelectionEvent on a JTree

I have a tree and a table. The table has to be updated every time the node selection in the tree changes. Now, updating my table takes a long, loonnngggg time and so, I dont want to do it frequently. The problem is this: I use a TreeSelectionListener to track changes in node selection. When I use the keyboard to change the selection, say to the fifth child of the currently selected node, I have to traverse the first four children before I come to the fifth. This fires a TreeSelectionEvent on all five children and my table starts updating long before I reach the desired node(and when that happens, I take a real long time reaching my node because I have to wait till the table finishes updating before I can move to the next node!) What I want is an event that gets fired say a second or two after the key has been released. I have tried adding key listeners, creating threads that sleep for some time and then fire, etc. But I dont get consistent results and, sometimes, I get multiple events.
Can someone help me?
Ravi

Let your table, which is listening via a TreeSelectionListener, only save the event it got and the time it got the event.
Take another Thread which tests, if the last saved event is older than say 2 sec. If so, then do a looong update of your table. If not, do nothing. Hence it is possibble, that an user "walks" down in your Tree and the Table is only updated, if the user makes a pause of more than 2 secs.

Similar Messages

  • Inconsistent results for adding child node in a JTree

    I have a JTree where I add child nodes when a user clicks on the node or handle. When the user clicks on the node, through implementing TreeSelectionListener interface, I add a node, the tree expands, and I see the newly added node. However, when the user clicks on the handle, through implementing the TreeExpansionListener, the tree does not expand and I do not see the newly added node. The problem is repeatable by compiling the code below.
    Why is there this difference? Aren't all the methods implemented through the TreeSelectionListener and TreeExpansionListener in the SWT thread?
    public class TestFrame extends JFrame implements TreeSelectionListener, TreeExpansionListener {
         public TestFrame() {
              String[] alphabets = {
                        "a", "b", "c", "d", "e", "f", "g",
                        "h", "i", "j", "k", "l", "m", "n",
                        "o", "p", "q", "r", "s", "t", "u",
                        "v", "w", "x", "y", "z"
              DefaultMutableTreeNode top = new DefaultMutableTreeNode("CEDICT");
              for(int i=0; i < alphabets.length; i++) {
                   DefaultMutableTreeNode node =
                        new DefaultMutableTreeNode(alphabets) {
                        public boolean isLeaf() { return false; }
                   top.add(node);
              JTree tree = new JTree(top);
              tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              tree.addTreeSelectionListener(this);
              tree.addTreeExpansionListener(this);
              tree.setShowsRootHandles(true);
              JScrollPane treePane = new JScrollPane(tree);
              treePane.setHorizontalScrollBarPolicy(
                        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              treePane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              treePane.setSize(new Dimension(200,400));
              treePane.setPreferredSize(new Dimension(200,400));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(treePane, BorderLayout.CENTER);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              int inset = 50;
    setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
              setLocationRelativeTo(null);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
              show();
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        JFrame.setDefaultLookAndFeelDecorated(true);
                        TestFrame frame = new TestFrame();
         public void valueChanged(TreeSelectionEvent e) {
              JTree tree = (JTree)e.getSource();
              DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
              System.out.println(node);
              Date date = new Date();
              node.add(new DefaultMutableTreeNode(date.toString()));
         public void treeCollapsed(TreeExpansionEvent event) {
              JTree tree = (JTree)event.getSource();
              TreePath path = event.getPath();
              DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode) path.getLastPathComponent();
              System.out.println(node);
              Date date = new Date();
              node.add(new DefaultMutableTreeNode(date.toString()));
              tree.invalidate(); //does not help to show newly added child
         public void treeExpanded(TreeExpansionEvent event) {
              JTree tree = (JTree)event.getSource();
              TreePath path = event.getPath();
              DefaultMutableTreeNode node =
                   (DefaultMutableTreeNode) path.getLastPathComponent();
              System.out.println(node);
              Date date = new Date();
              node.add(new DefaultMutableTreeNode(date.toString()));
              tree.invalidate(); //does not help to show newly added child

    I couldn't figure out why inserting a node in the valueChanged(...) method works. In all three methods no listeners are notified about the change, so you would think all three would fail.
    For a JTree using the DefaultTreeModel the nodesWereInserted(...) method needs to be called. For example, if I change your last three methods to this
    public void valueChanged(TreeSelectionEvent e) {
       insertNode((JTree) e.getSource(),
                  (MutableTreeNode) e.getPath().getLastPathComponent());
    public void treeCollapsed(TreeExpansionEvent event) {
       insertNode((JTree) event.getSource(),
                  (MutableTreeNode) event.getPath().getLastPathComponent());
    public void treeExpanded(final TreeExpansionEvent event) {
       insertNode((JTree) event.getSource(),
                  (MutableTreeNode) event.getPath().getLastPathComponent());
    public void insertNode(JTree tree, MutableTreeNode parent) {
        Date date = new Date();
        MutableTreeNode child = new DefaultMutableTreeNode(date.toString());
        int index = parent.getChildCount();
        parent.insert(child,index);
        ((DefaultTreeModel) tree.getModel())
                .nodesWereInserted(parent,new int[]{index});
    }then it works as you desire. You can (and should) of course use the DefaultTreeModel's own insert method.
    DefaultTreeModel#insertNodeInto(MutableTreeNode,MutableTreeNode, int)

  • Server is up/down???

    Dear All,
         I am trying to get authentication from my server, by using the below function...Here is a doubt...Once if my server is in "DOWN" state, i am getting the errors fired in my command prompt...how can i avoid this???.....i mean, i want to avoid the process of authentication, if the server is "DOWN"....how to find out whether a server is running in that url or not????
    public String authenticateMe(String username, String password)
    String setcookie="";
    String cookie="";
    try
    URL theurl = new URL("http://192.168.10.55:8001/names.nsf?login&username=" + username + "&password=" + password);
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection hurl = (HttpURLConnection)theurl.openConnection();
    hurl.connect();
    setcookie = hurl.getHeaderField ("set-cookie");
    if(setcookie!=null)
    int index=setcookie.indexOf(";");
    cookie=(setcookie.substring(0,index)).trim();
    hurl.disconnect();
    hurl=null;
    catch(Exception exp)
    {exp.printStackTrace();}
    return cookie;
    bye,
    Sakthivel S.

    I haven't used the Timer class much myself. Would suggest you look at the tutorial at: http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html
    and at the API documentation. Together they should have all the info. you need.
    Then just experiment until you get it to work. If you run into any problems post again to ask someone else.
    To start you off, I was thinking of something along the following lines (untested, just typed straight in):
    private javax.swing.Timer timer;
    private final int MILLISECONDS_DELAY = 15 * 60 * 1000; // 15 minutes
    private void login()
        // code to login here
        // successful login
        if (timer == null) // if first time
             // create timer passing anonymous ActionListener to
             // handle event fired after delay
             timer = new Timer(MILLISECONDS_DELAY, new ActionListener()
                 public void actionPerformed(ActionEvent ev)
                     login();
             timer.setRepeats(true); // keeps repeating itself
             timer.start(); // start it off
    // assumes client has logged in to server already
    private void request()
        // send request to server
        timer.restart(); // reset timer to zero
    }

  • KeyListener anomoly: delay in firing KeyEvent

    Hello,
    I've implemented a KeyListener that's exhibiting some anomolies. I'm using it in a video game. I'm using it to control the main character's movement. It determines his movement based on strokes of the arrow keys. I've programmed it so that only one key has an effect at a time. That is, so long as (say) the up arrow was pressed first and held down, the character moves up, and no other key has an effect. Other keys only have an effect if the up arrow is released.
    The anomoly comes about when two keys are held down (only one of them determining the movement of the character - which ever was first), and then the first is released. When the first is released (but the second is still held down), the character freezes for about a second, and only after that second does he move in the direction of the second key which is still held down.
    It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key. Even though the second key is held down, it takes a second to fire the KeyEvent after the first key is released (though it seems to fire immediately upon depressing the key).
    I'm wondering if there's a way to get rid of the delay or at least shorten it so it's not noticeable.
    Here's my KeyListener code:
    import java.awt.event.*;
    public class InputProcessor implements KeyListener {
        // key codes
        public static final int      LEFT  = 37;
        public static final int      UP    = 38;
        public static final int      RIGHT = 39;
        public static final int      DOWN  = 40;
        private boolean      left_arrow_down  = false;
        private boolean      right_arrow_down = false;
        private boolean      up_arrow_down    = false;
        private boolean      down_arrow_down  = false;
        // flag to mark when a key (any key) is pressed
        private boolean     key_pressed      = false;
        public InputProcessor() {}
        public void keyPressed (KeyEvent KE) {
         if (key_pressed) return; // all other keys disabled if one key is down
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down true;
              key_pressed = true;
              break;
             case RIGHT:
              right_arrow_down = true;
              key_pressed = true;
              break;
             case UP:
              up_arrow_down = true;
              key_pressed = true;
              break;
             case DOWN:
              down_arrow_down = true;
              key_pressed = true;
              break;
        public void keyReleased (KeyEvent KE) {
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down = false;
              break;
             case RIGHT:
              right_arrow_down = false;
              break;
             case UP:
              up_arrow_down = false;
              break;
             case DOWN:
              down_arrow_down = false;
              break;
         // only set key_pressed to false if all keys have been released
         if (!left_arrow_down &&
           !right_arrow_down &&
           !up_arrow_down &&
           !down_arrow_down)
             key_pressed = false;
        public void keyTyped (KeyEvent KE) {}
        public boolean isLeftArrowDown()  {return left_arrow_down;}
        public boolean isUpArrowDown()    {return up_arrow_down;}
        public boolean isRightArrowDown() {return right_arrow_down;}
        public boolean isDownArrowDown()  {return down_arrow_down;}
        public static void main (String[] args) {
         InputProcessor IP = new InputProcessor();
    }I'm wondering if there might be a command I can execute at the end of the keyReleased() method, something like this:
        public void keyReleased (KeyEvent KE) {
         switch (KE.getKeyCode()) {
             case LEFT:
              left_arrow_down = false;
              break;
             case RIGHT:
              right_arrow_down = false;
              break;
             case UP:
              up_arrow_down = false;
              break;
             case DOWN:
              down_arrow_down = false;
              break;
         // only set key_pressed to false if all keys have been released
         if (!left_arrow_down &&
           !right_arrow_down &&
           !up_arrow_down &&
           !down_arrow_down)
             key_pressed = false;
         checkForKeyPressed();
        }Let me know if you'd like a SSCCE.
    Thanks

    It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key.That's the usual key-repeat behavior on most OSs.
    I'm wondering if there's a way to get rid of the delay Probably by setting booleans in the keyPressed(...) / keyReleased(...) and polling those booleans at equal intervals using a Timer.
    db

  • Pressing the space-bar on a JTree results in TreeSelectionEvent.

    Hello,
    Have a JTree and a TreeSelectionListener that listens.
    If the focus is on the tree and most of keys are pressed nothing happens.
    However, if the focus is on the tree and the space-bar is pressed then the TreeSelectionListener.valueChanged(TreeSelectionEvent e) method is called.
    How is it possible to know that the TreeSelectionListener.valueChanged(TreeSelectionEvent e) is called due to the space-bar press and not due to common tree navigation.
    thank you,
    Rami

    This may help:
    http://technology.niagarac.on.ca/staff/bgracey/prokeyboardrepair.html#toc

  • After upgrading to new version, my Zumba game is on a delayed firing, what happened?

    the game appears normal until I get to the discharging of the colored balls. Then it is on a delayed response time. I am on a Zumba chat line on Facebook with others that are experiencing the same problem.

    I just got the iBooks update and that fixed the problem, except the book covers look like they were done in a government printing office.

  • How to select node in JTree without firing event?

    I have got standard situation. JTree in the left panel, and several edit boxes in right panel. Certainly, I have TreeSelectionListener, which on every tree node selection shows corresponding model values in edit boxes.
    I'd like to implement next logic:
    1. Something was changed in any edit box in right panel. Model has been changed.
    2. User clicks on different node in tree.
    3. Dialog "Message was not saved. Save?" with Yes/No/Cancel buttons are shown.
    Yes/No buttons are easy to handle.
    Question is about Cancel. I'd like on Cancel button left all edit boxes in their present state (do not restore values from saved model) and select back node, which wasn't saved.
    Problem is next. If I select node by setSelectionPath or smth like that, but... JTree fires event and my listener receives onTreeItemSelected back, which checks that node wasn't saved and ......
    Who does have any idea, or have done similar tasks? How can I select node and do not allow tree fire event this time?
    Thanks in advance.

    First, as soon as the model changes (when editing any
    combo box) some flag will be set. Now the logic which
    updates the combo boxes will do it only on a change of
    the current node and (this is new) if the flag wasn't
    set. You should have some flag anyway because somehow
    you must determine when to show the dialog, shouldn't
    you?Yes, I have got this logic implemented. But it's only the half :)
    I know exactly when my model has been changed, but if it was changed, i'd like to ask user what to do next - svae/loose changes/cancel
    And on cancel i'd like to select last edited tree node and do not get event from tree at that moment.
    >
    Second way, prevent selecting a new node if that flag
    has been set. You could do this by subclassing
    DefaultTreeSelectionModel and overriding some methods
    (setSelectionPath() et al).Ok. I'll investigate this.
    >
    MichaelThanks.

  • Help - valueChanged(TreeSelectionevent) firing twice

    Hi,
    I have a Jtree in which I need to display directories and the files in them.
    I need to be able to choose multiple leafs(which contains file names) only if the selected nodes represents file names with the same extension, otherwise select only the last node which broke the uniformity.
    For this I have implemented a selectionmodel class in which I iterate through all the nodes and call the super.addSelectionPaths(TreePath[]) method.
    My problem now is that the valueChanged() method in the listener class is fire twice for every selection.
    I have no idea why is it happening like that.
    Can anyone please help me out?

    Hi,
    Thank you for going through my problem.
    I have got the solution now.
    The problem was that since I was overriding two methods viz. setSelectionPaths() and addSelectionPaths(), the first time a node is selected both the methods are triggered, and the subsequent selections call only the addSelectionPaths() methods.
    Thanks

  • JTree + FK with same value causing problems

    Hi
    I can't figure this out. If I create biz components for 2 tables having a parent-child relationship and a jTree with appropriate rules, things are ok only if the parent's id are of different values than the child. When parent.id and child.id have the same values the jTree seems to recursively fire valueChanged() at strange times.
    Example:
    CREATE TABLE PARENT
    PARENT_ID NUMBER CONSTRAINT PARENT_ID_NN NOT NULL,
    PARENT_NAME VARCHAR2(40 BYTE),
    CONSTRAINT PARENT_C_ID_PK
    PRIMARY KEY
    (PARENT_ID)
    CREATE TABLE CHILD
    CHILD_ID NUMBER CONSTRAINT CHILD_ID_NN NOT NULL,
    CHILD_NAME VARCHAR2(40 BYTE),
    PARENT_ID NUMBER,
    CONSTRAINT CHILD_C_ID_PK
    PRIMARY KEY
    (CHILD_ID)
    ALTER TABLE CHILD ADD (
    CONSTRAINT PARENT_FK
    FOREIGN KEY (PARENT_ID)
    REFERENCES PARENT (PARENT_ID));
    INSERT INTO PARENT VALUES (1, 'Parent 1');
    INSERT INTO PARENT VALUES (2, 'Parent 2');
    INSERT INTO PARENT VALUES (3, 'Parent 3');
    INSERT INTO CHILD VALUES (100, 'Child A', 1);
    INSERT INTO CHILD VALUES (200, 'Child B', 2);
    INSERT INTO CHILD VALUES (300, 'Child C', 3);
    I use the JDev 10.1.2 wizard to create biz components and test the AppMod to make sure the link works. Now I create a blank panel and drag over the ParentView data control. Using the jTree tree binding editor I create two rules:
    1) DataCollectionDef.ParentView - DisplayAttribute.ParentName - BranchRuleAccessor.ChildView
    2) DataCollectionDef.ChildView - DisplayAttribute.ChildName
    Now I add a tree selection listener:
    jTree1.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent e)
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
    if (selectedNode != null)
    System.out.println(selectedNode.getUserObject().toString());
    When I run my panel and watch in JDev everything is fine, i.e. nothing is printed to the screen when it first loads and when I click a node, the correct UserObject prints.
    Here's the rub, now I close the panel and update my child table as follows:
    UPDATE pdssuser.child SET child_id = 1 WHERE child_id = 100;
    UPDATE pdssuser.child SET child_id = 2 WHERE child_id = 200;
    UPDATE pdssuser.child SET child_id = 3 WHERE child_id = 300;
    This time, when I run my panel, the console shows that valueChanged() has been fired 3 times on load:
    Parent 1
    Parent 2
    Parent 3
    This behavior is causing problems with my real tree.
    I haven't had any luck finding threads about this. Any ideas?
    Thanks
    John

    ok, last one (i hope)
    The same issue occurs with 10.1.2.1
    ...but changing the location where I add the treeSelectionListener to after setBindingContext() seems to fix the problem.
    The second call to panelBinding.refreshControl() in setBindingContext() (the one after the call to jbinit()) is what fires the valueChanged events. Somewhere in there, DCBindingContainer.java or DCIteratorBinding.java, the treeSelectionListener is hearing that a value changed (maybe due to a query execution?). I guess the jTree1.setModel(...) call in jbinit() simply sets up the tree but the VO queries described in the Branch Rule accessors are executed on the refreshControl.....i'm out of my comfort zone here and may be confusing you with my "troubleshooting" so I'll just tell you my work-around.
    So to fix it I add the treeSelectionListener in my main method (not jbinit()) after the setBindingContext() has been called.
    I still have no idea why the FK triggers this behavior...but at least it's working.
    * the main method
    public static void main(String [] args)
    try
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch(Exception exemp)
    exemp.printStackTrace();
    Panel1 panel = new Panel1();
    panel.setBindingContext(JUTestFrame.startTestFrame("DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(400, 300)));
    panel.revalidate();
    // Now add the treeSelectionListener
    panel.addSelectionListener();
    * the JbInit method
    public void jbInit() throws Exception
    this.setLayout(borderLayout1);
    this.add(jTree1, BorderLayout.CENTER);
    jTree1.setModel((TreeModel)panelBinding.bindUIControl("ParentView1", jTree1));
    // DON'T ADD treeSelectionListener here
    * Add the selection listener to the tree
    public void addSelectionListener()
    jTree1.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent e)
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)jTree1.getLastSelectedPathComponent();
    if (selectedNode != null)
    System.out.println(selectedNode.getUserObject().toString());
    }

  • JTree Selection Behavior with Custom TreeCellEditor

    I've recently had the need to build a custom TreeCellEditor with a JTree that allows single path selection. I've toyed around with it but don't understand it. When a node is clicked, the editor takes over rendering/handling the cell, and a TreeSelectionEvent is fired from the tree, but the isSelected boolean value passed to the TreeCellEditor is initially false. Then on a second click of the same path in the tree, no TreeSelectionEvent is fired, but the isSelected boolean value is true. It's as if the tree selection is occuring after the editor renders the cell. I would like the cell to appear selected on the first click. Can anyone shed some light on why this is happening and how I can fix it?
    I included some code to demonstrate the problem below (though no actual editing takes place; the test code is only to demonstrate how the cells only appear selected with a yellow background after the second click of the same cell; note also that the valueChanged only executes on the first click). This test was run on Windows with Java 1.5.
    public class TestTreeCellEditor extends JLabel implements TreeCellEditor {
         private String st;
         public TestTreeCellEditor() {
              setOpaque(true);
         public Component getTreeCellEditorComponent(JTree tree, Object value,
                   boolean isSelected, boolean expanded, boolean leaf, int row) {
              this.st = value.toString();
              setBackground(isSelected? Color.YELLOW : Color.WHITE);
              setText(st);
              return this;
         public void addCellEditorListener(CellEditorListener l) {
              // not important for test
         public void cancelCellEditing() {
              this.st = null;
         public Object getCellEditorValue() {
              return st;
         public boolean isCellEditable(EventObject anEvent) {
              return true;
         public void removeCellEditorListener(CellEditorListener l) {
              // not important for test
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
         public boolean stopCellEditing() {
              return true;
    public class TestTreeCellEditorFrame extends JFrame implements TreeSelectionListener {
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        launchGUI();
         private static void launchGUI() {
              TestTreeCellEditorFrame frame = new TestTreeCellEditorFrame();
              JPanel treePanel = new JPanel();
              DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node");
              DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("Child 1");
              rootNode.add(childNode);
              childNode = new DefaultMutableTreeNode("Child 2");
              rootNode.add(childNode);
              JTree testTree = new JTree(rootNode);
              testTree.addTreeSelectionListener(frame);
              testTree.setCellEditor(new TestTreeCellEditor());
              testTree.setEditable(true);
              testTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              treePanel.add(testTree);
              frame.setContentPane(treePanel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(600,400);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public void valueChanged(TreeSelectionEvent event) {
              TreePath path = event.getNewLeadSelectionPath();
              if (path != null) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                   System.out.println("TreeSelectionEvent on " + node.getUserObject().toString());
    }

    Since my last post, I decided that I do want to be able to edit a cell that is not selected. In particular, when using a tree with checkboxes. What I'm doing for the time being, which works well enough, is to highlight the cell based on the isSelected value in combination with calling tree.stopEditing() in a TreeSelectionListener valueChanged method. This is somewhat of a hack solution, and has the side effect of a cell not appearing selected until the mouseReleased event. I'm still looking for a better solution, but for now it works well enough.

  • JTree display issues and thread safety

    I've recently ran into some issues with a JTree not displaying correctly. Infrequently, blank space will appear in the tree (big gaps between consecutive nodes), or the text of a node will be cut off ending with a "...". This happens when (but not yet proven a direct result of) one thread is expanding a node of the tree while another thread is inserting nodes into one of the expanding node's children through calls to DefaultTreeModel.insertNodeInto. (what I'm doing here is lazy loading the children's children when the parent is expanded, and the lazy loading is performed by a seperate thread so as not to delay the main thread.) It does not happen if the second thread simply adds child nodes without using the DefaultTreeModel's insertNodeInto method.
    I think what might be happening here is that the DefaultTreeModel.insertNodeInto method is calling fireTreeNodesInserted which I think is in turn causing nodes in the tree to be re-rendered. This got me thinking that the problem may come down to the DefaultTreeCellRenderer being used by the two threads simultaneously. DefaultTreeCellRenderer extends JLabel and returns itself in the getTreeCellRendererComponent method. If two threads were causing nodes to be rendered at the same time, it would seem the rendered label could be occasionally in an inconsistent state.
    Anyone ran into a situation like this before? The problem of text being cut off seems to be eliminated by having a custom renderer return a new component each time, rather than returning itself, but this results in degraded performance. It's almost as if each thread would need it's own renderer (or the renderer would need to return a different component for each thread), but I'm not sure how this would be done. And this doesn't solve the problem of gaps appearing in the tree.
    As for the gaps, I think this might be solved by changing when the children's children are getting loaded in respect to the parent node expanding. At first I was using a TreeWillExpandListener that fired off loading the children's children. I think I might can solve the white space in the tree problem by changing that to a TreeExpansionListener that uses the treeExpanded method. So far this seems to be working...so that the parent node is done expanding before the second thread begins loading the children's children.
    Any thoughts?

    I actually found the thread3 article first... since there doesn't seem to be direct links between them, I thought I would add for anyone who reads this thread that there are several related articles. sabre150 linked the first; the others are the same base URL but with the number incremented for each. For example, the 2nd article is:
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html]
    And the 3rd article, which most directly applies to what I am doing, is:
    [http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html]
    Edited by: Skotty on Mar 5, 2009 9:35 PM -- links turned into actual links
    Edited by: Skotty on Mar 5, 2009 9:36 PM -- formatted for nicer display

  • ValueChanged- and keyReleased-Events in JTree

    Hello,
    Suppose I have Items in a JTree. Any time the selected item changes, heavy work has to be done to get the details of the node and present it to the user.
    Suppose further the user uses the arrow-keys to scroll through the list an he holds down the key. I do get many calls to my Listeners valueChanged(TreeSelectionEvent event), but I am interested just in the last event, in order to avoid all the heavy work. How can this be done?
    I tried the following, but I do get a keyReleased-Event at any new selection. (Maybe because a nested component of the JTree feels like I had released the arrow-key. Is this a bug?):
    private class NodeSelectionEventHandler implements KeyListener, TreeSelectionListener {
    private boolean forwardEvents = true;
    private EventObject lastEvent;
    public void keyTyped(KeyEvent e) {
    public void keyPressed(KeyEvent e) {
    forwardEvents = false;
    public void keyReleased(KeyEvent e) {
    //System.out.println(e.getComponent());
    // Leider bekomme ich nach jeder auswahl mit Cursortaste auch einen
    // keyReleased-Event, obwohl die Taste immer noch gedrueckt ist.
    forwardEvents = true;
    if (lastEvent != null) {
    lastEvent = null;
    fireNodeSelectionChanged();
    //System.out.println("Last Selection forwarded");
    public void valueChanged(TreeSelectionEvent event) {
    // there is no event.getValueIsAdjusting() in JDK1.3
    handelEvent(event);
    private void handelEvent(EventObject event) {
    //Thread.dumpStack();
    if (forwardEvents) {
    lastEvent = null;
    fireNodeSelectionChanged();
    //System.out.println("Selection forwarded");
    else {
    lastEvent = event;
    //System.out.println("Selection eaten");

    I have a JTree from which I generate classes on selection.
    To ensure only one event is fired I install two listeners.
    I install a mouse listener and capture an event when the mouse is clicked, and I install a key listener and only catch the enter key being pressed as follows:
    tree.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
              showFunction();
    tree.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
    showFunction();
    This means something happens only if a user clicks on the node with the mouse or selects the node and presses the enter button. I have used this as a general standard throughout my application and it works on all platforms.
    Hope this helps

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

  • Focus Problem with JTree and Menus

    Hi all,
    I have a problem with focus when editing a JTree and selecting a menu. The problem occurs when the user single clicks on a node, invoking the countdown to edit. If the user quickly clicks on a menu item, the focus will go to the menu item, but then when the countdown finishes, the node now has keyboard focus.
    Below is code to reproduce the problem. Click on the node, hover for a little bit, then quickly click on the menu item.
    How would I go about fixing the problem? Thanks!
    import java.awt.Container;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class MyTree extends JTree {
         public MyTree(DefaultTreeModel treemodel) {
              setModel(treemodel);
              setRootVisible(true);
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JMenuBar bar = new JMenuBar();
              JMenu menu = new JMenu("Test");
              JMenuItem item = new JMenuItem("Item");
              menu.add(item);
              bar.add(menu);
              frame.setJMenuBar(bar);
              Container contentPane = frame.getContentPane();
              contentPane.setLayout(new GridLayout(1, 2));
              DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("Root");
              root1.add(new DefaultMutableTreeNode("Root2"));
              DefaultTreeModel model = new DefaultTreeModel(root1);
              MyTree tree1 = new MyTree(model);
              tree1.setEditable(true);
              tree1.setCellEditor(
                   new ComponentTreeCellEditor(
                        tree1,
                        new ComponentTreeCellRenderer()));
              tree1.setRowHeight(0);
              contentPane.add(tree1);
              frame.pack();
              frame.show();
    import java.awt.FlowLayout;
    import java.util.EventObject;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    public class ComponentTreeCellEditor
         extends DefaultTreeCellEditor
         implements TreeCellEditor {
         private String m_oldValue;
         private TreeCellRenderer m_renderer = null;
         private DefaultTreeModel m_model = null;
         private JPanel m_display = null;
         private JTextField m_field = null;
         private JTree m_tree = null;
         public ComponentTreeCellEditor(
              JTree tree,
              DefaultTreeCellRenderer renderer) {
              super(tree, renderer);
              m_renderer = renderer;
              m_model = (DefaultTreeModel) tree.getModel();
              m_tree = tree;
              m_display = new JPanel(new FlowLayout(FlowLayout.LEFT));
              m_field = new JTextField();
              m_display.add(new JLabel("My Label "));
              m_display.add(m_field);
         public java.awt.Component getTreeCellEditorComponent(
              JTree tree,
              Object value,
              boolean isSelected,
              boolean expanded,
              boolean leaf,
              int row) {
              m_field.setText(value.toString());
              return m_display;
         public Object getCellEditorValue() {
              return m_field.getText();
          * The edited cell should always be selected.
          * @param anEvent the event that fired this function.
          * @return true, always.
         public boolean shouldSelectCell(EventObject anEvent) {
              return true;
          * Only edit immediately if the event is null.
          * @param event the event being studied
          * @return true if event is null, false otherwise.
         protected boolean canEditImmediately(EventObject event) {
              return (event == null);
    }

    You can provide a cell renderer to the JTree to paint the checkBox.
    The following code checks or unchecks the box with each click also:
    _tree.setCellRenderer(new DefaultTreeCellRenderer()
      private JCheckBox checkBox = null;
      public Component getTreeCellRendererComponent(JTree tree,
                                                    Object value,
                                                    boolean selected,
                                                    boolean expanded,
                                                    boolean leaf,
                                                    int row,
                                                    boolean hasFocus)
        // Each node will be drawn as a check box
        if (checkBox == null)
          checkBox  = new JCheckBox();
          checkBox .setBackground(tree.getBackground());
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
        checkBox.setText(node.getUserObject().toString());
        checkBox.setSelected(selected);
        return checkBox;
    });

  • Selection problem in JTree

    Hi,
    I am setting the selection mode for a JTree to be single selection. Suppose the node which I selected was in expanded state, after making the selection it is in collapsed state. Now suppose I want to resume the expanded state and again try to select the same node without making any intermediate selection the listener doesn't listen. But if I make make a different node selection in between the 2 consecutive selections made to the same node the 2nd selection is listened.
    Is it something like if two similar selections are made one after the other the second one is discarded or not listened. If so how can I overcome this? If not please tell me where am I making the mistake.

    selection will be fired only when the selection property changed. so, collapsing and expanding should be done in mouse event handlers.

Maybe you are looking for

  • Can you write to files with an applet or what?

    Hi I can't get the bufferwriter to output any text to a file. Not sure if this is because I'm using an applet? I wouldn't assume so, but any help would be appreciated The problem area is : private boolean registerNewUser()         FileOutputStream wr

  • Export to Excel Formating Option Problem

    Hi all! I create a Crystal Reports.when i export to Excel File in a winform app,there has the 'Create page breaks for each page' option,but in asp.net web page.there is only two option,and not include the 'Create page breaks for each page' .I excpet

  • Error starting resources with srvctl

    Hi, Has any experienced the following errors when trying to start resource in a 10.2.0.3 rac cluster? [node1:oracle]:/appl/oracle > srvctl start listener -n node1 CRS-1028: Dependency analysis failed because of: CRS-0223: Resource 'ora.node1.LISTENER

  • Is there anyway to edit gapless playback info in iTunes 11?

    I know that one of the many bizzare and ridiculous changes in iTunes 11 is that they removed gapless playback options, which I just REALLY can't understand why they'd do. So I'm just wondering if there is any way through something 3rd party or anythi

  • Faces and Struts Intregration

    Its a hot topic nowadays.but there is no any help/answer is avaialable in this forum... i and many other develpers want to intregarte both framework. anybody knows the TESTED n VALID examle or sampe application.kindly give us link here.....or if anyb