Monday, January 28, 2008

How to use List interface

List interface is an extension of Collection interface. List interface indicates the behavior of the collection of objects. It allows duplicate objects and one or more elements to be null.

Useful methods of the List Interface:

Method

Usage

add()

Adds an objects to the collection

clear()

Removes all objects from the collection.

contains()

Returns true if a special object is an element with in the collection.

get()

Returns the element at the specified index position in this collection.

isEmpty()

Returns true if the collection has no elements.

listIterator()

Returns a ListItertor object for the collection which may then be used to retrieve an object.

Remove()

Removes the element at the specified index position in this collection.

size()

Returns the number of elements in the collection.

In this code ListIterator is used for reading the objects of the list. It allows reading objects from the collection in both the forward and backward directions.

import java.util.*;

public class DemoList {

public static void main(String[] args) {

List ls = new LinkedList();

for(int i=1; i<=5; i++){
ls.add(new StringBuffer("Object " + i));
}

//display how many objects are in the collection
System.out.println("The collection has " + ls.size() + "objects");

//Instantiate a ListIterator
ListIterator li = ls.listIterator();
System.out.println("Forward Reading");

//Forward direction
while(li.hasNext()){
System.out.println(" " + li.next());
}

System.out.println("Backward Reading");

//backword direction
while(li.hasPrevious()){
System.out.println(" " + li.previous());
}
}

}

Output Screen:

The collection has 5objects
Forward Reading
Object 1
Object 2
Object 3
Object 4
Object 5
Backward Reading
Object 5
Object 4
Object 3
Object 2
Object 1

Tuesday, January 22, 2008

How to copy a directory from one location to another location

This Java tip demonstrates a method of copying a directory from one location to another. Copying is done from sourcedirectory to targetdirectory.


// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}

String[] children = sourceLocation.list();
for (int i=0; i) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {

InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);

// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}

Saturday, January 19, 2008

Finding Greatest Common Divisor recursively

In mathematics, the greatest common divisor (gcd), sometimes known as the greatest common factor (gcf) or highest common factor (hcf), of two non-zero integers, is the largest positive integer that divides both numbers.

The greatest common divisor of a and b is written as gcd(a, b), or sometimes simply as (a, b). For example, gcd(12, 18) = 6, gcd(−4, 14) = 2 and gcd(5, 0) = 5. Two numbers are called coprime or relatively prime if their greatest common divisor equals 1. For example, 9 and 28 are relatively prime.

The code below shows how to implement gcd function recursively.

/**
* Return the greatest common divisor
*/

public static long gcd(long a, long b) {

if (b==0)
return a;
else
return gcd(b, a % b);
}

Tuesday, January 15, 2008

Use of clone method - cloning objects

The reason for making a local copy of an object is if you’re going to modify that object and you don’t want to modify the caller’s object. If you decide that you want to make a local copy, you simply use the clone() method to perform the operation. For example, the standard library class ArrayList overrides clone(), so we can call clone() for ArrayList:
import java.util.*;

class Int {

private int i;

public Int(int ii) { i = ii; }

public void increment() { i++; }

public String toString() {
return Integer.toString(i);
}
}

public class DemoCloning {

public static void main(String[] args) {
ArrayList al = new ArrayList();

for(int i = 0; i < 10; i++ )
al.add(new Int(i));

System.out.println("al: " + al);

ArrayList al1 = (ArrayList)al.clone();

// Increment all al1's elements:
for(Iterator e = al1.iterator(); e.hasNext(); )
((Int)e.next()).increment();

// See if it changed al's elements:
System.out.println("al: " + al);
}
}

The clone() method produces an Object, which must then be recast to the proper type. This example shows how ArrayList’s clone() method does not automatically try to clone each of the objects that the ArrayList contains—the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it’s copying only the “surface” portion of an object. The actual object consists of this “surface,” plus all the objects that the references are pointing to, plus all the objects those objects are pointing to, etc. This is often referred to as the “web of objects.” Copying the entire mess is called a deep copy. You can see the effect of the shallow copy in the output, where the actions performed on al1 affect al:

