Click here to Skip to main content
15,894,180 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why don't I get printouts after typing arrowkeys? I get the image and the striped panel.
What other information would be needed to identify the problem?
Java
public class  MyFrame extends Frame {
	
	public MyFrame(String title) { 
		
		super(title);

		Container panel = new StripedPanel();
                add(panel, BorderLayout.CENTER);

/*
* GetImage is a class extending Component
*/
		Component image = new GetImage("1.gif"); 
	        panel.add(image);

	        pack();

	        EventQueue.invokeLater(new Runnable() {
			public void run() {
				setVisible(true);
			}
		});

	        addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				int c=e.getKeyCode();
				if (c == KeyEvent.VK_UP) {
					System.out.println("Up");
//...
Posted

Hi there, if you are using java 7 i suggest using a KeyboardFocusManager. Use it something like this:
Java
public class yourClass{
      KeyBoardFocusManager manager;

      public void aMethod(){

          //doing something with your frame in this method
          //like add components, seting the layout, the size etc.


          manager=KeyboardFocusManager.getCurrentKeyboardFocusManager();
          manager.addKeyEventDispatcher(new MyKeyEventDispatcher());


      }

}

//create a private class for recognizing the keys you pressed.
      private class MyKeyEventDispatcher implements KeyEventDispatcher{

		@Override
		public boolean dispatchKeyEvent(KeyEvent e) {
			
			if(e.getID()==KeyEvent.KEY_PRESSED){
				if(e.getKeyCode()==KeyEvent.VK_UP){
					

                                         //do whatever you want to do on pressing up
				}
			}
			return false;
		}


Here the oracle link to find out more about KeyBoardFocusManager: http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/KeyboardFocusManager.html[^]

Hope it helps.
 
Share this answer
 
v3
Comments
themrpacu 24-Apr-13 20:38pm    
I appreciate the solution, but the problem had already been solved. Thanks anyway!
nameJulian 25-Apr-13 14:58pm    
You're welcome.
It's unbelievable nobody has noticed it. KeyTyped does not react to arrowkeys!

http://www.leepoint.net/notes-java/GUI-lowlevel/keyboard/keyboard.html[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900