Tuesday, August 14, 2007

Can I Count The Ways? Let me...

I lost my lunch writing this, so in recompense, I decided to play some games online. There were so many options. “Like the Mahjong game?” Smiled. “I speak of it all the time, right?” “Okay which now?” “Won't tell. Since you can be Harry Porter, how soon will Oz be at your doorstep?” “What's the game, Cyp?”
But before you play, the code is long, your fingers have need some getting used to the typing.Nice day.



/*
*I JUST TRIED DOING A LITTLE BINARY OPERATORS
*HERE AFTER HAVING A LOOK AT SOME OLD CALC
*MACHINE. HOPY YOU LIKE IT.
*/

package overall;

import java.io.*;
import java.util.*;
import java.lang.*;

public class Postfix {
static List stackList = new ArrayList();
static List operatorList = new ArrayList(); //ignore generics.
//the index counts to tail lof list
static int listCounter = -1;

protected static void checkInput(String keyedIn){
//check for exit character once and for all
if (keyedIn.equals("@")){
System.exit(0);
}
//not ready to exit?
//make sure first number is a number
if (listCounter == -1){ //nothing in list at all
try{
//see if we can parse the keyed in figure to int
int received = Integer.parseInt(keyedIn);
//insert first number into the list
stackList.add(received);
//increase the counter
++listCounter;
System.out.println("Key in an operator, please.");
}
catch(NumberFormatException e){
System.err.println("First number must be a number. Thanks.");
}
}
//where the keyedin number is not the first number i.e something in stack
//we expect an operator for next number
//check if an operator is already waiting for an operand
int opCheck = operatorList.size();
if (opCheck == 0) {
//no operator waiting! if operand replace it with previous.
try{
int checking = Integer.parseInt(keyedIn);
//replace first number and count is still 0
stackList.remove(0);
stackList.add(checking);
}
//if operator, what was expected
catch(NumberFormatException e){
//send to operator then
doOperation(keyedIn);
}
}
//operator waiting, waiting for a number.
//number expected
if(opCheck > 0){
try{
int checked = Integer.parseInt(keyedIn);
//if number add to list and increase count
stackList.add(checked);
++listCounter;
compResult();
}
//if not number ask for number
catch(NumberFormatException e){
System.out.println("Input a valid number please.");
}
}
}

protected static void doOperation(String ourOperator){
//whenever any character is assumed operator, check for
//validity of operator
if (ourOperator.equals("/") || ourOperator.equals("*") || ourOperator.equals("%")
|| ourOperator.equals("-") || ourOperator.equals("+")){
//perform required operation. operator valid
char calc = ourOperator.charAt(0);
//do calculation now
doCalculate(calc);
}
else {
//ask for valid operator
System.out.println("Key in a valid operator please.");
}
}

protected static void doCalculate(final char theOperator){
//store in operator list
operatorList.add(theOperator);
//if only one operand in list, wait for next input
//lock on stack size
int contains = stackList.size();
if (contains == 1){
//lock on the size
System.out.println("Insert next number for operation.");
}
else if(contains == 2){
compResult();
}
}

public static void compResult(){
//get the last two elements in the stack list
//get the head of the operator list
//do the binary operation
//output the result
//get stack list tail
int stackTail = stackList.remove(listCounter);
--listCounter;
int tailAfterLast = stackList.remove(listCounter);
--listCounter;
//get operator list head
Object opHead = operatorList.remove(0);
System.out.print(tailAfterLast + " " + opHead + " "+stackTail + " is = ");
//do the binary operation
//check what operator we're using first though
if (opHead.equals('+')){
tailAfterLast += stackTail;
System.out.println(tailAfterLast);
//keep the result in head of operand list
stackList.add(tailAfterLast);
++listCounter;
}
else if (opHead.equals('-')){
tailAfterLast -= stackTail;
System.out.println(tailAfterLast);
//keep the result in head of operand list
stackList.add(tailAfterLast);
++listCounter;
}
else if (opHead.equals('%')){
tailAfterLast %= stackTail;
System.out.println(tailAfterLast);
//keep the result in head of operand list
stackList.add(tailAfterLast);
++listCounter;
}
else if (opHead.equals('*')){
tailAfterLast *= stackTail;
System.out.println(tailAfterLast);
//keep the result in head of operand list
stackList.add(tailAfterLast);
++listCounter;
}
else if (opHead.equals('/')){
tailAfterLast /= stackTail;
System.out.println(tailAfterLast);
//keep the result in head of operand list
stackList.add(tailAfterLast);
++listCounter;
}
else {
System.out.println("We're going nowhere.");
}
}

public static void main(String[] args) throws IOException{
BufferedReader bufR = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any character. First character must be a number");
System.out.println("Enter @ to end the program.");
boolean keepOn = true;
//keep getting input until single @ entered or end of operation
while (keepOn){
//get the input from keyboard
String dInserted = bufR.readLine();
//check whether it is an operator, operand or @ sign
checkInput(dInserted);
}
}
}

What Angle Does Three Make?

Am sure you guessed the answer, a triangle. Take three edges and join them by their edges, what you get is a triangle. Measure the angle if you can. We're following up on our staircase faces to build a triangle. You just have to think in alternation. How? Twist the stairs 180 degrees to the left, leave the first one remaining and voila!, you have a triangle. That's what three makes. Now four? A Mahjong game; read my lips, there is even a Mahjong messenger online. Officially. But if you go for poker...



/*
*TRY DOING A DIAMOND AFTER THIS CODE
* :-)
*/
package overall;

public class AtTriangle {

public static void main(String[] args){
//@ character unicode representation as char
char c = '\u0040';
//declaring our array
char[][] atTriangleArray;
//we now allocate only the rows
atTriangleArray = new char[6][];
//next the columns are allocated
for (int i=0; i<atTriangleArray.length; i++){
//for the six rows there are eleven columns
atTriangleArray[i] = new char[11];
//if this is the first column assign at to the
//6th column
switch(i){
case 0: atTriangleArray[i][5] =c; break;
case 1: atTriangleArray[i][4] =c;
atTriangleArray[i][5] =c;
atTriangleArray[i][6] =c;
break;
case 2: atTriangleArray[i][3] =c;
atTriangleArray[i][4] =c;
atTriangleArray[i][5] =c;
atTriangleArray[i][6] =c;
atTriangleArray[i][7] =c;
break;
case 3: atTriangleArray[i][2] =c;
atTriangleArray[i][3] =c;
atTriangleArray[i][4] =c;
atTriangleArray[i][5] =c;
atTriangleArray[i][6] =c;
atTriangleArray[i][7] =c;
atTriangleArray[i][8] =c;
break;
case 4: atTriangleArray[i][1] =c;
atTriangleArray[i][2] =c;
atTriangleArray[i][3] =c;
atTriangleArray[i][4] =c;
atTriangleArray[i][5] =c;
atTriangleArray[i][6] =c;
atTriangleArray[i][7] =c;
atTriangleArray[i][8] =c;
atTriangleArray[i][9] =c;
break;
case 5: atTriangleArray[i][0] =c;
atTriangleArray[i][1] =c;
atTriangleArray[i][2] =c;
atTriangleArray[i][3] =c;
atTriangleArray[i][4] =c;
atTriangleArray[i][5] =c;
atTriangleArray[i][6] =c;
atTriangleArray[i][7] =c;
atTriangleArray[i][8] =c;
atTriangleArray[i][9] =c;
atTriangleArray[i][10] = c;
break;
default : break;
}
}
for(int i=0; i<atTriangleArray.length;i++){
for(int j=0; j<atTriangleArray[i].length; j++){
System.out.print(atTriangleArray[i][j]);
}
System.out.println();
}
}
}

