java项目之——坦克大战 04

来源:互联网 发布:帮友贷网络借贷 编辑:程序博客网 时间:2024/04/29 11:25

功能:让坦克动起来

内容:改变位置,坦克就会动。a.设置成员变量,x  ,  y;

                                                        b.每一段时间重画一次:y+=5;

                                                        c.重画线程类。(优点:线程重画坦克,比较均匀。)

public class TankClient extends Frame {int x = 30; int y = 30;                //定义在方法外面public void paint(Graphics g) {Color c = g.getColor();g.setColor(Color.RED);g.fillOval(x, y, 30, 40);g.setColor(c);y += 5;}public void lauchFrame(){this.setSize(800,600);this.setTitle("TankWar");this.setLocation(80, 60);this.setVisible(true);this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e) {    System.exit(0);}});this.setResizable(false);new Thread(new paintThread()).start();}public static void main(String[] args) {TankClient tc = new TankClient();tc.lauchFrame();}private class paintThread implements Runnable {   //线程 内部类 为此线程服务public void run() {while(true){repaint();try {Thread.sleep(50);} catch (Exception e) {e.printStackTrace();}}}}}

关键代码:线程。
private class paintThread implements Runnable {   //线程 内部类 为此线程服务public void run() {while(true){repaint();try {Thread.sleep(50);} catch (Exception e) {e.printStackTrace();}}}}
实现Runnable接口,repaint()方法一直重画,延时时间sleep(50)

启动线程:

new Thread(new paintThread()).start();


0 1