Chargement et affichage d'un image
Pour charger une image d'abord il faut creer un objet de la classe Image. Pour ca on a besoin de deux location:
L'affichage de l'image se fait par la methode drawImage d'un objet Graphics:
la classe component "implemets" l'interface ImageObserver.
Dans le cas d'execution d'un applet c'est l'apllet qui joue la role
d'ImageObserver, donc on doit utiliser la reference this.
iimport java.applet.*;
import java.applet.*; import java.awt.*; public class frstImg extends Applet{
|
|
import java.applet.*; import java.awt.event.*; import java.awt.*; public class CardEx extends Applet{ Image Card[] = new Image[5]; Button ply,stp; AudioClip ding,fond; int wh=70,ht=100; int vX[]=new int[Card.length]; int vY[]=new int[Card.length]; boolean back[] = new boolean[Card.length]; boolean ctch[] = new boolean[Card.length]; int helpX,helpY,clicks; public void init(){ setBackground(Color.green); for(int i=0; i<Card.length;i++){ Card[i]=getImage(getCodeBase(),"images/C"+i+".jpg"); vX[i]=20+55*i; vY[i]=30; back[i]=ctch[i]=false; } addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); } class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent e){ helpX=e.getX(); helpY=e.getY(); for(int i=0;i<Card.length;i++){ if(chckIn(i,helpX,helpY)){ ctch[i]=true; if(e.getClickCount()==2){ if(back[i])Card[i]=getImage(getCodeBase(),"images/C"+i+".jpg"); else Card[i]=getImage(getCodeBase(),"images/Cback.jpg"); back[i]=!back[i]; repaint(vX[i],vY[i],wh,ht); } } } clicks=e.getClickCount(); repaint(); } public void mouseReleased(MouseEvent e){ for(int i=0;i<Card.length;i++) ctch[i]=false; repaint(); } } class MouseMotionHandler extends MouseMotionAdapter { public void mouseDragged(MouseEvent e){ int x = e.getX(); int y = e.getY(); for(int i=0;i<Card.length;i++) if(ctch[i]) { vX[i]+=(x-helpX); vY[i]+=(y-helpY); repaint(vX[i],vY[i],wh,ht); helpX=x; helpY=y; } } } class SpPlay implements ActionListener { public void actionPerformed(ActionEvent e){ fond.loop(); } } class SpStop implements ActionListener { public void actionPerformed(ActionEvent e){ fond.stop(); } } public void paint(Graphics g) { for(int i=0;i<Card.length;i++){ g.drawImage(Card[i], vX[i], vY[i], wh,ht,this); g.drawRect(vX[i], vY[i], wh,ht); } } boolean chckIn(int ncard, int x, int y){ if( (x>vX[ncard])&& (x< vX[ncard]+wh) && (y> vY[ncard])&& (y< vY[ncard]+ht) ) return true; return false; } } |