-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBallRolling.java
More file actions
81 lines (62 loc) · 1.46 KB
/
BallRolling.java
File metadata and controls
81 lines (62 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* 通过键盘控制小球移动
*/
package com.bj.event;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class BallRolling extends JFrame{
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
BallRolling br=new BallRolling();
}
public BallRolling(){
mp=new MyPanel();
this.add(mp);
this.addKeyListener(mp);
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//定义自己面板
class MyPanel extends JPanel implements KeyListener{
int x=10;
int y=10;
public void paint (Graphics g){
super.paint(g);
g.fillOval(x, y, 20, 20);
}
//具体按下某一个键
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("KeyType");
}
//键按下
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println("KeyPressed"+(char)e.getKeyCode());
if(e.getKeyCode()==KeyEvent.VK_DOWN){
//System.out.println("12");
this.y+=10;
}else if(e.getKeyCode()==KeyEvent.VK_UP){
this.y-=10;
}else if(e.getKeyCode()==KeyEvent.VK_LEFT){
this.x-=10;
}else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
this.x+=10;
}
//调用重绘函数repaint
this.repaint();
}
//键松开
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("KeyReleased");
}
}