我对Java有点新鲜,所以对不起,如果我做错了什么。当我按W
按钮时,我希望我的程序说The W key has been pressed
。我一直在遇到一些问题。这是我的代码的大纲:
public class Main extends JFrame implements ActionListener, KeyListener {
public void keyListener(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_W){
System.out.println("W is pressed");
}
}
@SuppressWarnings("null")
public static void main(String[] args) throws InterruptedException {
//Initial things like variables and JFrame setup (Like: JFrame frame = new JFrame("FrameDemo");)
for(step = 0; step == step; step++ ){
for(i = 0; i < constructor.length; i++){
//Some code
constructor[i].draw(g);
}
}
}
}
钥匙列表没有任何响应。我认为这可能是因为循环,但老实说我不知道。谁能透露为什么会发生这种情况以及我如何解决?
事实是:仅声明 a类都是钥匙列表...不会神奇地创建所需的 Connection 在运行时。
换句话说:听众的想法是在某个时候是注册;并且只有注册听众就会收到有关事件的通知。
因此,您只需要致电
addKeyListener(this)
您班上的某个地方;例如,在您的构造函数中。
或更具体地说:您创建了一种方法keyListener()
,该方法将使该方法 addKeyListener() call ...但是:但是:源代码中可能没有呼叫keyListener()
!
只是为了记录:keyListener()
不是方法的好名字;例如,您应该最好将其称为registerListeners()
。