泛不系舟

天行健,君子以自强不息;地势坤,君子以厚德载物。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

以阅读代码为主:

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) {

    }
}

 

posted on 2015-10-16 14:16  惊蝴蝶  阅读(677)  评论(0编辑  收藏  举报