Life is easy when you're on rails, especially when you are three: you, your girl beside you and your dog. I'd take a vacation to anywhere i'd call home. Now if you mind my talking about a home, I've been watching the prices of some real estate here. I can tell you without blinking that they are SPECIAL OFFERS and for you.

AM FEELILNG LIKE WOW!

Just finished watching the TV and a commercial was ringing in my head: Move On Up! I really didn't understand if they were to move me up or if my savings account was to move them up, so I wrote a code for steps and ladders which if you take the initiative, you're surely going on up.



/*
*we're building a staircase based on java's native handling
*of multidimensional arrays, as arrays of arrays
*
*/
package overall;

public class TFaces {

public static void main(String[] args){
char c = '\u0040';
char[][] atArray;
//declare the 2-dim array first with only the rows
//columns for each row are unallocated
atArray = new char[5][];

//now allocate columns for rows
for(int i=0; i<atArray.length; i++){
//each row has one step greater than
//its preceding one
atArray[i]= new char[i+2];
}
//initialise and print out the array
for(int i=0; i<atArray.length; i++){
for(int j=0; j<atArray[i].length; j++){
atArray[i][j] = c;
System.out.print(atArray[i][j]);
}
System.out.println();
}
}
}

If you can, pick as many images as you can find and put them faces on the staircases. You'll love the wow! effect. Picasa just popped out on my desktop. With picasa, you can make your computer images all searchable. Searchable. You don't need to think: where was that picture of I and Micheal taken in 1996 at Mimmy's matriculation? Nope. Picasa has it; straight in ya face!

Never Multi-thread Your System Clock 4

MAYBE THE FINAL SOLUTION

Threads. Threads. Threads. Do you need a real nice and cool loan for a house from your best bank? Have to check your credit score first, right? Well, for this you just have to do no checking. A trip to Hawaii or to New Zealand or to Malaysia or anywhere in the world. Anywhere in the world. Is it for free? Yes, but for your time. How? Right from the labs of google comes, Google Maps. It's just absolutely wonderful. I fell in love with google maps from the word go. Go anywhere. Let's see. Why not try the city of London?
Yeah, the final solution. Back from that travel, you can use just one thread and get as much time in any time zone that you so desire. The code below diverts off the piggy-backing threads class on these aspects: I removed the constructors for time zone threads and used a single thread in the run method. Then formatted the time instance in a single method, zoned(). Therefore, within this method, I can and you can create as many time zone instances as you like.



package overall;

import java.text.DateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

public class SingleThread implements Runnable {

public void run() {
//the limit on time
final long LIMIT = 1000*60*5;
//guard on time spent doing this shit
long timeSpent = 0;
//present time guard
Date dater = new Date();
//we'll catch an exception on this computation
try{
while(timeSpent < LIMIT){
//call the time formatter
zoned();
//sleep three second
Thread.sleep(1000*3);
//update the system time
Date now = new Date();
//compute time difference between start and now
timeSpent = now.getTime() - dater.getTime();
}
}
//catch any exception please
catch(Exception e){
e.printStackTrace();
}
}

protected void zoned(){
//an hour of time
long oneHour = 1000*60*60;
//get the date formatter
DateFormat formatter = DateFormat.getTimeInstance();
//declare the time zone. set initially to utc
SimpleTimeZone simp = new SimpleTimeZone((int)oneHour*0, "UTC");
//set the timezone of our dates to utc
formatter.setTimeZone(simp);
//print out the utc time at this moment in time
System.out.println("Time in UTC (London) is: "+ formatter.format(new Date()));
//set the time zone to hawaii time
simp.setID("HST");
simp.setRawOffset((int)oneHour*10);
formatter.setTimeZone(simp);
System.out.println("Time in HST (Hawaii) is: "+formatter.format(new Date()));
//set time zone new zealand time
simp.setID("NST"); //new zealand standard time
simp.setRawOffset(-(int)oneHour*12);
formatter.setTimeZone(simp);
System.out.println("Time in NST (Fiji) is: "+formatter.format(new Date()));
}

public static void main(String[] args){
//declare an instance of our time
SingleThread instar = new SingleThread();
//call its thread
Thread t = new Thread(instar);
//start the thread
t.start();
}
}

When I was young, we piggy-backed to get into the movie theater. This is how: A buys the ticket for the film, enters theater, the innocent one, wraps ticket on his pen, runs to the first floor of the building and throws it to B. Yeah, the ticket's already marked but the film house has a toilet that is at the outside. If B has a good tongue and can give and take shit, B can enter and so can C, and so can D, and so... The timing just has to be right. Piggy-backing and fond memories...!

Saturday, July 28, 2007

Never Multi-Thread Your System Clock 3

A FAIR ENOUGH IMPLEMENTAION.

Am sure you did read the first blog on this topic? Let me remind you a point from it: any number of men can pass through a door which is supposed to allow only one man at any time if they can all piggyback into the door, provided the height of the door is sufficient to take as much piggybackers.
I can implement piggybacking for this time zone problem by creating three separate threads for each time zone, such that the first thread calls the second and the second calls the third. You can create any number of time zone references this mind. Like the Mahjong game, you can even create four. But caution! Sshhh... read to the end first. This thread calling is best done with ThreadGroups. A ThreadGroup makes it possible that where one thread gets interrupted or a parent thread gets interrupted, all the threads die together.
Now for the code. For a challenge, write a third thread that is declared in the second thread or the Hawaii standard time thread in the code below.




import java.lang.*;
import java.util.*;
import java.text.*;

public class FairEnough implements Runnable {
String dZone = "Local";
//every thread exists in a group such that
//they all die together
ThreadGroup dGroup = new ThreadGroup("myGroup");
//the time zones am going to use, simp for UTC and
//zHst for Hawaii Standard Time.
SimpleTimeZone simp = null;
SimpleTimeZone zHst = null;
//computing this long now prevents future recursive
//computing
long oneHour = 1000*60*60;

/** Creates a new instance of FairEnough */
public FairEnough(String zoner) {
//if string is utc, run utc else if hst run hst
if (zoner == "UTC"){
this.dZone = zoner;
//set the time zone to utc
simp = new SimpleTimeZone((int)oneHour*0, dZone);
//create the utc thread in a a thread group and start it
Thread utc = new Thread(dGroup, this);
//start our thread
utc.start();
//utc object now calls the hst object
FairEnough second = new FairEnough("HST");
}else{
//this here is constructor code for hst object
this.dZone = "HST";
zHst = new SimpleTimeZone((int)oneHour*10, dZone);
//create hst thread
Thread hst = new Thread(dGroup, this);
hst.start();
}
}

//the run method defines the thread itself.
public void run() {
//LIMIT means i don't want this thread to run for
//more than five minutes
long LIMIT = 1000*60*5;
//this is the guard on five minutes limit
long timeSpent = 0;
//this is the guard on timer, reference to the
//instance in time when run started, +/- nanoseconds
Date dater = new Date();
//our thread could be interrupted, so let's put
//it in a try
try{
while(timeSpent < LIMIT ){
//create date formatter formatting only time
DateFormat formatter = DateFormat.getTimeInstance();
//specify time zone to use
if(this.dZone == "UTC"){
formatter.setTimeZone(simp);
}else if(this.dZone == "HST"){
formatter.setTimeZone(zHst);
}
//print out our time
System.out.println(this.dZone +" time is "+formatter.format(new Date()));
//sleep 3 seconds
Thread.sleep(1000*3);
//update system time
Date now = new Date();
//compute the time spent doing this stuff
timeSpent = now.getTime() - dater.getTime();
}
}
catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
//specify time zone to start with. if utc or hst.
//use upper case please!!Mine!!
FairEnough fair = new FairEnough("UTC");
}
}

