I am a little new to Java so, sorry if I'm doing something wrong. I want my program to say The W key has been pressed
when I press the W
button. I've been having a little bit of problems with this. Here is an outline of my code:
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);
}
}
}
}
The KeyListener doesn't respond whatsoever. I think this might be because of the loop but I honestly have no idea. Can anyone expain why this is happening and how I could fix it?
The thing is: just declaring a class to be a KeyListener ... doesn't magically create that connection that is required at runtime.
In other words: the idea of a Listener is that it is registered at some point; and only registered Listeners will be notified about events.
Therefore you only need to call
somewhere within your class; for example within your constructor.
Or more specifically: you created a method
keyListener()
that would make that addKeyListener() call ... but: there is probably no call tokeyListener()
in your source code!And just for the record:
keyListener()
isn't a good name for a method; you should better call itregisterListeners()
for example.