JTree Events

Hi

class HiKalyani{
     public static void main(String[] args){
          System.out.printf("%s\n", "Hi Kalyani! ^_^");
          throw new RuntimeException("http://forum.java.sun.com/thread.jspa?threadID=629779&tstart=0");
}

Similar Messages

  • JTree event question

    Hi,
    I am facing a problem and hoping somebody here can give me a clue.
    I have a JTree in my application, which has different types of nodes (all implement TreeNode ). One node there needs lazy-loading, what I want is when user clicks either '+' or folder icon/label then this node gets updated. I have added MouseListener to the tree, it works fine with clicking folder icon or label but not for clicking '+'. I also tried adding other listeners like TreeWillExpand etc. but it not seems a good solution to me since I just need to treat one node defferently.
    There are a couple of options I think can help:
    - catch clicking '+' event for specific node
    - display '+' even folder has no child (just for one node)
    - or disable '+' for this node
    Thank you in advance

    Well, after you expand row 1, the row count isn't 6 anymore, is it? It's something larger than that, depending on how many children the first node has.

  • URGENT----- JTree Event

    I have a JTree with parent node---- PARENT1.
    To it are added CHILDNODE1 and CHILDNODE2.
    Another parentnode PARENT2 with CHILDNODE3 CHILDNODE4.
    PARENT1 and PARENT2 added to ROOTNODE
    JTree is added to LHS of JSplitPane
    Similar to Explorer in Windows.
    Added listeners to JTree like this
    mTree.addTreeSelectionListener(new TreeHandler(this));
    mTree.addMouseListener(new TreeHandler(this));
    where TreeHandler is a class extending MouseAdapter and implementing TreeSelectionListener.
    Overidden public void valueChanged(TreeSelectionEvent aTreeEvent)
    by calling aTreeEvent.getPath() and from the obtained path, I determine PathCount and PathComponent.
    Based on this I display Panel on RHS of JSplitPane.
    I have a situation say CHILDNODE1 is selected and corresponding Panel is displayed. If I select CHILDNODE2 with mouse, I prompt for saving changes made to CHILDNODE1 panel...So I should reselect CHILDNODE1 in JTree programmatically and not CHILDNODE2
    I have used mTree.setSelectionPath(path_of_CHILDNODE1) .
    But the problem is it is triggering an event on selection of CHILDNODE1, which I donot want to. How do I stop this????
    and also will call to mTree.setSelectionPath(aPath) trigger a TreeSelectionEvent or my event handling is wrong ?
    Thanks in advance

    If I have understood clearly ur problem, When the other cell in the tree is selected the corresponding rHS componet will be updated is that right. And wht U wanna do is to holp updationg rhs before saving previous content.
    If that is right, then y dont U ask for the save option in the treeevent itself?i mean in the overridden value chnaged function

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

  • ValueChanged called multiple times

    Hi,
    I am having a problem with JTree events and wondered if someone has had the same problem. I have 3 JTrees that use the same DefaultTreeModel. Each however has its own selectionListener and willExpandListener. When a node is selected on one tree the valueChanged for all three Jtrees is called and I cannot figure out why. Its as if all three listeners are listening to all three trees, even though each JTree has a separate listener (the three listeners are the three instances of the same class however).
    I can't paste the code for copyright reasons but this is how I set up the listeners in pseudo code.
    DefaultTreeModel model = new DefaultTreeModel(root)
    JTree tree1 = new JTree(model)
    JTree tree2 = new JTree(model)
    JTree tree3 = new JTree(model)
    tree1.addTreeSelectionListener(new CustomTreeSelectionListener())
    tree2.addTreeSelectionListener(new CustomTreeSelectionListener())
    tree2.addTreeSelectionListener(new CustomTreeSelectionListener())
    tree1.addTreeWillExpandListener(new CustomTreeWillExpandListener())
    tree2.addTreeWillExpandListener(new CustomTreeWillExpandListener())
    tree3.addTreeWillExpandListener(new CustomTreeWillExpandListener())Since all the trees have their own selection and will expand listeners, shouldn't selecting a node on one tree only call valueChanged once and not once for each tree? What am I doing wrong?
    Thanks
    Paul