Caution: I ran the code above on a 1.2 Ghz Pentium III Intel and was my puter humming all the time. Not to worry, he's just complaining to deaf ears. That goes to show you that this is not a very good candidate for implementing this concept, just a solution just made it. If you're really that bold, try getting driver magic if you're experimenting with clocks and threads first.
In my magic bag is a simple, affordable solution that you'll make use of and your puter wouldn't realise you came into its machine space. Ready for the last and final blog on this topic? I sure am.

Never Multi-thread Your System Clock 2

HOW NOT TO GO ABOUT IT.

A little on threading. A thread is like a process that is running inside another process. Imagine the wheels of your car running when the car starts. But never imagine the beautiful baby on the left could ever be yours. Now, in Java programming, when a thread wants to access or reference a variable, it has to acquire the lock on the object or variable, which we'll refer to here as its monitor. And no two threads can acquire the same lock on a monitor. Rather, if a thread wants the lock on a monitor and another thread has it, it has to wait for that owner thread to release the lock first.






I love small cars

Our clock has to be in three time zones, one in the New Zealand Standard time, another in Universal Time and the other in Hawaii Standard Time. It looks simple to just create separate threads, taking from our example in the first blog for this title. No, creating three threads for the three time zones will not necessarily run. There are issues to consider.

Issue of monitor locking. If we have say three threads, thread A, B and C and A starts executing first. Other threads have to wait for it but they have already been called to start. There is no way we should expect B and C to return the same time as A. Clocking is dynamic and time never waits for any man. The error reporting chain gets propagated indefinitely as B gets the baton and as C acquires a subsequent lock.



Fighting with your throat? It stops right here.

Issue of thread sleeping. It would seem some solution to ask A to sleep and pass the baton to B and then to C and then to receive the baton or lock later. That was what we would all assume the normal should be. But this is no solution at all because if thread A enters a sleep state, are we sure it will ever recover from one? Will it not sleep forever? Let's say, A starts sleeping, to sleep for 1 second. B begins to run and then enters a sleep that lasts for also one second. Are we not to assume that A and B will ask for the lock at the same instance? Even if they have to sleep for any second at all! Both threads will have to eventually fight for the lock. We are setting the stage for a fight on the system time or our monitor. If B wins, A ends up fighting with C. Will A win? As in life and in threading, no thread can fight for long. One would give up and throw an interrupted exception and stop executing. So, why not put a usage clause on our thread. Imagine that! We'd rather never have to implement a thread in the first place.

But we'll never give up here. There's a solution for our threading problem. I found on the bottle to your right a natural solution to a throat problem, and it's the New Zealand way. That was while googling on New Zealand. In a new way, I'll demonstrate two ways this problem can be solved.

Thursday, July 26, 2007

NEVER MULTI-THREAD YOUR SYSTEM CLOCK

THE BREEZE SECTION.


If three men have to pass through a door that can take only one, how many men can pass through at any one time?

“Hey, you? ”

“One.”


“Why one?”

That's the question, why only one? Can't they piggyback through the door, like the one in front having another on his back and another on his back and another ad infinitum, provided the height of the door can accommodate as many? Well, convention and dynamism are two ends of the same stick. The longer one stays it becomes the other.


Now before we enter the door of seriosity, I'll like to unwind with a cup of Chinese tea. I like the ginseng blend. Which do you prefer? Choose yours.


I had this question thrown to me recently: How can one implement three threads such that they reference the same time while preventing deadlock and other issues known with threads.

What would you answer? As they always say, KISS. Keep it simple, stupid. So I decided to write a simple class that displays just one time, just one thread, my system time converted to UTC time. Foremost on my mind was what the thread was going to do: simple, just update my system time, convert it to Universal Time and format it in a simple human-readable format.





import java.text.DateFormat;
import java.util.*;
import java.lang.*;

