Monday, 16 July 2012

java Drawing Images


Java comes with many built-in multimedia capabilities. Java includes many classes and methods specially designed for drawing images and animation in both applications and applets. Drawing an image on applets, quiet varies, from drawing on applications.
Two programs are given showing the way of drawing images on applets and applications.

1. Images in Applets

While browsing, you come across, very often, beautiful and attractive images and animations. They can be done with applets. To draw the images, the java.awt.Graphics class comes with a method drawImage(). With the help of this method and ImageObserver at the background, images can be drawn on the applet window. Following program explains.

import java.awt.Image;
import java.awt.Graphics;
import java.applet.Applet;              
import java.net.URL;              
public class ImageWithApplet extends Applet  
{
    public void paint( Graphics g )  
    {
        URL url1 = getCodeBase();
        Image img = getImage(url1, "bird2.gif");
        g.drawImage(img, 60, 120, this);  
    }
}


HTML file to run the above applet – ImageWithApplet.html


applet code="ImageWithApplet.class"   width="350"  height="350">
</applet>





Let us see the coding.


URL url1 = getCodeBase();
Image img = getImage(url1, "bird2.gif");

Any image to be drawn should be converted into an object of Image class (like ImageIcon in case of Swing). The getImage() method of Applet class returns an object of Image, img. This method takes two parameters – the address of the image (bird2.gif) as an object of URL and the image itself as a string. Place the image, bird2.gif, in the same folder where the applet exists. getCodeBase() method of Applet class returns an object of URL (here, url1) that contains the address of the image (as image and applet exist in the same folder).


g.drawImage(img, 60, 120, this);


Graphics is an abstract class from java.awt package and contains many methods of drawing. One of such methods is drawImage() that takes four parameters. The first parameter is the image to be drawn as an object of Image class. The second and third parameters are x and y coordinates where the image is to be drawn on the applet window. The last parameter is an object of ImageObserver. The "this" argument in the above statement refers an object of ImageObserver.

Now, where from the JVM gets the reference of ImageObserver? The super class of Applet, java.awt.Component class implements the ImageObserver (observe, the hierarchy of Applet in Applets topic). From its super class, Applet gets the reference of ImageObserver.

Observe how drawImage() method is defined in Graphics class.

boolean drawImage(Image img, int x, int y, ImageObserver observer);

For the execution of this applet, run the HTML file, ImageWithApplet.html, either from appletviewer or a browser; for more information, refer Applet topic.

Programming Tip: java.awt.Image is an abstract class. Do not try to create an object. Get the Image object by calling getImage() method of Applet. getImage() method creates and returns an Image object in specific format known to the underlying OS.

2. Drawing Images in Applications (Frames)

After seeing how to draw images on applets, let us see how to draw on frames. Both come with different code. getImage() method works in applets as getImage() is a method of Applet class. To work with frames, getImage() method also exist with Toolkit class. Following program illustrates.


import java.awt.*;
public class ImageWithApplication extends Frame    
{
   public ImageWithApplication( )    
   {
      setTitle("Image on Frame");
      setSize(250, 250);    
      setVisible(true);
   }
   public void paint(Graphics g)  
   {
       Toolkit tkit = Toolkit.getDefaultToolkit( );
       Image img = tkit.getImage("bird4.gif");
       g.drawImage(img, 60, 80, this);
   }
   public static void main( String args[])   
   {
new ImageWithApplication();   // anonymous object to access the constructor 
   }
}



Toolkit tkit = Toolkit.getDefaultToolkit();
Image img = tkit.getImage("bird4.gif");

getDefaultToolkit() is a static method of abstract class, java.awt.Toolkit. This method returns an object of Toolkit. getImage() method of Toolkit class returns an object of Image class, here it is, img. img object represents bird4.gif as an object of Image class. drawImage() method is discussed in the earlier program.

class MediaTracker

In animation, multiple images are to be loaded sequentially. java.awt.MediaTracker keeps a track of image loading without loading partial images. It maintains the track with states – LOADING, ERRORED, COMPLETE and ABORTED. These states are defined as static, final and integer variables in MediaTracker class. MediaTracker does not avoid flickering. To eliminate flickering, use double-buffering or update() method (we get later).




java Multimedia


Drawing Images 
Animation and Flickering 
Multimedia – Image and Animation

Sunday, 15 July 2012

Java Event Handling






In AWT components, we came to know every component (except Panel and Label) generates events when interacted by the user like clicking over a button or pressing enter key etc. Listeners handle the events. Let us know the style (or design pattern) Java follows to handle the events.