    Please provide more information about your source code because of I have no problem on Java 1.4 with this code:
              TreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode("root"));
              JTree tree1 = new JTree(model);
              tree1.addTreeSelectionListener(new TreeSelectionListener() {
                   public void valueChanged(TreeSelectionEvent e) {
                        System.out.println("tree1 selection changed");
              JTree tree2 = new JTree(model);
              tree2.addTreeSelectionListener(new TreeSelectionListener() {
                   public void valueChanged(TreeSelectionEvent e) {
                        System.out.println("tree2 selection changed");
              JTree tree3 = new JTree(model);
              tree3.addTreeSelectionListener(new TreeSelectionListener() {
                   public void valueChanged(TreeSelectionEvent e) {
                        System.out.println("tree3 selection changed");
              JTabbedPane tabbedPane = new JTabbedPane();
              tabbedPane.add("tree1", tree1);
              tabbedPane.add("tree2", tree2);
              tabbedPane.add("tree3", tree3);

  • Changing the event that starts JTree cell editor

    I've implemented a JTree that uses a custom cell renderer and editor. Everything is going well except for a look and feel issue. When I double click on a JTree entry or single click on a node that has already been selected, the cell editor starts immediately. This is way to generous, and I'm finding I'm often editing cells when I just want to navigate the tree.
    I'd much prefer to have the edit event be something harder to do like a right click or a triple left click. Is there a way to change the event that starts the JTree cell editor?

    DefaultCellEditor provides a method boolean isCellEditable(EventObject anEvent), by default it always returns true. Override that method in your cell editor to only return true if the event is a right click, or whatever you want.

  • JTree traversal with key events

    I am looking for any classes available for traversing nodes in Jtree based on the input given through keyboard matching with nearest name in the tree being displayed. This is similar to the feature we have in windows explorer where based on the name we type it selects the nearest node in the tree taking into consideration the expanded paths.
    Thank you in anticipation,
    Srikanth

    What exactly you want to do.
    Have a look at my code, this is what I did a while ago. This may a good start for you.
    tree.addKeyListener(new java.awt.event.KeyAdapter() {
             public void keyPressed(KeyEvent e) {
                tree_KeyReleased(e);
        * JTree Key Released Functionality
        * @param e KeyEvent
       private void tree_KeyReleased(KeyEvent e) {
          try {
          MouseEvent me = new MouseEvent(tree, MouseEvent.MOUSE_RELEASED, 0, 0, 0, 0, 0, false);
          int keyCode = e.getKeyCode();
          // Get the Tree Path
          TreePath selPath = tree.getSelectionPath();
          if (keyCode == e.VK_DELETE) { //KeyCode - 127
             removeSelectedNode();
          else if (keyCode == e.VK_ADD) { // Key Code - 107
             tree.expandPath(selPath);
          else if (keyCode == e.VK_SUBTRACT) { // Key Code 109
             tree.collapsePath(selPath);
          else if (keyCode == e.VK_ENTER) {
             tree_mouseReleased(me);
          else {
          } catch (NullPointerException ex) {
          //System.out.println("Null");
       }

  • [JTree]Block event?

    Hello,
    I've got a problem. In fact, i have a JFrame with on the left a JTree and on the right some JEditorPane and 3 JButton (New, Save, Cancel).
    When I clic on a JTree's Node, my JEditorPane are updated with desirated info.
    |-------------------|------------------------------------|
    | JTree             | |-------------------------|        |
    |   - Node 1        | | JEditorPane1            |        |
    |   - Node 2        | |-------------------------|        |
    |   - Node 3        |                                    |
    |   - Node 4        | |-------------------------|        |
    |   - Node 5        | | JEditorPane2            |        |
    |   - Node 6        | |-------------------------|        |
    |                   |                                    |
    |                   |                                    |
    |                   |                                    |
    |                   |                                    |
    |                   |     |-----| |------| |--------|    |
    |                   |     | New | | Save | | Cancel |    |
    |                   |     |-----| |------| |--------|    |
    |                   |                                    |
    |-------------------|------------------------------------|I would like when i clic on JButton New, it is impossible to click on another Node in the Jtree: to block the Jtree or block event on Jtree.
    I've tried tree.setEnabled(false) but my CellRenderer applied to the JTree disappears ...
    I've also tried disableEvent(AWTEvent.ACTION_EVENT_MASK| AWTEvent.COMPONENT_EVENT_MASK|AWTEvent.CONTAINER_EVENT_MASK| AWTEvent.FOCUS_EVENT_MASK| AWTEvent.ITEM_EVENT_MASK| AWTEvent.KEY_EVENT_MASK| AWTEvent.MOUSE_EVENT_MASK) but it doesn't work.
    If someone have a idea
    ThanX !

    Remove the key listeners?
    JTree tree = new JTree();
    for(KeyListener listener : tree.getKeyListeners()) {
        tree.removeKeyListener(listener);
    }Another option would be to just do
    tree.setFocasable(false);

  • Events of Nodes in a JTree

    Okay, perhaps I am sidetracked today by all the sad craziness occuring in New York and DC, or perhaps I just don't have a grasp on JTrees yet...but...
    I have implemented a TreeCellRender to create panels with buttons and other information to be the nodes of a JTree I created. Everything shows up beautifully, however, I want the buttons on this panel to depress and perfom actions (work like normal) when the user clicks/selects such a button in the tree structure. I can't figure out how to properly set up event handlers to get from the tree to the tree node to the "bean" I'm using as a node. If anyone has any helpful hints, I'd appreciate it!
    Thanks in advance!

    add actionlistener to the JTree, and then get the object by getLastPathComponent, and compare it if its the button and do the action.

  • Tree selection event in jtree

    hi
    i'm using a jtree in my gui but im facing a problem
    jTree1.addTreeSelectionListener(new TreeSelectionListener() {
                   public void valueChanged(TreeSelectionEvent e)
                        jTree1_valueChange(e);
    as you can see that whenever i click on a particular node in the tree the tree selection event occurs which calls the valuechanged method and it does as required but if i click again on the same selection as before the tree selection event does not occur and it does not call the method so say that the node i'm selecting is supposed to be dynamic and has to be refreshed if i click on it again it will not update itself through the value changed method. can somebody please tell me a way to be able to get the valuechanged method even if i click on the same selection.
    im a bot new to java swing programing so please if you could be a little more explanatory it could help
    thanks

    You problem is talked about (and a solution proposed) in the JavaDoc.
    See the code sample in the doc header from http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTree.html

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

  • 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

  • Cancel JTree selection event ?

    Hello,
    I have defined a user object in the DefaultMutableTreeNode that holds a flag for disabled nodes - Now I would like to cancel events from the user when this node is being selected, also I would like to make this node appear disabled.
    How should I do this with JTree embedded inside an applet ?
    Thank you,
    Maxim.

    My rough idea is, store your previous selection, when you get selection change event, check if the node is disabled, if so, set the selection back to previous selection. Also, you can implement TreeCellRender interface, make the node's background gray to let user feel it is disabled.

  • Disable JTree and stop it from receiving mouse events

    Hi,
    I have a JTree which has a mouse listener associated with (which is used for right-click operations)..,..anyway I am trying to disable the tree, so I call setEnabled(false)...which, as documented, disables the tree but it will still receive mouse events. I also tried, setEditable(false)..... the only way I can think of is to remove the mouse listener, and then when I want to re-enable the tree, I have to add it back.
    is there some other way?
    thanks

    Hi,
    I have a JTree which has a mouse listener
    ner associated with (which is used for right-click
    operations)..,..anyway I am trying to disable the
    tree, so I call setEnabled(false)...which, as
    documented, disables the tree but it will still
    receive mouse events. I also tried,
    setEditable(false)..... the only way I can think of
    is to remove the mouse listener, and then when I want
    to re-enable the tree, I have to add it back.
    is there some other way?Why do you want another way? This seems like a perfectly viable way to accomplish what you want.

  • JTree and real Components / event forwarding

    Ok, so Ive seen some people forward events from JTree to node based Components.
    I was just wondering, whether thats the right way to go.
    Wouldn't it be better to write your own TreeLayoutManager, add the node based components with nodes as constraints to the the manager and add or remove them when the tree expands/collapses.
    My only problem is, when to trigger the doLayout and how to get the proper node sizes. The only given value is the available width in the cellrenderer.
    The cellrenderer would just return an empty, properly sized JLabel, and the "layoutmanager" would take care of the the real positioning.
    That way I could have the painting speed benefits of a Jtree, combined with the flexibility of real components stored as nodes in it, right?
    Well, I'm just looking for opinions on this.
    Shoot :-D

    Hi,
    Thanks for your post.
    >>What is meant by HeartbeatInterval and Max Latency Time?
    Heartbeat Interval determines how often collector will check if source is still online,
    MaxItems and MaxLatencyTime determine how source will batch items. In this example it will wait for 1 events or 1 seconds
    <MaxItems>1</MaxItems>
    <MaxLatencyTime>1000</MaxLatencyTime>
    >>Next: When configuring the source computer i have to configure a Refresh time in the Policy key. (Computer Settings - Policies - Administrative Templates - Windows Components - Event Forwarding)
    If you enable this policy setting, you can configure the Source Computer to contact a specific FQDN (Fully Qualified Domain Name) or IP Address and request subscription specifics.
    If you disable or do not configure this policy setting, the Event Collector computer will not be specified.
    >>when is this value being used for what? If I do not specify this refresh param, what is the default value?
    In my view, it is connection refresh time, we must set this parameter, for example,
    Use the following syntax when using the HTTPS protocol:
    Server=https://<FQDN of the collector>:5986/wsman/SubscriptionManager/WEC,Refresh=<Refresh interval in seconds>,IssuerCA=<Thumb print of the client authentication certificate>
    Meanwhile, i think you may ask in MSDN forums for technical support.
    https://social.msdn.microsoft.com/Forums/en-US/home
    Regards.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

Maybe you are looking for

  • Error message from Trend protection software about a dangerous page.

    Every time I open Firefox lately I get an warning from trend protection software that I'm tying to go to a dangerous page. The warning shows as I exiting Firefox. The address is always a very long string of characters.

  • Integrating PL / SQL with a Button on a Web Page ...

    I would be very grateful if someone could help with the following query. I have a database with a table called '*Tbl1*', which contains the following columns:- 1). tbl1_unique_id (number, primary key); 2). tbl1_title (VARCHAR2, 200); 3). tbl1_descrip

  • How to forbid browsering pages by IE "previous or next"

    in my program, i need to clear the buffer which could lead others go back to previous page bypass the server. in other word, i need to make the page out of date when i've submited it. who can help me , thanks in advance

  • MovieClip Tween Control

    Hey Everyone, I am new in actionscript 3.0, and I have a problem to control a Movieclip component ..... I have a Movieclip component which contains other components, I managed to tween the components in the Movieclip to fade Out once I call gotoAndPl

  • Installation of Linux @Parallels on Mac OS X 10.5

    Hi, i want to install an Oracle Server Standard Edition (at least 10gR1) on Mac OS X 10.5. Because of no certification on that platform my idea is to install the Parallels VM on the Mac and as guest OS a Linux. Parallels supports among others the fol