You need a class that subclasses ACM's Program
to add a key listener to. Secondly, you need a class that implements KeyListener
(this could be the same class) and then do your code in KeyListener#keyPressed
. You can get the pressed key's code via KeyEvent.getKeyCode
and check whether it equals your desired key (in this case the P key).
The following example illustrates how this may work. It didn't test it, but it should do the trick.
public class KeyListenerExample extends GraphicsProgram {
@Override
public void run() {
addKeyListeners(new MyKeyListener());
}
private class MyKeyListener implements KeyListener {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_P) {
System.out.println("Key 'P' has been pressed!");
}
}
@Override
public void keyReleased(KeyEvent e) { /* Empty body */ }
@Override
public void keyTyped(KeyEvent e) { /* Empty body */ }
}
}
It would be helpful if you could provide a Minimal, Complete, and Verifiable example for your question (especially for further questions).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…