The event handling involves four types of classes.

1. Event Sources
2. Event classes
3. Event Listeners
4. Event Adapters

1. Event Sources

Event sources are components, subclasses of java.awt.Component, capable to generate events. The event source can be a button, TextField or a Frame etc.


2. Event classes

Almost every event source generates an event and is named by some Java class. For example, the button generates ActionEvent and Checkbox generates ItemEvent. All events listed in java.awt.event package. Following list gives a few components and their listeners.


ComponentEvent it generates
Button, TextField, List, MenuActionEvent
FrameWindowEvent
Checkbox, Choice, ListItemEvent
ScrollbarAdjustmentEvent
Mouse (hardware)MouseEvent
Keyboard (hardware)KeyEvent

The events generated by hardware components (like MouseEvent and KeyEvent) are known as low-level events and the events generated by software components (like Button, List) are known as semantic events.

3. Event Listeners

The events generated by the GUI components are handled by a special group of classes known as "listeners". Listener is an interface. Every component has its own listener, say, AdjustmentListener handles the events of scrollbar Some listeners handle the events of a few components. For example, ActionListener handles the events of Button, TextField, List and Menus. Listeners are from java.awt.event package.

More description on listeners and list of listeners is available at Java AWT Listeners.

4. Event Adapters

When a listener includes many abstract methods to override, the coding becomes heavy to the programmer. For example, to close the frame, you override seven abstract methods of WindowListener, in which, infact you are using only one method. To avoid this heavy coding, the designers come with another group of classes known as "adapters". Adapters are abstract classes defined in java.awt.event package. Every listener that has more than one abstract method has got a corresponding adapter class.

More description on adapters and list of adapters is available at Java AWT Adapters.

What happens internally at a button click?

We know the events are handled by listeners and ActionListener handles the events of a button. Observe the following skeleton code.

public class ButtonDemo extends Frame implements ActionListener 
{
  public ButtonDemo()
  {
    Button btn = new Button("OK");
    btn.addActionListener(this);
    add(btn);
  }
  public void actionPerformed(ActionEvent e)
  { 
    String str = e.getActionCommand();
  }
}

The above program contains a small part of event handling code of a big program, and is used here just for the explanation of internal event handling mechanism.

A button object btn is created for which events must be linked. For this, the first step is implementing ActionListener to the class ButtonDemo. In the second step, we link or register the button btn with the ActionListener. For this addActionListener() method is Button class is used. The parameter “this” refers the ActionListener.

btn.addActionListener(this);

With the above statement, btn is linked with the ActionListener.

1. When the button btn is clicked, the button generates an event called ActionEvent. It is the nature of the button taken care by JVM.

2. This ActionEvent reaches the ActionListener because we registered the button with ActionListener earlier.

3. Now, what ActionListener does with the ActionEvent object it received?

The ActionListener simply calls actionPerformed() method and passes the ActionEvent object to the parameter as follows.

public void actionPerformed(ActionEvent e)

The parameter for the above method comes from ActionListener.

4. Finally the ActionEvent object generated by the button btn reaches the e object of ActionEvent. All this is done by JVM implicitly. For this reason, the getActionCommand() method of ActionEvent class knows the label of the button btn.

String str = e.getActionCommand();

The e represents an object of ActionEvent and the value for the e is coming from button btn. str is nothing but the label of the button OK.

Java Questions


Test Your Java Series
Theory Questions

Java AWT Components


Button
Dialog Boxes
Event Handling
Frame Closing
Layout Managers
Supporting Classes
Text Component

Java AWT Graphics

Drawing Geometrical Figures

Java Networking


InetAddress
TCP/IP Protocol
UDP Protocol
URLConnection & URL

Java Multithreading


Synchronization
Thread Groups

Java Singleton Pattern


What is Singleton?

Singleton is a design pattern. This designing style allows the programmer to create only one object of the class; even if more than one is created, it is not an error, but the code allows only one. In singleton class, there will be always only one object functioning, at a given time.

Advantages

This style is useful when only one object instantiation is enough to do with all the operations and also when the system operates more efficiently when one instance exists.

Disadvantages

If implemented unnecessarily, this pattern puts needless constraints in circumstances where actually one instance for the whole class is not needed and imposes more global environment in the code.

Implementation

The singleton object always access global data. The global values (state) must be persistent between all operations. The singleton object is created through a method call (not from directly accessing a constructor). The method returns the object, if no object already exists earlier. The method is coded in such a way if an object is created earlier, it returns the reference of the same object. This is completely transparent (unknown) to the programmer. Not to allow the programmer to create the object directly (not through method call), the constructor is declared private. Some developers declare it protected also as private does not allow the access to unit test operations.

