Small animation(画布小动画)

本文介绍了一个使用Java语言实现的小型动画应用,通过自定义Canvas绘制蓝色和红色方块,并使用两个线程分别控制方块的位置变化,展示了Java图形界面编程的基础知识。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
} /*

  */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值