adding KeyListener to JPanel !!!!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 7 of 7

Thread: adding KeyListener to JPanel !!!!

Hybrid View

  1. #1
    Join Date
    Jan 2005
    Posts
    9

    Exclamation adding KeyListener to JPanel !!!!

    hi....

    In my program, i want to add mouse and key listeners to a JPanel. there is no problem with the mouse listener. But the keylistener is not working. my code looks like

    myPanel.addMouseListener(this);
    myPanel.addKeyListener(this);

    my class implements these two listeners. the program compiles and it is running. i am not able to debug the error with keylistener. it seems key listener has not added to the JPanel. somebody pls help...

    thanx...

    sanu

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    I think you have to use the panel requestFocus() method to capture keyStrokes.
    Note, the KeyTyped event is partially deaf...
    Go for the KeyPressed event.
    eschew obfuscation

  3. #3
    Join Date
    Jan 2005
    Posts
    9
    ya....its working...
    i modified it to
    jpanel.setFocusable(true);
    jpanel.addKeyListener(this);
    now it works. But there still remains a problem. the listener tracks all keys except the TAB key. when TAB key is pressed neither keyPressed nor keyReleased is calling. wat could be the problem....

    sanu

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Beats me... :(

    I have tried with key binding also, but it responds to all the
    KeyEvent.VK_<key> but not to KeyEvent.VK_TAB.
    It would be nice if anyone could tell us...

    Her is the keylistener and keybinding setup (that fails), you may want to
    mess with it...

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    
    /**
     * Listen to keys typed
     */
    
    public class KeyListenerFrame extends JFrame implements KeyListener {
      GridLayout gridLayout1 = new GridLayout();
      JPanel listenerPan = new JPanel();
    
      public KeyListenerFrame() {
        try {
          jbInit();
          listenerPan.addKeyListener(this);
          addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
            }
          });      
          listenerPan.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0,true),
                                 "showKey");
          listenerPan.getActionMap().put("showKey",
                                  showKey);
    
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      public static void main(String[] args) {
        KeyListenerFrame klf = new KeyListenerFrame();
        klf.setBounds(10,10,200,200);
        klf.setVisible(true);
        klf.focusPanel();
      }
      public void focusPanel() {
         listenerPan.requestFocus();
      }
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(gridLayout1);
        this.getContentPane().add(listenerPan, null);
      }
      Action showKey = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("VK_PAGE_UP");
        }
      };
    
    
      public void keyTyped(KeyEvent e) {
        System.out.println(e.toString());
      }
      public void keyPressed(KeyEvent e) {
       System.out.println(e.toString());
      }
      public void keyReleased(KeyEvent e) {
        System.out.println(e.toString());
      }
    }
    PS: this php setup likes to put spaces in the code....
    eschew obfuscation

  5. #5
    Join Date
    Jan 2005
    Posts
    9

    Unhappy

    hi...

    once the tab key is pressed, keyListener seems to have stopped functioning. i am not able to track a single key after that. is it becoz the component (jpanel) loses its focus when we press the tab key. if so wat should be done...pls help

    sanu

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Got the BUGGER !!

    .. I think, but this solution may have some side effects. I have overridden
    the getFocusTraversalKeys method in Component and put this in
    a JFrame exension. (I think) this implementation stops all key entries
    that defines a forward/backward forcus traversal from actuall doing
    a traversal. Anyway, the TAB key comes through loud and clear, both tab
    and shift+tab

    Code:
    HashSet emptySet=new HashSet();
    .
    .
    public Set getFocusTraversalKeys (int id) {
      if (id==KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS ||
          id==KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS) {
        return emptySet;
      } else return super.getFocusTraversalKeys(id);
    }
    Last edited by sjalle; 03-14-2005 at 05:19 AM.
    eschew obfuscation

  7. #7
    Join Date
    Jan 2010
    Posts
    1
    I know this may be too late a response, but I think you will have to release Tab and SHift+Tab from their default traversal roles by doing

    JComponent.setFocusTraversalKeysEnabled(false);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center