The developer should be a little careful with singleton operations in multithreaded environment. If the code includes simultaneous processing activities, the method should be made mutually exclusive (by declaring something like synchronized). The code should take care of not to allow, the developer, accidental cloning of singleton object.

4 steps to implement in singleton creation


  • Make the constructor private not to be accessed directly
  • Create a method that returns a singleton object
  • Apply synchronization to the method to be thread-safe
  • Override clone() method for not allowing to clone the singleton object

Following program takes all the above 4 steps into consideration to create a singleton object. A Student class is taken to illustrate.


public class Student
{
  private int marks;                 // assigned with default 0
  private static Student std;        // assigned with default null

  private Student() 
  {     
     // some code if required
  }
  public static synchronized Student getMe()
  {
    if(std == null)
    {
      std = new Student();  
    }
    return std;
  }

  public Object clone() throws CloneNotSupportedException
  {
     throw new CloneNotSupportedException("Not allowed on this singleton object");
  }

  public static void main(String args[])
  {
      Student std1 = getMe();
      Student std2 = getMe();

      std1.marks = 50;
      std2.marks = 60;
      System.out.println("std1 marks when std2 changes: " + std1.marks);   // 60

      std1.marks = 70;
      System.out.println("std2 marks when std1 changes: " + std2.marks);    // 70

      System.out.println("\nstd1 hash code: " + std1.hashCode());
      System.out.println("std2 hash code: " + std2.hashCode());
  }
}




 private int marks;
     private static Student std;

In the Student class two global variables marks and std are declared of type int and Student. Reference variable std is made static simply for the reason to be accessed from the static main() method; else not required (of course, not suggestible also).

     private Student() 
     {     
       // some code if required
     }

Observe, the way of developing a singleton, declare the constructor private so that outside classes cannot create Student object directly and must go through a method call only to create. This is also another programming paradigm making "public methods and private variables".

     public static synchronized Student getMe()
     {
       if(std == null)
       {
         std = new Student();  
       }
       return std;
     }


getMe() method is declared public to allow the other classes to call the method freely and also static to have the facility of calling the method from main() without the help of an object.

First time when the method is called, as std is null, std is instantiated. Next time when called again the method, std is not again instantiated and instead the same std object, created earlier, is returned. It is checked every time in if condition. Moreover, the method is made synchronized to be thread-safe to work without any data inconsistency in multithreaded environment. For example, two different classes may call the getMe() method concurrently, these classes should be safe to get a singleton object.

     Student std1 = getMe();
     Student std2 = getMe();

Two objects std1 and std2 are obtained by calling getMe() method two times. Infact, they look two different objects; but only one as they refer the same object std. Let us prove this. Observe, when std1 changes its marks std2 is getting affected and when std2 changes std1 gets affected.

     System.out.println("\nstd1 hash code: " + std1.hashCode());
     System.out.println("std2 hash code: " + std2.hashCode());

As both std1 and std2 are same, their hashCode() method returned the same value. This is a good proof.

     public Object clone() throws CloneNotSupportedException
     {
       throw new CloneNotSupportedException("Not allowed");
     }


The clone() inherited from Object class is overridden with an exception message and this does not allow any class to clone the Student object.




Java Collections Framework


Arrays
Collections
Comparable
Comparator
General
Hashtable
Interfaces
Iterators
List
Map
Properties
Queue
Set
Stack




Supporting classes
Vector

OOPs Concepts


Abstract classes
Constructors
Inheritance
Interfaces
Overloading
Overriding
Polymorphism
Special Programs
Specifiers & Modifiers
Static keyword

Java Casting Operations


boolean to other

byte to other

char to other

double to other

float to other

int to other

long to others

short to other

Java boolean to short

The data type boolean is incompatible for converting into any other data type. That is, a boolean value cannot be converted into any other data type like char, int, double etc. The maximum permitted is one boolean can be assigned to another boolean.

Following are not permitted.

boolean b = true;
       short x = b;             // error, boolean to short

       short x = 10;
       boolean y = x;          // error, short to boolean

       boolean b = true;
       char ch = b;           // error, boolean to char

       char ch = 'A';
       boolean b =ch;         // error, char to boolean

Following is permitted (boolean assignment).



boolean b = true;
       boolean b1 = b;            // permitted
       System.out.println(b1);    // prints true


The keyword boolean is used in comparison operations.


       int x = 10;
       int y = 20;
       boolean b = (x == y);
       System.out.println(b);   // prints false


