码迷,mamicode.com
首页 > 编程语言 > 详细

Java从入门到精通15-方向键控制小球实例

时间:2015-10-16 15:06:04      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

以阅读代码为主:

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

/**
 * Created by Administrator on 2015-10-15.
 */
public class ArrawKey extends JFrame {
    CirclePanel circlePanel = null;

    public static void main(String[] args) {
        ArrawKey arrawKey = new ArrawKey();
    }

    //构造函数
    public ArrawKey() {
        circlePanel = new CirclePanel();
        this.add(circlePanel);
        this.addKeyListener(circlePanel);
        this.setSize(640, 480);
        this.setTitle("方向键控制小球实例");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}

//定义面板
class CirclePanel extends JPanel implements KeyListener {
    int x = 10;
    int y = 10;

    public void paint(Graphics graphics) {
        super.paint(graphics);
        graphics.fillOval(x, y, 10, 10);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_DOWN:
                y += 10;
                break;
            case KeyEvent.VK_UP:
                y -= 10;
                break;
            case KeyEvent.VK_RIGHT:
                x += 10;
                break;
            case KeyEvent.VK_LEFT:
                x -= 10;
                break;
        }
        this.repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }
}

 

Java从入门到精通15-方向键控制小球实例

标签:

原文地址:http://www.cnblogs.com/alphastudio/p/4885173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!