public class Availables implements Runnable {

DateFormat firstFormatter;

public void run() {
//get my present instance
Date date = new Date();
//an a simple utc time zone converter
SimpleTimeZone utcZone = new SimpleTimeZone(0, "UTC");
//i don't want this timer to run just five minutes
final long LIMIT = 1000*60*5;
//then i'll set a time guard on our time
long timeSpent = 0;
//while the thread is running, i expect to receive an
//interrupted exception. maybe from my puter
try{
//what next? until five minutes runs out
while(timeSpent < LIMIT){
//set the time zone for our time
firstFormatter = DateFormat.getTimeInstance();
firstFormatter.setTimeZone(utcZone);
//print out what the present time is
System.out.println(firstFormatter.format(new Date()));
//ask the thread to sleep for 3s seconds, to
//simulate a real timer
Thread.sleep(1000*3);
//update our thread, compute the elapsed time
Date now = new Date();
timeSpent = now.getTime()- date.getTime();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
//little checker. unecessary, but you never can tell
if (Thread.interrupted()){System.out.println("Finished.");}
}

public static void main(String[] args){
Availables newbie = new Availables();
Thread tre = new Thread(newbie);
tre.start();
}
}



Now, how about the other threads that had to show different time zones, say Hawaii standard time or New Zealand Standard Time? And to talk of Hawaii, if you had to choose between a special Home in Florida and a week in Hawaii, which would it be. I saw this lovely house, and my, did i fall in love with it. Would you still go to Hawaii?

Monday, July 23, 2007

DOES A PICTURE SAY A THOUSAND WORDS 3?

I won't bore you any longer with steps to take, you already know them. After the First and Second blog on this topic, this here is the last and am sure you'll appreciate coming here. The javax.imageio package provides a custom decoder (what I thought the CharsetDecoder class would do for me!) through the ImageIO class.

This here is the code. Before Coding, have you played some high performance games lately?





package examples;

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

public class Byter {

BufferedImage buffer;
File f;

protected void doThis(){
try{
//grab the file in a file reference, handle exception also
f = new File("amelipassport.jpg");
//use a static method read of ImageIO to buffer file
buffer = ImageIO.read(f);
//test buffer. You'll get two results, the ColorModel and Raster
//try and see
System.out.println(buffer.toString());
}
catch(IOException e){
e.printStackTrace();
System.err.println("File not found");
}
finally{
//finally call the raster for character rep.
//of the pixels in each cell. int returned by getRGB is 8 bits
for (int i=0; i<314;i++){
for(int j=0; j<274; j++){
System.out.print(buffer.getRGB(j,i)+",");
}
System.out.println();
}
}
}

public static void main(String[] args){
Byter by = new Byter();
by.doThis();
}

}

little challenge: send the output of Sysout to a “.txt” file and you'll see the table arrangement of the character representation of the colors you saw in the picture above.

A picture doesn't say a thousand words, you'll never understand them unless you know the language it was speaking in.

When the code ran, what I read from the output was that the picture has two components, a ColorModel and a Raster of image data. The results i got for the young beautiful dark african in the picture above is: This image is one of 8 bits in RGB colors, in windows style BGR color model with Red, Green and Blue of 3 bytes. There is no alpha value in the picture because this is false. The picture is set to 100% transparency and has a width of 274 pixels with a height of 314 pixels.
Try your hands on any picture of your choice and try reading what was said.

But for sure, appreciate colors, appreciate beauty and appreciate the picture even if the language seems difficult for you to understand.



DOES A PICTURE SAY A THOUSAND WORDS 2?

Faced with the task of decoding that picture of a young african girl, I said to myself, small fry. It'll be handled in a breeze. After I finished writing the first blog of this series, I went outside to the fresh air, drank some water and popped some gums into my mouth. How long should this take me? An hour, two, or three at most. Trust me, this is work just for a Gothamite.

First course of action : I'd grab the image files through a Bufferedinputstream, decode the files using the default charset decoder and maybe a decoder also of the utf-8 charset and then write the decoded data out through a BufferedWriter. That should do it. I'd get a character representation of the image data. So, I set out coding and this is what i wrote.


Standards are what we'll be living by in our codes, like engineering standards, Web standards...etc





package examples;

import java.io.*;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;

public class Tunes {

CharBuffer charBuf;
ByteBuffer byteBuf;
BufferedInputStream bin = null;
//writer wasn't called. i used Sysout to look ahead.
BufferedWriter bufWriter;
String strChar;
//default character set for my machine is windows-1252.
//tried default and also utf-8
Charset cs = Charset.defaultCharset();
byte[] toUse;
public void doFinal() throws FileNotFoundException,IOException {
try{
//create a buffered file inputstream
bin = new BufferedInputStream(new FileInputStream("amelipassport.jpg"));
//we want to use the default character encoding
//and the default byte buffer size
//we'll use a file writer on a file output stream'
bufWriter = new BufferedWriter (new FileWriter("writeout.txt"));
int c; // check on int returned by file read
//provided there are data in the file,
//keep reading your file and writing to output until
//you get to end of file
toUse = new byte[bin.available()];
while ((c =bin.read(toUse)) != -1){
byteBuf = ByteBuffer.wrap(toUse); //i have a byte buffer now
charBuf = byteBuf.asCharBuffer();
}
}
finally{
//call the charset decoder reset method
Tunes newTunes = new Tunes();
//i used a helper class, HelpDecode
Tunes.HelpDecode helpDecode = newTunes.new HelpDecode();
//follow api instructions to letter. first reset(), decode(),
//final decode(), then flush()
helpDecode.reset();
CoderResult coder = helpDecode.decode(byteBuf, charBuf,true);
//never used the buffer writer since i had to lookahead on
//what my machine was supposed to do
//decode returned malformed
//input byte sequence not legal for this character set,
//even on utf-8
System.out.println(coder.toString());
coder = helpDecode.flush(charBuf);
System.out.println(coder.toString());
System.out.println(charBuf.toString());
//close all your two streams if any is still open
if (bin != null) {bin.close();}
}
}

//helper class HelpDecode extends CharsetDecoder
private class HelpDecode extends CharsetDecoder{
protected HelpDecode(){
//let max and avg charsperbyte be similar
super(cs, 255.0f, 255.0f);
}

protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
//used underflow as a check on result
return CoderResult.UNDERFLOW;
}

}
public static void main(String[] args)
throws FileNotFoundException, IOException {
Tunes nTunes = new Tunes();
nTunes.doFinal();
}
}

From the code above you should realise that I can't decode the image file that way. It's not possible. I took a step from the code and asked myself: “what erroneous presumptions do I have about decoding this file?”

One, the “.jpg” file can be referenced by a File object.
Two, image files should be binary data.

The decoding process just can't do what I want it to do and by the way, my decoder class that was supposed to inherit from CharsetDecoder doesn't inherit any method that reads bytes and decodes them straight to char values, just as I expected.

Bad day. There goes my lunch. There must be a way.

Yes there is. I found one late at night. The java.awt.image package and the javax.imageio packages have just what I wanted. They can even decode images. Great. I had to write the third and definitive piece just for you.



Friday, July 20, 2007

DOES A PICTURE REALLY SAY A THOUSAND WORDS?

I took a look at a picture, a picture of a young beautiful dark african lady on my laptop and decided, what if i see how the computer translates this simple picture into text. What would the computer say about this lady? I had to go about it.


I delved into the Java API and was told, just read the image binary file, buffer the input stream and then write it out in another buffered output stream. Pronto. I checked the java tutorials and was told the same story. Just do that and you'll be fine. So i tried it and am giving you the result.
If you love chinese games, you really might be interested in Mahjong. There is also one for PocketPCs.




package examples;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.*;

public class Google {
BufferedInputStream bin;
BufferedOutputStream bout;

public void doingThis() throws FileNotFoundException, IOException{
try{
//create the input stream
bin = new BufferedInputStream(new
FileInputStream("amelipassport.jpg"));
//create the output stream
bout = new BufferedOutputStream(new
FileOutputStream("pix2words.txt"));
//now there's this int type that i'll use to read the
//bytes coming from the buffered input stream
int c;
//we'll keep reading the stream and writing to output
//until we each end of file, eof
while((c = bin.read()) != -1){
bout.write(c);
}

}
finally{
//at the end of everything, close all streams
if (bin != null){ bin.close();}
if (bout != null) {bout.close();}
}
}

//now this is the class loader
public static void main(String[] args) throws FileNotFoundException, IOException{
Google blogger = new Google();
blogger.doingThis();
}

}

I had the honor of asking the unholy question: What would the computer say? Now these are a few lines of my result.


ÿØÿþ WANG2ÿà JFIF  x x  ÿÛ C  
(1#%(:3=<9387@H\N@DWE78PmQW_bghg>Mqypdx\egcÿÛ C//cB8BccccccccccccccccccccccccccccccccccccccccccccccccccÿÀ :! ÿÄ    ÿÄ µ  } !1AQa"q2‘¡#B±ÁRÑð$3br‚
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡&circ
;‰Š’“”•–—˜™š¢£
¤¥¦§¨©ª²³´µ¶·¸
¹ºÂÃÄÅÆÇÈÉÊÒÓ
ÔÕÖרÙÚáâ&atild

I really don't know what the computer said. I can see WANG2 and then after...Gibber-gibber-gabber-dash? Or something like that?There must be a way to understand this gibber language. Yes, there is, i have to decode the gibberish stuff. Going back to ask the API.“Hey, API, you told me some half truth. Now, wise man, how do i translate this gibber?”

I've already written a solution. It's a breeze away.

And for those who cannot do without being mobile, here's something you might like, Mundu for Mobiles.


Tuesday, July 17, 2007

EXPLORING TWO BOOLEAN OPERATORS

Two operators that are quite similar in functionality but for which a developer has to be conscious of bugs creeping into his code are the boolean logical inclusive or, | and conditional-or, ||, operators.

The operands for both operators should be of type boolean or the boolean wrapper, Boolean. One difference between both of them is that the conditional-or || operator evaluates its operands differently and in a subtle fashion than its counterpart, the boolean logical inclusive-or | operator.

Let's illustrate this with a truth table.


































table illustrating both boolean operators
T F Result: Logical inclusive-or | operator Result: conditional-or operator ||
T T T T. Ignores right operand and proceeds to next expression.
T F T T. ignores right operand; proceeds to next expression
F T T T. evaluates right operand which is true where left operand if false and proceeds to next expression.
F F F F. evaluates right operand which is false where left operand is false. Proceeds to next expression.


This is the difference between both operators: although they give the same result for truth or falsity, operand evaluation is different. From the table, realize that where the left operand is false for a conditional-or operand, the right operand is then evaluated, else where the left operand is true, the right operand is ignored.

So what's the consequence of this effect?

Let's take a simple question: which of the options below is not robust enough to throw a null pointer exception?


Option A: if ( (myArray != null) | (num == myArray.length()) );
Option B: if ( (myArray != null) || (num == myArray.length()) );
Option C: if ( (myArray == null) | (num == myArray.length()) );
Option D: if ( (myArray == null) || (num == myArray.length()) );

Answers:

Option A: if left operand is true and right operand is true or false, the if-statement evaluates to true and the expression after the if statement is next evaluated. If left operand is false, the if-statement will always throw a null pointer exception.

Option B: if left operand is true, execution jumps to the expression following the if statement, else a null pointer exception is immediately thrown.

Option C: if left operand is true, a null pointer exception is immediately thrown because the right operand would never be evaluated. If left operand is false, if statement evaluates to true if the right operand is true, false otherwise.

Option D: if left operand is true, execution immediately jumps to the statement following the if-statement. If left operand is false, right operand is then evaluated. If right operand is true or false, no null pointer exception will ever be executed.

So which option will never throw a null pointer? You guessed right, option D.

Monday, July 16, 2007

Generating Random Numbers

Quest: a trivial exercise in generating random integers that one can class as either zero, even or odd between zero (inclusive) and eleven exclusive. After these integers, nine in all, are generated, classification is done and the result of the number of zeros, evens and odds in the total numbers generated is then printed to the screen.


Find: i”ll use an instance of a RandGenerator class to reach the above goal. Importing the class Random from the package, java.util, the following fields are declared by our RandGenerator class:



import java.util.*;

public class RandGenerator {
//the array to hold the numbers generated
private int[] boxArray = new int[9];
//declaring an instance of our random number class
private Random rand;
//counters for the integers generated
private int oddCount=0, evenCount=0, zeroCount=0;

we'll make use of two methods, a generator() that uses the Random class to generate nine integers from between zero (0) and ten (10) and then inserting the integers into an array.



//method that generates random numbers as int values
private void generator(){
rand = new Random();
//this for loop generates 9 consecutive random numbers
for (int i =0; i<9; i++){
//get a random number between 0 and 11 exclusive
//and store in an array of ints
boxArray[i] = rand.nextInt(11);
}
}

Another method, probing(), accesses the array for its int values, maps each int trivially to either a zero, even or odd class and increases the count for each class so mapped. Note that the mapping is assumed. Finally, this class prints out the numeric value of the numbers generated for each of zero, even or odd classes from accessing the array.



//method that evaluates the numeric count of the integers
//generated randomly according to a zero, even and odd class
private void probing(){
//starting from the first to the last element in the array find out
//what integer was generated
for (int i=0; i‹boxArray.length; i++){
int take = boxArray[i];
//if integer generated is zero, increase zero count
if (take == 0) {
zeroCount++;
}
//if even integer generated, increase even count
//by one
else if (take % 2 == 0){
evenCount++;
}
//otherwise odd integer generated, increase count
else {
oddCount++;
}
}
//print out the result of the count values
System.out.println("Number of odd values"+
"generated were "+ oddCount+" .");
System.out.println("Number of even values"+
"generated were "+evenCount+" .");
System.out.println("The zeros generated were" +
zeroCount+" in number.");
}

Finally, you can run this code by instantiating the class and just calling the two methods.



public static void main(String[] args){
RandGenerator random = new RandGenerator();
random.generator();
random.probing();
}

Thinking of another quest for next blog. Promise it'll be great

Monday, June 11, 2007

my pix

 

Posted by Picasa

Saturday, June 9, 2007

GRAPHICS DEBUGGING.

GRAPHICS DEBUGGING.

Debugging graphics involves the ability to observe every painting operation as it occur during the rendering of a component and all of its children. Intended for problem finding with rendering, layout and container hierarchies. i.e everything display related.

When graphics debugging is enabled, the graphics object used in painting is an instance of DebugGraphics class which extends the Graphics class. JComponent and every swing component support graphics debugging which can be turned on or off with Jcomponent's setDebugGraphicsOption( ) method. This methods takes an int parameter that details the debug options. This parameter determines how the component should display the information:

if :
1.DebugGraphics.LOG_OPTION – a text message is printed.
2.DebugGraphics.FLASH_OPTION - The display flashes several times.
3.DebugGraphics.BUFFERED_OPTION - It creates an external window that displays the operations performed on this view's offscreen buffer.
4.DebugGraphics.NON_OPTION - Debug disabled.
5.If 0 no change is issued to the debugging option.

Note that these values can be bitwise OR'd into the current value.

Let's explore the options one after the other:

1.DebugGraphices.FLASH_OPTION.

Each paint operation flashes a specified number of times, in a specified flash color, with a specified flash interval.

You set this values with the following methods from the DebugGraphcics static methods :

setFlashTime(int flashTime)
setFlashCount (int flashCount)
setFlashColor (Color flashColor)

to see the flashing as it occurs you must disable buffering like this:

RepaintManager.currentManager(null).setDoubleBuffereingEnabled(false).

After this every component's doubleBuffered properyty will henceforth be ignored.

I loved the flashing at first instance and have been flashing my computer since.

So let me drop a code for that. See how the buttons changed color.

package tests;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

//declaring an instance
static Color dColor = new Color(0, 255, 100, 125);

//the dimension
static Dimension dim = new Dimension(400, 400);

static JButton jButton1 = new JButton(" ");
static JTextArea jText;

/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);

//we'll use the instance as foreground.
jButton1.setBackground(dColor);
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();

//buffering and opaque value for painting and updating
nProp.setOpaque(true);
nProp.setDoubleBuffered(true);

//graphics debugging
nProp.setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);
DebugGraphics.setFlashColor(Color.red);
DebugGraphics.setFlashCount(5);
DebugGraphics.setFlashTime(10);
RepaintManager.currentManager(null).setDoubleBufferingEnabled(false);


//set max, min and preferred sizes
nProp.setMaximumSize(dim);
nProp.setMinimumSize(dim);
nProp.setPreferredSize(dim);

frame.setContentPane(nProp);

//let the above size stay 4ever
frame.setResizable(false);

frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.append(txt+"\n");

}

