上机题目(初级)- 键盘控制小球(Java)

这里实现键盘监听,监听上下左右四个按键,操控小球上下左右移动,代码如下:

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyListenerDemo {

	public static void main(String[] args) {
		Frame frame = new Frame();
		frame.setSize(800, 800);
		frame.setBackground(Color.BLACK);
		MyPanel myPanel = new MyPanel();
		frame.add(myPanel);
		frame.addKeyListener(myPanel);
		myPanel.addKeyListener(myPanel);

		frame.show();

	}
}

class MyPanel extends Panel implements KeyListener {
	int x = 150;
	int y = 150;

	@Override
	public void paint(Graphics g) {
		g.setColor(Color.WHITE);
		g.fillOval(x, y, 20, 20);
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == 37) {
			x--;
		} else if (e.getKeyCode() == 38) {
			y -= 10;
		} else if (e.getKeyCode() == 39) {
			x += 10;
		} else if (e.getKeyCode() == 40) {
			y += 10;
		}
		repaint();// 不要忘了!!!!!

	}

	@Override
	public void keyReleased(KeyEvent e) {// 松开键盘,返回到起点
		x = 150;
		y = 150;
		repaint();

	}

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

	}
}

松开键盘时小球回到起点,运行实例如下:


你可能感兴趣的:(java)