From f25d185079d43a91c48c31f80c8b5fbd090707a5 Mon Sep 17 00:00:00 2001 From: bingor_yhj Date: Thu, 29 Sep 2022 17:18:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=94=AE=E7=9B=98=E7=9B=91?= =?UTF-8?q?=E5=90=AC=E4=BA=8B=E4=BB=B6=EF=BC=8C=E9=80=9A=E8=BF=87=E9=94=AE?= =?UTF-8?q?=E7=9B=98=E6=8E=A7=E5=88=B6=E6=96=B9=E5=9D=97=E7=9A=84=E7=A7=BB?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/com/msb/TankDemo.java | 8 +++++++- src/com/msb/TankFrame.java | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) 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); + } + } + }