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.

Tuesday, April 7, 2009

Open any file using Java

This is a simple code which will explain how you can open any application on your system, using Java.
First lets take a look at the source code.



//DesktopOpenImpl.java

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/*
* Java Code to Launch any application.
*/
public class DesktopOpenImpl implements ActionListener
{
JFrame desktopFrame;
JPanel mainPanel;
JLabel pathLabel, listLabel;
JTextField pathText;
JButton goButton, openButton;
JComboBox listFilesCombo;
Desktop desktop;

public DesktopOpenImpl()
{

pathLabel=new JLabel("Path : ");
pathText=new JTextField(30);
goButton=new JButton("Go");
goButton.addActionListener(this);
listLabel=new JLabel("List : ");
listFilesCombo=new JComboBox();
openButton=new JButton("Open");
openButton.addActionListener(this);

mainPanel=new JPanel();
mainPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

mainPanel.add(pathLabel);
mainPanel.add(pathText);
mainPanel.add(goButton);
mainPanel.add(listLabel);
mainPanel.add(listFilesCombo);
mainPanel.add(openButton);

desktopFrame=new JFrame("Application Opener");
desktopFrame.setLayout(new BorderLayout());

desktopFrame.add(mainPanel,BorderLayout.NORTH);
desktopFrame.setVisible(true);
desktopFrame.pack();

}

public static void main(String args[])
{
new DesktopOpenImpl();
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==goButton)
{
if(Desktop.isDesktopSupported()==false)
{
JOptionPane.showConfirmDialog(null,"Desktop not supported","Error",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE);
desktopFrame.dispose();
}

desktop=Desktop.getDesktop();

File root=new File(pathText.getText());
File listFiles[]=root.listFiles();

for(File file : listFiles)
{
listFilesCombo.addItem(file);

}

desktopFrame.pack();

}

else if(ae.getSource()==openButton)
{
if(!desktop.isSupported(Desktop.Action.OPEN))
{
JOptionPane.showConfirmDialog(null,"Application Type Not Supported","Error",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE);
desktopFrame.dispose();
}

try
{
desktop.open(new File(listFilesCombo.getSelectedItem().toString()));
}
catch(IOException e)
{
e.printStackTrace();
}

}
}
}



Explanation

The code uses the Desktop classes defined in java.awt package to open the file using the native OS' application opener.
This means that in order to open a .pdf file you need to have a PDF reader installed in your system or in order to open a .doc file
you need to have MS Word or any such software installed in your system.
Desktop class doesnt try to reinvent the wheel, it simply checks what the default application is for the file, you selected and opens it accordingly.

The GUI of the code has a TextField wherein you can enter the directory where you want to search for a file.
On click of the Go Button, the code first checks whether the Desktop is supported on your machine. In case its not then the code displays an error message and closes down.
In case Desktop is supported on your system then the contents of the textfield are taken and passed as input in the constructor,for the object of File class.
The root is the object of the File class and root.listFiles() lists all the files and directories that are present in the directory mentioned by root.
The combo box is populated with the list of files/directories which we got from the root.listFiles().

Now you can select any of the file from here and click on Open button. In case you select another directory then its opened in the explorer (Windows).
In case you select a file then it checks for the default application for that and opens the file in that.
The desktop.open() does that task.

Thursday, April 2, 2009

Using File::Find in Perl

This tutorial will explain the usage of File::Find Perl Module

The source code is as follows :

#!c:\perl\bin\

use File::Find;

@directories_to_search=("D:/");
find(\&wanted,@directories_to_search);

sub wanted
{

#print "Looking in $File::Find::dir.....\n";
if($_ =~ /\.pl$/)
#if($_ =~ /^find.*/)
{
print "Found : $_ in $File::Find::dir\n";
}
}



Explanation

The File::Find can be used in your code by writing the 'use' statement.
The use statement will ensure that you can use the functions defined under File::Find.
Now, the find() function requires the list of directories where you want it to search.
I have entered D:\ as the only directory (drive in this case) as the location where I want to search. Multiple names can be separated with a comma.

The find() function calls the wanted() during each of its traversal. What find() basically does is a Depth First Search over the list of directories which have been mentioned earlier.
The wanted() is called for every file found within that directory.

Now, wanted() function is where you can filter out the type of file you want to Find.
What I am looking for over here is all perl files. So what I have done is written a regular expression of this form -- /\.pl$/
This regular expression searches if the file which is being traversed ends with .pl
If it ends with .pl then it prints the file name and the directory name where it is located.
This is where you come across three inbuilt variables
1. $File::Find::dir -- gives the name of the current directory which is being traversed.
2. $_ -- gives the file name only which is currently being traversed.
4. $File::Find::name -- this is combination of $File::Find::dir and $_ thereby giving the full path name for the file.

So there you go inside the if() I am checking whether $_ matches the regular expression for .pl and if it matches then I am printing it.
This regular expression can vary, like for instance the regular expression which is in comment. /^find.*/
This regular expression will search for all files beginning with the name 'find'. This is like doing 'dir find*' on windows command line or 'ls find*' on Unix.