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");
   }

Similar Messages

  • Object Movement with Key Events

    Hi everybody!
    Im trying to move an object over the screen with keyboard buttons. The problem I have come across with is that I would like to use the right button to move right, up button to move forward, etc. but I cant push, for example, right and up buttons at the same time to make a diagonal movement. How can I solve this?
    Thank you and regards.

    I added key events to a sequence and than check them in the program.
    Something like this:
    class Car extends CustomNode {
        var keys:KeyCode[];
        public override function create(): Node {
            ImageView {
                transforms: [ Translate{ x: bind x, y: bind y }, Rotate{ angle: bind direction}]
                x: -w
                y: -h
                image: Image { url: "{__DIR__}car.png"}
                onKeyPressed: function( e: KeyEvent ) {
                    insert e.code into keys;
                    if(e.code == KeyCode.VK_UP){
                        ds = 2.0;
                    }else if(e.code == KeyCode.VK_DOWN){
                        ds = -2.0;
                    }else if(e.code == KeyCode.VK_LEFT){
                        da = -1.0;
                    }else if(e.code == KeyCode.VK_RIGHT){
                        da = 1.0;
                onKeyReleased: function( e: KeyEvent ) {
                    delete e.code from keys;
        public function move(){
              // check keys
    }

  • Help with key event

    hi everyone i need some help. i have to write an java application thatcreates a panel with three labels and three key events to call upon different methods. i try to creat a JFrame but have problems. anyone can help?
    Thanks

    public class MyClass extends JFrame{
    public MyClass(){
    getContentPane().add( new Label("One") );
    getContentPane().add( new Label("Two") );
    getContentPane().add( new Label("Three") );
    setSize(400,400);
    setVisible(true);
    public static void main(String[] args){
    MyClass myclass = new MyClass();
    public static void main is the starting point of a program.
    When the frame is created using
    MyClass myclass = new MyClass();
    The control goes to the constructor where you can add three labels.
    You can add three methods to MyClass and implement KeyListener in MyClass to build upon it.

  • Probelm with key events

    Hi all
    I am trying to open a swing form from a menu on a Frame object
    On the frame I have a Canvas3D
    everything is going well the canvas3d read my key events and I can walk gladly in my universe
    untill I am opening JFrame and do some stuff on it (changeing values in text fields)
    Hiding the Jframe and trying to keep moveing in my universe is not working any more any ideas???

    I checked it more closly and found out that the I do get the events and the behvior do act on them but I see nothing on the screen help....

  • How can I get around Javascipt issue with keyboard events?

    Javascript issue: keydown, keypress, keyup events cause quick search to initiate with the division key on the keypad and slash key on the keyboard. I am trying to program a graphic representation of a 10 key pad and the division (/) sign is problematic for roll over and processing based on key events. How can I get around this? further notes: Safari also has problems with key events and the division key(s) but no search function connected. Thankyou for time and attention

    A good place to ask questions and advice about web development is at the mozillaZine Web Development/Standards Evangelism forum.<br />
    The helpers at that forum are more knowledgeable about web development issues.<br />
    You need to register at the mozillaZine forum site in order to post at that forum.<br />
    See http://forums.mozillazine.org/viewforum.php?f=25

  • Iphoto events showing with key photo of a palm tree in gray?

    iphoto events showing with key photo of a palm tree in gray? Also indicates no photos but there are photos within the event??

    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Repair Database. If that doesn't help, then try again, this time using Rebuild Database.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. (In early versions of Library Manager it's the File -> Rebuild command. In later versions it's under the Library menu.)
    This will create an entirely new library. It will then copy (or try to) your photos and all the associated metadata and versions to this new Library, and arrange it as close as it can to what you had in the damaged Library. It does this based on information it finds in the iPhoto sharing mechanism - but that means that things not shared won't be there, so no slideshows, books or calendars, for instance - but it should get all your events, albums and keywords, faces and places back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one.  
    Regards
    TD

  • Help with understanding key event propagation

    Hello,
    I am hoping someone can help me understand a few things which are not clear to me with respect to handling of key events by Swing components. My understanding is summarized as:
    (1) Components have 3 input maps which map keys to actions
    one for when they are the focused component
    one for when they are an ancestor of the focused component
    one for when they are in the same window as the focused component
    (2) Components have a single action map which contains actions to be fired by key events
    (3) Key events go to the currently focused component
    (4) Key events are consumed by the first matching action that is found
    (5) Key events are sent up the containment hierarchy up to the window (in which case components with a matching mapping in the WHEN_IN_FOCUSED_WINDOW map are searched for)
    (6) The first matching action handles the event which does not propagate further
    I have a test class (source below) and I obtained the following console output:
    Printing keyboard map for Cancel button
    Level 0
    Key: pressed C
    Key: released SPACE
    Key: pressed SPACE
    Level 1
    Key: pressed SPACE
    Key: released SPACE
    Printing keyboard map for Save button
    Level 0
    Key: pressed SPACE
    Key: released SPACE
    Level 1
    Key: pressed SPACE
    Key: released SPACE
    Printing keyboard map for Main panel
    Event: cancel // typed SPACE with Cancel button having focus
    Event: save // typed SPACE with Save button having focus
    Event: panel // typed 'C' with panel having focus
    Event: panel // typed 'C' with Cancel button having focus
    Event: panel // typed 'C' with Save button having focus
    I do not understand the following aspects of its behaviour (tested on MacOSX although I believe the behaviour is not platform dependent):
    (1) I assume that the actions are mapped to SPACE since the spacebar clicks the focused component but I don't explicitly set it?
    (2) assuming (1) is as I described why are there two mappings, one for key pressed and one for key released yet the 'C' key action only has a key pressed set?
    (3) assuming (1) and (2) are true then why don't I get the action fired twice when I typed the spacebar, once when I pressed SPACE and again when I released SPACE?
    (4) I read that adding a dummy action with the value "none" (i.e. the action is the string 'none') should hide the underlying mappings for the given key, 'C' the my example so why when I focus the Cancel button and press the 'C' key do I get a console message from the underlying panel action (the last but one line in the output)?
    Any help appreciated. The source is:
    import javax.swing.*;
    public class FocusTest extends JFrame {
         public FocusTest ()     {
              initComponents();
              setTitle ("FocusTest");
              setLocationRelativeTo (null);
              setSize(325, 160);
              setVisible (true);
         public static void main (String[] args) {
              new FocusTest();
    private void initComponents()
         JPanel panTop = new JPanel();
              panTop.setBackground (java.awt.Color.RED);
    JLabel lblBanner = new javax.swing.JLabel ("PROPERTY TABLE");
    lblBanner.setFont(new java.awt.Font ("Lucida Grande", 1, 14));
    lblBanner.setHorizontalAlignment (javax.swing.SwingConstants.CENTER);
              panTop.add (lblBanner);
              JPanel panMain = new JPanel ();
              JLabel lblKey = new JLabel ("Key:");
              lblKey.setFocusable (true);
              JLabel lblValue = new JLabel ("Value:");
    JTextField tfKey = new JTextField(20);
    JTextField tfValue = new JTextField(20);
    JButton btnCancel = new JButton (createAction("cancel"));     // Add a cancel action.
    JButton btnSave = new JButton (createAction("save"));          // Add a sve action.
              panMain.add (lblKey);
              panMain.add (tfKey);
              panMain.add (lblValue);
              panMain.add (tfValue);
              panMain.add (btnCancel);
              panMain.add (btnSave);
              add (panTop, java.awt.BorderLayout.NORTH);
              add (panMain, java.awt.BorderLayout.CENTER);
    setDefaultCloseOperation (javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // Add an action to the panel for the C key.
              panMain.getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "panel");
              panMain.getActionMap ().put ("panel", createAction("panel"));
              // FAILS ???
              // Add an empty action to the Cancel button to block the underlying panel C key action.
    btnCancel.getInputMap().put (KeyStroke.getKeyStroke (java.awt.event.KeyEvent.VK_C, 0), "none");
    // Print out the input map contents for the Cancel and Save buttons.
    System.out.println ("\nPrinting keyboard map for Cancel button");
    printInputMaps (btnCancel);
    System.out.println ("\nPrinting keyboard map for Save button");
    printInputMaps (btnSave);
              // FAILS NullPointer because the map contents are null ???
    System.out.println ("\nPrinting keyboard map for Main panel");
    // printInputMaps (panMain);
    private AbstractAction createAction (final String actionName) {
         return new AbstractAction (actionName) {
              public void actionPerformed (java.awt.event.ActionEvent evt) {
                   System.out.println ("Event: " + actionName);
    private void printInputMaps (JComponent comp) {
         InputMap map = comp.getInputMap();
         printInputMap (map, 0);
    private void printInputMap (InputMap map, int level) {
         System.out.println ("Level " + level);
         InputMap parent = map.getParent();
         Object[] keys = map.allKeys();
         for (Object key : keys) {
              if (key.equals (parent)) {
                   continue;
              System.out.println ("Key: " + key);
         if (parent != null) {
              level++;
              printInputMap (parent, level);
    Thanks,
    Tim Mowlem

    Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.
    1) In the Metal LAF the space bar activates the button. In the Windows LAF the Enter key is used to activate the button. Therefore these bindings are added by the LAF.
    2) The pressed binding paints the button in its pressed state. The released binding paint the button in its normal state. Thats why the LAF adds two bindings.
    In your case you only added a single binding.
    3) The ActionEvent is only fired when the key is released. Same as a mouse click. You can hold the mouse down as long as you want and the ActionEvent isn't generated until you release the mouse. In fact, if you move the mouse off of the button before releasing the button, the ActionEvent isn't even fired at all. The mouse pressed/released my be generated by the same component.
    4) Read (or reread) the [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html#howto]How to Remove Key Bindings section. "none" is only used to override the default action of a component, it does not prevent the key stroke from being passed on to its parent.

  • How to block JTree key event listeners

    I have a JToolbar I am managing keyboards events for (e.g. PageUp, PageDown, right, left, up, down). I also have a JTree in another panel. I have to use 'Alt + PageUp' instead of PageUp because, if I use 'PageUp' (without also using the Alt key), and, the JTree gets the focus, then the JTree will respond to 'PageUp' instead of my JToolbar.
    I have my key actions in a 'getKeystrokeActions()' method which I pass the JToolbar into so I tried passing the JTree to the same method. This doesn't quite do what I want as both components now respond to a 'PageUp' key event.
    There must be some way to tell the JTree not to handle key events but I can't seem to find it. Any help much appreciated.

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

  • KeyListener Problems with Directional Key events

    Here's the problem: If I press and hold the up and right directional keys (non-numpad) and then press the left directional key, it doesn't recognize that I pressed left (i.e. "LeftKeyPressed" is not printed). What's up? Is there something I don't know about directional keys that makes them special like this? Thanks.
    Here's the code:
    public void keyPressed(KeyEvent e)
         if(e.getKeyCode() == 37)
                   left = true;
                   System.out.println("LeftKeyPressed");
         if(e.getKeyCode() == 38)
              forward = true;
         if(e.getKeyCode() == 39)
              right = true;
    }

    So you want to hold the up key and the right key down and then also press the left key down, but the left key will not activate when the up and right key are pressed and held down first.
    You might be at the point that you should ask yourself -- why do I want to have a left key event happen when I already have a right and up going on. It's obviously not for directions, you cannot go left and right at the same time.

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

  • How to disable the F4 Key Event?

    Hi Guys,
    I have written my own FocusManager which allows me to traverse through disabled components. If a user presses the F4 key while the focus is in a disabled JComboBox, the popup becomes activated. Is there any way deactivate the F4 keystroke?
    I have tried:
    event.consume();
    combobox.setPopupVisible(false);
    combobox.hidePopup();
    I also read that F4 is a low-level event maintained by Windows. Is this true? Is there no alternative?
    -Sri :)

    To anyone who may be interested:
    I have tried all available solutions:
    1. hidePopup()
    2. setPopupVisible(false)
    3. unregistering the F4 key event
    4. catching the F4 key event and snubbing it
    I have had no luck with the above solutions. It leads me to believe that F4 key is registered under the windows environment and it is a low-level event.
    -Sri :)

  • How to catch key events

    Hello!
    I have a component which extends JPanel. Now I dynamically add a JTextField as a child to this component. The problem is: when the textfield has focus, how can I get key events in my panel before the textfield gets them (and maybe intercept them so that the textfield doesn't get them at all)?
    Background: the component is a self written table and the textfield is an editor. Now I have to make sure that when I am editing and press e.g. "cursor up", that not the textfield will get this key event but the table (which should traverse the current cell then ...)
    The problem is: I cannot change the textfield (extend it or something) because a possible solution has to work with any java awt "Component" (or at least with JComponent).
    Any help very appreciated.
    Michael

    Hello,
    implement the keyListener interface for the Extended component...
    and in Keypressed method
    keyPressed(keyEvent){
    // do all ur reuirements here
    //and comsume the keyEvent...
    hope this helps

  • Macbook misses some key events for a few seconds

    I have noticed that for last two months or so something strange happens to my Retina MBP. Once in a couple of days it stops responding to some key events. It is like it handles only one keypress out of 4-5. Nothing seems to be wrong with the keyboard and it is not about a particular key or keys. And about 10-15 seconds later everything goes back to normal. I do not see any suspicious messages in the logs, the computer is connected to the power supply...It happens just by itself in the middle of the day, when I am typing.
    Almost looks like some interrupts get lost by the system while it is busy with something else. But I have checked the load level and running processes - nothing interesting there....And whatever it is - it happens during a very short period of time.

    Hi,
    No, I have not returned my MBP yet. In fact, I would rather avoid doing this unless I am convinced if it is a hardware issue. And I do believe it is not. Just recently I have spent some time investigating it and I have found very stroing correlation between the moments when this happens and these messages in the kernel log:
    Jan 13 10:49:54 mbp-wifi kernel[0]: Sandbox: sandboxd(96471) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi kernel[0]: Sandbox: sandboxd(96499) deny mach-lookup com.apple.coresymbolicationd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96497]): mdworker(96497) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:54:31 mbp-wifi.home sandboxd[96499] ([96498]): mdworker(96498) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96503]): mdworker(96503) deny mach-lookup com.apple.ls.boxd
    Jan 13 10:56:32 mbp-wifi.home sandboxd[96504] ([96502]): mdworker(96502) deny mach-lookup com.apple.ls.boxd
    And I have also noticed that my Spotlight database gets reconstructed too often, which means it gets corrupted.
    From all this I conclude that it is most likely the software issue and it seems to be linked to spotlight. I saw people reporting similar things. So now I am researching on how to fix it without disabling the spotlight.
    In general, I believe that the quality of Apple software is going down, it is not like 4-5 years ago And Apple does seem to care less and less about it.
    If in your case it happens all the time, not just once in a while, and you see that a particular key has problems - it is possible that we are talking about the different issues and yours might be really about the keyboard.

  • Detect key events on anything

    If I have a JFrame with many components on it, how do I detect if a key is pressed, without having to add a listener to every component? For example, how can I check for the escape key being pressed, but not having to have componentN.addKeyListener(this); for everything?
    Thanks
    US101

    The correct way to collect the key events is the following:
    from java 1.2 to java 1.3 use the FocusManager. This class can be found in the javax.swing package. You would then need to extend the DefaultFocusManager and override specific behavior.
    for java 1.4 use the KeyBoardFocusManager. This class can be found in the java.awt package.
    Please see the following for a better explanation:
    http://java.sun.com/j2se/1.4/docs/api/java/awt/doc-files/FocusSpec.html
    Thanks for your time,
    Nate

  • Catching key events in application

    I have a JFrame with a JDesktop containing lots of JInternalFrame with various of components such as JTextFields etc.
    Now, i want to have a "main" listener that will catch key events no matter which component that has focus. For example pressing CTRL+A should produce something in the application no matter which component that has focus.
    How do I implement this in an easy way?

    It doesnt seem to work to add a KeyListener to the JFrame...
    this.addKeyListener(new KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        System.out.println("KeyTyped()");
                   public void keyPressed(KeyEvent e){
                        System.out.println("KeyTyped()");
              });Adding that to the JFrame gives nothing to System.out when a JTextArea inside an JInternalFrame has focus.

Maybe you are looking for