Java多线程实现同时进行小球的自由落体与平抛

来源:互联网 发布:js explode 编辑:程序博客网 时间:2024/05/21 10:54

Java多线程的实现方法有继承Thread和实现接口Runnable。我这里用的是通过实现接口Runnable来创建新线程的。

要实现自由落体与平抛。

首先,是小球在窗口中运动。将小球封装成一个类,继承Canvas。通过new小球的类,添加到窗口上。

运动的是不断的变化小球的位置,通过Sleep一小段时间。来实现动画的效果。


下面的是代码,有详细注释。

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class BallDemo{public static void main(String[] args){Movement m = new Movement();m.setResizable(false);  //设置窗口大小不可变化}}class Movement extends JFrame implements Runnable{/** *  */private static final long serialVersionUID = 1L;JButton button;Thread pinkball, yellowball;Ball pink, yellow;double time = 0.0;Movement(){super("Ball Show");             //窗口标题setBounds(300, 200, 600, 400);  //设置窗口位置和大小setLayout(null);                //空的布局管理器,里面的部件位置可以根据自己的想法放在任意位置setVisible(true);               //设置可见button = new JButton("Start");  //创建一个按钮button.setBounds(530, 0, 65, 30);//设置按钮位置和大小add(button);                     //添加到窗口上pinkball = new Thread(this);     //创建线程,里面加的是this,因为这个类实现了接口Runnableyellowball = new Thread(this);   //创建线程pink = new Ball(Color.pink);     //创建粉色小球yellow = new Ball(Color.yellow); //创建黄色小球add(pink);                       //添加到窗口上add(yellow);                     //添加到窗口上pink.setLocation(150, 20);       //设置显示的位置yellow.setLocation(300, 20);     //设置显示的位置button.addActionListener(new ActionListener()  //按钮添加活动事件监听,一旦按下按钮,就执行下面的函数{public void actionPerformed(ActionEvent e)    //开启线程{pinkball.start();yellowball.start();}});this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   //设置点击右上角的关闭窗口时  关闭窗口。}public void run()   //run方法{while(true){time += 0.2;   //时间递增if(time > 20)  //超过了20,重新来过time = 0.0;if(Thread.currentThread() == pinkball)  //粉色的球的线程{int x = 150;int y =  (int)(1.0 / 2 * time * time * 9.8) + 20;   //通过1/2gt^2 + 原始位置上的y算出之后的位置pink.setLocation(x, y);   //设置位置try{Thread.sleep(50);    //线程睡眠50MS}catch(Exception e){e.printStackTrace();}}if(Thread.currentThread() == yellowball){int x = 300 + (int)(30 * time);         //通过s = vt公式加上原始位置的x算出之后的位置    <span style="white-space:pre"></span>int y = (int)(1.0 / 2 * time * time * 9.8) + 20;  //<span style="font-family: Arial, Helvetica, sans-serif;">通过1/2gt^2 + 原始位置上的y算出之后的位置</span>yellow.setLocation(x, y);     //设置位置try{Thread.sleep(50);    //线程睡眠50MS}catch(Exception e){e.printStackTrace();}}}}}class Ball extends Canvas    //Ball 类,继承了Canvas,{/** *  */private static final long serialVersionUID = 2L;Color color;public Ball(Color color)    //通过构造函数设置好大小和颜色{this.color = color;setSize(20, 20);}public void paint(Graphics g)    //画出一个圆形。{g.setColor(color);g.fillOval(0, 0, 20, 20);}}

这里只放一张截图,不会弄GIF动态图。



0 0
原创粉丝点击