📄 applettest6_multi_noflash.java
字号:
/*本例是用多线程来画动画--航行中的小船*/
/*本例用双缓冲来消除闪烁*/
import java.applet.*;
import java.awt.*;
public class AppletTest6_multi_noflash extends Applet implements Runnable
{
Image bufferImage;
Graphics bufferGraphics;
Thread r; //定义一个新的线程,在这个线程的run()中来绘图。
int xpos;
int up_down,i; //船上下颠簸值
public void start()
{
xpos=0;
i=0;
up_down=0;
if(r==null)
{
r=new Thread(this);
r.start(); //执行线程的start()方法时即调用run()
}
}
public void run()
{
while(true) //这里使用死循环让此线程一直运行,除非你人为中断(如调用此线程的stop()方法)
{
repaint();
try {
Thread.sleep(300); //此线程休眠,其它线程就可以工作(本例中即调用Applet的paint()方法)
}
catch(InterruptedException e) {}
}
}
public void stop()
{
if(r!=null)
{
r.stop();
r=null;
}
}
public void paint(Graphics g)
{
setBackground(Color.black);
int w=getSize().width;
int h=getSize().height;
int[] wave_len={w/3,w/4,w/6,w/10};
xpos+=10;
if(xpos>=w) xpos=0;
switch (i)
{
case 0: {up_down=h/40;break;}
case 1: {up_down=0;break;}
case 2: {up_down=-h/30;break;}
case 3: {up_down=0;break;}
}
i++;
if(i==4) i=0;
bufferImage=createImage(w,h);//以Applet窗口大小来创建bufferImage
bufferGraphics=bufferImage.getGraphics();
/* Image =“画布”,Graphics = “画笔”,Image.getGraphics()方法就是绑定画布和画笔 */
bufferGraphics.setColor(Color.green);
bufferGraphics.drawLine(0, 7*h/10, w, 7*h/10);//画水面
for(int i=0;i<wave_len.length;i++) //画波浪
{
bufferGraphics.drawLine(w/2-wave_len[i]/2-xpos, 7*h/10+(i+1)*h/40, w/2+wave_len[i]/2-xpos, 7*h/10+(i+1)*h/40);
bufferGraphics.drawLine(w/2-wave_len[i]/2-xpos+w/2, 7*h/10+(i+1)*h/40, w/2+wave_len[i]/2-xpos+w/2, 7*h/10+(i+1)*h/40);
bufferGraphics.drawLine(w/2-wave_len[i]/2-xpos+w, 7*h/10+(i+1)*h/40, w/2+wave_len[i]/2-xpos+w, 7*h/10+(i+1)*h/40);
}
bufferGraphics.setColor(Color.blue);
bufferGraphics.fillArc(w/4, h/2+up_down, w/2, h/4, 0, -180); //船仓
bufferGraphics.setColor(Color.pink);
bufferGraphics.fillRect(w/4, 5*h/8-h/100+up_down, w/2, h/100); //船弦,高度=h/100
bufferGraphics.setColor(Color.yellow);
bufferGraphics.fillArc(w/2-w/12-3*h/16, h/4+up_down, 3*h/8, 3*h/8-h/20, 90, -180); //船帆
bufferGraphics.setColor(Color.red);
bufferGraphics.fillRect(w/2-w/12-w/100, h/4+up_down, w/100, 3*h/8-h/100); //桅杆
bufferGraphics.setColor(Color.white);
bufferGraphics.fillArc(10, 10, h/4, 3*h/16, 90, -180);
bufferGraphics.setColor(Color.black);
bufferGraphics.fillArc(10+h/20, 10, h/4-h/10, 3*h/16, 90, -180); //月亮
g.drawImage(bufferImage,0,0,this);
}
public void update(Graphics g) //覆盖update以使它不在两次画操作之间清屏
{
paint(g);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -