diff --git a/src/com/msb/TankDemo.java b/src/com/msb/TankDemo.java index ab9dadd..4e41ec8 100644 --- a/src/com/msb/TankDemo.java +++ b/src/com/msb/TankDemo.java @@ -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(); + } } } diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index 3d49731..588e466 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -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); + } + } + }