public void paintComponent(Graphics g){
super.paintComponent(g);

//counter
int c = 0;

//for use below
int w=0;
int h=0;
int d=0;

//get damaged region
Rectangle r = g.getClipBounds();
int clipx = r.x;
int clipy = r.y;
int clipw = r.width;
int cliph = r.height;

//fill only damaged region
g.setColor(Color.white);
g.fillRect(clipx, clipy, clipw, cliph);

//filled yellow circle only if bounding region is damaged
if (clipx <= 240 && clipy <= 240){
g.setColor(Color.yellow);
g.fillOval(0, 0, 240, 240);
c++;
}

//filled magenta cirlce if bounding region has been damaged
if (clipx + clipw>=160 && clipx<=400 && clipy+cliph>=160 && clipy<=400){
g.setColor(Color.magenta);
g.fillOval(160, 160, 240, 240);
c++;
}


}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

2.DebugGraphics.LOG_OPTION: each paint operation is messaged as they occur and by default are directed to standard output i.e System.out. Note that these output can be redirected with DebugGraphic's static setLogStream() method which method takes a PrintStream instance as a parameter.

we can also instance any string into the log using the debuggraphics static logStream () method.
3.DebugGraphics.BUFFERED_OPTION . This pops up a frame that gives offscreen rendering. Double-buffering must be enabbled.
4.DebugGraphics.NONE_OPTION. Basically shuts down graphics debugging by nullifying the settings.


