Keyboard listening event, listening event
Package tank. world;
Import java. awt. Graphics;
Import java. awt. event. KeyEvent;
Import java. awt. event. KeyListener;
Import java. awt. image. BufferedImage;
Import javax. swing. JPanel;
Public class Object extends JPanel implements KeyListener {
Public static final int U = 1;
Public static final int D = 2;
Public static final int L = 3;
Public static final int R = 4;
Public static final int S = 5;
Protected int state = U;
Public static BufferedImage up;
Public static BufferedImage down;
Public static BufferedImage right;
Public static BufferedImage left;
Public static BufferedImage bullet;
Static {
Right = TankObject. loadImage ("1.png ");
Up = TankObject. loadImage ("2.png ");
Down = TankObject. loadImage ("3.png ");
Left = TankObject. loadImage ("yellowL.png ");
Bullet = TankObject. loadImage ("3.gif ");
}
Int x = 400;
Int y= 600;
Public void outOfBounds (){
If (this. y> = 800 ){
Y = 800;
}
}
Public void paint (Graphics g ){
Super. paint (g );
Switch (state) // call a constant
{
Case U: // up // If the button is up, the image is called up.
G. drawImage (up, x, y, null );
System. out. println ("111 ");
Break;
Case D: //
G. drawImage (down, x, y, null); // call the down image if the button is down.
System. out. println ("222 ");
Break;
Case L: // left
G. drawImage (left, x, y, null); // call the image to the left when the key is left.
System. out. println ("333 ");
Break;
Case R: // right
G. drawImage (right, x, y, null); // call the image to the right if the button is right.
System. out. println ("444 ");
Break;
Case S: // Space
G. drawImage (bullet, 100,100, null); // call the bullet image when the key is a space
System. out. println ("555 ");
Break;
}
}
Public void keyPressed (KeyEvent e) {// method when a key is pressed
// System. out. println ("pressed" + (char) e. getKeyCode ());
Switch (e. getKeyCode ()){
Case KeyEvent. VK_UP: //
Y-= 10; // The speed value to adjust the speed
If (this. y> = 800 ){
Y = 800;
}
If (this. y <= 0 ){
Y = 0;
}
This. repaint (); // call the repaint () method to redraw the tank position
State = U;
Break;
Case KeyEvent. VK_DOWN: //
Y + = 10; // The speed value to adjust the speed
If (this. y> = 700 ){
Y = 700;
}
If (this. y <= 0 ){
Y = 0;
}
This. repaint (); // call the repaint () method to redraw the tank position
State = D;
Break;
Case KeyEvent. VK_LEFT: // left
X-= 10;
If (this. x> = 800 ){
X = 800;
}
If (this. x <= 0 ){
X = 0;
} // The speed value to adjust the speed
This. repaint (); // call the repaint () method to redraw the tank position
State = L;
Break;
Case KeyEvent. VK_RIGHT: // right
X + = 10; // The speed value to adjust the speed
If (this. x> = 735 ){
X = 735;
}
If (this. x <= 0 ){
X = 0;
}
This. repaint (); // call the repaint () method to redraw the tank position
State = R;
Break;
Case KeyEvent. VK_SPACE:
State = S;
This. repaint ();
Break;
}
}
Public void keyTyped (KeyEvent e ){
}
Public void keyReleased (KeyEvent e ){
}
}