键盘事件——TankGame3

 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * 事件处理加深理解:
 *     实现:
 *         频幕中绘制一个小球
 *         可以用键盘控制其上下左右移动
 * @author ybz
 *Last_update2018年9月22日上午9:02:56
 */
public class ActionDemo2 extends JFrame {
    MyPanel2 mp=null;
    public ActionDemo2() {
        mp=new MyPanel2();    
        
        
        this.addKeyListener(mp);    //事件源是整个页面,监听类型是键盘事件,监听者是mp,MyPanel2类的实例
        this.add(mp);
        this.setSize(600,500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
    
    public static void main(String[] args) {
        ActionDemo2 ad2=new ActionDemo2();
    }

}

//定义自己的面板
class MyPanel2 extends JPanel implements KeyListener{
    int x=10;
    int y=10;
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x, y, 20, 20);
        
    }

            //可用来获取键盘按下的值
    public void keyTyped(KeyEvent e) {
//        System.out.println(e.getKeyChar()); //将按下的键名打印出来

        
    }

            //键盘被按下时触发
    public void keyPressed(KeyEvent e) {
//        System.out.println("键盘被按下");
        if(e.getKeyCode() == KeyEvent.VK_S) {
            y=y+2;
            y=y > 500? 0:y;
        }else if(e.getKeyCode() == KeyEvent.VK_W) {
            y-=2;
            y=y < 00? 500:y;
        }
        else if(e.getKeyCode() == KeyEvent.VK_A) {
            x-=2;
            x = x < 0? 600:x;
        }
        else if(e.getKeyCode() == KeyEvent.VK_D) {
            x+=2;
            if(x > 600) x = 0;
        }
        this.repaint();

    }

            //键盘被释放
    public void keyReleased(KeyEvent e) {
        
    }
}
 
  
 
 

  

一个类实现监听的步骤:

  1.实现相应的接口(ActionListener, KeyListener, MouseListener ,WindowListener 、、、)

  2.把接口的时间按处理方法按照你的需求重写(Override)

  3.在事件源注册监听

  4.事件传递要依靠事件对象

猜你喜欢

转载自www.cnblogs.com/ybzmy/p/9689661.html