Steps to Java Internationalization (i18n)
Java #6 I Wanna hold your hand - longer
Mouse Event Handling in Java 1.0
You are here: irt.org | Articles | Java | Java Applets #3 [ previous next ]
Published on: Saturday 4th April 1998 By: Tarique Sani
blackbug@bom4.vsnl.net.in wrote "I went through your article -The lifecycle of an applet- with a great deal of interest in the hope of finding the promised free applet" <snip>.
Though I don't recall promising any such thing I would hate to disappoint an old faithful like Black Bug! So download your free tsMenu applet now or first see what you are going to get.
In this article we will look into the details of the KTN applet, of all the applets which I have written so far the KTN applet - one of my earliest - remains my favourite despite the fact that it is not the most sophisticated looking of the lot. Here are some of the features and intricacies which make it programmatically so appealing:
Having sung praises for my own creation lets dive into the code to find out if all that is really true, if you are a newbie to Java, I suggest that you first read the previous two articles of the series Java Applets #1 and Java Applets #2, even if you are not a complete newbie it is strongly recommended that you take out your Java API reference.
The Applet was so named because it was first put up at the Kalptaru Net, a website managed by me for a friend's ISP outfit, The first chunk of code reads as follows:
// ktn.java import java.awt.*; import java.awt.image.*; import java.applet.*; import java.util.*; import java.net.*; public class ktn extends java.applet.Applet implements Runnable{ // implements Runnable because we want it to Multithread! String items[]=new String[25]; // Declare an array of [25] string objects String tags[]=new String[25]; // Same as Above String frm[]=new String[25]; // Again same as above URL page[]=new URL[25]; // Declare an array of [25] URL objects int nItems=0; int current=0; int y=0; int x=0; // Declare a bunch of integer variables Image img[]=new Image[25]; Image mirror[]=new Image[25]; AppletContext ac=null; int delay=5; Image arrow=null; int w,h; Color BLUE=new Color(0,0,0x80); // Declare other variable objects.
The applet begins with importing all the classes that will be needed, and then the variables which will be needed later in the program are declared! This business of declaring and knowing what variables you are going to use will seldom be known to you before hand, the most common method is that you keep adding the variables here as and when you feel the need, rather than scatter you variables around the program!
The init() method is is the longest piece of code in the whole applet lets take it bit by bit:
public void init(){ setLayout(null); // We don't want any in built Java layout! setBackground(BLUE); getParent().setBackground(BLUE); Graphics gr=getParent().getGraphics(); // Get the Graphics reference which will be used later for drawing. w=size().width; h=size().height/2; String welcome=getParameter("welcome"); // Get the string specified in welcome <param> gr.setColor(Color.white); gr.setFont(new Font("Helvetica",Font.PLAIN,18)); gr.drawString(welcome,10,h); // Draw the welcome string in white Helvetica 18pt gr.drawLine(0,h+5,w,h+5); ac=getAppletContext();
This part of the code is very simple - it just sets the color of the background, and draws the welcome string and a line in the applet window. The next bit is tricky!
try{ for (nItems=0;nItems<25;nItems++){ StringTokenizer st=new StringTokenizer(getParameter("item"+(nItems)),"+"); items[nItems]=st.nextToken(); page[nItems]=new URL(getDocumentBase(),st.nextToken()); tags[nItems]=st.nextToken(); if (st.hasMoreTokens()) frm[nItems]=st.nextToken(); else frm[nItems]="_top"; if (items[nItems]==null) break; } } catch (Exception e){ } delay=Integer.parseInt(getParameter("delay"))*1000;
What this seemingly complicated code is doing is nothing but getting all the parameters defined in the applet tag into the applet environment! This is achieved by creating a for loop and feeding each of the item <param> to a StringTokenizer. What the StringTokenizer does is breaks up the item parameter string in to different parts depending on the presence of '+' symbol in the string. Lets look at a sample parameter for better understanding
<param name=item0 value="Welcome+main.html+Welcome from Dr. Tarique Sani+splash">
Welcome goes into the items array main.html goes into the page array (after due conversion) Welcome from Dr. Tarique Sani goes into the tags array and the last token splash goes into the frm array - if this last thing is missing then the frm (frame) is set to _top.
This code is finally wrapped inside a try - catch clause so that any error occuring would not bring the applet down!
The last line here gets the delay parameter converts the string into an integer and then multiplies it by 1000 to get the delay in milliseconds - Java understands only milliseconds!
int xp[]=new int[3]; int yp[]=new int[3]; xp[0]=0+4;yp[0]=0+2; xp[1]=0+4;yp[1]=20+2; xp[2]=10+4;yp[2]=10+2; Polygon pp=new Polygon(xp,yp,3); arrow=createImage(25,25); Graphics g=arrow.getGraphics(); g.setColor(new Color(0x80,0x80,0x80)); g.fill3DRect(0,0,25,25,true); g.setColor(new Color(0,0xff,0)); g.fillPolygon(pp); // Creates an Image of gray filled 3D rectangle // with a green triangle (polygon) on it Font fnt=new Font("Helvetica",Font.BOLD,30); FontMetrics fm=getFontMetrics(fnt); // FontMetrics hold all the measurements of a font for (int i=0;i<nItems;i++){ // Start loop to cycle through all items! img[i]=createImage(w,h); Graphics gc=img[i].getGraphics(); //getGraphics so that we know where to draw! gc.setFont(fnt); gc.setColor(BLUE); gc.fillRect(0,0,w,h); int blue=0; char c; int p=(w-fm.stringWidth(items[i]))/2; for (int j=0;j<items[i].length();j++){ //Start loop to cycle through all characters in the item! gc.setColor(new Color(0xff-blue,0xff-blue,0xff-blue)); c=items[i].charAt(j); gc.drawString(""+c,p,h-6); p+=fm.charWidth(c); blue+=0x80/items[i].length(); //increment blue to make characters darker! } gc.setColor(Color.white); gc.drawLine(0,h-1,w,h-1); //Draw a white line!
This is the part where the visual effects begin - the first part creates an image object which contains a gray rectangle and a green triangle over it! In the next part the Strings in the items() array are converted to images with progressively darker shade of gray in each character - this gives a beautiful graduated look to the string (call it a light effect if you want to!) Please note BLUE and blue here are not actual colors but names of the variables which hold color - A hang over from the old program on the basis of which this applet was built - not a good practice but it happens when you have used the variable often enough changing names midway gives rise to wierd results and you give up trying to rename them!
int pixels[]=new int[w*h]; int mirror_pixels[]=new int[w*h]; PixelGrabber pg=new PixelGrabber(img[i],0,0,w,h,pixels,0,w); try{ pg.grabPixels(); } catch (InterruptedException e){ } for (int hh=0;hh<h;hh++) for (int ww=0;ww<w;ww++){ mirror_pixels[hh*w+ww]=processIt(pixels[(h-hh-1)*w+ww]); } mirror[i]=createImage(new MemoryImageSource(w,h,mirror_pixels,0,w)); } }// End of init() int processIt(int c){ int r,g,b; r=(c&0xff0000)>>16; g=(c&0xff00)>>8; b=c&0xff; if (r!=0){ r-=40; g-=40; b-=40; } return ((0xff000000)|(r<<16)|(g<<8)|b); }
This is the last piece of code in the init() method (Whew!) The image of string which was created in the previous part of the code is now taken and its pixels put into an array using the PixelGrabber. These pixels are then manipulated using a small routine - processIt()-to make them a bit darker than the original. After they have been darkened they are placed in another array but now at the mirror image position! Lastly the pixels in the array are used to create a new Image using the createImage() along with MemoryImageSource().
This brings us to the end of this episode of the Kalptaru Net applet in the next and concluding part we will add interactivity to the Applet!
I have been often asked what IDE or development tool is best for developing Java Applets for the Web. For most my answer is Notepad! This is specially true if you are learning Java or intend to write only Applets. If you don't believe me try and replicate ktn applet in any IDE.
However if you are developing Java applications or you are programming for an Intra Net it makes a great deal of sense to use an IDE tool - simply because the supplied components (Called Beans) do most of the work for you and these days almost every Java IDE comes with a whole gamut right from picture buttons to database connectivity tools! The Leaders in the pack include - Visual Cafe from Symantec, Visual J++ form Microsoft and the late comer but the best liked by me JBuilder from Borland.
Steps to Java Internationalization (i18n)
Java #6 I Wanna hold your hand - longer
Mouse Event Handling in Java 1.0