faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 21 people (52%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

When using the KeyPressed event, how does one code a getKeyChar to accept one of the arrow keys?

Oct 27th, 2004 22:48
Tom McGuire, Las Vegas,


Unless you are using an odd keyboard or set up (like an older version 
of Java on a Mac [just a made-up example, don't flame me]) the answer 
should be quite trivial:

EXAMPLE 1:
Given a component which will have focus at the time the user presses an 
arrow key, add the following code:

   component.addKeyListener(new KeyAdapter(){
      public void keyPressed(KeyEvent e){
         switch(e.getKeyCode()){
            case KeyEvent.VK_LEFT:
               //do something...
               break;
            case KeyEvent.VK_RIGHT:
               //do something...
               break;
         }
      }
   };

Notes on above example: 
1) KeyAdapter (an empty implementation of KeyListener) to simplify the 
code, KeyListener could just as easily been used with empty 
implementations of keyReleased() and keyTyped().
2) The component must be focusable! If you are trying to intercept 
keypresses on something like a JPanel (perhaps you're using an empty 
JPanel as a canvas) you need to call "setFocusable(true)" on the panel 
or the above code will not work.


EXAMPLE 2:
A more complex example which frequently isn't necessary is to use the 
InputMap and ActionMap for the component:

   InputMap im = getInputMap();
   im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),"Left");
   im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),"Right");
		
   ActionMap am = getActionMap();
   am.put("Left", new AbstractAction(){
         public void actionPerformed(ActionEvent ae){
            //do something...
         }
      });
		
   am.put("Right", new AbstractAction(){
         public void actionPerformed(ActionEvent ae){
            //do something...
	 }
   });