用键盘控制小球的方向

面板类

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class TetrisPanel extends JPanel implements Runnable,KeyListener{//绘图线程类

    public int ypos = -80, xpos = 90;
    private Image iBuffer;
    private Graphics gBuffer;

    public TetrisPanel(){
        //创建一个新的线程
        Thread t = new Thread(this);
        //启动线程
        t.start();
        //设定焦点在本面板并作为监听对象
        setFocusable(true);
        addKeyListener(this);
    }

    @Override
    public void run() {//重载类方法
        // TODO Auto-generated method stub
        while (true){
            try{
                Thread.sleep(30);
            }catch(InterruptedException e){}
            ypos += 5;//修改小球的纵坐标
            if (ypos > 300)
                ypos = -80;
            repaint();//床口重绘
        }
    }

    public void paint(Graphics g){//重载绘图方法
       // super.paint(g);//将原来画布上的东西擦掉
        g.clearRect(0, 0, this.getWidth(), this.getHeight());
        g.setColor(Color.RED);
        g.fillOval(xpos, ypos, 80, 80);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        int keyCode = e.getKeyCode();
        switch(keyCode){
        case KeyEvent.VK_LEFT:
            xpos -= 10;
            break;
        case KeyEvent.VK_RIGHT:
             xpos += 10;
             break;
        }

        repaint();
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

}

你可能感兴趣的:(java)