<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cnicollonline</title>
	<atom:link href="http://cnicollonline.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cnicollonline.com</link>
	<description>&#34;I was just guessing at numbers and figures, pulling the puzzles apart&#34;</description>
	<lastBuildDate>Mon, 23 Aug 2010 19:16:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Custom PHP exception handling</title>
		<link>http://cnicollonline.com/programming/custom-php-exception-handling/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/custom-php-exception-handling/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 19:08:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[exception-handling]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=297</guid>
		<description><![CDATA[A large project I&#8217;ve been working on as of late has many moving parts. It allowed a lot of dynamic edits that utilized AJAX for sending dynamic information to and from a database. When errors occurred it was alright for me, because I could debug them however what it came the client&#8230; Well let&#8217;s just [...]]]></description>
			<content:encoded><![CDATA[<p>A large project I&#8217;ve been working on as of late has many moving parts. It allowed a lot of dynamic edits that utilized AJAX for sending dynamic information to and from a database. When errors occurred it was alright for me, because I could debug them however what it came the client&#8230; Well let&#8217;s just say they were convinced that with these errors their computer was going to spontaneous&nbsp;combust.</p>
<p>I&#8217;ll admit it now that I was a little lazy when developing some of the classes. I went back and modified them so that they would implement <a href="http://www.w3schools.com/php/php_exception.asp">exception handling</a>, only I went one step further and used custom exception handling so that I could log any errors that may&nbsp;occur.</p>
<p>Within this posting, im going to create a class that will have errors, and I&#8217;ll also create a custom exception class that will catch any of these errors and log them to a&nbsp;file</p>
<p style="text-align: center;"><img class="aligncenter" src="http://farm5.static.flickr.com/4073/4920516367_e94b52e37f.jpg" alt="cantcatch2" width="500" height="367" /></p>
<p><span id="more-297"></span></p>
<p>You can download the complete source <a href="http://cnicollonline.com/wp-downloads/08-23-10_12-03_php_custom_exception.zip#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">here</a>. This class will be a <span style="text-decoration: underline;">very</span> basic SQL class that&nbsp;will:</p>
<ul>
<li>Connect to a&nbsp;database</li>
<li>Disconnect from a&nbsp;database</li>
<li>Select from a&nbsp;database</li>
</ul>
<p>The directory setup after this tutorial should look as&nbsp;follows:</p>
<ul>
<h4>Directory&nbsp;Setup</h4>
<li>index.php</li>
<li>/lib/
<ul>
<li>SQL.class.php</li>
<li>SQL.exception.class.php</li>
</ul>
</li>
<li>/sql/
<ul>
<li>world.sql</li>
</ul>
</li>
<li>SQLException.log</li>
</ul>
<p><em>Make sure you have the world database installed within your database. You can download it <a href="http://dev.mysql.com/doc/world-setup/en/world-setup.html">here</a> or find it in the download of the completed&nbsp;source.</em></p>
<h2>The SQL&nbsp;class</h2>
<p>Before I jump into the mix, this is written for people whom already have a basic grasp on any OOP language, as well as some of the basics of exception&nbsp;handling.</p>
<h4>SQL.class.php</h4>
<pre class="brush: php;">
&lt;?php

include('SQL.exception.class.php');

class SQL {

	private $username;
	private $password;
	private $database;
	private $connection;

	/**
	*
	*
	*/
	public function  __construct($u,$p,$d) {
		$this-&gt;username = $u;
		$this-&gt;password = $p;
		$this-&gt;database = $d;
		$this-&gt;connection = false;
	}

	public function connect() {
		if(!$this-&gt;connection) {
			// use @ to surpress the error
			if(!@mysql_connect('localhost',$this-&gt;username,$this-&gt;password)) {
				throw new SQLException('Can\'t connect to the database, either the username or password are wrong');
			}

			// use @ to surpress the error
			if (!@mysql_select_db($this-&gt;database)) {
				throw new SQLException('The database '.$this-&gt;database.' does not exist.');
			}

			$this-&gt;connection = true;
		}
	}

	public function disconnect() {
		if($this-&gt;connection) {
			mysql_close();
			$this-&gt;connection = false;
		}
	}

	public function getCity($city) {
		$cities = array();

		$query = 'SELECT * FROM City WHERE NAME ='.&quot;'$city'&quot;;
		$results = @mysql_query($query);
		if ($results) {
			while($row = mysql_fetch_array($results)) {
				$cities[] = $row;
			}

			if (sizeof($cities) &gt; 0) {
				return $cities;
			}
			else {
				throw new SQLException('The following city: '.$city.' was not found',$query);
			}
		}
		else {
			throw new SQLException('Error with query when trying to get a city: ',$query);
		}
	}
}

?&gt;
</pre>
<p>Theres the SQL class. Theres a few things in here that I should make note of. First, I&#8217;ve included the SQLException custom class, we have yet to create that, so hang on for now! Secondly the way that a try catch block works, is that it needs to try to do something and if that something does not work, it will catch that exception to better handle it. In order to catch an exception one must be thrown. We&#8217;re throwing the exceptions anytime we feel an error might need to be&nbsp;reported.</p>
<h2>Next up the custom exception&nbsp;class</h2>
<p>Create a new file within your lib folder called&nbsp;&#8220;SQL.exception.class.php&#8221;</p>
<h4>SQL.exception.class.php</h4>
<pre class="brush: php;">
&lt;?php
class SQLException extends Exception {

	// path to the log file
	private $log_file;

	public function __construct($message=NULL, $query = NULL) {

		// NOTE:: THIS MAY NEED TO CHANGE
		$this-&gt;log_file =  $_SERVER['DOCUMENT_ROOT'].'/'.$_SERVER['REQUEST_URI'].'/SQLException.log';

		$code = mysql_errno();
		$sql_error = mysql_error();

		// open the log file for appending
		if ($fp = fopen($this-&gt;log_file,'a')) {

			// construct the log message
			$log_msg = date(&quot;[Y-m-d H:i:s]&quot;) .
				&quot; Code: $code &quot; .
				&quot; || Message: $message&quot;.
				&quot; || SQL error: $sql_error \n&quot;.
				&quot;Query: $query\n-------\n&quot;;

			fwrite($fp, $log_msg);

			fclose($fp);
		}

		// call parent constructor
		parent::__construct($message, $code);
	}

}
?&gt;
</pre>
<p>All the magic here happens when we extend PHP&#8217;s Exception class. Moving down to the class constructor, I&#8217;ve set up two parameters. <code>$message</code> takes the message that will be passed into the parent constructor. This message will be shown to the user to better explain whats going. The second parameter <code>$query</code> is meant for the log file. This is passed in so that we as the developers can view the query that may have been botched. Moving into the constructor now, it&#8217;s important to provide a path to the logfile, so the first line of code we see does just that. Next the two variables <code>$code</code> and <code>$sql_error</code> grab a little more information for the log file. The las bit of code opens the log file, appends a new entry, saves and closes it. To finish the class off, run the parents&nbsp;constructor.</p>
<h2>Finally the index or testing&nbsp;file.</h2>
<p>This is the index file that will be within our root directory. It contains sets of variables to help generate exceptions. This file is also where we &#8220;try&#8221; to complete a statement and if anything goes wrong we &#8220;catch&#8221; that exception, kill the script and explain why things didn&#8217;t work&nbsp;out.</p>
<h4>index.php</h4>
<pre class="brush: php;">
&lt;?php
include_once('lib/SQL.class.php');

// ==================== EXCEPTION ERROR ====================
// switch these two database variables to see a exception error occur
$database = 'world';
//$database = 'wrongDB';			// &lt;--- this will result in an exception error when uncommented.

// ==================== EXCEPTION ERROR ====================
// switch these two username variables to see a exception error occur
$username = 'root';
//$username = 'wrongUserName';		// &lt;--- this will result in an exception error when uncommented.

// ==================== EXCEPTION ERROR ====================
// switch these two username variables to see a exception error occur
$password = 'root';
//$password = 'wrongPassword';		// &lt;--- this will result in an exception error when uncommented.

// ==================== EXCEPTION ERROR ====================
// switch these two city variables to see a exception error occur
$city = 'Vancouver';
//$city = 'Gotham City';			// &lt;--- this will result in an exception error when uncommented.

$db = new SQL($username,$password,$database);

/**
* try catch block.
* try - to connect to the database and once connected, disconnect.
* catch - any exception that will occur and kill the script.
*/
try {
	$db-&gt;connect();
	$db-&gt;disconnect();
} catch (SQLException $e) {
	$db-&gt;disconnect();
	die($e-&gt;getMessage());
}

/**
* try catch block
* try to connect to the database
* try to run a select query (note: to get an exception error change the city variable above)
* print the query
* disconnect
* catch any error that may occur.
*/
try {
	$db-&gt;connect();
	$r = $db-&gt;getCity($city);

	// print the results
	echo '&lt;pre&gt;';
		print_r($r);
	echo '&lt;/pre&gt;';

	$db-&gt;disconnect();
} catch (SQLException $e) {
	$db-&gt;disconnect();
	die($e-&gt;getMessage());
}

?&gt;
</pre>
<h2>Conclusion</h2>
<p>Exception handling is a fun subject. The possibilities of being able to recover from errors that might occur create endless possibilities when scripting, just don&#8217;t do what I do and leave it all to the bitter&nbsp;end!</p>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/custom-php-exception-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Objective-C images</title>
		<link>http://cnicollonline.com/programming/objective-c-images/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/objective-c-images/#comments</comments>
		<pubDate>Fri, 20 Aug 2010 18:46:12 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=261</guid>
		<description><![CDATA[When programming in any language I find that there are always several things that no matter how hard I try to remember will never stick. One thing as of late has been using images within objective-c and iPhone&#160;development. So many&#160;ways! There are several ways to get images onto your display. The two I find I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>When programming in any language I find that there are always several things that no matter how hard I try to remember will never stick. One thing as of late has been using images within objective-c and iPhone&nbsp;development.</p>
<p><span id="more-261"></span></p>
<h3>So many&nbsp;ways!</h3>
<p>There are several ways to get images onto your display. The two I find I&#8217;m using the most are calling an image from the web, and using an image from your resource directory. Below are two snippets that I find useful to have within your snippet&nbsp;collection.</p>
<h3>Snippet 1: Getting an image from the&nbsp;web</h3>
<ul>
<li>The image link I&#8217;ll be using in the first example is:&nbsp;<a href="http://goo.gl/QL0z">http://farm5.static.flickr.com/4098/4911106000_9c3a16bb59.jpg</a></li>
</ul>
<pre class="brush: objc;">
// ----------------------- .h ------------------------
...
UIImageView *imgHolder;
...
@property(nonatomic, retain) IBOutlet UIImageView *imgHolder;

// ----------------------- .m ------------------------
// PART 1 - update url of path to the image
// PART 2 - update the variable reference to the UIImageView object
// -----------------------------------------------

// ===== PART 1 =====
NSString *imgURLpath = @&quot;http://farm5.static.flickr.com/4098/4911106000_9c3a16bb59.jpg&quot;;
UIImage *imgURL = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: imgURLpath]]] retain];

if (imgURL != nil) { // Image was loaded successfully.
	// ===== PART 2 =====
	[imgHolder setImage:imgURL];
	// ===== PART 2 =====
	[imgHolder setUserInteractionEnabled:NO];
	[imgURL release]; // Release the image now that we have a UIImageView that contains it.
}
</pre>
<h3>Snippet 2: Getting an image from the resource&nbsp;folder</h3>
<ul>
<li>The image I&#8217;ll be using&nbsp;is:</li>
<p>	<a href="http://www.flickr.com/photos/98682661@N00/4911106000/" title="08-20-10_11-19 by Cosizzle, on Flickr"><img src="http://farm5.static.flickr.com/4098/4911106000_9c3a16bb59.jpg" width="230" height="380" alt="08-20-10_11-19" /></a></p>
<li>The image above will need to be added to your applications resource folder. <em>Note: Don&#8217;t forget to check off &#8220;Copy items to destination group&#8217;s folder. Unless that&#8217;s not your style&#8221; <img src='http://cnicollonline.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </em></li>
</ul>
<pre class="brush: objc;">
	// ----------------------- .h ------------------------
	...
	UIImageView *imgHolder;
	...
	@property(nonatomic, retain) IBOutlet UIImageView *imgHolder;

	// ----------------------- .m ------------------------
	// PART 1 - create an image object
	// PART 2 - update the variable reference to the UIImageView object
	// -----------------------------------------------

	// ===== PART 1 =====
	// note: the image in use should be in your resource folder
	NSString *imgName = @&quot;4911106000_9c3a16bb59.jpg&quot;;
	UIImage *myImg = [UIImage imageNamed:imgName];

	if (myImg != nil) { // Image was loaded successfully.
		// ===== PART 2 =====
		[imgHolder setImage:myImg];
		// ===== PART 2 =====
		[imgHolder setUserInteractionEnabled:NO];
		[myImg release]; // Release the image now that we have a UIImageView that contains it.
	}
	</pre>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/objective-c-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UITableView Application Tutorial</title>
		<link>http://cnicollonline.com/programming/uitableview-application-tutorial/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/uitableview-application-tutorial/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 22:29:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=249</guid>
		<description><![CDATA[Learning Objective-C coupled with the Interface Builder, I found that using a UIImageHolder, or UITextLabel, or even the UIScrollBar came more and more simple each time I used them. I had my laptop with a full battery, a fresh piece of paper to scribble on and I was ready to tackle a Navigation-based&#160;Application. Now this [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- Wobjobjc]ORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>Learning Objective-C coupled with the Interface Builder, I found that using a UIImageHolder, or UITextLabel, or even the UIScrollBar came more and more simple each time I used them. I had my laptop with a full battery, a fresh piece of paper to scribble on and I was ready to tackle a Navigation-based&nbsp;Application.</p>
<p>Now this wasn&#8217;t a hard feat, but it wasn&#8217;t an one easy either. I feel I have a good foot in the door with this, but far from a &#8220;pro&#8221;&nbsp;status.</p>
<p><span id="more-249"></span></p>
<h2>Why so&nbsp;simple?</h2>
<p>I wanted to keep things simple here. The basis for this tutorial is to quickly show how to build a Navigation-based Application that does no more than load a view when clicking on a&nbsp;cell.</p>
<p>I&#8217;m not sure if this is the best way to do it, and in more complex projects this may not prove to be resourceful. However for getting started, for me this did the&nbsp;trick!</p>
<h3>Step&nbsp;1</h3>
<p>Go ahead and create a new Table View Application within&nbsp;xCode</p>
<div class="tutorial_image"><img src="http://farm3.static.flickr.com/2719/4409500308_48cd222162.jpg" border="0" /></div>
<h3>Step&nbsp;2</h3>
<p>Create a few controller classes for our views to work with. For this tutorial I created&nbsp;three.</p>
<ol>
<li>SubViewControllerOne</li>
<li>SubViewControllerTwo</li>
<li>SubViewControllerThree</li>
</ol>
<p><em>note: that you need both .m and .h&nbsp;files</em></p>
<p>Next create the nib, or view files to work along with the&nbsp;controllers</p>
<ol>
<li>SubViewOne.xib</li>
<li>SubViewTwo.xib</li>
<li>SubViewThree.xib</li>
</ol>
<p>I understand that at the time when creating a controller, you also have the option to create a nib file at the sime time. I choose not to do this because of how Xcode names it&#8217;s nibs. for example &#8220;SubViewControllerOne&#8221; controller would have a nib file called &#8220;SubViewControllerOne&#8221; which is fine, however because my controller contains the word &#8220;controller&#8221; that could lead to confusion down the road. It also doesnt stick the nib file in the Resource folder but rather the class folder. There is no right or wrong answer here, just whatever makes you sleep better at night I&nbsp;suppose.</p>
<p>By now your classes and resource folder should look like the&nbsp;following</p>
<div class="tutorial_image"><img src="http://farm3.static.flickr.com/2680/4408785065_78f7837d79_o.jpg" border="0" /></div>
<p><em>note: I subgrouped my sub view controllers. Again personal&nbsp;preference.</em></p>
<h3>Step&nbsp;3</h3>
<p>We need to link our nib files to their controllers, so open up each nib file and assign the <b>File Owner</b> to the correct&nbsp;controller</p>
<div class="tutorial_image"><img src="http://farm5.static.flickr.com/4067/4408771637_5f4dc82665.jpg" width="500" height="179" alt="03-02-10_19-32_UITableView_03" /></div>
<p> Then ctrl+click on the <b>File Owner</b> delegate and drag the blue line to the view - to link up the&nbsp;view.</p>
<div class="tutorial_image"><img src="http://farm3.static.flickr.com/2789/4409543602_c8cb84ef06.jpg" border="0" /></div>
<p>While we&#8217;re at it we might as well put a label on our view so we know that indeed the view is being&nbsp;loaded.</p>
<div class="tutorial_image"><img src="http://farm5.static.flickr.com/4070/4409558504_5003a7db66.jpg" border="0" /></div>
<h3>Step&nbsp;3</h3>
<p>Rinse and repeat step 2 for the other two nib&nbsp;files</p>
<h3>Step&nbsp;4</h3>
<p>Alright with everything linked up and ready to go, we can dive into some code! Most of, if not all the programming we&#8217;re going to be using will be within the <em>RootViewController</em> class. Go ahead and open&nbsp;<em>RootViewController.h</em></p>
<p>We&#8217;re not going to do a whole lot in here, however to load in and out different views, depending on the cell, I plan to store all this within an NSMutableArray that will hold a NSDictionary object. Let&#8217;s declare the NSMutable array within the <em>RootViewController.h</em>&nbsp;file.</p>
<p>Your <em>RootViewController.h</em> should now look like&nbsp;this</p>
<h4>RootViewController.h</h4>
<pre class="brush: objc;">
@interface RootViewController : UITableViewController {

	NSMutableArray *views;
}

@property(nonatomic, retain) IBOutlet NSMutableArray *views;

@end
</pre>
<p>Next head over to <em>RootViewController.m</em> and let&#8217;s add some code. First off it&#8217;s important we include all the view controllers we plan to use as well as synthesize the view&nbsp;object</p>
<pre class="brush: objc;">
#import &quot;RootViewController.h&quot;
#import &quot;SubViewControllerOne.h&quot;
#import &quot;SubViewControllerTwo.h&quot;
#import &quot;SubViewControllerThree.h&quot;

@implementation RootViewController
@synthesize views;

...
</pre>
<p>Next we call the
<pre class="brush: objc;">-(void) awakeFromNib {...}</pre>
<p> function and start adding our NSDictionary objects to the view. The NSDictionary will hold to&nbsp;properites:</p>
<ol>
<li><em>@title</em> - Title you see at the top of the&nbsp;view</li>
<li><em>@controller</em> - The controller&nbsp;object</li>
</ol>
<pre class="brush: objc;">
-(void) awakeFromNib
{
	views = [[NSMutableArray alloobjc] init];

	// ============================== CELL 1 ==============================

	//init the view
	SubViewControllerOne *viewOne = [[SubViewControllerOne alloobjc] init];

	// value - key pairing
	[views addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					  @&quot;cell 1&quot;,	@&quot;title&quot;,
					  viewOne,		@&quot;controller&quot;,
					  nil]];

	[viewOne release];

	// ============================== CELL 2 ==============================

	//init the view
	SubViewControllerTwo *viewTwo = [[SubViewControllerTwo alloobjc] init];

	// value - key pairing
	[views addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					  @&quot;cell 2&quot;,	@&quot;title&quot;,
					  viewTwo,		@&quot;controller&quot;,
					  nil]];

	[viewTwo release];

	// ============================== CELL 3 ==============================

	//init the view
	SubViewControllerThree *viewThree = [[SubViewControllerThree alloobjc] init];

	// value - key pairing
	[views addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					  @&quot;cell 3&quot;,	@&quot;title&quot;,
					  viewThree,	@&quot;controller&quot;,
					  nil]];

	[viewThree release];
}
</pre>
<h3>Step&nbsp;4</h3>
<p>Ok cool, we&#8217;re getting somewhere. We&#8217;ve now loaded our views array with Objects that will load a view as well as create a title, next we have to modify how many rows there will be, what the title is, and what view is&nbsp;loaded.</p>
<p>First start off by stating how many rows are within the table. Locate this function and modify it. All that&#8217;s going on is that you&#8217;re specifying how many objects are in your view array, which should equal the amount of rows&nbsp;needed.</p>
<pre class="brush: objc;">
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [views count];
}
</pre>
<p>Next let&#8217;s get the titles in place. Find this function and modify&nbsp;it</p>
<pre class="brush: objc;">
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @&quot;Cell&quot;;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloobjc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

	// Configure the cell.
	cell.textLabel.text = [[views objectAtIndex:indexPath.row] objectForKey:@&quot;title&quot;]; 

    return cell;
}
</pre>
<p>And finally, let&#8217;s load in the appropriate view depending on the cell being clicked. Modify this&nbsp;function&#8217;</p>
<pre class="brush: objc;">
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Navigation logic may go here -- for example, create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloobjc] initWithNibName:@&quot;AnotherView&quot; bundle:nil];
	// [self.navigationController pushViewController:anotherViewController animated:YES];
	// [anotherViewController release];

	UIViewController *targetViewController = [[views objectAtIndex:indexPath.row] objectForKey:@&quot;controller&quot;];
	[self.navigationController pushViewController:targetViewController animated:YES];
}
</pre>
<h3>Step&nbsp;5</h3>
<p>We&#8217;re almost there! Just one (well 3) minor things. It would be nice for the user to get back home. So let&#8217;s create the functionality for that. You will need to do this in all 3 of your viewController&nbsp;classes.</p>
<p>Open up <em>SubViewControllerOne.m</em> and replace the function as well as create the other function seen&nbsp;below</p>
<pre class="brush: objc;">
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloobjc] initWithTitle:
	    @&quot;HOME&quot; style:UIBarButtonItemStylePlain
	    target:self
		action:@selector(goHome:)] autorelease]; //auto released memory

    [super viewDidLoad];
}

