Java Unit 5
Java Unit 5
Prepared By:
Milan Vachhani
Assistant Professor, MCA Department,
B. H. Gardi College of Engineering and Technology, Rajkot
M 9898626213
milan.vachhani@gmail.com
http://milanvachhani.blogspot.com
&
Research Scholar, Department of Computer Science,
Saurashtra University, Rajkot
Unit 5
Java Applet
An applet is a special kind of java program that is designed to be transmitted over the
internet and automatically executed by a java-compatible web browser.
Furthermore, an applet is downloaded on demand, just like an image, sound file, or video
clip.
The important difference is that an applet is an intelligent program, not just an animation or
media file.
In other words, an applet is a program that can react to user input and dynamically changenot just run the same animation or sound over and over.
The Applet class is contained in the java.applet package. Applet contains several methods
that give you detailed control over the execution of your applet.
Java.applet also defines 3 interfaces: AppletContext, AudioClip and AppletStub.
All applets are subclasses of Applet. Thus, all applets must import java.applet. Applet must
also import java.awt (abstract window toolkit). Since all applets run in a window, it is
necessary to include support for that window.
Applets are not executed by the console based java run-time interpreter. Rather they are
executed by either a web browser or an applet viewer called appletviewer, provided by the
JDK.
Once an applet has been compiled, it is included in an HTML file using APPLET tag. The
applet will be executed by a java-enabled web-browser when it encounters the APPLET tag
within the HTML file.
To view and test an applet more conveniently, simple include a comment at the head of your
java source code file that contains the APPLET tag. This way, your code is documented with
the necessary HTML statements needed by your applet and you can test the compiled applet
by starting the applet viewer with your java source code file specified as the target.
[1]
Applet code uses the services of two classes, Applet and Graphics from the java class library.
The Applet class which is contained in the java.applet package provides life and behaviour to
the applet through its methods such as init(), start(), and paint(). Unlike with applications
where java calls the main() method directly to initiate the execution of the program, when
an applet is loaded, java automatically calls a series of Applet class methods form starting,
running and stopping the applet code. The Applet class therefore maintains the lifecycle of
an applet.
The paint() method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics, or sound. The paint() method,
which requires a Graphics object as an argument, is defined as follows:
Public void paint(Graphics g)
This requires that the applet code imports the java.awt package that contains the Graphics
class. All output operations of an applet are performed using the methods defined in the
Graphics class.
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="FirstApplet" width=200 height=200>
</applet>
*/
public class FirstApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("This is my first applet.",20,100);
}
}
[2]
Paint() is responsible for generating the output of the applet. It accepts a Graphics object as
its one argument. It is automatically invoked whenever the applet needs to be displayed.
The actual output of the string is done by calling the drawString() method of the Graphics
object. x,y coordinate at which to begin the string.
Applet viewer executes an applet by using the HTML source code. Width and height
attributes of the applet tag define the dimensions of the applet display area.
Applet may also be executed by a web browser.
import java.applet.Applet;
import java.awt.Graphics;
public class SecondApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("This is my 2nd applet.",20,100);
}
}
Javac SecondApplet.java
<html>
<body>
<applet code="SecondApplet.java" width=200 height=200>
</applet>
</body>
</html>
SecondApplet.html
On browser run the file SecondApplet.html
(1)
(2)
(3)
(4)
Every java applet inherits a set of default behaviors from the Applet class. As a result, when
an applet is loaded, it undergoes a series of changes in its state as shown in fig. The applet
states include:
Born and initialization state
Running state
Idle state
Dead or Destroyed state
Initialization state
Applet enters the initialization state when it is first loaded. This is achieved by calling the
init() method of Applet class. The applet is born. At this stage we may do the following if
required:
[3]
[4]
Display state
Applet moves to the display state whenever it has to perform some output operations on
the screen. This happens immediately after the applet enters into the running state. The
paint() method is called to accomplish this task. Almost every applet will have a paint()
method. Like other methods in the life cycle, the default version of paint() method does
absolutely nothing. We must therefore override this method if we want anything to be
displayed on the screen.
public void paint( Graphics g)
{
Display statement;
}
It is to be noted that the display state is not considered as a part of the applets life cycle. In
fact, the paint() method is defined in the Applet class. It is inherited form the component
class, a super class of Applet.
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code="AppletLifeCycle" width=300 height=50>
</applet>
*/
public class AppletLifeCycle extends Applet
{
String str="";
public void init()
{
str+="init";
}
public void start()
{
str+="start";
}
public void stop()
{
str+="stop";
}
public void destroy()
{
System.out.println("destroy");
}
public void paint(Graphics g)
{
g.drawString(str,10,25);
}
}
[5]
Applet class
An applet is a small program that is intended not to be run on its own, but rather to be
embedded inside another application.
The Applet class must be the superclass of any applet that is to be embedded in a Web page
or viewed by the Java Applet Viewer. The Applet class provides a standard interface between
applets and their environment.
Method
Description
void destroy()
AppletContext getAppletContext()
URL getCodeBase()
URL getDocumentBase()
void init()
void start()
void stop()
Example:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code="BackgroundForeground" width=300 height=100>
[6]
</applet>
*/
public class BackgroundForeground extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.yellow);
setForeground(Color.blue);
g.drawLine(0,0,200,200);
g.fillRect(100,40,50,50);
}
}
The AppletContext class
The java.applet.AppletContext interface defines methods that allow an applet to interact
with the context (or environment) in which it is executing. This context is provided by either
a tool such as the appletviewer or a web browser.
Methods defined by this interface are:
Method
Description
Enumeration getApplets()
The firstform of showDocument() causes the web browser to retrieve and display the web
page identified by url. The second form of showDocument() allows you to specify where this
web page is displayed. The argument target may be _self(show in current frame),
_parent(show in parent frame), _top(show in top frame), and _blank (show in a new
browser window). It may also equal the name of a frame.
Many browsers allow you to divide their display area into frames. These are rectangular
regions that can independently display different URLs. A web page can use the <frameset>
tag to define how its display areas are to be divided into frames. A simple example of this
technique is shown in the following listing. The display is divided into two columns. The left
and right columns are 25 percent and 75 percent of the browser window, respectively.
[7]
<frameset cols=25%,75%>
<frame name=left src=left.html>
<frame name=right src=right.html>
</frameset>
Framesets provide additional functionality. For example, you can specify a fixed width in
pixels for a frameset or define nested framesets. Consult other texts for more information.
The AppletContext interface is implemented by the applet viewer. However, these methods
do not have the same functionality as you would find in a web browser environment. For
example, if you use the showDocument() method in an applet and then execute that applet
with the applet viewer, you will find that this method has no effect.
import java.applet.*;
import java.awt.*;
import java.net.*;
/*
<applet code="ShowDocument" width=200 height=50>
</applet>
*/
public class ShowDocument extends Applet
{
public void init()
{
AppletContext ac=getAppletContext();
try
{
URL url=new URL("http://www.osborne.com");
ac.showDocument(url,"frame2");
}
catch(Exception e)
{
showStatus("Exception:"+e);
}
}
public void paint(Graphics g)
{
g.drawString("show document applet",10,25);
}
}
Graphics Class
[8]
A Graphics object encapsulates a set of methods that can perform graphics output.
Specifically, it allows you to draw lines, ovals, rectangles, strings, images, characters, and
arcs.
Methods of Graphics class are:
Method
Description
[9]
Color getColor()
Font getFont()
FontMetrics
getFontMetrics()
Example:
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="DrawShapes" width=400 height=400>
</applet>
*/
public class DrawShapes extends Applet
{
public void paint(Graphics g)
{
g.drawArc(20,20,160,160,0,135);
g.drawOval(50,50,60,30);
g.drawString("All shapes",10,15);
g.fillRect(100,100,70,40);
}
}
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="DrawPolygon" width=400 height=400>
</applet>
*/
public class DrawPolygon extends Applet
{
public void paint(Graphics g)
{
int n=5;
int x[]=new int[n];
int y[]=new int[n];
x[0]=10;
y[0]=100;
x[1]=60;
y[1]=10;
x[2]=70;
[10]
y[2]=140;
x[3]=140;
y[3]=90;
x[4]=190;
y[4]=10;
g.drawPolygon(x,y,n);
}
}
Following are the applications, created by applet
[11]
[12]
[13]
[14]
Component
Component is the superclass of most of the displayable classes defined within the AWT.
Note: it is abstract.
MenuComponent is another class which is similar to Component except it is the superclass
for all GUI items which can be displayed within a drop-down menu.
The Component class defines data and methods which are relevant to all Components
Following are the important methods, practiced very often, of Component class that can be
used by all the sub classes (components).
1. setEnabled(boolean): The parameter false makes the component disabled so that it
does not respond to user interactions (say, clicks).
2. setBounds(): Using this method, the programmer can give his own size to the
component in terms of width and height and also the location where he can place the
component in the container. This method is not used often as the programmer prefers
to place the component in the container using layout managers.
3. getWidth(): The programmer can obtain the width of the component.
4. getHeight(): The programmer can obtain the height of the component.
5. paint(): Used very extensively to draw graphics. This method is called implicitly when the
frame is created or resized.
6. repaint(): Used by the programmer to call the paint() method explicitly anywhere in the
program.
7. setBackground(): Used to give a background color to a component.
8. setForeground(): Used to give a foreground color to a component.
9. setFont(): Used to give a font to a component to display the text.
10. getSize(): Returns the size of the component.
11. setSize(): Used to give the size to the component.
12. update(): The is method is called implicitly by the repaint(). A call to this method clears
the earlier drawings existing on the container.
Container
Container is a subclass of Component. (ie. All containers are themselves, Components)
Containers contain components
For a component to be placed on the screen, it must be placed within a Container
The Container class defined all the data and methods necessary for managing groups of
Components
add
getComponent
getMaximumSize
getMinimumSize
getPreferredSize
remove
removeAll
[15]
Panels
When writing a GUI application, the GUI portion can become quite complex.
To manage the complexity, GUIs are broken down into groups of components. Each group
generally provides a unit of functionality.
A Panel is a rectangular Container whose sole purpose is to hold and manage components
within a GUI.
Panel aPanel = new Panel();
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Cancel"));
Frame aFrame = new Frame("Button Test");
aFrame.setSize(100,100);
aFrame.setLocation(10,10);
aFrame.add(aPanel);
[16]
}
}
class MyWindowAdapter extends WindowAdapter
{
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame)
{
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we)
{
sampleFrame.setVisible(false); //System.exit(0);
}
}
// Create frame window.
public class AppletFrame extends Applet
{
Frame f;
public void init()
{
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start()
{
f.setVisible(true);
}
public void stop()
{
f.setVisible(false);
}
public void paint(Graphics g)
{
g.drawString("This is in applet window", 10, 20);
}
}
[17]
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
// Create frame window.
class MyFrame extends Frame
{
public MyFrame()
{
addWindowListener(new MyWindowAdapter());
setSize(250, 250);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("This is a Frame", 50, 50);
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
public class AppletFrame
{
public static void main(String args[])
{
MyFrame a = new MyFrame();
a.setTitle("Frame");
}
}
What is Swing and MVC? And Differentiate between AWT and Swing.
Swing was developed to provide a more sophisticated set of GUI components than the
earlier Abstract Window Toolkit (AWT).
Swing is a principal GUI toolkit for the Java programming language. It is a part of the JFC
(Java Foundation Classes), which is an API for providing a graphical user interface for Java
programs. It is completely written in Java.
[18]
Using Colors
The java.awt.Color class is used to work with colors. Each instance of this class represents a
particular color. With the help of this class we can draw colored strings, lines, and shapes in
an applet. It is possible to fill a shape such as an oval or rectangle with a color. We can also
set the background and foreground colors of an applet.
This class has following constructors:
Color( int red, int green, int blue)
Color( int rgb)
Color( float r, float g, float b)
Color c = new Color(255, 255, 240); this.setBackground(c);
Here, red, green, and blue are int values that range between 0 and 255, inclusive. The
argument rgb contains an encoding of a color in which the red, green, and blue components
are specified in bits 23 to 16, 15 to 8 and 7 to 0, respectively. Finally, r,g, and b are float
values that range between 0.0 and 1.0f inclusive.
The Color class also defines several constants that represent specific colors. These are black,
blue, cyan, darkGray, gray, green, lightGray, magenta, orange pink, red, white, and yellow.
Table shows some of the methods defined by Color class:
[19]
Method
Description
Color brighter()
Color darker()
Int getBlue()
Int getGreen()
Int getRGB()
Int getRed()
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code="BlueString" width=300 height=100>
</applet>
*/
public class BlueString extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawString("Blue string",100,50);
}
}
[20]
import java.applet.Applet;
import java.awt.*;
/*
<applet code="ColorBars" width=300 height=300>
</applet>
*/
public class ColorBars extends Applet
{
Color colors[]={Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green,
Color.lightGray,Color.magenta, Color.orange, Color.pink, Color.red,
Color.white, Color.yellow};
public void paint(Graphics g)
{
int bar=300/colors.length;
for(int i=0;i<colors.length;i++)
{
g.setColor(colors[i]);
g.fillRect(i*bar,0,(i+1)*bar,300);
}
}
}
import java.applet.Applet;
import java.awt.*;
/*
<applet code="ColorTriangle" width=400 height=300>
</applet>
*/
public class ColorTriangle extends Applet
{
public void paint(Graphics g)
{
int n=3;
int xdata[]=new int[n];
int ydata[]=new int[n];
xdata[0]=50;
ydata[0]=150;
xdata[1]=200;
ydata[1]=50;
xdata[2]=350;
ydata[2]=150;
int rgb=Color.HSBtoRGB(2.3f,1.2f,1.0f);
g.setColor(new Color(rgb));
g.fillPolygon(xdata,ydata,n);
}
}
[21]
FlowLayout
FlowLayout is the default layout manager.
FlowLayout implements a simple layout style, which is similar to how words flow in a text
editor. Components are laid out from the upper-left corner, left to right and top to bottom.
When no more components fit on a line, the next one appears on the next line. A small
space is left between each component, above and below, as well as left and right. Here are
the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels
of space between each component. The second form lets you specify how each line is
aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively. The third form allows
you to specify the horizontal and vertical space left between components in horz and vert,
respectively.
BorderLayout
The BorderLayout class implements a common layout style for top-level windows. It has
four narrow, fixed-width components at the edges and one large area in the center.
The four sides are referred to as north, south, east, and west. The middle area is called the
center. Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
GridLayout
GridLayout laysout components in a two-dimensional grid.
[22]
When you instantiate a GridLayout, you define the number of rows and columns. The
constructors supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid layout
with the specified number of rows and columns. The third form allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimited-length columns. Specifying numColumns as zero allows for unlimited-length
rows.
CardLayout
The CardLayout class is unique among the other layout managers in that it stores several
different layouts. Each layout can be thought of as being on a separate index card in a deck
that can be shuffled so that any card is on top at a given time.
This can be useful for user interfaces with optional components that can be dynamically
enabled and disabled upon user input. You can prepare the other layouts and have them
hidden, ready to be activated when needed.
CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
Use of a card layout requires a bit more work than the other layouts. The cards are
typically held in an object of type Panel. This panel must have CardLayout selected as its
layout manager. The cards that form the deck are also typically objects of type Panel.
Thus, you must create a panel that contains the deck and a panel for each card in the deck.
Next, you add to the appropriate panel the components that form each card. You then add
these panels to the panel for which CardLayout is the layout manager. Finally, you add this
panel to the main applet panel. Once these steps are complete, you must provide some
way for the user to select between cards. One common approach is to include one push
button for each card in the deck.
When card panels are added to a panel, they are usually given a name. Thus, most of the
time, you will use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name);
Here, name is a string that specifies the name of the card whose panel is specified by
panelObj.
After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
[23]
Event Handling
Delegation Event Model
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
The delegation event model provides a standard mechanism for a source to generate an
event and send it to a set of listeners.
Event
An event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a graphical user interface.
Some of the activities that causes events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed. We are free to define
events that are appropriate for our application.
[24]
Event Sources
A source is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the
general form:
public void addTypeListener(TypeListener el)
Here, type is the name of the event, and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener().
The method that registers a mouse motion listener is called addMouseMotionListener().
When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them.
Some sources may allow only one listener to register. The general form of such a method is
this:
public void addTypeLIstener(TypeListener el)
throws java.util.TooManyListenersException
Here,type is the name of the event, and el is a reference to the event listener. When such
an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, type is an object that is notified when an event listener. For example, to remove a
keyboard listener, you would call removeKeyListener()
Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, it must implement methods to receive and process these
notifications.
The method that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved. Any object may receive and
process one or both of these events if it provides an implementation of this interface.
EVENT CLASSES
Event Object
At the root of the Java event class hierarchy is EventObject, which is in java.util. it is the
superclass for all events. Its one constructor is shown here:
EventObject(Object src)
here, src is the object that generates this event.
[25]
AWTEvent
The abstract AWTEvent class extends EventObject and is part of the java.awt package. All
of the AWT event types are subclasses of AWTEvent.
Constructor:
AWTEvent(Object source, int id)
here, source is the object that generates the event and id identifies the type of the event.
The possible values of id are described in the remainder of this section.
Two of its methods are:
Int getId()
String toString()
The getId() returns the type of the event, and toString() returns the string equivalent of the
event.
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are handled by the delegation event
model.
The package java.awt.event defines several types of events that are generated by various
user interface elements.
Event Class
Description
ActionEvent
Generated when a button is pressed, a list item is doubleclicked, or a menu item is selected.
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
[26]
MouseEvent
MouseWheelEvent
TextEvent
WindowEvent
ActionEvent
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and
SHIFT_MASK.
In addition, there is an integer constant, ACTION_PERFORMED, which can be used to
identify action events.
ActionEvent has these three constructor:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here,src is a reference to the object that generated this event. The type of the event is
specified by type, and its command string is cmd. The argument modifiers indicates which
modifier keys were pressed when the event was generated. The when parameter specifies
when the event occurred.
String getActionCommand() obtain the name for the invoking ActionEvent object by using
this method. For example, when a button is pressed, an action event is generated that has
a command name equal to the label on that button.
Int getModifiers() method returns a value that indicates which modifier keys were pressed
when the event was generated.
Long getWhen() returns the time at which the event took place. This called the events
timstamp.
AdjustmentEvent
An AdjustmentEvent is genrated by a scroll bar. There are five types of adjustment events.
The AdjustementEvent class defines integer constants that can be used to identify them.
The constants are:
BLOCK_DECREMENT
The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT
The user clicked inside the scroll bar to increase its value.
[27]
TRACK
UNIT_DECREMENT
UNIT_INCREMENT
COMPONENT_MOVED
COMPONENT_RESIZED
COMPONENT_SHOWN
[28]
InputEvent
InputEvent is a subclass of ComponentEvent and is the superclass for component input
events.
Its subclasses are KeyEvent and MouseEvent.
The InputEvent class defines seven int constants that can be used to obtain information
about any modifiers associated with this event.
These are
[29]
ALT_MASK
BUTTON1_MASK
BUTTON2_MASK
BUTTON3_MASK
CTRL_MASK
META_MASK
SHIFT_MASK.
The isAltDown(), isControlDown(), isMetaDown(), and isShiftDown() methods test if these
modifiers were pressed at the time the event was generated. The forms of these methods
are shown here:
boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
ItemEvent
An ItemEvent is generated when a check box or a list item is clicked or when a checkable
menu item is selected or deselected.
There are two types of item events, which are identified by the following integer
constants:
DESELECTED = the user deselected an item
SELECTED = the user selected an item.
ItemEvent(ItemSelectable src, int type,Object entry, int state)
here, src is a ref. to the component that generated this event. For example, this might be a
list or choice element. The type of the event is specified by type. The specific item that
generated the item event is passed in entry. The current state of that item is in state.
KeyEvent
A KeyEvent is generated when keyboard input occurs.
There are 3 types of key events, which are identified by these integer constants:
KEY_PRESSED
KEY_RELEASED
KEY_TYPED.
The first two events are generated when an key is pressed or released. The last event
occurs only when a character is generated.
MouseEvent
There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED
[30]
MOUSE_DRAGGED
MOUSE_ENTERED
MOUSE_EXITED
MOUSE_MOVED
Mouse moved
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_WHEEL
MouseWheelEvent
The mouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of
MouseEvent.
MouseWheelEvent defiens two integer constants:
WHEEL_BLOCK_SCROLL
WHEEL_UNIT_SCROLL
[31]
MouseWheelEvent (Component src, int type, long when, int modifiers, int x, int y, int
clicks, boolean triggersPopup, int scrollHow, int count)
Here, src is a ref. to the object that generated the event. The type of the event is specified
by type. The system time at which the mouse event occurred is passed in when. The
modifiers argumnt indicats which modifiers were pressed when the event occurred. The
coordinates of the mouse are passed in x and y. the number of clicks the weeel has rotated
is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to
appear on this platform. The scrollHow value must be either WHEEL_UNIT_SCROLL or
WHEEL_BLOCK_SCROLL. The no. of units to scroll is passed in amount. The count
parameter indicates the number of rotational units that the wheel moved.
TextEvent
Instance of this class describe text events. These are generated by text fields and text areas
when characters are entered by a user or program.
TextEvent defiens the integer constant TEXT_VALUE_CHANGED.
TextEvent(Object src, int type)
here, src is a ref. to the object that generated this event. The type of the event is specified
by type.
WindowEvent
There are ten types of window events.
WINDOW_ACTIVATED
WINDOW_CLOSED
WINDOW_CLOSING
WINDOW_DEACTIVATED
WINDOW_DEICONIFIED
WINDOW_GAINED_FOCUS
WINDOW_ICONIFIED
WINDOW_LOST_FOCUS
WINDOW_OPENED
WINDOW_STATE_CHANGED
[32]
Sources of Events
Button
Checkbox
Choice
List
Menu Item
Scrollbar
Text
Component
Window
Description
ActionListener
AdjustmentListener
ComponentListener
FocusListener
ItemListener
[33]
keyListener
MouseListener
TextListener
ActionListener Interface
This interface defines the actionPerformed() method that is invoked when an action event
occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
This interface defines the adjustmentValueChanged() method that is invoked when an
adjustment event occurs. Its general form is:
void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Interface
This interface defines four methods that are invoked when a component is resized, moved,
shown or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Interface
This interface contains two methods. When a component is added to a container,
componentAdded() is invoked. When a component is removed from a container,
componentRemoved() is invoked.
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
[34]
FocusListener Interface
This interface defines two mehtods. When a component obtains keyboard focus,
focusGained() is invoked. When a component loses keyboard focus, focusLost() is called.
Their general form is shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemListener Interface
This interface defines the itemStateChanged() method that is invoked when the state of an
item changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie)
KeyListener Interface
This interface defines three methods. The keyPressed() and keyReleased() method are
invoked when a key is pressed and released, respectively. The keyTyped() method is
invoked when a character has been entered.
For example, if a user presses and releases the A key, three events are generated in
sequence key pressed, typed and released. If a user presses and releases the HOME key,
two key events are generated in sequence keypressed and released.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same
point, mouseClicked() is invoked. When the mouse enters a component, the
mouseEntered() method is called. When it leaves, mouseExited() is called. The
mousePressed() and mouseReleased() methods are invoked when the mouse is pressed
and released, respectively.
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener Interface
This interface defines two methods. The mouseDragged() method is called multiple times
as the mouse is dragged. The mouseMoved() method is called multiple times as the mouse
is moved. Their general form:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
[35]
MouseWheelListener Interface
This interface defines the mouseWheelMoved() method that is invoked when the mouse
wheel is moved. Is general form is shown here:
void mouseWheelMoved(MouseWheelEvent me)
TextListener Interface
This interface defines the textChanged() method that is invoked when a change occurs in a
text area or text field. Its general form is shown here:
void textChanged(TextEvent te)
WindowFocusListener Interface
This interface defines two methods: windowGainedFocus() and windowLostFocus(). These
are called when a window gains or loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Interface
This interface defines seven methods. The windowActivated() and windowDeactivated()
methods are invoked when a window is activated or deactivated, respectively. If a window
is iconified, the windowIconified() method is called. When a windwo is opened or clsoed,
the windwoOpened() or windwoClosed() methods are called, respectively. The
windowClosing() mehtod is called when a window is being closed.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconofied(WindowEvent we)
void windowOpened(WindowEvent we)
[36]
AdjustmentEv
ent
ItemEvent
Event Source
Button
List
MenuItem
TextField
Scrollbar
Event Listener
ActionListener
AdjustmentListener adjustmentValueChanged(Adjustme
ntEvent e)
KeyEvent
Choice
ItemListener
Checkbox
CheckboxMenu
Item
List
TextField
TextListener
TextArea
Component
KeyListener
MouseEvent
Component
MouseListener
FocusEvent
Component
MouseMotionListe
ner
FocusListener
WindowEvent
Window
WindowListener
TextEvent
Event Handler
actionPerformed(ActionEvent e)
[37]
ItemStateChanged(ItemEvent e)
TextValueChanged(TextEvent e)
keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
mouseClicked(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseMoved(MouseEvent e)
mouseDragged(MouseEvent e)
focusGained(FocusEvent e)
focusLost(FocusEvent e)
windowOpened(WindowEvent e)
windowClosing(WindowEvent e)
windowClosed(WindowEvent e)
windowIconified(WindowEvent e)
windowDeiconified(WindowEvent e)
windowActivated(WindowEvent e)
windowDeactivated(WindowEvent e)
Java annotation
Annotations provide data about a class that is not part of the programming logic itself.
They have no direct effect on the code they annotate.
An annotation, in the Java computer programming language, is a form of syntactic
metadata that can be added to Java source code. Classes, methods, variables, parameters
and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in
that they can be embedded in class files generated by the compiler and may be retained by
the Java VM to be made retrievable at run-time. It is possible to create meta-annotations
out of the existing ones in Java.
Uses of Annotations
Annotations are far more powerful than java comments and javadoc comments. One main
difference with annotation is it can be carried over to runtime and the other two stops
with compilation level. Annotations are not only comments, it brings in new possibilities in
terms of automated processing.
Annotation Structure
There are two main components in annotations. First is annotation type and the next is the
annotation itself which we use in the code to add meaning. Every annotation belongs to a
annotation type.
@interface <annotation-type-name>
{
method declaration;
}
Annotation type is very similar to an interface with little difference.
We attach @ just before interface keyword.
Methods will not have parameters.
Methods will not have throws clause.
Method return types are restricted to primitives, String, Class, enums,
annotations, and arrays of the preceding types.
We can assign a default value to method.
[38]
Custom Annotations
We can create our own annotations and use it. We need to declare a annotation type and
then use the respective annotation is java classes.
Following is an example of custom annotation, where this annotation can be used on any
element by giving values. Note that I have used @Documented meta-annotation here to
say that this annotation.
@Documented
public @interface Team {
int teamId();
String teamName();
String teamLead() default "[unassigned]";
String writeDate(); default "[unimplemented]";
}
Annotation for the Above Example Type
... a java class ...
@Team(
teamId
= 73,
teamName = "Rambo Mambo",
teamLead = "Yo Man",
writeDate = "3/1/2012"
)
public static void readCSV(File inputFile)
{
...
}
... java class continues ...
Meta Annotations
Annotations itself is meta information then what is meta annotations? As you have rightly
guessed, it is information about annotation. When we annotate a annotation type then it is
called meta annotation. For example, we say that this annotation can be used only for
methods.
@Target(ElementType.METHOD)
public @interface MethodInfo
{}
[39]
Built-In Annotations
Java defines a set of annotations that are built into the language.
Annotations applied to java code:
@Override - Checks that the method is an override. Causes a compile error if the
method is not found in one of the parent classes or implemented interfaces.
@Deprecated - Marks the method as obsolete. Causes a compile warning if the
method is used.
@SuppressWarnings - Instructs the compiler to suppress the compile time warnings
specified in the annotation parameters
Annotations applied to other annotations (Meta-annotation):
@Retention - Specifies how the marked annotation is storedWhether in code only,
compiled into the class, or available at runtime through reflection.
@Documented - Marks another annotation for inclusion in the documentation.
@Target - Marks another annotation to restrict what kind of java elements the
annotation may be applied to
@Inherited - Marks another annotation to be inherited to subclasses of annotated
class (by default annotations are not inherited to subclasses).
Example
This example shows the use of the @Override annotation. It instructs the compiler to
check parent classes for matching methods. In this case, an error is generated that
the Cat's gettype() method does not in fact override Animal's getType() as desired. If
the @Override annotation was absent, a new method of name gettype() would be
created in class Cat.
public class Animal {
public void speak() {
}
public String getType() {
return "Generic animal";
}
}
public class Cat extends Animal {
@Override
public void speak() { // This is a good override.
System.out.println("Meow.");
}
[40]
@Override
public String gettype() { // compile-time error due to mistyped name.
return "Cat";
}
}
Annotations themselves may be annotated to indicate where and when they can be used:
@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at
runtime via reflection.
@Target({ElementType.METHOD})
// This annotation can only be applied to
class methods.
public @interface Tweezable {
}
The compiler reserves a set of special annotations (including @Deprecated, @Override and
@SuppressWarnings) for syntactic purposes.
The annotations are not method calls and will not, by themselves, do anything. Rather, the
class object is passed to the JPA implementation at run-time, which then extracts the
annotations to generate an object-relational mapping.
A complete example is given below:
File 1
package com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,
ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
@Inherited
public @interface Unfinished {
public enum Priority { LOW, MEDIUM, HIGH }
String value();
String[] changedBy() default "";
String[] lastChangedBy() default "";
[41]
File 2
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.annotation.UnderConstructio;
import com.annotation.Unfinished;
import com.annotation.Unfinished.Priority;
import com.util.Util;
@UnderConstruction(owner="Navin Gujarish")
public class DateValidator implements Validator{
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException
{
String date = (String) value;
String errorLabel = "Please enter a valid date.";
if(!component.getAttributes().isEmpty())
{
errorLabel = (String) component.getAttributes().get("errordisplayval");
}
if(!Util.validateAGivenDate(date))
{
@Unfinished(changedBy = "Steve"
,value="whether to add message to context or not, confirm"
,priority=Priority.HIGH
)
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary(errorLabel);
[42]
message.setDetail(errorLabel);
throw new ValidatorException(message);
}
}
}
[43]