Caveats in graphics debugging.

You'll notice that the button color changed from the default to brown due to its being blended with the flash color, red. Yeah, that's a caveat in graphics debugging.
1. Where the UI delegate of the component is null. If a component's UI delegate is null, graphics debugging will not work. The best way to go around this is if you declared a class without a UI delegate so as to define a trivial (empty) UI delegate.

2. DebugGraphics does not properly clean up after itself. A flash results in painting over of the color of the components and it does not get erased. This presents a problem because transparent rendering now becomes alpha blended with the flash color. You can hide the flash color though by giving its color an alpha value of invisible, i.e 0 or 0.0. we can sidestep this blending by making the flash time and flashcount to wait long enough between operations.

To implement the above we can rewrite the above code adding the below:


package tests;

import javax.swing.plaf.ComponentUI;
import javax.swing.*;

public class EmptyUI extends ComponentUI {

private static final EmptyUI sharedInstance = new EmptyUI();

public static ComponentUI createUI(JComponent c){
return sharedInstance;
}
}

then to the Property class we add this code as the first line in its constructor:

super.setUI(EmptyUI.createUI(this));

Friday, June 8, 2007

DEALING WITH GRAPHICS AND TEXT

DEALING WITH GRAPHICS AND TEXT

first of all know that every component owns its own graphics context, which context is defined in the Graphics class of java.awt package and has the following properties:

1.the component object on which to draw
2.a translation origin for rendering and clipping coordinates
3.the current clip
4.the current color
5.the current font
6.the current logical pixel operation function (XOR or paint)
7.the current XOR alternation color

although in AWT to paint we typically override component's paint() method, to do rendering we use the update() method for implementing our own double buffering and background filling before calling paint(), but in swing, if any component wants to take charge of its rendering, it should override the paintComponent() method and not the paint() method and should always begin the paintComponent() method with a call to super.paintComponent() thereby it acts as its own lightweight canvas.

Note before: the above is useful for simple custom components but for normal swing component, since the UI delegate is in charge of rendering, never attempt it.

Inside the paintComponent() method, we have access to the component's graphics object or its graphics context used for painting shapes and drawing lines and text. Check the graphics class for useful methods.

Some code that illustrates the above.

package tests;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

//declaring an instance
static Color dColor = new Color(0, 255, 100, 125);
static Color mainRed = new Color(255, 0, 0, 150);
static Color mainGreen = new Color(0, 255, 0, 150);
static Color mainBlue = new Color (0, 0, 255, 150);

static Font mainBIFont = new Font("Monospace", Font.BOLD| Font.ITALIC, 36);
static Font mainPFont = new Font("SansSerif", Font.PLAIN, 12);
static Font mainBFont = new Font("Serif", Font.BOLD, 24);

//the dimension
static Dimension dim = new Dimension(400, 400);

static JButton jButton1 = new JButton(" ");
static JTextArea jText;

/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);

//we'll use the instance as foreground.
jButton1.setBackground(dColor);
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();

//buffering and opaque value for painting and updating
nProp.setOpaque(true);
nProp.setDoubleBuffered(true);

//set max, min and preferred sizes
nProp.setMaximumSize(dim);
nProp.setMinimumSize(dim);
nProp.setPreferredSize(dim);

frame.setContentPane(nProp);

//let the above size stay 4ever
frame.setResizable(false);

frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.append(txt+"\n");

}

public void paintComponent(Graphics g){
super.paintComponent(g);

//fill entire component white
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());

//fills yellow circle
g.setColor(Color.yellow);
g.fillOval(0, 0, 240, 240);

//filled magenta circle
g.setColor(Color.magenta);
g.fillOval(160, 160, 240, 240);

g.setColor(Color.black);

//text is bold, italic, 36-point, "Nigeria"
g.setFont(mainBIFont);
FontMetrics fm = g.getFontMetrics();
int w = fm.stringWidth("NIGERIA");
int h = fm.getAscent();
g.drawString("NIGERIA", 120-(w/2), 120+(h/4));

//plain, 12-point, "go"
g.setFont(mainPFont);
fm = g.getFontMetrics();
w = fm.stringWidth("go");
h = fm.getAscent();
g.drawString("go", 200-(w/2), 200+(h/4));

//bold, 24-point, "SURVIVE"
g.setFont(mainBFont);
fm = g.getFontMetrics();
w = fm.stringWidth("GO");
h = fm.getAscent();
g.drawString("SURVIVE", 280-(w/2), 280+(h/4));

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

If you run the above code, it'll display: “NIGERIA go SURVIVE” in bright colors that illustrates the power of the rendering and painting properties of every graphics context for swing component. Worthy of note though is that not the totality of the area of a component is painted but for the sake of efficiency there are some so-called “dirtied” areas or damaged areas which are defined as the bounds of the clipping area which are not painted. You can get a Rectangle object showing this by calling getClipBounds() method of the Graphics class.

COLORS IN SWING

COLORS IN SWING

the color class encapsulates colors in the default sRGB color space or colors in the arbitrary color spaces identified by a ColorSpace class. Every color has an implicit alpha value of 1.0 or an explicit one provided in the constructor, which alpha values denote the color's transparency and 1.0 means totally transparent if denoted with a float range or 255 if an int range. Also alpha values of 0 or 0.0 means completely transparent color. Note that color classes do not pre-multiply alpha values.

