What do you get if you cross Keith Richards with Michael Jackson?
@ Iulian Anghel - If you do manage to hack into my server, while you're there, would you mind fixing the login scripts? (-:
public class PeekaBooAppletJar extends JApplet implements MouseListenerIn our "init()" method, we have to change the pathnames given for the image files from a relative pathname in a file-system to an absolute pathname within the ".jar".
images [PEEKA] = loadImage("/Images/peeka.jpg"); images [BOO] = loadImage("/Images/boo.jpg");That's it for code changes - told you they were minimal.
Main-Class: PeekaBooAppletJarOne point to note there has to be a newline at the end of the "Min-Class:" line. We've no idea why - just stick a blank line at the end of the file.
@echo off echo Making PeekaBooAppletJar jar... jar cvmf mainClass.txt PeekaBooAppletJar.jar PeekaBooAppletJar.class Images echo. echo Indexing jar... jar i PeekaBooAppletJar.jar echo done
<applet code="PeekaBooApplet.class" archive="http://mgt.yourhda.com/Java/PeekaBooAppletJar.jar" codebase="http://mgt.yourhda.com/Java/" width="237" height="315"> </applet>Putting it all together:
public class PeekaBooApplet extends JApplet implements MouseListenerNext, 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.
<applet code="PeekaBooApplet.class" codebase="http://mgt.yourhda.com/Java/" width="237" height="315"> </applet>to point the browser to the right working directory.
public class PeekaBoo extends JPanel implements MouseListenerWe 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 BooOur 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.
// 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.
// 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.
private static final int LEFT = 0; // images[0] faces L private static final int RIGHT = 1; // images[1] faces RDon't forget to load images of Gere rather than Hitler.
images [0] = loadImage("Images/richard_gere_0.jpg"); images [1] = loadImage("Images/richard_gere_1.jpg");Now we change our Timer response method "actionPerformed()" to test which side of the window the mouse is at before painting the corresponding image.
public void actionPerformed(ActionEvent e) { imageIndex = getMouseDirection(); // is mouse to L or R? repaint(); }Here's the code of the "getMouseDirection()" function. Note that "MouseInfo.getPointerInfo().getLocation()" returns the position of the mouse in screen co-ordinates. I.e the point (0,0) is at the top-left corner of the screen. We need to call "SwingUtilities.convertPointFromScreen" to convert to component co-ordinates. I.e. the point (0,0) is at the top-left corner of the panel. If the mouse's x-co-ordinate in component co-ordinates is less than half the window width, return "LEFT", otherwise return "RIGHT".
public int getMouseDirection(){ // mouse location in *screen* co-ordinates Point mouseCoordinates = MouseInfo.getPointerInfo().getLocation(); // convert to *component* co-ordinates SwingUtilities.convertPointFromScreen(mouseCoordinates,this); if (mouseCoordinates.x>=PWIDTH/2) return RIGHT; else return LEFT; }Please note, in Java, like most other programming environments, the y-axis is inverted. I.e. the top row of screen pixels is row 0 and the bottom row will be row 767 or 1023 (or whatever the size of your screen is -1).
// ShowGere.java import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; import javax.imageio.*; import java.io.*; public class ShowGere extends JPanel implements ActionListener { private static final int PERIOD = 1000; // Swing timer interval (ms) private static final int PWIDTH = 243; private static final int PHEIGHT= 244; private static final int LEFT = 0; // image 0 points left private static final int RIGHT = 1; // image 1 points right private BufferedImage [] images = new BufferedImage [2]; private int imageIndex; public ShowGere() { setPreferredSize(new Dimension(PWIDTH,PHEIGHT)); images [LEFT] = loadImage("Images/richard_gere_0.jpg"); images [RIGHT] = loadImage("Images/richard_gere_1.jpg"); imageIndex = LEFT; new Timer(PERIOD, this).start(); // start Swing timer } // ShowGere 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; } } // triggered by the timer: face the mouse and repaint public void actionPerformed(ActionEvent e) { imageIndex = getMouseDirection(); // is mouse to left or right? repaint(); } // Is the mouse to the LEFT or RIGHT of the middle of the window? public int getMouseDirection(){ // mouse location in *screen* co-ordinates Point mouseCoordinates = MouseInfo.getPointerInfo().getLocation(); // convert to *component* co-ordinates SwingUtilities.convertPointFromScreen(mouseCoordinates,this); if (mouseCoordinates.x>=PWIDTH/2) return RIGHT; else return LEFT; } // getMouseDirection public void paintComponent(Graphics g) { g.drawImage(images [imageIndex],0,0,this); } public static void main(String args[]) { final ShowGere showPanel = new ShowGere(); JFrame showFrame = new JFrame("Show Images"); showFrame.getContentPane().add(showPanel,BorderLayout.CENTER); showFrame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE); showFrame.pack(); showFrame.setResizable(false); showFrame.setVisible(true); } // main } // ShowGere classTo run the program, copy and save the program listing to a file called "ShowGere.java" in your working directory. (Remember, the filename must match the class name.)
import java.awt.event.*;We need a new constant to define the period (in milliseconds) between picture changes.
private static final int PERIOD = 1000;Now, we change our declaration of variable "image" to an array "images".
private BufferedImage [] images = new BufferedImage [2];We also need a variable to keep track of which image from our array we should be displaying.
private int imageIndex;In the "ShowImageApp()" constructor method, we change the initialization code to:
public ShowImageApp() { setPreferredSize(new Dimension(PWIDTH,PHEIGHT)); images [0] = loadImage("Images/hitler_bambi_0.jpg"); images [1] = loadImage("Images/hitler_bambi_1.jpg"); imageIndex = 0; new Timer(PERIOD, this).start(); // start the Swing timer } // ShowImageAppThis loads both images, sets the image index to point at the first (0th!) image, and starts a Timer with period 1000ms.
public void paintComponent(Graphics g) { g.drawImage(images [imageIndex],0,0,this); }The only other change we need to make is to tell the program what to do every time the Timer "goes off". For that we define an "actionPerformed" method as follows.
public void actionPerformed(ActionEvent e) { repaint(); imageIndex = (imageIndex + 1) % 2; }So, each time the Timer period expires, the "actionperformed" method is called. The method calls "repaint()" to trigger our "paintComponent()" method. The "imageIndex" is then toggled between 0 and 1.
public class ShowImageApp extends JPanel implements ActionListenerIn Java jargon, the class implements the abstract interface "ActionListener".
// ShowImageApp.java import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; import javax.imageio.*; import java.io.*; public class ShowImageApp extends JPanel implements ActionListener { private static final int PERIOD = 1000; // Swing timer interval 1.0 secs private static final int PWIDTH = 417; private static final int PHEIGHT= 400; private BufferedImage [] images = new BufferedImage [2]; private int imageIndex; public ShowImageApp() { setBackground(Color.black); setPreferredSize(new Dimension(PWIDTH,PHEIGHT)); images [0] = loadImage("Images/hitler_bambi_0.jpg"); images [1] = loadImage("Images/hitler_bambi_1.jpg"); imageIndex = 0; new Timer(PERIOD, this).start(); // start the Swing timer } // end of constructor 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; } } // triggered by the timer: repaint and toggle the image index public void actionPerformed(ActionEvent e) { repaint(); imageIndex = (imageIndex + 1) % 2; // toggle between 0 and 1 } public void paintComponent(Graphics g) { g.drawImage(images [imageIndex],0,0,this); } public static void main(String args[]) { final ShowImageApp showPanel = new ShowImageApp(); JFrame showFrame = new JFrame("Show Images"); showFrame.getContentPane().add(showPanel,BorderLayout.CENTER); showFrame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE); showFrame.pack(); showFrame.setResizable(false); showFrame.setVisible(true); } // main } // ShowImageApp ClassSave the program as "ShowImageApp.java" and compile and run in the same way as yesterday and you should get the cutest flashing image ever.
// ShowImageApp.java // import definitions for the pre-defined classes & methods we'll be using import java.awt.*; import java.awt.image.*; import javax.swing.*; import javax.imageio.*; import java.io.*; public class ShowImageApp extends JPanel { // define constants to determine the width & height of our window private static final int PWIDTH = 417; private static final int PHEIGHT= 400; // declare a variable to hold our image; private BufferedImage image; // ShowImageApp() is a constructor method for initializing new ShowImageApp objects public ShowImageApp() { setPreferredSize(new Dimension(PWIDTH,PHEIGHT)); image = loadImage("Images/hitler_bambi_0.jpg"); } // Load the image from <filename>Whoah! That's a big jump in complexity from the "Hello World" program. Let's strip out some of the noise and show some simplified pseudo-code., returning it as a BufferedImage 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; } } // tells the window manager how to paint the window public void paintComponent(Graphics g) { g.drawImage(image,0,0,this); } public static void main(String args[]) { // construct a new object, showPanel, of class ShowImageApp ShowImageApp showPanel = new ShowImageApp(); // construct a new window-frame object, showFrame JFrame showFrame = new JFrame("Frame title goes here"); // link the panel to the frame showFrame.getContentPane().add(showPanel,BorderLayout.CENTER); // tell Java to shut down when we close the window showFrame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE); // don't allow the window to be resized showFrame.setResizable(false); // display the window showFrame.pack(); showFrame.setVisible(true); } // main } // ShowImageApp class
import definitions; public class ShowImageApp extends JPanel { define constants & declare variables; ShowImageApp() is a constructor method for the ShowImageApp class loadImage(filename) loads an image into a BufferedImage paintComponent(Graphics g) tells the JVM how to paint the window public static void main(String args[]) { construct a new ShowImageApp object called showPanel; construct a new window frame called showFrame; tell JVM that showPanel is the content of showFrame; tell JVM to shut down when we close the window; make the window size fixed; display the window; } }
ShowImageApp showPanel = new makeShowImageApp();Sadly, we're stuck with Java's execrable syntax.
try{some action}catch{some exception}quite a lot in Java - usually when performing input/output (I/O) of some kind. It just tells the JVM to try to do something, and if something goes wrong, to handle the exception gracefully.
class HelloWorldApp { public static void main(String[] args) { System.out.println("Viva Sucio!"); } }There's a very good description of what every word of this program is doing at <Jimmy Wales' blog>. For now, we'll just say that the program defines a class of objects called HelloWorldApp and tells Java what the object can do (its methods - in this case, just the method main).
,/, ,.%((.))) |.
'///_, (///)\\))) , |||/
\ ,' (([]-[]-\\\) y-";,-"
| | )| - @))) | |
| \ ((\___,"(( / |
| `---.__))| |())___.---' |
`-._ "-_ _ -" _,-"
"-.__," ".__.-"
( @ / \ @ )
`---' `---'
| |
| . |
/ \
/ "-.-" \
/ /^\ \
/ / \ \
/ / \ \
( ." ". \
\ ) \ \
\ ". `. \
". \ \ \
`. `) \ ".
\ ( \ \
.mno/ | \
Oonm'
"Sarah Palin nude" - That should get the google hits up.class HelloWorldApp { public static void main(String[] args) { System.out.println("Viva Sucio!"); } }