Your one stop destination for all data type conversions



byte TOshortintlongfloatdoublecharboolean
short TObyteintlongfloatdoublecharboolean
int TObyteshortlongfloatdoublecharboolean
float TObyteshortintlongdoublecharboolean
double TObyteshortintlongfloatcharboolean
char TObyteshortintlongfloatdoubleboolean
boolean TObyteshortintlongfloatdoublechar

String and data type conversions




String TO
byte
short
int
long
float
double
char
boolean
byte
short
int
long
float
double
char
boolean
TO String






Java Introduction

Java Features – Buzz Words

Java Drawbacks

Strongly typed language

Primitive Data Types

Data Types Default Values – No Garbage

Java Naming Conventions – Readability

Static Blocks – Static Initialization

Backslash in Java





Backslash in Java


Like C/C++, Java also comes with a group of characters treated as a single character and this single character also represents an ASCII value. These characters are known as escape sequences and precede (starts) with a backward slash \ like \n and \t etc. The name is so derived as they escape the normal flow or printing of characters. The \n escapes of printing in the same line and instead prints in a separate line.

The following table prints the list of escape sequences supported by Java..

Escape sequenceASCII valueMeaning
\b8backspace
\t9tab
\n10new line
\f12form feed
\r13carriage return
\"34double quote
\'39single quote
\\92backslash

Following program shows the way to print the ASCII values of escape sequences (the same procedure you followed in C/C++).

public class StringCapitalize
{
  public static void main(String args[])
  {
    System.out.println("\\b ASCII value: " + (int)'\b');
    System.out.println("\\t ASCII value: " + (int)'\t');   
    System.out.println("\\n ASCII value: " + (int)'\n');
    System.out.println("\\f ASCII value: " + (int)'\f');  
    System.out.println("\\r ASCII value: " + (int)'\r');  
    System.out.println("\\\" ASCII value: " + (int)'\"');  
    System.out.println("\\' ASCII value: " + (int)'\'');   
    System.out.println("\\\\ ASCII value: " + (int)'\\');   
  }
}



Observe the println() statements in the above code; all confusing with multiple backslashes. This is where the programmer should be careful with backslash menace.

Backslash Menace



String str1 = “hello\sir”;
System.out.println(“hello\sir”);





The above two statements do not compile and compiler raises "illegal escape character" regarding \s. Any letter suffixed to \ is treated as an escape sequence by the JVM. Now \s is checked with the standard list of escape sequences and did not find, the JVM raised an error. Suppose if you would like to have really \s in the code, instead of one \ place two \\. \\ is also an escape sequence and JVM places a single slash (instead of two slashes) in the output. The following works nice.



String str1 = “hello\\sir”;
System.out.println(“hello\\sir”);.

In writing the regular expressions also, it must be taken care of.


String str2 = str1.replaceAll(“\\d”, “OK”);


The above statement is used in "Java String replaceAll" to replace each digit in the string with OK. The \\d is a regular expression where d represents each digit in the string. It is actually \d is required; but \d raises an error. Instead, \\d is placed which is converted to \d by the JVM and evaluated. This is where the programmer should be capable of.

Regular expressions are discussed, to some extent, in way2java.com in JDK 1.4 (J2SE 4) Version. But regular expressions usage is a big subject which requires a good study. You are advised to refer a good Web site that primarily discusses regular expressions.


Java Naming Conventions – Readability


Apart grammar, Java also includes a concept known as "conventions". Conventions increase the readability of the program. Conventions are applied to identifiers. An identifier, in Java, may denote a class name, a variable name or a method name. Java follows "Hungarian notation" in naming conventions. Conventions are very simple to remember.

1. Convention for class Names

The starting letter of each word, in a class name, should be of uppercase.

Identifier acceptsConvention says
myfirsthouseMyFirstHouse
firsthouseFirstHouse
houseHouse
wishesWishes
numberformatexceptionNumberFormatException

2. Convention for Variable Names

The starting letter of the first word should be of lowercase and the starting letter of all the remaining words should be of uppercase.


Identifier acceptsConvention says
myfirsthousemyFirstHouse
firsthousefirstHouse
househouse
wisheswishes
lightgraylightGray
priceprice
xx

3. Convention for Method Names

Convention for method is simply that of variable only but followed by parenthesis.


Identifier acceptsConvention says
myfirsthouse()myFirstHouse()
firsthouse()firstHouse()
house()house()
display()display()
indexof()indexOf()
lastindexof()lastIndexOf()





There was an error in this gadget