Зареждане и изобразяване на изображения
За да бъде заредено едно изображение трябва да бъде създаден обект от клас Image. За целта са необходими два адреса:
Изобразяването на изображение се извършва чрез метода drawImage от създаден обект Graphics:
Класът Сomponent "прилага" (наследява)
интерфейса ImageObserver. При изпълнение на
аплет, то той изпълнява ролята на
ImageObserver, следователно трябва да се използва
псевдонима this.
Преди JDK 1.2, аплетите можеха да свирят
файлове само във формата на Sun (.au files). JDK 1.2
въведе нова аудио машина, която поддържа
следните формати:
MIDI (type 0 and type 1)--The Musical Instrument Digital Interface, a
digital
format for musical instruments.
RMF--The Rich Music Format, an audio file format created by Headspace,
Inc. for
online playback through the Beatnik plug-in.
WAVE--The Microsoft Windows audio file format.
AIFF--The Audio Interchange File Format, typically used with Macintosh
and
Silicon Graphics computers.
AU--The Sun audio file format.
Интерфейсът AudioClip позволява представянето на звуци. За целта е необходим аудио файл който се зарежда чрез метода getAudioClip (намиращ се в класа Applet), който има две форми :
За да може да се чуе звук, асоцииран към AudioClip се използват следните методи :
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class ImgScBarD extends Applet{
Image n;
Button ply,stp;
AudioClip ding,fond;
Scrollbar
scrollbar,scrollbarV;
int
valueX=50,valueY=50;
public void init(){
n = getImage(getCodeBase(), "images/1_MAGIC.JPG");
BorderLayout layout = new BorderLayout();
setLayout(layout);
ding=getAudioClip(getCodeBase(),"ding.au");
fond=getAudioClip(getCodeBase(),"spacemusic.au");
ply=new
Button("Play");
stp=new
Button("Stop");
ply.addActionListener(new SpPlay());
add("West",ply);
stp.addActionListener(new SpStop());
add("South",stp);
scrollbar = new Scrollbar(Scrollbar.HORIZONTAL,50, 5, 1, 100);
//parametres:
orientation, initValue, sizeBubble, minVal,maxVal
scrollbarV = new
Scrollbar(Scrollbar.VERTICAL,50, 5, 1, 100);
scrollbar.addAdjustmentListener(new SB());
add("North",
scrollbar);
scrollbarV.addAdjustmentListener(new SBV());
add("East",
scrollbarV);
}
class SB
implements AdjustmentListener {
public
void adjustmentValueChanged(AdjustmentEvent e) {
valueX = scrollbar.getValue();
ding.play();
repaint();
}
}
class SBV
implements AdjustmentListener {
public
void adjustmentValueChanged(AdjustmentEvent e) {
valueY = scrollbarV.getValue();
ding.play();
repaint();
}
}
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) {
g.drawImage(n, valueX, valueY,90,90, this);
}
}
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; } } } 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; } } |
Още един пример:
import java.applet.*; |
application |
import
javax.swing.*; public class Ex1 { static Image img=Toolkit.getDefaultToolkit().getImage("1_MAGIC.JPG"); static MyCanvas cs = new MyCanvas(); public static void main (String[] arg){ JFrame f = new JFrame("Ex 1"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add("Center",cs); f.setSize(250,350); cs.setBackground(Color.yellow); cs.setForeground(Color.BLUE); cs.setFont(new Font("TimesRoman",Font.ITALIC,24)); cs.repaint(); f.setVisible(true); } static class MyCanvas extends Canvas{ int x=50,y=70; public void paint (Graphics g){ g.drawString("This an image", 20, 20) ; g.drawImage(img, x, y,120,120, this); } } } |
Използване на мишка |
import
java.awt.*; import java.awt.event.*; import javax.swing.*; public class Ex1 { static Image img=Toolkit.getDefaultToolkit().getImage("1_MAGIC.JPG"); static MyCanvas cs = new MyCanvas(); public static void main (String[] arg){ JFrame f = new JFrame("Ex 1"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cs.addMouseListener(new MyMouse()); f.add(cs); f.setSize(250,350); cs.setBackground(Color.yellow); cs.setForeground(Color.BLUE); cs.setFont(new Font("TimesRoman",Font.ITALIC,24)); cs.repaint(); f.setVisible(true); } static public class MyMouse extends MouseAdapter { public void mouseClicked(MouseEvent ev) { cs.x=ev.getX(); cs.y=ev.getY(); cs.repaint(); System.out.println("x="+ev.getX() + " y="+ ev.getY()); } } static class MyCanvas extends Canvas{ int x=50,y=70; public void paint (Graphics g){ g.drawString("This an image", 20, 20) ; g.drawImage(img, x, y,120,120, this); } } } |
Пример с карти |
import
java.applet.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; public class CardEx extends Canvas{ Image Card[] = new Image[5]; 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 static void main(String[] arg){ JFrame fr = new JFrame("Card example"); fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fr.setSize(400, 400); fr.setVisible(true); CardEx ce = new CardEx(); fr.add(ce); ce.init(); } public void init(){ setBackground(Color.green); for(int i=0; i<Card.length;i++){ Card[i]=Toolkit.getDefaultToolkit().getImage("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]=Toolkit.getDefaultToolkit().getImage("C"+i+".jpg"); else Card[i]=Toolkit.getDefaultToolkit().getImage("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; } } } 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; } } |
Втори пример с карти |
import
java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; class CardObj{ Image card,cardBack; int vx,vy; static int cLen=70,cHeight=100; boolean back; CardObj(int num,int x, int y,PassEx passEx){ card=Toolkit.getDefaultToolkit().getImage("C"+num+".jpg"); cardBack=Toolkit.getDefaultToolkit().getImage("Cback.jpg"); vx=x; vy=y; back=false; } void draw(Graphics g,PassEx passEx){ if(!back) g.drawImage(card,vx,vy,cLen,cHeight,passEx); else g.drawImage(cardBack,vx,vy,cLen,cHeight,passEx); g.drawRect(vx, vy, cLen,cHeight); } } class CardStack extends Stack{ int vx,vy; CardStack(int x, int y){ vx=x; vy=y; } boolean inStack(int x, int y){ if( (x>vx)&&(x<vx+CardObj.cLen)) if((y>vy) && (y<vy+CardObj.cHeight)) return true; return false; } void push(CardObj card){ card.vx=vx; card.vy=vy; card.back=!card.back; super.push(card); } } class TablCard extends Vector{ int vx,vy; static int dist=10; TablCard(int x, int y, int d){ vx=x; vy=y; dist=d; } int indTabl(int x, int y){ for(int i=0; i < size(); i++){ if((x > vx+i*(CardObj.cLen+dist))&& (x < vx+i*(CardObj.cLen+dist)+CardObj.cLen)) if((y > vy) && (y < vy+CardObj.cHeight)) return i; } return -1; } void addElement(CardObj card){ card.vx = vx+size()*(CardObj.cLen+dist); card.vy = vy; super.addElement(card); } void deleteAt(int i){ for(int k =i+1; k<size(); k++) ((CardObj)get(k)).vx-=CardObj.cLen+dist; super.removeElementAt(i); } void draw(Graphics g,PassEx place){ for(int i =0; i < size(); i++) ((CardObj)get(i)).draw(g,place); } } public class PassEx extends Canvas{ CardStack StackSrc,StackDest; TablCard desk; public void init() { setBackground(Color.green); StackSrc=new CardStack(20,20); StackDest= new CardStack(200,20); desk = new TablCard(20,200,10); for(int i= 0;i<5;i++) StackSrc.push(new CardObj(i,StackSrc.vx,StackSrc.vy,this)); addMouseListener(new MouseHandler()); } public void paint(Graphics g) { if(!StackSrc.empty()){ ((CardObj)StackSrc.peek()).draw(g,this); } if(!StackDest.empty()){ ((CardObj)StackDest.peek()).draw(g,this); } if(!desk.isEmpty()) desk.draw(g,this); } class MouseHandler extends MouseAdapter { public void mousePressed(MouseEvent e){ int x=e.getX(), y=e.getY(), k; if(StackSrc.inStack(x,y) && !StackSrc.empty()){ StackDest.push((CardObj)StackSrc.pop()); } else if(StackDest.inStack(x,y) && !StackDest.empty()) desk.addElement((CardObj)StackDest.pop()); else if((k=desk.indTabl(x,y))>=0){ StackSrc.push((CardObj)(desk.elementAt(k))); desk.deleteAt(k); } repaint(); } } public static void main(String[] arg){ JFrame fr = new JFrame("Solitaire"); fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fr.setSize(400, 400); PassEx cv = new PassEx(); fr.add(cv); cv.init(); fr.setVisible(true); } } |