JavaSE学习之二,细节!

来源:互联网 发布:我的世界js制作器 编辑:程序博客网 时间:2024/06/17 18:41

卡了半天的错误,原来是少打了一个字母Runable –Runnable

import java.awt.*;import java.awt.event.*;//0.2v 让坦克动起来 1,将位置改变为变量。2,启动线程不断重画,每次重画改变坦克位置public class TankClient extends Frame{    int x = 50, y = 50;    public static void main(String[] args) {        TankClient tc = new TankClient();        tc.LauchFrame();    }    //画坦克,override TankClient    public void paint(Graphics g) {        Color c = g.getColor();        g.setColor(Color.RED); //己方坦克为红色        g.fillOval(x, y, 30, 30);//画圆,即坦克。 x,y为坦克位置,改为变量        g.setColor(c);//换回原来的颜色        y += 5; //重画一次改变位置    }    //画登陆框    public void LauchFrame() {        this.setLocation(400, 300);//左上角位置        this.setSize(800, 600);  //分辨率        this.setTitle("TankWar"); //标题名字        this.setBackground(Color.GREEN); //背景颜色        //关闭窗口,使用匿名类        this.addWindowListener(new WindowAdapter() {            public void windowClosing(WindowEvent e) {                        System.exit(0);                    }                });        this.setResizable(false);//不能改变窗口大小        setVisible(true);        new Thread(new PaintThread()).start();     }    //内部类 线程重画    private class PaintThread implements Runnable{        public void run() {            while(true) {                repaint();                try {                    Thread.sleep(50);                }catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

成功让圆动起来了。
同时记录下创建线程的两种方式:
第一种:继承Thread,并重写run()方法。

public class MyThread extends Thread{    public void run() {        //    }}//使用线程MyThread mt = new MyThread(); //创建线程mt.start();                   //启动线程

第二种:使用Runnable接口(因为Java的不允许多继承)

public class MyThread implements Runnable{    public void run() {        //    }}MyThread mt = new MyThread();Thread thread = new Thread(mt);//创建线程,将一个Runnable接口的实例化对象作为参数去实例化Thread类对象thread.start();                //启动线程

激活线程:
1,线程必须扩展自Thread类,使自己成为它的子类。
2,线程的处理必须写在run()方法内。

原创粉丝点击