您的位置:首页 > 编程语言 > Java开发

java项目之——坦克大战 04

2016-08-12 16:18 465 查看
功能:让坦克动起来

内容:改变位置,坦克就会动。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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: