Вы находитесь на странице: 1из 1

LISTENING TO KEYPRESSES

To create an interesting game, you will probably want your rectangle to be able to respond
to keypresses. To do this, you write an inner class called KeyPressListener, which you put
inside your frame class. Here is a simple example, which has the rectangle move up when
you press the q key, and move down when you press the z key.
private class KeyPressListener extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyChar() == 'q')
{
gr.translate(0,-10);
}
if(e.getKeyChar() == 'z')
{
gr.translate(0,10);
}
repaint();
}
}

You will also need a new import for this code. import java.awt.event.*;
Since the rectangle is not going to do anything at all until you press the key, change the run
method inside the MoveThread class to this:
public void run()
{
while (true)
{}
}
Finally, you need to write code to attach the listener to the frame. Add these two lines of
code to the constructor:
KeyPressListener keylistener = new KeyPressListener();
this.addKeyListener(keylistener);
Try it! If you get it to work, try activating other keys to do different things.

Вам также может понравиться