package cy.event_;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/*
通过键盘控制小球上下左右
继承JFrame和键盘监听器
*/
public class BallMove extends JFrame {
MyPanel mp = null;
public static void main(String[] args) {
BallMove ballMove = new BallMove();
}
public BallMove(){
mp = new MyPanel();
this.add(mp);
this.setSize(400,300);
//让面板可以监听键盘事件
this.addKeyListener(mp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//面板,可以画出小球
class MyPanel extends JPanel implements KeyListener{
//将小球左上角的坐标设置成变量
static int x = 10;
static int y = 10;
@Override
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x,y,20,20);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
//根据用户按下的不同的按键来处理小球的移动(上下左右)
if(e.getKeyCode() == KeyEvent.VK_DOWN){
y+=5;
}else if(e.getKeyCode() == KeyEvent.VK_UP){
y-=5;
}else if(e.getKeyCode() == KeyEvent.VK_LEFT){
x-=5;
}else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
x+=5;
}
//面板重绘
this.repaint();
}
@Override
public void keyReleased(KeyEvent e) {
}
}