2016-12-30 91 views
-2

此代码应返回工作“A”时,按下右箭头键和返回“B”你放开之后。但它不会返回任何东西。我能做些什么来解决这个问题?KeyListener的不带箭头键

import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 

public class KeyIna implements KeyListener{ 

     @Override 
     public void keyPressed(KeyEvent ke0) { 
      if (ke0.getKeyCode() == KeyEvent.VK_RIGHT) { 
       System.out.println("A"); 
     } 
     } 

     @Override 
     public void keyReleased(KeyEvent ke1) { 
      if (ke1.getKeyCode() == KeyEvent.VK_RIGHT) { 
       System.out.println("B"); 
     } 

     } 

     @Override 
     public void keyTyped(KeyEvent ke2) { 
      // TODO Auto-generated method stub 

     } 
} 
+2

您是否已将KeyListener正确添加到组件中? – Jyr

回答

1

好了,关键听众是一个对象,你可以分配到任何东西在屏幕上,如一个窗口,或JComponent。只有听众自己不会做任何事情。一个关键的监听器只是在它所属的窗口关注并接收到一个按键/释放时负责响应。如果你只想有任何通用的窗口,你可能只是这样做(一个main函数内):

JFrame frame = new JFrame("title"); // creates a window 
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // makes it so that the window closes when you press the close button or Alt-F4 
frame.setSize(200, 500); // or whatever size you want 
frame.add(new KeyIna()); // adds the listener to the window 
frame.setVisible(true); // shows the frame 

然后,如果您单击窗口,然后按键,伟大的事情会发生。

+0

谢谢!我将它添加到面板,而不是jframe。 –

+0

@SaurishSuman哦,好的。很高兴解决方案的作品!虽然,您可以将它添加到面板,并且只要将面板添加到jframe,如果您单击该面板将其放在焦点上,它仍然可以工作。 – HyperNeutrino