添加键盘监听事件,通过键盘控制方块的移动

Network
bingor_yhj 2 years ago
parent ef93249b91
commit f25d185079

@ -8,8 +8,14 @@ package com.msb;
*/
public class TankDemo {
public static void main(String[] args) {
public static void main(String[] args) throws InterruptedException {
TankFrame tankFrame = new TankFrame();
//现实当中,虽然可以过按键来改变方块的坐标并且重新刷新画板来实现移动,但是敌方的坦克应该是自动在跑
while (true) {
Thread.sleep(50);
tankFrame.repaint();
}
}
}

@ -1,6 +1,8 @@
package com.msb;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
@ -16,10 +18,12 @@ public class TankFrame extends Frame {
private int y = 200;
public TankFrame() {
setTitle("Tank war");
setSize(800, 600);
setResizable(true);
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
@ -27,11 +31,31 @@ public class TankFrame extends Frame {
System.exit(0);
}
});
addKeyListener(new MyKeyListener());
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.fillRect(x, y, 50, 50);
x += 10;
}
//这里使用内部内的原因是只有TankFrame用到
class MyKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
/*x += 10;
repaint();*/
}
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
}
}
}

Loading…
Cancel
Save