-(void)goHome:(id)sender{
	NSLog(@&quot;Go Home!&quot;);
	[self.navigationController popToRootViewControllerAnimated:YES];
}
</pre>
<p><em>Be sure to do this in all three of your&nbsp;ViewControllers</p>
<h2>Closing&nbsp;thoughts</h2>
<p>By now you should be ready to compile and build, hopefully everything should be up and running. If it&#8217;s not I&#8217;ve attached my file&nbsp;<a href="http://www.cnicollonline.com/wp-articles/03-02-10_19-32_UITableView/TableViewApplication.zip" target="_self">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/uitableview-application-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Templates within xCode</title>
		<link>http://cnicollonline.com/programming/custom-templates-within-xcode/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/custom-templates-within-xcode/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 19:02:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=223</guid>
		<description><![CDATA[While sitting in my Objective-C class learning about the Tab Bar Application and it&#8217;s uses our teacher brought up a point in that Apple&#8217;s pre-made Tab Bar Application, is good&#8230; but not great. The problem is that it starts you up with two views (which is good), However the first view is the main controller. [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>While sitting in my Objective-C class learning about the Tab Bar Application and it&#8217;s uses our teacher brought up a point in that Apple&#8217;s pre-made Tab Bar Application, is good&#8230; but not great. The problem is that it starts you up with two views (which is good), However the first view is the main controller. The second view has it&#8217;s own controller assigned to it. After a little research and a quick modification to the Tab Bar Application I was able to create my own template that I now use for Tab Bar&nbsp;projects.</p>
<div class="tutorial_image"><img src="http://farm3.static.flickr.com/2772/4348683609_dda7901693_o.jpg" border="0" /></div>
<p><span id="more-223"></span></p>
<p>To start off, and as my teacher suggested it&#8217;s probably best for the project to have 3 different&nbsp;controllers.</p>
<ol>
<li>MainController which connects the NIB MainWindow.xib
<ul>
<li>This will be the main view in which links the other view&#8217;s to the tab&nbsp;bar</li>
</ul>
</li>
<li>FirstViewController which connects the NIB&nbsp;FirstView.xib</li>
<li>SecondViewController which connects the NIB&nbsp;SecondView.xib</li>
</ol>
<p>To create a custom&nbsp;template:</p>
<p><strong>NOTE:</strong> It&#8217;s probably a good idea to quit xCode.app before going&nbsp;ahead!</p>
<ol>
<li>Download the template&nbsp;<a title="Template Download" href="http://www.cnicollonline.com/wp-articles/02-11-10_00-00_customTemplate_xCode/Tab Bar Application [Modded].zip">here</a></li>
<li>Within the Finder open: <strong>~/Library/Application&nbsp;Support/Developer/Shared/Xcode/</strong></li>
<li>If a folder doesn&#8217;t exist, create a new folder called &#8220;Project Templates&#8221; within that directory
<ul>
<li>You should now have a directory like &#8220;<strong>~/Library/Application Support/Developer/Shared/Xcode/Project&nbsp;Templates/</strong>&#8221;</li>
</ul>
</li>
<li>Create a new &#8220;Category&#8221; (new folder). In my case I called in &#8220;Custom Templates&#8221; within /Project&nbsp;Templates/</li>
<li>Drag the &#8220;Tab Bar Application [Modded]&#8221; folder within your newly made Category&nbsp;folder</li>
<li>Launch xCode and it should all be there and&nbsp;working!</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/custom-templates-within-xcode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Start to Objective-C</title>
		<link>http://cnicollonline.com/programming/a-start-to-objective-c/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/a-start-to-objective-c/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 20:09:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=217</guid>
		<description><![CDATA[It&#8217;s been a short time since I&#8217;ve gotten anything written, this was due to work being busy, a few small side projects, school projects and exams, summer starting and well - a new love. This love however can be bought with money and it involves selling a bit of your&#160;soul. After waiting a year I [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>It&#8217;s been a short time since I&#8217;ve gotten anything written, this was due to work being busy, a few small side projects, school projects and exams, summer starting and well - a new love. This love however can be bought with money and it involves selling a bit of your&nbsp;soul.</p>
<p>After waiting a year I was finally able to get a iPhone. 3Gs at that! This quickly pulled my interest away from my every day languages and set me on a course to learn&nbsp;Objective-C.</p>
<p><span id="more-217"></span></p>
<h3>Back to the&nbsp;start</h3>
<p>Through a <a href="http://www.iphonesdkarticles.com/2008/07/first-iphone-application.html" target="_blank">tutorial</a> a while back I was able to build a &#8216;helloworld&#8217; application that ran! It was very exciting and it brought me back to why I enjoy programming so much. However coming from a PHP and Java background (very little C-anything) it was pretty deep water at times. There were odd function calls, and the instance variables were hard identify. It was clear that all elements of an OOP language were there, just at the cost of an odd syntax&nbsp;layout.</p>
<p>Not to get overwhelmed by the complexity of the language I went out and picked up <a href="http://www.amazon.com/Programming-Objective-C-2-0-Developers-Library/dp/0321566157/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1246909328&#038;sr=8-1" target="_blank">Programming in Objective-C 2.0 (2nd Edition)</a>. I&#8217;m only on Chapter 3 but unknown tidbits are starting to make a little more sense, and I am now able to identify the common elements between Objective-C and other OOP&nbsp;languages.</p>
<h3>The&nbsp;Code</h3>
<p>This article isn&#8217;t a whole lot on the learning part, just a quick demo on a helloworld application written in PHP, Java and,&nbsp;Objective-C</p>
<h4>PHP</h4>
<pre class="brush: php;">
&lt;?php
$word1 = 'hello';
$word2 = 'world';

function $printText() {
	return $word1.' '.$word2
}

echo $printText();
?&gt;
</pre>
<h4>Java</h4>
<pre class="brush: java;">
package ocTest;

public class HelloWorld {
	private String word1;
	private String word2;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new HelloWorld();
	}

	private HelloWorld() {
		setWord1(&quot;hello&quot;);
		setWord2(&quot;world&quot;);

		System.out.println(printText());
	}

	/**
	 * @param word1 the word1 to set
	 */
	public void setWord1(String word1) {
		this.word1 = word1;
	}

	/**
	 * @param word2 the word2 to set
	 */
	public void setWord2(String word2) {
		this.word2 = word2;
	}

	private String printText() {
		return word1 + &quot; &quot; + word2;
	}

}
</pre>
<h4>Objective-C</h4>
<pre class="brush: cpp;">
#import &lt;Foundation/Foundation.h&gt;

// --- @interface ----
@interface TheString: NSObject
{
	char word1;
	char word2;
}

-(void) printText;
-(void) setWord1: (char) w1;
-(void) setWord2: (char) w2;

@end

// --- @implementation ---
@implementation TheString

-(void) printText
{
	NSLog(@&quot;%@ %@&quot;, word1, word2);
}

-(void) setWord1: (char) w1
{
	word1 = w1;
}

-(void) setWord2: (char) w2
{
	word2 = w2;
}

@end

// --- Main ---
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	TheString *myString;

	[myString setWord1: 'hello'];
	[myString setWord2: 'world'];

	[myString printText];
	[myString release];

    [pool drain];
    return 0;
}
</pre>
<h3>Conclusion</h3>
<p>I find it quite interesting that such a simple application such as &#8216;hello world&#8217; can become so complex. Of course I went a little overboard with the instance variables and the setters. More to come soon, hopefully something on the iPhone&nbsp;soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/a-start-to-objective-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Class: File Details released</title>
		<link>http://cnicollonline.com/programming/class-file-details-released/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/class-file-details-released/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 19:41:16 +0000</pubDate>
		<dc:creator>Cosizzle</dc:creator>
				<category><![CDATA[Class]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Snippits]]></category>
		<category><![CDATA[arrays]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=209</guid>
		<description><![CDATA[I was tasked with a project at work in which I had to build a site that would be quite dynamic. The problem however was that I could not use a database to hold information. What I did (and something I would avoid if I could) was create a class that looks within a folder [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>06-15-09_00-00_fileDetails<br />
-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>I was tasked with a project at work in which I had to build a site that would be quite dynamic. The problem however was that I could not use a database to hold information. What I did (and something I would avoid if I could) was create a class that looks within a folder thats specified and builds an array off the files within the&nbsp;folder.</p>
<p><span id="more-209"></span></p>
<h3>How it&nbsp;works</h3>
<p>Reads a folder of files, breaks apart the file name by a specified &#8220;breaker&#8221;. It then creates a new array off the specified file name&nbsp;attributes</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/06-15-09_00-00_fileDetails/fileInfo.jpg" border="0" /></div>
<h3>Demo</h3>
<p>File&nbsp;setup:</p>
<pre class="brush: php;">
include_once('FileDetail.class.php');
// a new object reference using an array for the parameter which specifies the file name attributes
// FileDetail(array(attributes));
$files = new FileDetail(array('id','movie','name','ext'));

// loadFiles(Folder, separator)
$files-&gt;loadFiles('test_files2','_');

// New variable to hold the file name array
$fileNames = $files-&gt;getFileNames();

// New Variable to hold the file details array
$fileDetails = $files-&gt;getFileDetails();
</pre>
<p>Testing the&nbsp;arrays:</p>
<pre class="brush: php;">
// ========================================= EXAMPLE =========================================
echo '&lt;h4&gt;File Names Test 2&lt;/h4&gt;';
echo '&lt;pre&gt;';
	print_r($fileNames);
echo '&lt;/pre&gt;';

// ========================================= EXAMPLE =========================================
echo '&lt;h4&gt;File Details&lt;/h4&gt;';
echo '&lt;pre&gt;';
	print_r($fileDetails);
echo '&lt;/pre&gt;';
</pre>
<p><strong>File&nbsp;Names</strong></p>
<pre>
Array
(
    [0] => 01_wall-e_walle02.jpg
    [1] => 02_batman_joker02.jpg
    [2] => 02_wall-e_walle.jpg
    [3] => 04_batman_joker02.jpg
    [4] => 05_batman_joker.jpg
)
</pre>
<p><strong>File&nbsp;Details</strong></p>
<pre>
Array
(
    [0] => Array
        (
            [id] => 01
            [movie] => wall-e
            [name] => walle02
            [ext] => jpg
        )

    [1] => Array
        (
            [id] => 02
            [movie] => batman
            [name] => joker02
            [ext] => jpg
        )

    [2] => Array
        (
            [id] => 02
            [movie] => wall-e
            [name] => walle
            [ext] => jpg
        )

    [3] => Array
        (
            [id] => 04
            [movie] => batman
            [name] => joker02
            [ext] => jpg
        )

    [4] => Array
        (
            [id] => 05
            [movie] => batman
            [name] => joker
            [ext] => jpg
        )

)
</pre>
<p>Real World&nbsp;Example:</p>
<pre class="brush: php;">
echo '&lt;h4&gt;Get files of a specific parameter&lt;/h4&gt;';
echo '&lt;h5&gt; movie -&gt; batman&lt;/h5&gt;';
echo '&lt;pre&gt;';
	print_r($files-&gt;getFilesByKey('movie','batman'));
echo '&lt;/pre&gt;';
</pre>
<p><strong>Get files of a specific parameter (movies->batman)</strong></p>
<pre>
Array
(
    [0] => Array
        (
            [id] => 02
            [movie] => batman
            [name] => joker02
            [ext] => jpg
        )

    [1] => Array
        (
            [id] => 04
            [movie] => batman
            [name] => joker02
            [ext] => jpg
        )

    [2] => Array
        (
            [id] => 05
            [movie] => batman
            [name] => joker
            [ext] => jpg
        )

)
</pre>
<h3>Conclusion</h3>
<p>The class can be used in many which ways whether it&#8217;s loading a gallery of images or building a website based off of the attributes of the images. The class and demo files can be downloaded&nbsp;<a href="http://www.cnicollonline.com/wp-articles/06-15-09_00-00_fileDetails/fileDetails.zip">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/class-file-details-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Arrays and Loops with php [Level 2]</title>
		<link>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-2/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-2/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 18:27:01 +0000</pubDate>
		<dc:creator>Cosizzle</dc:creator>
				<category><![CDATA[Notes]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[multidimensional arrays]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=204</guid>
		<description><![CDATA[A few weeks ago I had wrote Arrays and Loops with php [Level 1]. This topic is expanding on that idea. I&#8217;ll be covering more complex array examples using 2D multidimensional&#160;arrays. Multidimensional&#160;Arrays The idea of a multidimensional array is something that can easily confuse someone, especially when they become complex with information (ie. 2D and [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>A few weeks ago I had wrote <a href="http://cnicollonline.com/?p=186#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" target="_self">Arrays and Loops with php [Level 1].</a> This topic is expanding on that idea. I&#8217;ll be covering more complex array examples using 2D multidimensional&nbsp;arrays.</p>
<p><span id="more-204"></span></p>
<h3>Multidimensional&nbsp;Arrays</h3>
<p>The idea of a multidimensional array is something that can easily confuse someone, especially when they become complex with information (ie. 2D and 3D arrays). I like to think of multidimensional arrays as a miniature&nbsp;database.</p>
<p>A multidimensional array can hold multiple values to a single key. Take a look at the output&nbsp;below.</p>
<pre>Array
(
    [0] => Array
        (
            [name] => Cody
            [gender] => male
            [colour] => green
            [fruit] => apples
            [sport] => frisbee
        )

    [1] => Array
        (
            [name] => Sam
            [gender] => male
            [colour] => blue
            [fruit] => oranges
            [sport] => golf
        )

    [2] => Array
        (
            [name] => Jenny
            [gender] => female
            [colour] => pink
            [fruit] => pineapple
            [sport] => hockey
        )

)
</pre>
<p>This example is an example of a 2D array using key values. By default PHP will auto fill the keys, but this can lead to confusion down the road. To set up the&nbsp;array: </p>
<pre class="brush: php;">
$people = array( array(&quot;name&quot;=&gt;&quot;Cody&quot;,
						&quot;gender&quot;=&gt;&quot;male&quot;,
						&quot;colour&quot;=&gt;&quot;green&quot;,
						&quot;fruit&quot;=&gt;&quot;apples&quot;,
						&quot;sport&quot;=&gt;&quot;frisbee&quot;),
				array(&quot;name&quot;=&gt;&quot;Sam&quot;,
					&quot;gender&quot;=&gt;&quot;male&quot;,
						&quot;colour&quot;=&gt;&quot;blue&quot;,
						&quot;fruit&quot;=&gt;&quot;oranges&quot;,
						&quot;sport&quot;=&gt;&quot;golf&quot;),
				array(&quot;name&quot;=&gt;&quot;Jenny&quot;,
						&quot;gender&quot;=&gt;&quot;female&quot;,
						&quot;colour&quot;=&gt;&quot;pink&quot;,
						&quot;fruit&quot;=&gt;&quot;pineapple&quot;,
						&quot;sport&quot;=&gt;&quot;hockey&quot;)
				);

echo '&lt;pre&gt;';
	print_r($people);
echo '&lt;/pre&gt;';
</pre>
<p>There&#8217;s a lot going on, take some time and read through it. First we set up a main container that will hold all of our information
<pre>$people</pre>
<p> we then put a new array within our already created&nbsp;array.</p>
<p>Retrieving a single value is quite easy. We just call on what array element we want, then we ask for a specific property, in this example the&nbsp;name.</p>
<pre class="brush: php;">
echo '&lt;pre&gt;';
echo $people[0]['name'];
echo '&lt;/pre&gt;';
</pre>
<h3>How this can be&nbsp;used</h3>
<p>By looping of course! We can loop through this in many different ways to provide an&nbsp;example:</p>
<pre class="brush: php;">
for ($i=0; $i&lt;sizeOf($people); $i++) {
	$string = $people[$i]['name'] . &quot;'s favorite fruit is &quot; . $people[$i]['fruit'];
	if ($people[$i]['gender'] === &quot;male&quot;) {
		$string .= &quot; his favorite colour is &quot; . $people[$i]['colour'] . &quot; and he enjoys to play &quot; . $people[$i]['sport'];
	}
	else if ($people[$i]['gender'] === &quot;female&quot;) {
		$string .= &quot; her favorite colour is &quot; . $people[$i]['colour'] . &quot; and she enjoys to play &quot; . $people[$i]['sport'];
	}
	echo $string;
	echo '&lt;br&gt;';
}
</pre>
<p>output:</p>
<pre>
Cody's favorite fruit is apple his favorite colour is green and he enjoys to play frisbee
Sam's favorite fruit is oranges his favorite colour is blue and he enjoys to play golf
Jenny's favorite fruit is pineapple her favorite colour is pink and she enjoys to play hockey
</pre>
<p>Here I used a if statement within my for loop to check the gender value. If it were a male I had the output specify &#8220;he&#8221;, and the same check for a&nbsp;female.</p>
<p>Another use for a multidimensional array is a table layout, or&nbsp;grid.</p>
<pre class="brush: php;">
$grid = array(array('Cody','male','green'),
			array('Sam','male','blue'),
			array('Jenny', 'female','pink')
);
for ($r=0; $r&lt;sizeOf($grid); $r++) {
	for($c=0; $c&lt;sizeOf($grid[$r]); $c++) {
		echo $grid[$r][$c]. &quot; | &quot;;
	}
	echo '&lt;br&gt;';
}
</pre>
<p>output:</p>
<pre>
Cody | male | green |
Sam | male | blue |
Jenny | female | pink |
</pre>
<h3>Conclusion</h3>
<p>multidimensional arrays make for an interesting topic, there is so much you can do, but without doing they can be hard to explain. Here is the source to help you get&nbsp;started.</p>
<pre class="brush: php; collapse: true; light: false; toolbar: true;">
&lt;?php
$people = array( array(&quot;name&quot;=&gt;&quot;Cody&quot;,
						&quot;gender&quot;=&gt;&quot;male&quot;,
						&quot;colour&quot;=&gt;&quot;green&quot;,
						&quot;fruit&quot;=&gt;&quot;apples&quot;,
						&quot;sport&quot;=&gt;&quot;frisbee&quot;),
				array(&quot;name&quot;=&gt;&quot;Sam&quot;,
					&quot;gender&quot;=&gt;&quot;male&quot;,
						&quot;colour&quot;=&gt;&quot;blue&quot;,
						&quot;fruit&quot;=&gt;&quot;oranges&quot;,
						&quot;sport&quot;=&gt;&quot;golf&quot;),
				array(&quot;name&quot;=&gt;&quot;Jenny&quot;,
						&quot;gender&quot;=&gt;&quot;female&quot;,
						&quot;colour&quot;=&gt;&quot;pink&quot;,
						&quot;fruit&quot;=&gt;&quot;pineapple&quot;,
						&quot;sport&quot;=&gt;&quot;hockey&quot;)
				);

echo '&lt;pre&gt;';
	print_r($people);
echo '&lt;/pre&gt;';

// Get a single value
echo '&lt;pre&gt;';
echo $people[0]['name'];
echo '&lt;/pre&gt;';
// ================================================= LOOP =================================================
for ($i=0; $i&lt;sizeOf($people); $i++) {
	$string = $people[$i]['name'] . &quot;'s favorite fruit is &quot; . $people[$i]['fruit'];
	if ($people[$i]['gender'] === &quot;male&quot;) {
		$string .= &quot; his favorite colour is &quot; . $people[$i]['colour'] . &quot; and he enjoys to play &quot; . $people[$i]['sport'];
	}
	else if ($people[$i]['gender'] === &quot;female&quot;) {
		$string .= &quot; her favorite colour is &quot; . $people[$i]['colour'] . &quot; and she enjoys to play &quot; . $people[$i]['sport'];
	}
	echo $string;
	echo '&lt;br&gt;';
}

// ================================================= GRID =================================================
$grid = array(array('Cody','male','green'),
			array('Sam','male','blue'),
			array('Jenny', 'female','pink')
);
for ($r=0; $r&lt;sizeOf($grid); $r++) {
	for($c=0; $c&lt;sizeOf($grid[$r]); $c++) {
		echo $grid[$r][$c]. &quot; | &quot;;
	}
	echo '&lt;br&gt;';
}

?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Arrays and Loops with php [Level 1]</title>
		<link>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-1/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-1/#comments</comments>
		<pubDate>Tue, 26 May 2009 18:19:43 +0000</pubDate>
		<dc:creator>Cosizzle</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[loops]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=186</guid>
		<description><![CDATA[Way back when I started programming there were two things I just could not wrap my head around. Unfortunately they fell hand in hand which made doing an alternative quote tedious. Loops and arrays were nightmares. This post is outlines a few small pointers I&#8217;ve picked up along the&#160;way. What is an array, what is [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>Way back when I started programming there were two things I just could not wrap my head around. Unfortunately they fell hand in hand which made doing an alternative quote tedious. Loops and <a href="http://www.php.net/array" target="_blank">arrays</a> were nightmares. This post is outlines a few small pointers I&#8217;ve picked up along the&nbsp;way.</p>
<p><span id="more-186"></span></p>
<h3>What is an array, what is a&nbsp;loop?</h3>
<p>The best way to think of an <a href="http://www.php.net/array" target="_blank">array</a> is as a container, or box. The box (<a href="http://www.php.net/array" target="_blank">array</a>) can hold values and objects for safe keeping, we can put things into the box, and we can take them out. We do this by using a <strong>loop.</strong> The loop will cycle through the <a href="http://www.php.net/array" target="_blank">array</a>, and within the loop we can perform actions to all the objects, a group of objects or any single&nbsp;object.</p>
<p>There are three types of loops are the <a href="http://ca2.php.net/manual/en/control-structures.for.php" target="_blank">for loop</a>, the <a href="http://ca2.php.net/manual/en/control-structures.foreach.php" target="_blank">foreach</a>, and the <a href="http://ca.php.net/while" target="_blank">while loop</a>. What loop to use and when I belive comes with experience and practice. The three loops are similar in what they do, but depending when you use them, or how they&#8217;re used is the tricky&nbsp;part.</p>
<h3>Defining an&nbsp;Array</h3>
<p>I stated earlier that an array was simply a collection of values or&nbsp;objects.</p>
<pre class="brush: php;">
$fruits = array(&quot;apples&quot;, &quot;oranges&quot;, &quot;pears&quot;, &quot;cherries&quot;);
</pre>
<p>Thats all there is to an array, I have it stored within a variable that acts as the container. Now how do we access these delicious&nbsp;fruits?</p>
<pre class="brush: php;">
echo $fruits[0];
echo '&lt;br&gt;';
echo $fruits[1];
echo '&lt;br&gt;';
echo $fruits[2];
echo '&lt;br&gt;';
echo $fruits[3];
</pre>
<p><strong>NOTE:</strong>This is not a loop but its a wonderful method to quickly print out all the elements within an array. I use this a lot when developing and&nbsp;debugging.</p>
<pre class="brush: php;">
// print array
echo '&lt;pre&gt;';
	print_r($fruits); // print array
echo '&lt;/pre&gt;';
</pre>
<p><em>outputs:</em></p>
<pre>Array
(
    [0] => apples
    [1] => oranges
    [2] => pears
    [3] => cherries
)
</pre>
<p><strong>What makes an array?</strong> You can see from the output above that there are two elements within the array [key]=>[value]. Each array element is assigned a unique key. The key is how we can call any given member within the&nbsp;array.</p>
<p><strong>How do we add a new fruit?</strong> To add something to our array we call the array, and give it a new value in an empty index position (php will do the math for&nbsp;you)</p>
<pre class="brush: php;">
$fruits[] = 'grapes';
$fruits[] = 'mango';
</pre>
<p>printing the array again we can now see that indeed our fruits have been&nbsp;added.</p>
<pre>Array
(
    [0] => apples
    [1] => oranges
    [2] => pears
    [3] => cherries
    [4] => grapes
    [5] => mango
)
</pre>
<h3>Working with&nbsp;loops</h3>
<p>You might be asking yourself &#8220;Well how is that any easier then writing it out?&#8221;. Thats when loops become a handy tool, we can simply call any of the three loops to loop through the array and print everything within the array (opposed to printing them individually using&nbsp;$fruits[x])</p>
<p><a href="http://ca2.php.net/manual/en/control-structures.foreach.php" target="_blank">foreach loop:</a> Perhaps as far as this demo goes the minimalist and simplest loop. It basically iterates over each element and outputs its&nbsp;value.</p>
<pre class="brush: php;">
// foreach
foreach ($fruits as $loop) {
	echo $loop;
	echo '&lt;br&gt;';
}
echo '&lt;hr&gt;';
</pre>
<p>The next two loops are similar in what they do. They both allow for more control within the loop allowing you to perform actions based on conditional&nbsp;statements.</p>
<p><a href="http://ca2.php.net/manual/en/control-structures.for.php" target="_blank">for&nbsp;loop</a></p>
<pre class="brush: php;">
// for loop
for ($i=0; $i&lt;sizeOf($fruits); $i++) {
	echo $fruits[$i];
	echo '&lt;br&gt;';
}
echo '&lt;hr&gt;';
</pre>
<p><a href="http://ca.php.net/while" target="_blank">while&nbsp;loop</a></p>
<pre class="brush: php;">
// while loop
$count = 0;
while ($count &lt; sizeOf($fruits)) {
	echo $fruits[$count];
	echo '&lt;br&gt;';
	$count++;
}
</pre>
<p>Theres so much you can do with loops and still I struggle on getting things done with them. I wanted to keep this post simple, there are still multidimensional arrays which add a whole layer of complexcity to the topic. Hopefully I&#8217;ll continue this topic&nbsp;soon.</p>
<p>Heres the full&nbsp;script</p>
<pre class="brush: php; collapse: true; light: false; toolbar: true;">
&lt;?php

// fruit array
$fruits = array(&quot;apples&quot;, &quot;oranges&quot;, &quot;pears&quot;, &quot;cherries&quot;);

// getting the fruit
echo $fruits[0];
echo '&lt;br&gt;';
echo $fruits[1];
echo '&lt;br&gt;';
echo $fruits[2];
echo '&lt;br&gt;';
echo $fruits[3];

// print array
echo '&lt;pre&gt;';
	print_r($fruits); // print array
echo '&lt;/pre&gt;';

// add to the array
$fruits[] = 'grapes';
$fruits[] = 'mango';

// print array
echo '&lt;pre&gt;';
	print_r($fruits); // print array
echo '&lt;/pre&gt;';

// ================================================= LOOPS =================================================
echo '&lt;hr&gt;';

// foreach
foreach ($fruits as $loop) {
	echo $loop;
	echo '&lt;br&gt;';
}
echo '&lt;hr&gt;';

// for loop
for ($i=0; $i&lt;sizeOf($fruits); $i++) {
	echo $fruits[$i];
	echo '&lt;br&gt;';
}
echo '&lt;hr&gt;';

// while loop
$count = 0;
while ($count &lt; sizeOf($fruits)) {
	echo $fruits[$count];
	echo '&lt;br&gt;';
	$count++;
}
?&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/arrays-and-loops-with-php-level-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Phone Validation</title>
		<link>http://cnicollonline.com/programming/phone-validation/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/phone-validation/#comments</comments>
		<pubDate>Thu, 14 May 2009 17:06:50 +0000</pubDate>
		<dc:creator>Cosizzle</dc:creator>
				<category><![CDATA[Notes]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Snippits]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[phone]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=174</guid>
		<description><![CDATA[I tend to do a lot of work with database entry through PHP forums. Over time I&#8217;ve seen nemorous ways in which someone will enter their phone&#160;number. The&#160;Problem Because there are so many different ways to enter a phone number. How it&#8217;s handled, processed and sent to the database becomes a challenge, and as a [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO&nbsp;NOTE:</p>
<p>-<br />
<h2>MAIN&nbsp;TITLE</h2>
<p>-<br />
<h3></h3>
<p>-<br />
<h4></h4>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>- adding a download link<br />
<a href="http://www.cnicollonline.com/wp-articles/PATH TO LINK" target="_self">click&nbsp;here</a></p>
<p>- adding an&nbsp;image</p>
<div class="tutorial_image"><img src="http://www.cnicollonline.com/wp-articles/PATH TO IMG/1.jpg" border="0" /></div>
<p>--></p>
<p>I tend to do a lot of work with database entry through PHP forums. Over time I&#8217;ve seen nemorous ways in which someone will enter their phone&nbsp;number.</p>
<p><span id="more-174"></span></p>
<h2>The&nbsp;Problem</h2>
<p>Because there are so many different ways to enter a phone number. How it&#8217;s handled, processed and sent to the database becomes a challenge, and as a programmer you have to ask &#8220;what is the best&nbsp;way&#8221;.</p>
<h2>The&nbsp;Solution</h2>
<p>
<p>The first solution would be to make your column in which will hold the phone number within your database a varchar(20). I suppose for something quick and dirty it will work, but in no means is this&nbsp;efficient.</p>
<p>The second solution would be to take a&nbsp;number:</p>
<ul>
<li>(555)555-5555</li>
<li>555.555.5555</li>
<li>555 555&nbsp;5555</li>
<li>55 55  55&nbsp;5555</li>
</ul>
<p>and remove unneeded characters and insert it into the database as a int value of&nbsp;5555555555</p>
</p>
<p>The&nbsp;class:</p>
<pre class="brush: php;">
&lt;?php
/**
* @author: cNicoll
* @dateCreated: 04-23-09
*
* VALIDATES A PHONE NUMBER AND STRIPS THE NUMBER OF ANY UNNEEDED CHARACTERS.
*
* Feel free to use and modify the script in anyway, but I do request that you keep my information
* within the comments. Enjoy!
*
* 2009 © http://www.cnicollonline.com
*/

class PhoneValidate {
	// instance variables
	private $illChars = '/(\W*)/';
	private $validChars = '/^(\W*)[0-9](\W*)/';
	private $number;

	// class constructor
	public function PhoneValidate($number) {
		$this-&gt;number = $number;
	}

	/**
	* @param give the number a value
	*/
	public function setNumber($number) {
		$this-&gt;number = $number;
	}

	/**
	* @return value of the phone number
	*/
	public function getNumber() {
		return $this-&gt;number;
	}

	/**
	* @param Validate input number and convert it
	*/
	public function validate() {
		// if its not null convert it
		if ($this-&gt;number != null &amp;&amp; preg_match($this-&gt;validChars, $this-&gt;number)) {
			if (preg_match($this-&gt;illChars, $this-&gt;number)) {
        		$this-&gt;number = preg_replace($this-&gt;illChars, '', $this-&gt;number);
        		// NOTE: count starts at 0
        		if (strlen($this-&gt;number) == 10) {
        			return true;
        		}
        		else {
        			return false;
        		}
    		}
		}
		return false;
	}

}
?&gt;
</pre>
<p>To use this&nbsp;class:</p>
<ol>
<li> Import the&nbsp;class</li>
<li> Check to ensure there is a number within the&nbsp;field</li>
<li> Create a new phone validation object and give it a phone&nbsp;number</li>
<li> Run the validation method within an if statement to ensure it&nbsp;worked.</li>
<li> If it did call the get method to retrieve the&nbsp;number.</li>
<li> Close the rest&nbsp;up!</li>
</ol>
<pre class="brush: php;">
&lt;h3&gt;Validate Phone&lt;/h3&gt;
&lt;form METHOD=POST ACTION=demo.php&gt;
Phone Number: &lt;input type=&quot;text&quot; name=&quot;phone&quot; maxlength=&quot;15&quot; size=&quot;15&quot;&gt;
&lt;input type=&quot;submit&quot; value=&quot;submit&quot; name=&quot;submit&quot;&gt;
&lt;/form&gt;

&lt;?php
// STEP ONE:
include_once('Phone.validate.class.php');

// STEP TWO:
if (isset($_POST['submit'])) {

	// STEP THREE:
	// is there a number?
	if (isset($_POST['phone'])) {

		// STEP FOUR:
		// create the object
		$phoneValidate = new PhoneValidate($_POST['phone']);

		// STEP FIVE:
		// validate the phone number and remove un wanted characters
		if ($phoneValidate-&gt;validate() == true) {

			// STEP SIX:
			echo 'Phone number proccess complete:&lt;br&gt; '.$phoneValidate-&gt;getNumber();
		}
		else {
			// error with the characters or length
			echo 'There was an error with this number';
		}
	}

	//
}

?&gt;
</pre>
<p>Thats just about it. I am open for suggestions or feed back on this&nbsp;snippet.</p>
<ul>
<li> Download&nbsp;<a href="http://www.cnicollonline.com/wp-articles/05-14-09_00-00_phoneValidation/phoneValidation.zip" target="_self">source</a></li>
<li> See the&nbsp;<a href="http://www.cnicollonline.com/wp-articles/05-14-09_00-00_phoneValidation/demo/demo.php" target="_blank">demo</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/phone-validation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Java UI Part 1</title>
		<link>http://cnicollonline.com/programming/creating-a-java-ui/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://cnicollonline.com/programming/creating-a-java-ui/#comments</comments>
		<pubDate>Tue, 12 May 2009 05:47:40 +0000</pubDate>
		<dc:creator>Cosizzle</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Notes]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[School]]></category>
		<category><![CDATA[Action Event]]></category>
		<category><![CDATA[awt]]></category>
		<category><![CDATA[Java Libraries]]></category>
		<category><![CDATA[Menu Bar]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://cnicollonline.com/?p=121</guid>
		<description><![CDATA[Creating a basic Java UI can be a little overwhelming, but once you understand what&#8217;s going on there is not a lot to it. This post is about the Java User Interface and components within it. Today i&#8217;ll be&#160;covering: Creating a JFrame Configuring the&#160;window Adding a menu bar Adding&#160;mnemonics Adding key&#160;strokes Adding a popup &#8216;about&#8217;&#160;window [...]]]></description>
			<content:encoded><![CDATA[<p><!--<br />
- WORDPRESS TEMPLATE FOR CREATING OR POSTING TO MY BLOG.<br />
- COMMON TAGS TO NOTE:<br />
-<br />
<h1>MAIN&nbsp;TITLE</h1>
<p>-
<ul>
<li>LIST&nbsp;ITEM</li>
</ul>
<p>-
<ol>
<li>ORDER LIST&nbsp;ITEM</li>
</ol>
<p>--></p>
<p>Creating a basic Java UI can be a little overwhelming, but once you understand what&#8217;s going on there is not a lot to it. This post is about the Java User Interface and components within it. Today i&#8217;ll be&nbsp;covering:</p>
<ul>
<li>Creating a JFrame
<ul>
<li>Configuring the&nbsp;window</li>
</ul>
</li>
<li>Adding a menu bar
<ul>
<li>Adding&nbsp;mnemonics</li>
<li>Adding key&nbsp;strokes</li>
<li>Adding a popup &#8216;about&#8217;&nbsp;window</li>
</ul>
</li>
<p>	<!--</p>
<li>Layout Management
<ul>
<li>Creating&nbsp;tabs</li>
<li>Adding content to each&nbsp;tab</li>
</ul>
</li>
<p>    -->
</ul>
<p><span id="more-121"></span></p>
<h2>File&nbsp;Setup</h2>
<p>The following Java libraries that are used for this section&nbsp;are:</p>
<ul>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html" target="_blank">JFrame</a></li>
</ul>
<p>To start the project create the project folder with a bin and src folder. Once setup create the default package which will be used to compile and run the application. In the package create <em>MainDisplay.java</em> This will be the class which runs the&nbsp;application.</p>
<pre class="brush: java;">
/**
 * Project: cnicoll_javaUI
 * File: MainDisplay.java
 * Date: May 6, 2009
 * Time: 11:26:07 AM
 */ 

package cnicoll;

import javax.swing.JFrame;

import cnicoll.ui.MainFrame;

/**
 * @author cNicoll
 *
 */
public class MainDisplay {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
</pre>
<h2>Building the MainFrame&nbsp;(JFrame)</h2>
<p>Now that we have the basic structure, create a new extended package that will contain the ui. Within this package create a new class called MainFrame.java and have it extend the JFrame class. MainFrame is a class the will be, well, the main frame of the application. It will be a container which will hold all our application elements and&nbsp;components.</p>
<pre class="brush: java;">
/**
 * Project: cnicoll_javaUI
 * File: MainFrame.java
 * Date: May 6, 2009
 * Time: 11:46:14 AM
 */ 

package cnicoll.ui;

import javax.swing.JFrame;

/**
 * @author cNicoll
 *
 */
public class MainFrame extends JFrame {
	// Instance Variables

	/*
	 * Class Constructor
	 */
	public MainFrame() {
		// Window Name
		super(&quot;My Demo Application&quot;);
	}
}
</pre>
<p>Not much here is going&nbsp;on.</p>
<pre class="brush: java; toolbar: false;">super(&quot;My Demo Application&quot;);</pre>
<p>Gives a title to the window. Lets add some more properties to the mainframe, by adding the following below the super call. For further explanation read the Java&nbsp;comments.</p>
<pre class="brush: java;">
// call the method and change the width and height.
setSize(700, 600);
// exit the application on the window close
setDefaultCloseOperation(JFrame.EXITONCLOSE);
// disable window resizing
setResizable(false);
// centers window
setLocationRelativeTo(null);
</pre>
<p>Next go back to the <em>MainDisplay.java</em> class and create an object that will create the MainFrame when the application is run. <strong>NOTE: Also import the class ui package</strong>. Your <em>MainDisplay.java</em> should now look like&nbsp;this:</p>
<pre class="brush: java;">
/**
 * Project: cnicoll_javaUI
 * File: MainDisplay.java
 * Date: May 6, 2009
 * Time: 11:26:07 AM
 */ 

package cnicoll;

import javax.swing.JFrame;

import cnicoll.ui.MainFrame;

/**
 * @author cNicoll
 *
 */
public class MainDisplay {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame _frame = new MainFrame();
		// show the frame
		_frame.setVisible(true);

	}

}
</pre>
<p>Run the <em>MainDisplay.java</em> class and you should&nbsp;see:</p>
<div class="tutorial_image"><img src="http://farm4.static.flickr.com/3373/3507634409_3e375f0553.jpg" border="0" alt="050609_12185" width="500" height="429" /></div>
<p>Thats about it when it comes to setting up the main frame. Of course a lot more needs to be done which we will get to, but in order to create a simple&nbsp;JFrame.</p>
<ol>
<li>Set up your application working&nbsp;directory</li>
<li>Create a new package with a single class that will hold the main string&nbsp;method</li>
<li>Create a new package that will be used for your ui. In this package create a new class called&nbsp;MainFrame.ui</li>
<li>Extend the JFrame class and assign the window&nbsp;properties</li>
<li style="list-style: none">
<pre class="brush: java;">
	public MainFrame() {
		// Window Name
		super(&quot;My Demo Application&quot;);
		// call the method and change the width and height.
		setSize(700, 600);
		// exit the application on the window close
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// disable window resizing
		setResizable(false);
		// centers window
		setLocationRelativeTo(null);
	}
	</pre>
</li>
<li>Create the object within your MainDisplay&nbsp;class</li>
</ol>
<h4>At this&nbsp;point:</h4>
<ul>
<li><em>MainDisplay.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
	/**
 * Project: cnicoll_javaUI
 * File: MainDisplay.java
 * Date: May 6, 2009
 * Time: 11:26:07 AM
 */ 

package cnicoll;

import javax.swing.JFrame;

import cnicoll.ui.MainFrame;

/**
 * @author cNicoll, A00572953
 *
 */
public class MainDisplay {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame _frame = new MainFrame();
		// show the frame
		_frame.setVisible(true);

	}

}
	</pre>
</li>
<li><em>MainFrame.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
/**
 * Project: cnicoll_javaUI
 * File: MainFrame.java
 * Date: May 6, 2009
 * Time: 11:46:14 AM
 */ 

package cnicoll.ui;

import javax.swing.JFrame;

/**
 * @author cNicoll
 *
 */
public class MainFrame extends JFrame {
	// Instance Variables

	/*
	 * Class Constructor
	 */
	public MainFrame() {
		// Window Name
		super(&quot;My Demo Application&quot;);
		// call the method and change the width and height.
		setSize(700, 600);
		// exit the application on the window close
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// disable window resizing
		setResizable(false);
		// centers window
		setLocationRelativeTo(null);
	}
}
</pre>
</li>
</ul>
<h2>Adding a menu&nbsp;bar</h2>
<p>The following Java libraries that are used for this section&nbsp;are:</p>
<ul>
<li><a href="java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ActionEvent.html#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" target="_blank">ActionEvent</a></li>
<li><a href="java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ActionListener.html#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" target="_blank">ActionListener</a></li>
<li><a href="java.sun.com/j2se/1.4.2/docs/api/java/awt/event/KeyEvent.html#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed" target="_blank">KeyEvent</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFrame.html" target="_blank">JFrame</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JMenu.html" target="_blank">JMenu</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JMenuBar.html" target="_blank">JMenuBar</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JMenuItem.html" target="_blank">JMenuItem</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/KeyStroke.html" target="_blank">KeyStroke</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SwingUtilities.html" target="_blank">SwingUtilities</a></li>
<li><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/UIManager.html" target="_blank">UIManager</a></li>
</ul>
<p>A menu bar almost every application will use, and with every menu bar there are certain expectations to be met such as names, mnemonics, keystrokes and the display. To start create a new java class within your ui package and give it the name of <em>MainMenuBar.java .</em> Similar to what we did to the MainFrame we are going to extend this class out to <span style="text-decoration: line-through;">JFrame</span> JMenuBar. Your class should now look like&nbsp;this:</p>
<pre class="brush: java;">
/**
 * Project: cnicoll_javaUI
 * File: MainMenuBar.java
 * Date: May 6, 2009
 * Time: 2:52:21 PM
 */ 

package cnicoll.ui;

import javax.swing.JMenuBar;

/**
 * @author cNicoll
 *
 */
public class MainMenuBar extends JMenuBar {
	// Instance Variables

	/*
	 * Class Constructor
	 */
	public void MainMenuBar() {

	}
}
</pre>
<p>Next define the instance variables that will be used within the menu&nbsp;bar.</p>
<pre class="brush: java;">
// Instance Variables
private JMenu _file;
private JMenu _lookAndFeel;
private JMenu _help;
</pre>
<p>Also, create the menu item object within the&nbsp;constructor</p>
<pre class="brush: java;">
public void MainMenuBar() {
	// File Menu
	_file = new JMenu(&quot;File&quot;);
	add(_file);

	// Look and Feel Menu
	_lookAndFeel = new JMenu(&quot;Look &amp; Feel&quot;);
	add(_lookAndFeel);

	// Help Menu
	_help = new JMenu(&quot;Help&quot;);
	add(_help);
}
</pre>
<p>Now, that creates the menu bar, and adds menu items to it - however we have to set the menu bar to our main frame. To do&nbsp;this:</p>
<ol>
<li>Modify your instance Variables and add a frame object&nbsp;reference</li>
<li style="list-style: none">
<pre class="brush: java;">
	// Instance Variables

	// Adding the frame variable
	private final JFrame _frame;
	// What we had before
	private JMenu _file;
	private JMenu _lookAndFeel;
	private JMenu _help;
	</pre>
</li>
<li>Create a object and a value for the menu at the top of the constructor <strong>NOTE: You will need to import the JFrame&nbsp;class</strong></li>
<li style="list-style: none">
<pre class="brush: java; toolbar: false;">
	public MainMenuBar(JFrame frame) {
		this._frame = frame;
		//...
</pre>
</li>
<li>Set the menu at the bottom of the&nbsp;constructor</li>
<li style="list-style: none">
<pre class="brush: java; toolbar: false;">
		//...
		frame.setJMenuBar(this);
	}
	</pre>
</li>
<li>within the constructor of <em>MainFrame.java</em> add the following code at the end. This will create the menubar object within the MainFrame&nbsp;class</li>
<li style="list-style: none">
<pre class="brush: java; toolbar: false;">
	//...
	// add the menu bar
	menubar = new MainMenuBar(this);
	</pre>
</li>
</ol>
<p>Go ahead and compile and test. When you it runs, your MainFrame window should now look like&nbsp;this:</p>
<div class="tutorial_image"><img src="http://farm4.static.flickr.com/3655/3511351464_5a28e4c5fd.jpg?=0" border="0" alt="050609_12185" width="500" height="429" /></div>
<h4>At this&nbsp;point:</h4>
<ul>
<li><em>MainDisplay.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
/**
 * Project: cnicoll_javaUI
 * File: MainDisplay.java
 * Date: May 6, 2009
 * Time: 11:26:07 AM
 */ 

package cnicoll;

import javax.swing.JFrame;

import cnicoll.ui.MainFrame;

/**
 * @author cNicoll
 *
 */
public class MainDisplay {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame _frame = new MainFrame();
		// show the frame
		_frame.setVisible(true);

	}

}
</pre>
</li>
<li><em>MainFrame.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
/**
* Project: cnicoll_javaUI
* File: MainFrame.java
* Date: May 6, 2009
* Time: 11:46:14 AM
*/

package cnicoll.ui;

import javax.swing.JFrame;

/**
* @author cNicoll
*
*/
public class MainFrame extends JFrame {
// Instance Variables

/*
* Class Constructor
*/
public MainFrame() {
// Window Name
super(&quot;My Demo Application&quot;);
// call the method and change the width and height.
setSize(700, 600);
// exit the application on the window close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// disable window resizing
setResizable(false);
// centers window
setLocationRelativeTo(null);
}
}
</pre>
</li>
<li><em>MainMenuBar.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
/**
 * Project: cnicoll_javaUI
 * File: MainMenuBar.java
 * Date: May 6, 2009
 * Time: 2:52:21 PM
 */ 

package cnicoll.ui;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 * @author cNicoll
 *
 */
public class MainMenuBar extends JMenuBar {
	// Instance Variables
	private final JFrame _frame;
	private JMenu _file;
	private JMenu _lookAndFeel;
	private JMenu _help;

	/*
	 * Class Constructor
	 */
	public MainMenuBar(JFrame frame) {
		// Create the frame object
		this._frame = frame;

		// File Menu
		_file = new JMenu(&quot;File&quot;);
		add(_file);

		// Look and Feel Menu
		_lookAndFeel = new JMenu(&quot;Look &amp; Feel&quot;);
		add(_lookAndFeel);

		// Help Menu
		_help = new JMenu(&quot;Help&quot;);
		add(_help);

		// Set the menu bar
		frame.setJMenuBar(this);
	}

}
</pre>
</li>
</ul>
<h3>Adding menu items and key strokes to the&nbsp;menubar</h3>
<p>We have our frame, we have a menu bar within the frame, and it looks pretty snazzy, but&#8230; It doesnt do a whole lot. In this section I&#8217;ll be adding menu items to the menus as well as adding mnemonics and&nbsp;keystrokes.</p>
<p>Open <em>MainMenuBar.java</em> and add the following instance&nbsp;variables:</p>
<pre class="brush: java; toolbar: false;">
//...
private JMenuItem _exit;
private JMenuItem _about;
</pre>
<p>And within the class constructor of <em>MainMenuBar.java</em> add the following to the pre-existing&nbsp;code.</p>
<pre class="brush: java;">
// File Menu
_file = new JMenu(&quot;File&quot;);
_file.setMnemonic('F');
add(_file);
_exit = new JMenuItem(&quot;Exit&quot;, 'x');
_file.add(_exit);
</pre>
<pre class="brush: java;">
// Help Menu
_help = new JMenu(&quot;Help&quot;);
_help.setMnemonic('H');
add(_help);
_about = new JMenuItem(&quot;About&quot;, 'A');
_about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
_help.add(_about);
</pre>
<p>Go ahead and test this, you will now see drop downs within your&nbsp;menus.</p>
<p>Now for the big bit of code which will add an ActionListeners to tell &#8216;exit&#8217; to quit the program, also create a popup for the about window. Add this to <em>MainFrame.java</em>. The reason I put this within the MainFrame class is because of the MVC design&nbsp;pattern.</p>
<pre class="brush: java;">
menubar.exit.addActionListener(new ActionListener() {

	public void actionPerformed(ActionEvent e) {
		System.exit(0);
	}
});

menubar.about.addActionListener(new ActionListener() {

	public void actionPerformed(ActionEvent e) {
		JOptionPane.showMessageDialog(MainFrame.this, &quot;My own pop up window\nBy cNicoll&quot;, &quot;My Pop Up Window&quot;,
				JOptionPane.INFORMATION_MESSAGE);
	}
});
</pre>
<p>Finally i&#8217;ll add the Java GUI&#8217;s to the &#8216;Look and Feel&#8217; menu. I&#8217;m not going to into detail of how it works. Basically it Java has pre-built in GUI&#8217;s, this will display them and allow for you to change&nbsp;them.</p>
<p>First off, add the following to the look and feel&nbsp;menu.</p>
<pre class="brush: java;">
// add the look and feel GUIs
UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo info : infos) {
	makeMenuItem(info.getName(), info.getClassName());
}
</pre>
<p>Next add a new method within the same&nbsp;class.</p>
<pre class="brush: java;">
/**
 * Makes a button to change the pluggable look and feel.
 *
 * @param name
 *            the button name
 * @param plafName
 *            the name of the look and feel class
 */
private void makeMenuItem(String name, final String plafName) {
	// add button to panel

	JMenuItem item = new JMenuItem(name);
	lookAndFeel.add(item);

	// set button action
	item.addActionListener(new ActionListener() {

		public void actionPerformed(ActionEvent event) {
			// button action: switch to the new look and feel
			try {
				UIManager.setLookAndFeel(plafName);
				SwingUtilities.updateComponentTreeUI(MainMenuBar.this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});
}
</pre>
<p>After you compile and run the application you should have something looking like&nbsp;this.</p>
<div class="tutorial_image"><img src="http://farm4.static.flickr.com/3347/3511705320_57e28e1bd5.jpg?v=0" width="500" height="429" /></div>
<h4>At this&nbsp;point:</h4>
<ul>
<li><em>MainDisplay.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
/**
 * Project: cnicoll_javaUI
 * File: MainDisplay.java
 * Date: May 6, 2009
 * Time: 11:26:07 AM
 */ 

package cnicoll;

import javax.swing.JFrame;

import cnicoll.ui.MainFrame;

/**
 * @author cNicoll
 *
 */
public class MainDisplay {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame _frame = new MainFrame();
		// show the frame
		_frame.setVisible(true);

	}

}
	</pre>
</li>
<li><em>MainFrame.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
	/**
 * Project: cnicoll_javaUI
 * File: MainFrame.java
 * Date: May 6, 2009
 * Time: 11:46:14 AM
 */ 

package cnicoll.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * @author cNicoll
 *
 */
public class MainFrame extends JFrame {
	// Instance Variables
	private final MainMenuBar menubar;

	/*
	 * Class Constructor
	 */
	public MainFrame() {
		// Window Name
		super(&quot;My Demo Application&quot;);
		// call the method and change the width and height.
		setSize(700, 600);
		// exit the application on the window close
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// disable window resizing
		setResizable(false);
		// centers window
		setLocationRelativeTo(null);

		// add the menu bar
		menubar = new MainMenuBar(this);

		menubar._exit.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		menubar._about.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(MainFrame.this, &quot;My own pop up window\nBy cNicoll&quot;, &quot;My Pop Up Window&quot;,
						JOptionPane.INFORMATION_MESSAGE);
			}
		});
	}
}
</pre>
</li>
<li><em>MainMenuBar.java</em> should look&nbsp;like:</li>
<li style="list-style: none">
<pre class="brush: java; collapse: true; light: false; toolbar: true;">
	/**
 * Project: cnicoll_javaUI
 * File: MainMenuBar.java
 * Date: May 6, 2009
 * Time: 2:52:21 PM
 */ 

package cnicoll.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 * @author cNicoll
 *
 */
public class MainMenuBar extends JMenuBar {
	// Instance Variables
	private final JFrame _frame;
	private JMenu _file;
	JMenuItem _exit;
	private JMenu _lookAndFeel;
	private JMenu _help;
	JMenuItem _about;

	/*
	 * Class Constructor
	 */
	public MainMenuBar(JFrame frame) {
		// Create the frame object
		this._frame = frame;

		// File Menu
		_file = new JMenu(&quot;File&quot;);
		_file.setMnemonic('F');
		add(_file);
		_exit = new JMenuItem(&quot;Exit&quot;, 'x');
		_file.add(_exit);

		// Look and Feel Menu
		_lookAndFeel = new JMenu(&quot;Look &amp; Feel&quot;);
		add(_lookAndFeel);
		// add the look and feel GUIs
		UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
		for (UIManager.LookAndFeelInfo info : infos) {
			makeMenuItem(info.getName(), info.getClassName());
		}

		// Help Menu
		_help = new JMenu(&quot;Help&quot;);
		_help.setMnemonic('H');
		add(_help);
		_about = new JMenuItem(&quot;About&quot;, 'A');
		_about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
		_help.add(_about);

		// Set the menu bar
		frame.setJMenuBar(this);
	}

	/**
	 * Makes a button to change the pluggable look and feel.
	 *
	 * @param name
	 *            the button name
	 * @param plafName
	 *            the name of the look and feel class
	 */
	private void makeMenuItem(String name, final String plafName) {
		// add button to panel

		JMenuItem item = new JMenuItem(name);
		_lookAndFeel.add(item);

		// set button action
		item.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent event) {
				// button action: switch to the new look and feel
				try {
					UIManager.setLookAndFeel(plafName);
					SwingUtilities.updateComponentTreeUI(MainMenuBar.this);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

}
	</pre>
</li>
</ul>
<h2>Conclusion</h2>
<p>It seems like a lot but in the end its really not much, theres a lot more we can do - but all the hard work is done. In my next entry I plan on picking up from this and adding tabs to it. To download this project please <a href="http://www.cnicollonline.com/wp-articles/051209_120017_Creating_a_Java_UI/cnicoll_javaUI.zip" target="_self">click&nbsp;here</a>.</p>
<hr />
]]></content:encoded>
			<wfw:commentRss>http://cnicollonline.com/programming/creating-a-java-ui/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
