昨天某同学说她的Java-Applet作业遇到了一些小困难,请我帮忙~~一开始我真的很纠结,毕竟我对Java-Applet也不熟悉,但是同学竟然手绘了一张示意图给我传过来了,于是,我便决定帮这个忙~~~
其实这个程序说起来并不难,就是显示两张图片,在点击一张图片时显示一朵花,在点击另一张图片时显示另一朵花~~在鼠标点击的同时,还要发出声音~~
程序的结构很清楚也很简单,不过我却卡在了图片预载入这个地方~~试了多次图片都不能在第一次运行时成功载入,没办法~用PS降低了文件的大小~~~咔咔…(我尝试在程序中判断是否载入完成,结果没成功@_@)
附源代码:
import java.applet.*;
import java.awt.*;
public class MyApplet1 extends Applet{
String text;
Image cat1,cat2,flower1,flower2;
Image tmp1,tmp2;
int x1=0,y1=0,x2=550,y2=131;
public void init(){
//窗口大小
this.setSize(1000, 600);
//预装载图片
cat1 = getImage(this.getCodeBase(), "images/cat1.gif");
cat2 = getImage(this.getCodeBase(), "images/cat2.gif");
flower1 = getImage(this.getCodeBase(), "images/flower1.gif");
flower2 = getImage(this.getCodeBase(), "images/flower2.gif");
tmp1=null;
tmp2=null;
}
public void paint(Graphics g){
//判断图像是否载入完成
//while (tmp1.getHeight(null)==-1) {repaint();};
g.drawImage(cat1, x1, y1, this);//左上角的猫
g.drawImage(cat2, x2, y2, this);//右下角的猫
g.drawImage(tmp1, x1, y1, this);//修改左上角的花的位置改这里
g.drawImage(tmp2, x2, y2, this);//修改右下角的花的位置改这里
g.drawString(text,20,20);
}
public boolean mouseUp(Event evt,int x,int y)//获取鼠标点击事件
{
text=x+" "+y;
if (x>=42&&x< =272&&y>=25&&y< =402)
{
tmp1=flower1;//显示左上角的花
play(getCodeBase(),"images/click.wav");
}
else if (x>=668&&x< =920&&y>=220&&y< =590)
{
tmp2=flower2;//显示右下角的花
play(getCodeBase(),"images/click.wav");
}
repaint();
return true;
}
}