al: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
al: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How to use Key Events in Swing

Sunday, January 13, 2008

How to use Mouse Events in Swing

Mouse events are generated by the following types of user interaction:

  • A mouse click
  • A mouse entering a component's area
  • A mouse leaving a component's area

Any component can generate these events, and a class must implement MouseListener interface to support them.

The following example shows how to use mouse events in Swing:

import javax.swing.*;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Dimension;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JPanel
implements MouseListener {
BlankArea blankArea;
JTextArea textArea;
final static String newline = "\n";

public MouseEventDemo() {
super(new GridBagLayout());
GridBagLayout gridbag = (GridBagLayout)getLayout();
GridBagConstraints c = new GridBagConstraints();

c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
c.weighty = 1.0;

c.insets = new Insets(1, 1, 1, 1);
blankArea = new BlankArea(new Color(0.98f, 0.97f, 0.85f));
gridbag.setConstraints(blankArea, c);
add(blankArea);

c.insets = new Insets(0, 0, 0, 0);
textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(200, 75));
gridbag.setConstraints(scrollPane, c);
add(scrollPane);

//Register for mouse events on blankArea and the panel.
blankArea.addMouseListener(this);
addMouseListener(this);

setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}

public void mousePressed(MouseEvent e) {
saySomething("Mouse pressed (# of clicks: "
+ e.getClickCount() + ")", e);
}

public void mouseReleased(MouseEvent e) {
saySomething("Mouse released (# of clicks: "
+ e.getClickCount() + ")", e);
}

public void mouseEntered(MouseEvent e) {
saySomething("Mouse entered", e);
}

public void mouseExited(MouseEvent e) {
saySomething("Mouse exited", e);
}

public void mouseClicked(MouseEvent e) {
saySomething("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}

void saySomething(String eventDescription, MouseEvent e) {
textArea.append(eventDescription + " detected on "
+ e.getComponent().getClass().getName()
+ "." + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.
JFrame frame = new JFrame("MouseEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
JComponent newContentPane = new MouseEventDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}


import javax.swing.*;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;

public class BlankArea extends JLabel {
Dimension minSize = new Dimension(100, 100);

public BlankArea(Color color) {
setBackground(color);
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.black));
}

public Dimension getMinimumSize() {
return minSize;
}

public Dimension getPreferredSize() {
return minSize;
}
}

Wednesday, January 09, 2008

How to use PixelGrabber class to acquire pixel data from an Image object

PixelGrabber class available in java.awt.image packate can be used to access pixels of an Image object. PixelGrabber class can acquire pixel data synchronously or asynchronously. It can store pixel values in a user-specified array or create a suitable array itself.

The following example shows how to use PixelGrabber class to get pixel data from an Image object.

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;

public class PixelGrabberTest {

public PixelGrabberTest() {
}

public static void processImage(String inFile, String outFile) {

Image image = Toolkit.getDefaultToolkit().getImage(inFile);

try {

PixelGrabber grabber =
new PixelGrabber(image, 0, 0, -1, -1, false);

if (grabber.grabPixels()) {
int width = grabber.getWidth();
int height = grabber.getHeight();

if (isGreyscaleImage(grabber)) {
byte[] data = (byte[]) grabber.getPixels();

// Process greyscale image ...

}
else {
int[] data = (int[]) grabber.getPixels();

// Process Color image

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

public static final boolean isGreyscaleImage(PixelGrabber pg) {
return pg.getPixels() instanceof byte[];
}

public static void main(String args[]) {

if (args.length > 1) {
processImage(args[0], args[1]);
System.exit(0);
} else {
System.err.println(
"usage: java PixelGrabberTest ");

System.exit(2);
}

}
}