Information on the sRGB color space is defined by the World Wide Web consortium
the overloaded constructors for color take a colorspace parameter, float or int values. Check this out in the api.

Like the font accessor methods, getXX() methods are specified for the color class but in modifying any color instance, one is usually expected to create a new one. By specifying an alpha value, we can use a color instance on a component's background to make it transparent. Note that when setting the foreground of a component the look and feel may ignore the color specified.

Our button and textareas colored with Color.

package tests;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

//declaring an instance
static Color dColor = new Color(0, 255, 100, 125);

static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);

//we'll use the instance as foreground.
jButton1.setBackground(dColor);

jText = new JTextArea(" ", 10, 20);
add(jText);
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = genv.getAvailableFontFamilyNames();
for (int i=0; i simplyText(fontNames[i]);
}
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);

//and also use it here too
nProp.setBackground(dColor);

frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.append(txt+"\n");

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

keywords: color, swing, colorspace, alpha value, sRGB, GraphicsEnvironment

FONTS

FONTS

to work with fonts, two classes are worth noting, the GraphicsEnvironment and Font classes which are both in the java.awt package.

GraphicsEnvironment: this class describes a collection of GraphicsDevices and font objects that are available to a java application on a particular platform and note that the resources might be local or remote. GraphicsDevices might be screens, printers or image buffers. Each GraphicsDevice has a number of Graphicsconfiguration objects associated with it that specifies configuration usage for different GraphicsDevices.

Font: this represents a class for rendring text in a visible way. A font provides information needed to map sequence of characters to sequence of glyphs and to render a sequence of glyphs as Graphics on component classes.

we can retrieve font related properties from a local or remote machine using the GraphicsEnvironment and font classes working together.

Here is a code that demonstrates the fonts available on my windows xp machine:

package tests;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);
jText = new JTextArea(" ", 10, 20);
add(jText);
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = genv.getAvailableFontFamilyNames();
for (int i=0; i simplyText(fontNames[i]);
}
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.append(txt+"\n");

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

Although we can use the classic getXX() accessor methods for font objects note that to set them we have to derive fonts using an overloaded deriveFont() method.

USING TIMERS WITH SWING.

USING TIMERS WITH SWING.

A timer instance can be considered as a unique thread that fires one or more action events at specified intervals. The timer class for use in GUI contexts in java is defined in the javax.swing.Timer class.

Let's write a code for creating a Timer class.

package tests;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);
jText = new JTextArea("welcome", 2, 50);
add(jText);

//start the timer
int delay = 10000; // 3 sec. delay initially and between firing

//the action listener that processes the timer event
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae){
simplyText("Don't forget me.");
}
};

//create an instance of a timer with delay and action listener
//then start timer thread
Timer tim = new Timer (delay, al);
tim.start();
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.setText(txt);

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

THE EVENT DISPATCHING THREAD

THE EVENT DISPATCHING THREAD

Listeners, as we've mentioned before, process every event and every event is in an event-dispatching thread. In the api, a FIFO queue of events is associated with this thread, an EventQueue instance, that is the system events queue and defined in the java.awt.EventQueue class. This queue is filled in a serial fashion, FIFO-like. As events are executed, this is done serially too, whether the event is a component property update or repainting .

Please ensure that all your events are within this thread and none should be dispatched outside this event dispatching thread. Also ensure that event handling code and painting codes will be executed quickly, i.e keep them simple. Otherwise, one event that takes up time could block the whole queue and your application gets frozen or locked up.

I have written a code here that makes use of the event dispatching threads on two listeners that listen for the same type of event, a mouse click.

package tests;

import java.awt.event.*;

public class FirstListener extends MouseAdapter {

public void mouseClicked(MouseEvent e){
//after this listener processes event, remove from queue
//and just add the second to make sure we did not remove
//it earlier also
Property.simplyText("the first listener at attention.");
Property.jButton1.removeMouseListener(this);
Property.jButton1.addMouseListener(new SecondListener());
}

}

import java.awt.event.*;

public class SecondListener extends MouseAdapter {

public void mouseClicked(MouseEvent e){
//after this listener processes event, remove from queue
//and just add the second to make sure we did not remove
//it earlier also
Property.simplyText("the second listener at attention.");
Property.jButton1.removeMouseListener(this);
Property.jButton1.addMouseListener(new FirstListener());
}
}

import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

EventListenerList listenerList = new EventListenerList();
FirstListener fl = new FirstListener();
SecondListener sl = new SecondListener();
MouseEvent me;

static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);

//here are the two listeners added to the event dispatching
//queue
jButton1.addMouseListener(fl);
jButton1.addMouseListener(sl);

jText = new JTextArea("welcome", 5, 50);
add(jText);
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.setText(txt);

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

EVENT LISTENER LIST.

EVENT LISTENER LIST.

The EventListenerList class is defined in the javax,swing.event package. An EventListernerList is an array of XXEvent/XXListener pairs. JComponent and each of its descendants use an EventListenerList to maintain their listeners. All default models also maintain listeners and an EventListenerList.

On adding a listener to a swing component or model, the associated event's Class instance (used to identify event type) is added to its EventListenerList array followed by the listener itself.
Since these pairs are stored in an array rather than a mutable collection, a new array is created on each addition or removal using the System.arrayCopy() methods.

When events are received, the list is walked through and events are sent to each listener with a matching type. Because the array is ordered in an XXEvent, XXListener, YYEvent, YYListener fashion, a listener corresponding to a given event type is always next in the array. This gives for very efficient event-dispatching routines.

For thread safety, the methods for adding and removing listeners from an event listener synchronises access to the array when it is manipulated.

In JComponent, the EventListenerList is a protected field called listenerList so that all subclasses inherit it and most listeners are managed through listenerList.

Here is a code where the class itself handles the event and is the sole occupant of the component's event listener list.

import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.lang.*;

public class Property extends JPanel implements ActionListener{

JButton jButton1 = new JButton(" ");
JTextField jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);

//this object is its own action listener
jButton1.addActionListener(this);

jText = new JTextField("welcome", 50);
add(jText);

}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e){
//get the action listeners associated with this object, here one
ActionListener[] al = jButton1.getActionListeners();

jText.setText("the "+al[0].getClass().toString()+" is the action listener " +
"in the list");
}

public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

EVENT HANDLING AND DISPATCHING.

EVENT HANDLING AND DISPATCHING.

Pressing a key or mouse button generates events. The type of events that swing components can generate whether in java.awt.event or javax.swing.event packages are of different types. Some event types are component specific.

Each event type is represented by an object that identifies the source of the event and other additional information about what specific kind of event it is and information about the state of the source before and after the event was generated. Sources of events are most commonly components or models but also different kinds of objects can generate events.

To receive notification of events, we need to register listeners with the target object . A listener is an implementation of any of the XXListener classes (where XX is an event type) defined in the java.awt.event, java.beans and javax.swing.event packages. There is at least one method defined in each interface that takes a corresponding XXEvent as parameter. Any class supporting XXEvents notification generally implements the XXListener interface and have support for registering those listeners through addXXListener methods and unregistering those listeners through removeXXLister methods. Most event targets allow any number of listeners to be registered with them. Also any listener instance can be registered to receive events for any number of event source. Usually classes that support XXEvents() provide protected fireXX() methods used for constructing event objects and sending them to the event handlers for processing.

