问题
I have public class MainFrame extends JFrame implements ActionListener {
and then later on:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_LEFT) {
int x = ball.getX() + 1;
ball.setX(x);
}
}
however it does not seem to respond when I believe it should.
If I add keylistener instead of actionlister I cannot compile which I can't understand. I'm new to java however i'm used to C#
回答1:
- You need to implement
java.awt.event.KeyListener
not aActionListener
to listen for key events. - You need to register your listener on the element (frame) you want to listen on by invoking
addKeyListener(...)
.
Example:
public class TestFrame extends JFrame implements KeyListener {
public static void main(String[] args) throws FileNotFoundException {
TestFrame testFrame = new TestFrame();
testFrame.setSize(100, 100);
testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
testFrame.addKeyListener(testFrame);
testFrame.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) { }
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e);
}
@Override
public void keyReleased(KeyEvent e) { }
}
来源:https://stackoverflow.com/questions/22131146/cannot-make-a-keylistener-work