我们先实现一个简单的小球运动:“一个小球在窗体打开时,做匀速直线运动。”
1、创建一个 线程小球类(ThreadBall)实现Runnable 接口
public class ThreadBall extends JFrame implements Runnable{
public void ui(){
this.setSize(1200, 1000);
this.setLocationRelativeTo(null);
this.setVisible(true);
2、创建一个画图的方法:用来画一个小球。(在“ThreadBall类”中继承JFrame)
在这里我们需要调用父类的paint方法====>因为小球每运动一次我们都需要将它保存并重新绘制一遍。
//定义小球的开始位置
int x = 50, y =100
//重绘小球的方法
public void paint (Graphics g) {
super.paint(g);
g.fillOval(x+i,y,50,50)
}
*3、复制Runnable接口下的run方法 ====> 用来让小球运动*
//定义小球运动的次数
int i = 0
//小球运动的方法
public void run(){
while(true){ //循环语句
i++;
this.repaint; //调用小球的重绘方法
System.out.println(i+"----");
try {
Thread.sleep(10); // 减小小球的运动速度
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
4、主方法:线程的启动 :直接调用对象的start方法
public static void main(String[] a){
ThreadBall threadball = new ThreadBall();
threadball.ui();
//线程
Thread th = new Thread(threadball); //在实现Runnable接口下,需要重新建立Thread对象
//启动线程
th.start(); //Thread类的对象调用start() 方法
}