The code below was repeated from an earlier one but with comments that emphasis some aspects of events handling.

import javax.swing.*;
import java.awt.event.*;

//implementing listeners that processes this event type
public class Property extends JPanel implements ActionListener{

JButton jButton1 = new JButton(" ");
JTextField jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("button1");
add(jButton1);

//registering instances of this class to receive this events
jButton1.addActionListener(this);
jText = new JTextField("welcome", 20);
add(jText);

}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e){
//event handler with associated object as parameter
jText.setText(jButton1.getMaximumSize().toString());
}

public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

Wednesday, June 6, 2007

JCOMPONENT SIZING AND POSITIONING METHODS.

JCOMPONENT SIZING AND POSITIONING METHODS.

Since JComponent extends java.awt.container, it inherits the sizing and positioning functionality of the AWT (for those familiar with AWT).

To manage a component's preferred, minimum and maximum size, the following methods are used:

the setters: setPreferred size(), setMinimumSize(), setMaximumsize().
The getters: getPreferredSize(), getMinimumSize(), getMaximumSize().

All these methods return a Dimension instance. Note that the size of components in a container is layout manager specific (the layout manager is the class responsible for laying out the components of a a container. ) The layout manager might ignore or respect sizing commands.

To assign a component both a size and a position with its parent container, we use JComponent's setBounds() method. The method takes a rectangle parameter or 4 int parameters that represent the x-coordinate, y-coordinate, width and height. Note that layout managers always have the first crack at component sizing, so setBounds() might be ignored in some cases. Use setBounds though if your component has no layout manager.

You can query a component's size using its getHeight() and getWidth() methods.

Also we can set a component's position within its container using the setLocation(int x, int y) method.

JComponent also maintains an alignment. Horizontal and vertical alignment can be specified by float values between 0.0 and 1.0. 0.5 means center, close to 0.0 means left or top and closer to 1.0 means right or bottom. The JComponent methods are : setAlignmentX(float f), setAlignmentY(float f).

JCOMPONENT PROPERTIES.

JCOMPONENT PROPERTIES.

All swing components conform to the javabeans specification. The javabeans specification will be discussed later. Among the five features a javabean is expected to support are a set of properties and associated accessor methods for them.

Property: a property is a global variable. Accessor methods, if any, of a property are of the setPropertyName(), getPropertyName(), or isPropertyName() methods.

a. Simple, bound and constrained properties.

A simple property is a property that has no event firing associated with a change in its value.

A bound property is a property from which a property change event is/are fired after it changes state. We can register propertyChangeListeners to listen for propertyChangeEvents through JComponent's addPropertyChangeListener method.

Constrained porperty is a property for which propertyChangeEvents are fired before a change in state occurs. We can register vetoableChangeListeners to listen for propertyChangeEvents through JComponent's addVetoableChangeListener method. A change can be vetoed in the event handling code of a vetoableChangeListener by throwing a propertyVetoException. Only one swing class has constrained properties, the JInternalFrame class.

PropertyChangeEvents carry three pieces of information: name of the property, old value and new values. Beans can use an instance of propertyChangeSuppport to manage the dispatching of propertyChangeEvents corresponding to each bound property to each registered listener. Also, an instance of vetoabableChangeSupport can be used to manage the sending of all propertyChangeEvents corresponding to each constrained property. There is a class in swing, swingPropertyChangeSupport in the javax.swing.events package that extends the propertyChangeSupport class and provides more efficient methods.

Code for a class that demonstrates bound properties.

import javax.swing.*;
import java.awt.event.*;

public class Property extends JPanel implements ActionListener{

JButton jButton1 = new JButton(" ");
JTextField jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("button1");
add(jButton1);
jButton1.addActionListener(this);
jText = new JTextField("welcome", 20);
add(jText);

}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e){
jText.setText(jButton1.getText());
}

public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

b. Change properties.

Change properties carry information about the source of a change. We use changeListeners to listen for changeEvents that get fired when these properties change state. ChangeEvents carry only one information, the source of the event.

c. client property
this property is implemented on a list such that for every propertyChange associated with a propertyChangeEvent, a list of propertyChangeListeners sought to notify all listeners for that event that a change has occurred.

Properties of swing components will be discussed in the course of these discussion.

HOW SWING IMPLEMENTS MVC.

HOW SWING IMPLEMENTS MVC.

Swing packages each component's view and controller into an object called a user interface (UI) delegate, that is why, while reading the online java tutorial you'll be told that swing's architecture is not really MVC but a model-delegate. Model-delegate communication is indirect, like the MVC conception therefore one UI delegate can be associated with more than one model.

The base class of all UI delegates is in the swing pluggable look and feel architecture, i.e javax.swing.plaf.ComponentUI or in brief, ComponentUI class.

Important methods of the ComponentUI class although this class is not invoked directly are:
a. createUI. This method is a static public method and it returns a ComponentUI while accepting a JComponent as its parameter. The method returns an instance of the UI delegate for the specified component. Each subclass of this class must provide a static createUI method.
b. installUI. This method configures the specified component appropriate for the look and feel. Invoked when the ComponentUI instance is being installed as the UI delegate on the specified component. This method completely configures the component for the look and feel.

Read up the above method and others in the api. UI delegate and their use in swing components will be discussed in forthcoming discussions.

In swing, there are sets of UI delegates which contains ComponentUI implementation of most swing components, and each of the sets is called a look and feel or a pluggable look and feel (PLAF). From the api, you'll realize that there are four pluggable look and feel packages, basic, metal, multiplexing and synth. Basic is the set from which every component implements

MVC ARCHITECTURE:

MVC ARCHITECTURE:

Model view controller, (MVC), is a user interface design decomposition that breaks down components into three parts: a model, a view and a controller.

In this three-way separation model, a mode l is responsible for maintaining all aspects of the component state e.g whether a button was pressed or unpressed, the character data of a text component, the opacity value of a window. A model communicates indirectly with the view and the controller i.e this communication is carried out without the model knowing its view or controller.

The view is the visual representation of the component's model or what is called the “look”. One noticeable example is the font of a character on a button or color of a label. The view receives indirect messages from the model and direct messages from the controller and is responsible for keeping its on-screen representation updated.

The controller is responsible for event management or the reaction of the component to events such as input devices such as the keyboard or mouse. The controller is the “feel” of the component, determining component actions. The controller receives direct messages from the view, and indirect messages from the model.

Let's illustrate the MVC concept: imagine a button with the state unpressed. On the model, this is the state and the view shows a button that is unpressed, idle. If a user clicks on the button, an event received by the controller, the controller translates this as a press or the button sends a direct message to the view, the view now looks “pressed” and send a message to the model to change its state to press = true.

Advantages of the MVC architecture:
1.we can customize the “look”(view) and “feel”(controller) of a component without affect the model.
2.We can customize specific parts of a component without affecting the model.
3.We can customize and replace a component's data model.

If you check the api there are various interfaces for the swing components that implement models and you will find references to the models that are implemented. In the course of the following weeks we will also be implementing this models in our classes for the swing components.