Paid for writing

In case you like my writing and would like me to write for your website, then please leave a comment to any of my blog article, mentioning your Email Id and I will reply back. Thanks

Friday, April 24, 2009

Drawing Moving Banners in Java Applet

The following source code explains how to draw a simple moving banner in java applets

Lets check out the source code first.



//MovingBanners.java
import java.awt.*;
import java.applet.*;

/*
<applet code="MovingBanners" width=600 height=600>
*/


public class MovingBanners extends Applet implements Runnable
{
String msg="ANAND";
Thread t;
boolean stop;
int x1,x2,x3,y1,y2,y3,y4,x4;

public void init()
{
setForeground(Color.red);
x1=x2=x3=x4=y1=y2=y3=y4=300;
}

public void start()
{
t=new Thread(this);
stop=false;
t.start();
}

public void run()
{
while(x1<600)
{
try
{
repaint();
Thread.sleep(500);
x1+=10;
y2+=10;
x3+=10;
y3+=10;
x4-=10;
y4-=10;

}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

public void stop()
{
t=null;
msg="";

}

public void paint(Graphics g)
{
g.drawString(msg,x1,y1);
g.drawString(msg,x2,y2);
g.drawString(msg,x3,y3);
g.drawString(msg,x4,y4);
}
}



Explanation

1. The class imports two java packages the applet.* and awt.*. This are required for the applet as a whole and the elements inside the applet.
2. Class MovingBanners extends the Applet class and implements the Runnable interface.
3. The Applet class is extended to override the functions init(), start(), stop(), destroy() and paint().
4. The moving banner will move the text "ANAND" inside the applet window.
5. The init() funtion will set the foreground color to red and will define the starting co-ordinates.
6. The start() function will will create a new Thread and will call the thread's start() function.
7. The thread's start() function will call the run() function which simply does the job of changing the co-ordinates and calling the repaint() function.
8. Although variables x1--x4 and y1--y4 are used. You will observe that variables y1 and x2 are not changing.
9. The thread will sleep for 500 milliseconds after it calls the repaint().
10. repaint() internally calls the paint() function. The paint function uses the drawString() function of Graphics class and draws the message on the screen.

Novice Code to draw in an Applet

This tutorial will explain a simple code to draw on your applet window using your mouse.

Lets check out the source code first



//DrawOn.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/*
<applet code="DrawOn" width=300 height=300>
</applet>
*/

public class DrawOn extends Applet implements MouseMotionListener
{
int x,y;

public void init()
{
addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}

public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
showStatus("You are at : " + x+ ","+y+". Click and Drag to Draw");
}

public void update(Graphics g)
{
g.drawString(".",x,y);
}
}


Explanation:

1. The DrawOn Class implements the MouseMotionListener, which as the name suggests, catches actions related to motion of your mouse.
2. Since we have implemented MouseMotionListener, we need to implement every single methods defined in MouseMotionListener interface.
3. So that means, writing code for functions, mouseMoved() and mouseDragged(). You can obviously leave the body of these functions empty or use an Adapter class so that you dont have to implement both these methods. A different tutorial on the Adapter classes later on.
4. The mouseDragged function is the most important to us now. It required an object of the MouseEvent class.
5. The getX() and getY() function of MouseEvent gets the X and Y Co-ordinate on the applet window wherein you are dragging the mouse. Now, this is the place where you intend to draw.
6. So the value of X and Y co-ordinate are taken in two variables x and y.
7. The repaint() function is called which calls the update() function.
8. The only difference between the paint() function which is generally used and update() function is that update() will refresh only the part of the window which is changing.
9. So the drawString() function of the Graphics class will paint a DOT(.) at x,y.
10. The mouseMoved() is also implemented, which again gets the x and y co-ordinates of your current mouse location and shows that in the status using the message showStatus().

A Simple Java Applet Source Code

//Sample.java
import java.awt.*;
import java.applet.*;

/*
<applet code="Sample" width=300 height=50>
</applet>
*/

public class Sample extends Applet
{
String msg;

public void init()
{
msg="Inside init() function";
}

public void start()
{
msg+= " ** Inside start() function";
}

public void paint(Graphics g)
{
msg+="**Inside paint";
g.drawString(msg,10,30);
}
}

Implementing NetworkInterface class in Java

Below is simple jave code to demonstrate the functionality of java.net.NetworkInterface class


<pre>
//NetworkInterface.impl

import java.net.NetworkInterface;
import java.net.SocketException
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Scanner;


public class NetworkInterfaceImpl
{
Scanner scanner;
Enumeration<NetworkInterface> interfaces;
ArrayList iterator;

public NetworkInterfaceImpl()
{
scanner=new Scanner(System.in);
try
{
interfaces=NetworkInterface.getNetworkInterfaces();
}
catch(SocketException se)
{
se.printStackTrace();
}

iterator=Collections.list(interfaces);

}

public static void main(String args[])
{
NetworkInterfaceImpl network=new NetworkInterfaceImpl();
network.displayInterface();
}

public void displayInterface()
{
try
{
for(int i=0;i<iterator.size();i++)
{
System.out.println("\n\n------------------------------------------------\n\n");
NetworkInterface ni=(NetworkInterface)iterator.get(i);

System.out.println("1. Display Name of Network interface: " + ni.getDisplayName());
System.out.println("2. Hardware Address of MAC: " + ni.getHardwareAddress());
System.out.println("3. Maximum Transmission Unit(MTU) of this interface: " + ni.getMTU());
System.out.println("4. Name of NetworkInterface: " + ni.getName());
if(ni.getParent()!=null)
{
System.out.println("5. Parent is : " + ni.getParent().getDisplayName());
}
else
{
System.out.println("5. No Parent Exist");
}
System.out.println("6. Is Network Interface Loop Back Interface? : " + ni.isLoopback());
System.out.println("7. Is Network Interface Point to Point Interface? : " + ni.isPointToPoint());
System.out.println("8. Is Network Interface Up and Running? : " + ni.isUp());
System.out.println("9. Is Network Interface Virtual Interface? : " + ni.isVirtual());
System.out.println("10. Does Network Interface support Multicast? : " + ni.supportsMulticast());

}
}
catch(SocketException se)
{
se.printStackTrace();
}
}

}

</pre>

Implementing the Util.Arrays class in Java

The tutorial below explains the java.util.Arrays class in JDK6

Lets check out the source code first



//UtilArraysImpl.java

import java.util.Scanner;
import java.util.Arrays;

public class UtilArraysImpl
{
Scanner scanner;
int mainArray[];
int[] resultArray;

public UtilArraysImpl()
{
scanner=new Scanner(System.in);
}

public static void main(String args[])
{
UtilArraysImpl arrays=new UtilArraysImpl();
arrays.displayMenu();
}

public void displayMenu()
{
int ch=0;

do
{
System.out.println();
System.out.println("1.Enter Array Elements");
System.out.println("2.Binary Search");
System.out.println("3.Copy Complete");
System.out.println("4.Copy Range");
System.out.println("5.Replace All");
System.out.println("6. Sort");
System.out.println("7. Exit");

System.out.println("Enter input: ");
ch=scanner.nextInt();

switch(ch)
{
case 1:
enterElements();
break;

case 2:
binarySearch();
break;

case 3:
copyComplete();
break;

case 4:
copyRange();
break;

case 5:
replaceAll();
break;

case 6:
sort();
break;

case 7:
System.exit(0);
break;

default:
System.out.println("You have entered wrong option");
}

}while(ch!=7);

}

public void enterElements()
{
System.out.println("Enter the total no. of elements in the array");
int total=scanner.nextInt();

mainArray=new int[total];

System.out.println("Enter the elements of your integer array:");
for(int i=0;i<total;i++)
{
mainArray[i]=scanner.nextInt();
}

}

public void binarySearch()
{
System.out.println("Enter the element to find");
int element=scanner.nextInt();

System.out.println("Element " + element + " is found at index " + Arrays.binarySearch(mainArray, element));


}

public void copyComplete()
{
System.out.println("Enter the length of the new array");
int length=scanner.nextInt();

resultArray=Arrays.copyOf(mainArray, length);
System.out.println("The resultant Array is : " + Arrays.toString(resultArray));
}

public void copyRange()
{
System.out.println("Enter the starting index");
int start=scanner.nextInt();

System.out.println("Enter the ending index");
int end=scanner.nextInt();

resultArray=Arrays.copyOfRange(mainArray, start, end);
System.out.println("The resultant Array is : " + Arrays.toString(resultArray));
}

public void replaceAll()
{
System.out.println("Enter the element to fill the array with");
int fill=scanner.nextInt();

Arrays.fill(mainArray, fill);
System.out.println("The resultant Array is : " + Arrays.toString(mainArray));

}

public void sort()
{
Arrays.sort(mainArray);
System.out.println("The sorted Array is : " + Arrays.toString(mainArray));
}


}

Explanation


JDK 6 has the java.util.Arrays class to ease out out working on Arrays. This class provides us functionality like sorting, copying range, copying complete, binary search etc on Arrays which are of int[], char[], float[], double[] and long[].
All the methods in Arrays class (except those inherited from Object) are static methods.

1. Binary Search
The code above uses the Arrays.binarySearch(mainArray,element), to search for 'element' inside the mainArray array. The result is the index of the matched element.

2. Copy Complete
Arrays.copyOf(mainArray,length). This function copies the mainArray elements to a new array , of length mentioned in length variable. 0 padding is done in case the length of the new array is greater thatn the original array.

3. Copy Range
Arrays.copyRange(mainArray,start,end). This functon copies range of mainArray (mentioned in start index and end index) to a new Array.

4. Replace All
Arrays.fill(mainArray,fill). This function will fill your entire Array with the value mentioned in the variable fill.

5. Sort
Arrays.sort(mainArray). This function sorts the contents of mainArray in ascending order.

6. Displaying the Array
Although not separately implemented, Arrays.toString(mainArray) is implemented inside other functions to display the resultArray.
This is again a static function which displays the array mentioned in paranthesis as an argument.

Note :
This is a simple java code which does not provide any error handling(performing what-if for elements not present during binary search etc..) and its main purpose is to illustrate the working of the java.util.Arrays class.