Wednesday, February 23, 2011

Java : Comment Applet Vous? (Part 1)

As promised, we're going to show how to convert our "PeekBoo" application into an applet and embed it in a Blogger page. We'll split the process into two posts: part 1 is about writing an applet where you have some control of the directory structure of the hosting server. Part 2 will be about bundling the applet and its data files into a ".JAR" (Java Archive) file.

Our first code change is to define our class as an extension of JApplet rather than JPanel.
public class PeekaBooApplet extends JApplet implements MouseListener
Next, we replace our declaration of the constructor method "PeekaBoo()" with an "init()" method. (The code of the method is unchanged.)
public void init()
Our paint method changes name from "paintComponent(g)" to "paint(g)" (the code is again unchanged).
public void paint(Graphics g)
Now all that's left is to delete the entire "main()" method, and our code is complete:
public class PeekaBooApplet extends JApplet implements MouseListener
{
 private static final int PWIDTH =  237;
 private static final int PHEIGHT=  315;
 private static final int PEEKA =  0; // images[0] is Peeka
 private static final int BOO =  1; // image [1] is Boo
 
 private BufferedImage [] images = new BufferedImage [2];
 
 private int imageIndex;
 
 public void init()
 {
  setPreferredSize(new Dimension(PWIDTH,PHEIGHT));

  images [PEEKA] = loadImage("Images/peeka.jpg");
  images [BOO]   = loadImage("Images/boo.jpg");
  
  imageIndex = PEEKA;
  
  addMouseListener(this);  
 }

 public BufferedImage loadImage(String fileName) 
 {
   try {
   BufferedImage im =  ImageIO.read(getClass().getResource(fileName));
   return im; 
  } catch(IOException e) {
   System.out.println("Load Image error for "+fileName+":\n"+e);
   return null;
  }
  }
  
 public void paint(Graphics g){g.drawImage(images [imageIndex],0,0,this);}

 // stubs for you to play around
 public void mousePressed(MouseEvent e) {}
 public void mouseReleased(MouseEvent e) {}
 public void mouseEntered(MouseEvent e) {}
 
 // On mouse-click, display Boo image
 public void mouseClicked(MouseEvent e) {imageIndex=BOO; repaint();}
 
 // When mouse leaves window, display Peeka image
 public void mouseExited(MouseEvent e) {imageIndex=PEEKA; repaint();}
}
Great, so how do we call it? Save the above code to file "PeekaBooApplet.java" and compile using "javac". Then, save the following piece of HTML code to file "PeekaBooApplet.html" in the same directory. (Check that the directory has a sub-directory called "Images" containing "peeka.jpg" and "boo.jpg" from yesterday.)
<applet
 code="PeekaBooApplet.class"
 width="237"
 height="315">
</applet>
Click on the file "PeekaBooApplet.html" to open it in your browser and you should see CatWoman.
Click on her and move the mouse to see the action of the program.

What's happening here is that the browser is looking for the file "PeekaBooApplet.class" in the same directory as your ".html" file. If found, the program is run using the Java Runtime Environment - pretty much like typing "java" from the command line.

The running program then attempts to load the image files from an "Images" sub-directory of the current directory.

Okay, so now how do we embed our applet in our blogger page? Just putting the above HTML code into your post won't work, because the browser will look for the file "PeekaBooApplet.class" in whatever directory Blogger holds your blog page in.

So, we need to copy our ".class" file to a directory on a server that our readers can see. We're using "http://mgt.yourhda.com/Java" so we amend our HTML to read:
<applet
 code="PeekaBooApplet.class"
 codebase="http://mgt.yourhda.com/Java/"
 width="237"
 height="315">
</applet>
to point the browser to the right working directory.
Now all we need to do is to make sure that our images "peeka.jpg" and "boo.jpg" are copied to the right server sub-directory: "http://mgt.yourhda.com/Java/Images".

Let's try it: click on CatWoman then move your mouse away.








That was easy. But we were messing with our own server, and for this small example it was easy to copy all the required image files to the right place relative to our ".class" file. Next time we'll look at how to bundle everything up into a single ".jar" file.

If you add an applet to your blog, please link in the comments or send us an email:

java@vote-sanchez.com

25 comments:

  1. I don't even know what an applet is :(

    ReplyDelete
  2. the dress took a couple weeks to make. each piece for the skirt was cut out and sewn individually with its own stitch then layered on in rows. so alot of hours.

    mermaidnotebook.blogspot.com

    ReplyDelete
  3. wow this stuff takes me back to an old mobile java course I once did

    ReplyDelete
  4. Way over my head...but I came by to say hi!

    ReplyDelete
  5. u love tht batty photo of urs, dont u?

    ReplyDelete
  6. Slowly but surely, I'm getting this down. Must. Animate. Poorly done shoops...

    ReplyDelete
  7. Your talent is lost on some...me. Sorry.

    ReplyDelete
  8. Java applets: hilarity ensues.

    ReplyDelete
  9. Heh, this looks like a good way to set up a screamer. :X

    ReplyDelete
  10. @ Tal Zahn - we should get on to playing MP3s in a few days.

    ReplyDelete
  11. I'm sure this will come in handy some day, but for now I'm too lazy.

    ReplyDelete
  12. the man with all the answers. lol thanks. i liked michelle phifer as cat woman.

    ReplyDelete
  13. it's hard to understand this java script for people like me

    ReplyDelete
  14. Had no idea you are into Java! Great stuff :)

    Will look into your older posts a bit later!

    ReplyDelete
  15. I think I am flunking out of Java 101 here. I think I am going to smash some crap too. Your blog has taken me on an unexpected roller-coaster of emotions that I have not felt since trying to get my C64 to display multiple sprites.

    I hate you, but I love you.

    I hate you. :D

    ReplyDelete