编写一个Java GUI应用程序,采用Java多线程技术,模拟自由落体和平抛运动:一个球自由落下,一个球水平抛出。
(自由落体物理公式:h= g *t2/2 ;平抛运动物理公式:h= g *t2/2 ,x=26*t ;
h代表高度,t代表时间,g代表重力加速度=9.8 m/s2 )。
(自由落体物理公式:h= g *t2/2 ;平抛运动物理公式:h= g *t2/2 ,x=26*t ;
h代表高度,t代表时间,g代表重力加速度=9.8 m/s2 )。
import java.awt.event.*;public class asd {
public static void main(String args[]) {
MyFrame frame = new MyFrame();
frame.setBounds(10, 10, 500, 500);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}class MyFrame extends Frame implements Runnable {
Thread 红色球, 兰色球;
MyCanvas red, blue;
double t = 0; MyFrame() {
红色球 = new Thread(this);
兰色球 = new Thread(this);
red = new MyCanvas(Color.red);
blue = new MyCanvas(Color.blue);
setLayout(null);
add(red);
add(blue);
red.setLocation(60, 100);
blue.setLocation(60, 100);
红色球.start();
兰色球.start();
} public void run() {
while (true) {
t = t + 0.2;
if (t > 20)
t = 0;
if (Thread.currentThread() == 红色球) {
int x = 60;
int h = (int) (1.0 / 2 * t * t * 3.8) + 60;
red.setLocation(x, h);
try {
红色球.sleep(50);
} catch (InterruptedException e) {
}
} else if (Thread.currentThread() == 兰色球) {
int x = 60 + (int) (26 * t);
int h = (int) (1.0 / 2 * t * t * 3.8) + 60;
blue.setLocation(x, h);
try {
兰色球.sleep(50);
} catch (InterruptedException e) {
}
}
}
}
}class MyCanvas extends Canvas {
Color c; MyCanvas(Color c) {
setSize(20, 20);
this.c = c;
} public void paint(Graphics g) {
g.setColor(c);
g.fillOval(0, 0, 20, 20);
}
}