- Home
- Tutorials
- Flash
- Intermediate
- AS3 On Screen Keyboard
AS3 On Screen Keyboard
This article has been added to your 'Articles to Read' list.

CustomKeyboard Class File
Complete source code for file CustomKeyboard.as

day
package actionscript{
import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.*;
import flash.text.TextField;
public class CustomKeyboard extends MovieClip {
static var keyData:XML = new XML;// used to store the loaded XML data.
static var keyHolder:MovieClip = new MovieClip;// used to hold all the buttons
static var textScreen:TextField = new TextField;// Our textfield that we write to.
static var shift:Boolean = false;// Tells if the shift key is down.
static var caps:Boolean = false;// Tells if the Caps Loack key is down.
public function CustomKeyboard() {
buildTextScreen();
loadKeyboardinfo();
setupKeyHolder();
}
static public function capsToggle():void {
if (caps) {
caps = false;
} else {
caps = true;
}
}
static public function shiftToggle():void {
if (shift) {
shift = false;
} else {
shift = true;
}
if (caps) {
caps = false;
}
}
private function buildTextScreen():void {
textScreen.x = 5;// position on the main stage
textScreen.y = 5;// position on the main stage
textScreen.width = 640;// width of the textScreen
textScreen.height = 190;// height of the textScreen
textScreen.htmlText = "";//
textScreen.wordWrap = true;// makes the textScreen wrap text to a newline once it reaches the end.
textScreen.selectable = false;// restricts teh user from being able to select the text in textScreen
textScreen.border = true;// draws a border around the textScreen
addChild(textScreen);// adds the textScreen to the main stage
}
private function loadKeyboardinfo():void {
var xmlLoader:URLLoader = new URLLoader;// creates a loader to load the xml data.
var xmlRequester:URLRequest = new URLRequest("xml/keys.xml");// this request object is used to tell the loader what and where to load.
xmlLoader.addEventListener(Event.COMPLETE,xmlLoaded);// adds an event listener that fires once the loader has completed loading the xml file.
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);// this event listener fires if there is a problem finding or loading the xml file.
xmlLoader.load(xmlRequester);// starts the loading of the xml file.
}
private function setupKeyHolder():void {
keyHolder.x = 20;// positions the keyHolder movieclip on the main stage.
keyHolder.y = 200;// positions the keyHolder movieclip on the main stage.
addChild(keyHolder);// adds the keyHolder movieclip to the main stage.
}
private function buildKeyboard():void {
var numKeys:Number = getNumberOfKeys();// uses a function to find out how many keys are in the XML file.
var xPlacement:Number = 0;// used to position the keys in the keyHolder movieclip.
for (var i = 0; i < keyData.row.length(); i++) {// loop used to draw each row.
for (var j = 0; j < keyData.row[i].key.length(); j++) {// loop used to draw all the keys in a row.
var newKey:KeyButton = new KeyButton;// creates a new instance of the KeyButton class ( our onscreen button ).
newKey.code = keyData.row[i].key[j].code;// sets the newKey's code variable to the appropriate XML node value for that key.
newKey.char = keyData.row[i].key[j].char;// sets the newKey's char variable to the appropriate XML node value for that key.
newKey.shiftChar = keyData.row[i].key[j].shiftChar;// sets the newKey's shiftChar variable to the appropriate XML node value for that key.
newKey.keyWidth = checkWidth(keyData.row[i].key[j].char);// uses a function to determine the width of the key.
newKey.x = xPlacement + 5;// used to position the key on the x (up and down).
newKey.y = (newKey.keyHeight + 5) * i;// used to position the key on the y ( left and right ).
newKey.build();// calls a function that is inside the newKey object. More info in KeyButton.as
xPlacement += newKey.keyWidth+ 5;// sets the xPlacement variable for the next pass through the loop.
keyHolder.addChild(newKey);// adds the newKey to the keyHolder movieclip. The keyHolder is already on the stage by now so the key will display.
}
xPlacement = 0;// resets the x postions once a row has been drawn so the next row starts where it is suppose to.
}
}
private function checkWidth(char:String):Number {
var mediumKeys:Array = new Array('Tab','Enter','Backspace','Caps Lock');
var shiftKey:String = "Shift";
var spaceKey:String = "Space Bar";
for (var m = 0; m < mediumKeys.length; m++) {
if (char == mediumKeys[m]) {
return 75;
}
}
if (char == shiftKey) {
return 95;
}
if (char == spaceKey) {
return keyHolder.width;
}
return 35;
}
private function getNumberOfKeys():Number {
var keyCounter:Number = 0;
for (var i = 0; i < keyData.row.length(); i++) {
keyCounter += keyData.row[i].key.length();
}
return keyCounter;
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);// if the loader fails to load the XML file this will trace out the error.
}
private function xmlLoaded(event:Event):void {
var loader:URLLoader=URLLoader(event.target);// must have
keyData = new XML(loader.data);// takes the loaded XML data and puts it in to our XML object.
buildKeyboard();/// since the XML is loaded we now can build the keyboard since it requires the XML data.
}
}
}
Breakdown of the code. This is where the fun begins.
First thing we are doing in this file is setting up the package. The name of the package is associated with the location of this file in relation to CustomKeyboard.fla. Since this file is located in the "actionscript" directory we must name the package "actionscript.
The next few lines are our import files. Since we will need to use other classes inside this class we must import them.
The final line in this code block creates our class, CustomKeyboard.
package actionscript{
import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.*;
import flash.text.TextField;
public class CustomKeyboard extends MovieClip {
This next section is used to declare out class variables. Notice how they have static in front of them. The use of static specifies that a variable, constant, or method belongs to the class, rather than to instances of the class. If we don't use the static method it can cause errors later on.
static var keyData:XML = new XML; // used to store the loaded XML data.
static var keyHolder:MovieClip = new MovieClip; // used to hold all the buttons
static var textScreen:TextField = new TextField; // Our textfield that we write to.
static var shift:Boolean = false; // Tells if the shift key is down.
static var caps:Boolean = false; // Tells if the Caps Loack key is down.
Now on to the classes constructor. This is executed when the class is created for the first time. Since we need stuff initialized when the application is executed, we put it in this function. Explanation of the methods:
buildTextScreen() creates the textfield and adds it to the stage of the application.
loadKeyboardinfo() loads the keys.xml file and once it is loaded it builds the keyboard on the screen.
setupKeyHolder() positions and adds the keyHolder movieclip to the stage.
public function CustomKeyboard() {
buildTextScreen();
loadKeyboardinfo();
setupKeyHolder();
}
This code block shows you the three functions that are called by the constructor. Once these are called the application stops until the xml file loads. But since it loads really fast it is hard to tell.
private function buildTextScreen():void {
textScreen.x = 5; // position on the main stage
textScreen.y = 5; // position on the main stage
textScreen.width = 640; // width of the textScreen
textScreen.height = 190; // height of the textScreen
textScreen.htmlText = ""; //
textScreen.wordWrap = true; // makes the textScreen wrap text to a newline once it reaches the end.
textScreen.selectable = false; // restricts teh user from being able to select the text in textScreen
textScreen.border = true; // draws a border around the textScreen
addChild(textScreen); // adds the textScreen to the main stage
}
private function loadKeyboardinfo():void {
var xmlLoader:URLLoader = new URLLoader; // creates a loader to load the xml data.
var xmlRequester:URLRequest = new URLRequest("xml/keys.xml"); // this request object is used to tell the loader what and where to load.
xmlLoader.addEventListener(Event.COMPLETE,xmlLoaded); // adds an event listener that fires once the loader has completed loading the xml file.
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler); // this event listener fires if there is a problem finding or loading the xml file.
xmlLoader.load(xmlRequester); // starts the loading of the xml file.
}
private function setupKeyHolder():void {
keyHolder.x = 20; // positions the keyHolder movieclip on the main stage.
keyHolder.y = 200; // positions the keyHolder movieclip on the main stage.
addChild(keyHolder); // adds the keyHolder movieclip to the main stage.
}
Next we will be looking at the event listeners that were previously setup. Now most of you coming from AS2 are new to event listeners. Well to put it simpley. If you want something to perform an action during runtime, you will most likely need to use an event listener. Lets say you want to create a button. Well your button would need many event listeners. For example: you would need a seperate one for clicking, mouse over, and mouse out. why would you need so many event listeners, well when you do any of those actions usually seperate things need to happen. If you click you may want it to go to a new website, if you mouse over you may want it to change it's appearance, and if you mouse out you may want it to go back to its default appearance. We will be getting in to MouseEvents when we look at the KeyButton class. For now we will be looking at the events that are called when the loader completes or fails.
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event); // if the loader fails to load the XML file this will trace out the error.
}
private function xmlLoaded(event:Event):void {
var loader:URLLoader=URLLoader(event.target); // must have
keyData = new XML(loader.data); // takes the loaded XML data and puts it in to our XML object.
buildKeyboard(); /// since the XML is loaded we now can build the keyboard since it requires the XML data.
}
Well now we just wait until the XML loads and then the buildKeyboard() function is called. Once this is called, the keyboard is built on the screen ready to be played with. This function takes the XML data that we loaded and goes through it to build all the keys. It uses loops to go through all the nodes in the XML and takes the nodes values and assigns it to the keyButton object.
private function buildKeyboard():void {
var numKeys:Number = getNumberOfKeys(); // uses a function to find out how many keys are in the XML file.
var xPlacement:Number = 0; // used to position the keys in the keyHolder movieclip.
for (var i = 0; i < keyData.row.length(); i++) { // loop used to draw each row.
for (var j = 0; j < keyData.row[i].key.length(); j++) { // loop used to draw all the keys in a row.
var newKey:KeyButton = new KeyButton; // creates a new instance of the KeyButton class ( our onscreen button ).
newKey.code = keyData.row[i].key[j].code; // sets the newKey's code variable to the appropriate XML node value for that key.
newKey.char = keyData.row[i].key[j].char; // sets the newKey's char variable to the appropriate XML node value for that key.
newKey.shiftChar = keyData.row[i].key[j].shiftChar; // sets the newKey's shiftChar variable to the appropriate XML node value for that key.
newKey.keyWidth = checkWidth(keyData.row[i].key[j].char); // uses a function to determine the width of the key.
newKey.x = xPlacement + 5; // used to position the key on the x (up and down).
newKey.y = (newKey.keyHeight + 5) * i; // used to position the key on the y ( left and right ).
newKey.build(); // calls a function that is inside the newKey object. More info in KeyButton.as
xPlacement += newKey.keyWidth+ 5; // sets the xPlacement variable for the next pass through the loop.
keyHolder.addChild(newKey); // adds the newKey to the keyHolder movieclip. The keyHolder is already on the stage by now so the key will display.
}
xPlacement = 0; // resets the x postions once a row has been drawn so the next row starts where it is suppose to.
}
}
Now for the final functions in this class. Quick breakdown:
- getNumberOfKeys(): This function goes through the XML object and counts how many keys there should be.
- checkWidth(char:String): This function is used to calculate the width of the key. It compares the value char (the character that will show up on the key) againts an array and a string to determine its width. The width it returned from this function and is set to the newKey's value "keyWidth".
- capsToggle(): This is used to toggle the caps lock key.
- shiftToggle(): This is used to toggle the shifht key.
private function getNumberOfKeys():Number {
var keyCounter:Number = 0;
for (var i = 0; i < keyData.row.length(); i++) {
keyCounter += keyData.row[i].key.length();
}
return keyCounter;
}
private function checkWidth(char:String):Number {
var mediumKeys:Array = new Array('Tab','Enter','Backspace','Caps Lock');
var shiftKey:String = "Shift";
var spaceKey:String = "Space Bar";
for (var m = 0; m < mediumKeys.length; m++) {
if (char == mediumKeys[m]) {
return 75;
}
}
if (char == shiftKey) {
return 95;
}
if (char == spaceKey) {
return keyHolder.width;
}
return 35;
}
static public function capsToggle():void {
if (caps) {
caps = false;
} else {
caps = true;
}
}
static public function shiftToggle():void {
if (shift) {
shift = false;
} else {
shift = true;
}
if (caps) {
caps = false;
}
}

