Tuesday, February 22, 2011

Java : Peeka, Boo!

Our last program responded to mouse movements by polling: every time the Timer event "went off", we checked the current mouse position using MouseInfo.getPointerInfo().getLocation(). Today we're going to modify our program to respond directly to mouse events.

It's best if you make a new working directory, let's say "PeekaBoo", with its own "Images" sub-directory.
Now we need two new images: save them as "peeka.jpg" and "boo.jpg" in the new "Images" directory.



Instead of implementing "ActionListener" (listening for timer events), our class now implements "MouseListener" (listening for mouse events).
public class PeekaBoo extends JPanel implements MouseListener
We can drop the definition of the PERIOD constant, as we're not using a timer, and change LEFT & RIGHT to PEEKA & BOO.
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
Our constructor (initialization) method becomes:
public PeekaBoo()
{
 setPreferredSize(new Dimension(PWIDTH,PHEIGHT));
 images [PEEKA] = loadImage("Images/peeka.jpg");
 images [BOO] = loadImage("Images/boo.jpg");
  
 imageIndex = PEEKA;
  
 addMouseListener(this);  
}
Instead of starting a Timer, we add a mouse listener.
Now all that's required is to tell Java how to respond to mouse events.
// 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();} 
So, when a mouse-click is detected somewhere in the program window, display the "Boo" image. When the mouse leaves the program window, revert to the "Peeka" image.

And that's it. Here's the full program:
// PeekaBoo.java

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
import java.io.*;

public class PeekaBoo extends JPanel 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 PeekaBoo()
 {
  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 paintComponent(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();}
 
 public static void main(String args[])
 {
  final PeekaBoo showPanel = new PeekaBoo();

  JFrame showFrame = new JFrame("Peeka-Boo");
  showFrame.getContentPane().add(showPanel,BorderLayout.CENTER);
  showFrame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
  showFrame.pack();
  showFrame.setResizable(false);  
  showFrame.setVisible(true); 
 }
}
And that's all there is too it. Save as "PeekaBoo.java" and compile and run in the usual way. Let's try it out. Click on the image below, then move the mouse away.






Something's different...

Apart from the obvious change of image, the program running above is an applet embedded in a web page, rather than a stand-alone app like our program listing.

Next time we'll go through the steps required to convert our app into an applet and post it on blogger.

27 comments:

  1. Neat trick... Sorry that I don't understand the rest of the stuff though... Hope you have a nice day. :)

    ReplyDelete
  2. This is pretty cool. Thanks for sharing the code.

    ReplyDelete
  3. but nothing happens when i mouse over or click.. i just see white... >:3

    ReplyDelete
  4. Error : Invalid path, \bin\javac.exe

    I think I should not of said "F U" to your earlier instructions about installation.
    (I think I spread my butter too much.)

    Also, I am slightly disappointed you had nothing to say about your sanity-rating. :(

    ReplyDelete
  5. @ shishimaru - if you're near San Antonio, it looks as though you have the same software setup as one of my machines: Firefox (Mozilla/4.0), Windows XP (5.1), Java 1.6.0_20.

    Maybe you don't have a required Firefox plug-in?
    When I click tools,add-ons,plugins on Firefox (3.6.13), I see "Java(TM) platform SE 6 U20" and the "Java deployment Toolkit 6.0.200.2".

    You can update your JRE (Java Runtime Environment) with this free download from sun/oracle.

    This Firefox help page may be useful.

    ReplyDelete
  6. Once again , my brain cannot compute this computer speak, but I quite like the picture.... Mmmm titties

    ReplyDelete
  7. Your posts got a little too complicated :P but i still enjoyed the last image so we're cool :P

    ReplyDelete
  8. Good as ever again but my big strawberry blonde brain aches.

    ReplyDelete
  9. lol i use my name for all online games i play. like guild wars or sc or cod. i think its a pretty sick name. nice underboob pic too.

    ReplyDelete
  10. it always fun to learn java with you

    ReplyDelete
  11. Unfortunately this isn't working on my end either. I'm gonna try some of your troubleshooting tips and try again. Hrrmmm...

    ReplyDelete
  12. lol...wasn't expecting that!

    ReplyDelete
  13. I gotta check my browser settings, because I can't see the image

    ReplyDelete
  14. Hahaha. I love ceeling cat. Classic.

    ReplyDelete
  15. Learning this stuff is fun :D

    ReplyDelete
  16. kool post and interesting pics.. You look awesome as batman never knew tht Christian Bale walked out

    ReplyDelete
  17. im totally lost with the technical aspect of this post....but uh, Catwoman FTW? I guess. haha

    ReplyDelete
  18. this goes over the top of my head.

    ReplyDelete
  19. epic underboob is epic.

    ceiling cat is cute.

    ReplyDelete
  20. So if i enter all that i get nice underboob of any jpg of a chick?!





    AWWWWWWWWWWW
    SOMMMMMMMEEEE!

    ReplyDelete
  21. Cool, I look forward to learning how to make an Applet. Might make some game and stick it on my blog. Who knows.

    ReplyDelete
  22. interesting. i'll follow these steps in order to get the underboob i desire.

    if you're into moustaches, check out my blog! it's super pimp

    http://epicmoustacheblog.blogspot.com/

    ReplyDelete
  23. Thanx for the info. A lot to absorb, but worth it.

    ReplyDelete
  24. Oh that looks cool! Why couldn't my stupid java class teach this! ...Oh wait, because i was a stupid high schooler not paying attention, haha.

    ReplyDelete