package com.hatherly.babykeyboardfun;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.IOException;
import javax.swing.ImageIcon;
/**
* Factory class that is called to return the image relevant to
* the key-press to the swing app so that it can be displayed
* on screen.
*/
public class ImageFactory {
private static ImageIcon[] letterImages = new ImageIcon[26];
private static ImageIcon[] numberImages = new ImageIcon[10];
/**
* Constructor - loads images into memory
*/
public ImageFactory() {
/*
Images were from:
http://www.flickr.com/photos/lwr/87325319/
http://flickr.com/photos/holeymoon/2098822334/
*/
String path = "/resources/";
System.out.println("Loading sounds from path: " + path);
String filename = "";
for (int n=0; n<26; n++) {
filename = path + ((char)(n+97)) + ".jpg";
System.out.println("Loading image with filename: " + filename);
letterImages[n] = getImageIcon(filename);
}
for (int n=0; n<10; n++) {
filename = path + ((char)(n+48)) + ".jpg";
System.out.println("Loading image with filename: " + filename);
numberImages[n] = getImageIcon(filename);
}
}
/**
* Factory method - called to return the correct image for a
* given key code
* @param character Key code to return image for
* @returns ImageIcon of image, or null if there is no image for given keycode
*/
protected ImageIcon getImage(char character) {
if (character > 64 && character < 91) {
character = (char)(character + 32);
}
if (character > 96 && character < 123) {
return letterImages[character - 97];
} else if (character > 47 && character < 58) {
return numberImages[character - 48];
} else {
return null;
}
}
/**
* This method was added to allow images to be loaded correctly when
* they are inside a JAR file. The code for the below came from:
* http://forum.java.sun.com/thread.jspa?threadID=765281&messageID=4364162
*/
private static ImageIcon getImageIcon(String path) {
int MAX_IMAGE_SIZE = 350000; //Change this to the size of
//your biggest image, in bytes.
int count = 0;
BufferedInputStream imgStream = new BufferedInputStream(
ImageFactory.class.getResourceAsStream(path) );
if( imgStream != null ) {
byte buf[] = new byte[MAX_IMAGE_SIZE];
try {
count = imgStream.read(buf);
}
catch( IOException ieo ) {
System.err.println( "Couldn't read stream from file: " + path );
}
try {
imgStream.close();
}
catch( IOException ieo ) {
System.err.println( "Can't close file " + path );
}
if( count <= 0 ) {
System.err.println( "Empty file: " + path );
return null;
}
return new ImageIcon( Toolkit.getDefaultToolkit().createImage(buf) );
}
else {
System.err.println( "Couldn't find file: " + path );
return null;
}
}
}
syntax highlighted by Code2HTML, v. 0.9.1