Small animation(画布小动画)

来源:互联网 发布:db2 连接数据库 编辑:程序博客网 时间:2024/06/06 13:15
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

//Small animation
public class Test3 implements Runnable{
private JFrame f;
private JPanel p;
private JLabel l;
public MyCanvas canvas1, canvas2;
Thread t1, t2;

Test3(){
//画布
canvas1 = new MyCanvas(Color.BLUE); //参数传递成功
canvas2 = new MyCanvas(Color.RED);

//界面
f = new JFrame();
p = new JPanel();
l = new JLabel("小动画");

p.setLayout(new FlowLayout());
f.setLayout(new BorderLayout());

p.add(canvas1);
p.add(canvas2);
canvas1.setBounds(50, 50, 50, 50); //之前找不到方块是因为没有设定位子
canvas2.setBounds(50, 50, 50, 50);

f.add(l,"North");
f.add(p,"Center");

f.setBounds(50,50,500,500);
f.setVisible(true);


//添加线程
t1 = new Thread(this);
t2 = new Thread(this);

t1.start();
t2.start();

}

//重点!!!!:要获取线程名字执行多个路线 即一个Runnable 要主函数实现接口
double t = 0;
public void run(){
while(true){
t = t + 0.2;
if(t > 20)
t = 0;

//判断哪个线程
if(Thread.currentThread().equals(t1)){
int x = 60;
int h = (int) (1.0 / 2 * t * t * 3.8) + 60; //利用二次函数

canvas1.setLocation(x, h);

try {
Thread.sleep(50); //时间延长到3秒 会发现red和blue高度明显不相同 
} catch (InterruptedException e) {
}

}else if (Thread.currentThread().equals(t2)){
int x = 60 + (int) (26 * t);
int h = (int) (1.0 / 2 * t * t * 3.8) + 60;

canvas2.setLocation(x, h);

try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}

}

}

public static void main(String args[]){
new Test3();
}

}


@SuppressWarnings("serial")
class MyCanvas extends Canvas{
Color c;
MyCanvas(Color c){
this.c = c;
}

public void paint(Graphics g){
g.setColor(c);
g.drawRect(0, 0, 20, 20);
}
} /*

  */
原创粉丝点击