UNIT_V - WordPress.com

Download Report

Transcript UNIT_V - WordPress.com

APPLETS
1
What is Applets?
1. An applet is a program written in the Java programming language that can be included in an
HTML page, much in the same way an image is included in a page.
2. When you use a Java technology-enabled browser to view a page that contains an applet, the
applet's code is transferred to your system and executed by the browser's Java Virtual
Machine (JVM).
What are the differences between Applets and Application?
1. Applets do not use the main() method for initiating the execution of the code. Applets, when
loaded, automatically call certain methods of Applet class to start and execute the applet code.
2. Unlike stand – alone applications, applets cannot be run independently. They are run from
inside a Web page using a special feature known as HTML tag.
3. Applets cannot read from or write to the files in the local computer.
4. Applets cannot communicate with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++. (Java
language supports this feature through native methods.)
2
Applet Architecture
1. An applet is a window – based program.
2. First, applets are event driven.
3. Event – driven architecture impacts the design of an applet.
4. An applet resembles a set of interrupt service routines.
5. An applet waits until an event occurs.
6. The AWT notifies the applet about an event by calling an event handler appropriate action
and then quickly return control to the AWT.
7. Second, the user initiates interaction with an applet - not the other way around.
8. As you know, in a non - windowed program, when the program needs input, it will prompt
the user and then call some input method, such as readLine().
9. This not the way it works in an applet. Instead, the user interacts with the applet as he or she
wants, when must respond.
10. For example, when the user clicks a mouse inside the applet’s window, a mouse – clicked
event is generated. If the user presses a key while the applet’s window has input focus, a
keypress event is generated.
11. Applets can contain various controls, such as push buttons and check boxes.
3
Applet Architecture . . . .
12. When the user interacts with one of these controls, an event is generated.
13. While the architecture of an applet is not as easy to understand as that of a console – based
program, Java’s AWT makes it as simple as possible.
14. If you have written programs for windows, you know how intimidating that environment can
be.
15. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.
4
An Applet Skeleton or Applet Life Cycle
Begin
Born
(Load Applet)
Initialization
start( )
stop( )
Running
Stopped
Idle
start( )
Display
paint( )
destroy( )
Destroyed
Dead
End
5
Exit of Browser
An Applet Skeleton or Applet Life Cycle
1. All but the the most trivial applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the applet and controls its
execution.
2. Four of these methods – init( ), start( ), stop( ), and destroy( ) – are defined by Applet.
Another, paint(), is defined by the AWT Component class.
3. Default implementations for all of these methods are provided.
4. Applets do no need to override those methods they do not use.
5. However, only very simple applets will not need to define all of them.
The applet states is:
1. Born or initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
5. Display state
6
1. Initialization State
Applet enters the initialisation 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,
a. Create objects needed by the applet.
b. Set up initial values
c. Load images or fonts
d. set up colors
public void init( )
{
----------------------------------------------------------------}
Action
7
2. Running State
Applets enters the running state when the system call the start () method of Applet Class.
This occurs automatically after the applet is initailized. Starting can also occur if the applet is
already in “stopped” state. For example, we may leave the web page containing the applet
temporarily to another page and return back to the page. This again starts the applet running.
Note that, unlike init() method, the start() method may be called more than once. We may
override the start() method to create a threa to control the applet.
public void start( )
{
----------------------------------------------------------------}
Action
8
3. Idle or Stopped State
An applet becomes idle when it is stopped from running. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the
stop() method explicitly. If we use a thread to run the applet, then we must use stop() method
to terminate the thread. We can achieve by overriding the stop( ) method:
public void stop( )
{
----------------------------------------------------------------}
Action
9
4. Dead State
An applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage
occurs only once in the applet’s life cycle. If the applet has created any resources. Like
threads we may override the destroy( ) method to clean up these resouces.
public void destroy( )
{
----------------------------------------------------------------}
Action
10
5. 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 Statements
--------------------------------}
11
The repaint() method has four forms.
Void repaint()
Void repaint(int left,int top, int width,int height)
Void repaint(long maxDelay)
Void repaint(long maxDelay, int x, int y, int width, int height)
The HTML Applet Tab
The APPLET tag is used to start an applet from both an HTML document
and from an applet viewer.
The syntax for the standard APPLET tag is shown here. Bracketed items
are optional.
<APPLET [CODEBASE=codebaseUTL] CODE=appletfile
[ALT=alternateText] [NAME=appletInstanceName]
WIDTH=pixels HIEGHT=pixels [ALIGN=alignment]
[VSPACE=pixels] [HSPACE=pixels]>
[<PARAM NAME=AttibuteName VALUE=AttibuteValue>]
[<PARAM NAME=AttibuteName2 VALUE=AttibuteValue>]
.................
[HTML Displayed in the absence of Java]
</APPLET>
CODE: Code is a required attribute that gives the name of the file containing
your applet’s compiled .class file.
WIDTH and HEIGHT: Width and Height are required attributes that gives
the size of the applet display area.
PARAM NAME and VALUE : The PARAM tag allows you to specify appletspecific arguments in an HTML page. Applets access their attributes with
the getParameter() method.
import java.awt.*;
import java.applet.*;
/*
<applet code = "AppletDemo" width = 300 height = 300>
</applet>
*/
public class AppletDemo extends Applet
{
String msg;
public void init()
{
setBackground(Color.cyan);
}
public void start()
{
msg += "This is Start method";
}
public void stop()
{
msg += "This is Stop method";
}
public void destroy()
{
msg += "This is Destroy method";
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
Specified Colors
Specified Colors
1. Color.black
10. Color.pink
2. Color.blue
11. Color.red
3. Color.cyan
12. Color.white
4. Color.darkGray
13. Color.yellow
5. Color.gray
6. Color.green
7. Color.lightGray
8. Color.magenta
9. Color.orange
14
How the applets to be displayed in the Browser
<HTML>
<HEAD>
<TITLE>WELCOME TO cHETTINAD</TITLE>
</HEAD>
<BODY>
<APPLET
CODE = AppletDemo.class
WIDTH = 300
HEIGHT = 200
</APPLET>
</BODY>
</HTML>
15
The HTML APPLET Tag
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
.......
[HTML Displayed in the absence of Java]
</APPLET>
16
ATTRIBUTE
MEANING
CODE = AppletFileName.class
Specifies the name of the applet class to be loaded. That is, the name of the
already – compiled .class file in which the executable. Java bytecode for the
applet is stored. This attribute must be specified.
CODEBASE = codebase_URL
(Optional)
Specifies the URL of the directory in which the applet resides. If the applet
resides in the same directory as the HTML file, then the CODEBASE
attirbute may be omitted entirely.
WIDTH = pixels
HEIGHT = pixels
These attributes specify the width and height of the space on the HTML
page that will be reserved for the applet.
NAME=applet_instance_name
(Optional)
A name for the applet may optionally be specified so that other applets on
the page may refer to this applet. This facilitates inter applet
communication.
ALIGN = alignment
(Optional)
This optional attribute specifies where on the page the applet will appear.
Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT,
MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE.
HSPACE = pixels
(Optional)
Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies
the amount of horizontal blank space the browser should leave surrounding
the applet.
VSPACE = pixels
(Optional)
Used only when some vertical alignment is specified with the ALIGN
attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical
blank space the browser should leave surrounding the applet.
ALT = alternate_text
(Optional)
Non – java browser will display this text where the applet would normally
go. This attribute is optional.
PARAM NAME AND VALUE
The PARAM tag allows you to specify applet – specific arguments
17 in an
HTML page. Applets access their attributes with the getParameter() method
Passing Parameters to Applets
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width = 300 height = 300>
<param name = fontName value=Courier>
<param name = fontSize value = 30>
<param name = leading value=2>
<param name = accountEnabled value = true>
</applet>
*/
public class ParamDemo extends Applet
{
String fontName;
int fontSize;
float leading;
boolean active;
public void start()
{
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
18
param = getParameter("fontSize");
try
{
if(param != null) //if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
}
catch(NumberFormatException e)
{
fontSize = -1;
}
param = getParameter("leading");
try
{
if(param != null) //if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
}
catch(NumberFormatException e)
{
leading = -1;
}
19
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font name: " + fontName,0,10);
g.drawString("Font Size: " + fontSize,0,20);
g.drawString("Leading: " + leading, 0,42);
g.drawString("Account Active: " + active,0,58);
}
}
20
getCodeBase() and getDocumentBase()
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code=ParamDemo_2.class width = 300 height = 300>
</applet>
*/
public class ParamDemo_2 extends Applet
{
public void paint(Graphics g)
{
String msg;
URL url = getCodeBase();
msg = "Code Base: " + url.toString();
g.drawString(msg,10,20);
url = getDocumentBase();
msg = "Document Base: " + url.toString();
g.drawString(msg,10,40);
}
}
21
The AudioClip Interface
The AudioClip interface defines these methods:
1. play ( )
– play a clip from the beginning.
2. stop ( )
– stop playing the clip.
3. loop ( )
– play the loop continuously.
4. getAudioClip ( ) - After you have loaded an audio clip
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
/*
<applet code=SoundExample width = 300 height = 300>
</applet>
*/
public class SoundExample extends Applet implements MouseListener
{
AudioClip soundFile1;
AudioClip soundFile2;
22
public void init()
{
soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav");
soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav");
addMouseListener(this);
setBackground(Color.yellow);
soundFile1.play();
}
public void paint(Graphics g)
{
g.drawString("Click to hear a sound",20,20);
}
public void mouseClicked(MouseEvent evt)
{
soundFile2.play();
}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
23
AppletStub Interface
The AppletStub interface provides a way to get information from the run-time browser
environment. The Applet class provides methods with similar names that call these
methods. Methods
public abstract boolean isActive ()
The isActive() method returns the current state of the applet. While an applet is
initializing, it is not active, and calls to isActive() return false. The system marks the
applet active just prior to calling start(); after this point, calls to isActive() return true.
public abstract URL getDocumentBase ()
The getDocumentBase() method returns the complete URL of the HTML file that loaded
the applet. This method can be used with the getImage() or getAudioClip() methods to
load an image or audio file relative to the HTML file.
public abstract URL getCodeBase ()
The getCodeBase() method returns the complete URL of the .class file that contains the
24
applet. This method can be used with the getImage() method or the getAudioClip()
method to load an image or audio file relative to the .class file.
public abstract String getParameter (String name)
The getParameter() method allows you to get parameters from <PARAM> tags within the
<APPLET> tag of the HTML file that loaded the applet. The name parameter of
getParameter() must match the name string of the <PARAM> tag; name is case insensitive.
The return value of getParameter() is the value associated with name; it is always a String
regardless of the type of data in the tag. If name is not found within the <PARAM> tags of
the <APPLET>, getParameter() returns null.
public abstract void appletResize (int width, int height)
The appletResize() method is called by the resize method of the Applet class. The method
changes the size of the applet space to width x height. The browser must support changing
the applet space; if it doesn't, the size remains unchanged.
25
The Delegation Event Model
1. The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events.
2. Its concept is quite simple: a source generates an event and sends it to one or more listeners.
3. In this scheme, the listener simply waits until it receives an event.
4. Once received, the listener processes the event and then returns.
5. The advantage of this design is that the application logic that processes events is cleanly separated
from the user interface logic that generates those events.
6. A user interface element is able to “delegate” the processing of an event to a separate piece of code.
Events
1. In the delegation model, an event is an object that describes a state change in a source.
2. It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
3. Some of the activities that cause events to be generated are pressing a button, entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.
4. Event 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
26
hardware failure occurs, or an operation is completed.
Event Sources
1. A source is an object that generates an event.
2. This occurs when the internal state of that object changes in some way.
3. Sources may generate more than one type of event.
4. A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
5. Each type of event has its own registration method.
6. Here is the general form:
public void addTypeListener(TypeListener el)
7. Here, type is the name of the event and el is a reference to the event listener.
8. For example the method that registers a keyboard event listener is called addKeyListener().
9. The method that registers a mouse motion listener is called addMouseListener().
10. When an event occurs, all registered listeners are notified and receive a copy of the event object.
11. This known as multicasting the event. Some sources may allow only one listener to register.
12. The general form of such method is this:
27
public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException
13. Here, Type is the name of the event and el is a reference to the event listener.
14.When such an event occurs, the registered listener is notified. This is known a s unicasting the
event.
15. A source must also provide a method that allows a listener to unregister an interest in a specific type
of event.
16. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
17. Here, Type is the name of the event and el is reference to the event listener.
18. For Example, to remove a keyboard listener, you would call removeKeyListener().
19. The methods that add or remove listeners are privided by the source that generates events.
20. For example, the Component class provides methods to add and remove keyboard and mouse event
listeners.
Event Listeners
21. A Listener is an object that is notified when an event occurs. It has major requirements.
22. First, it must have been registered with one or more sources to receive notification about specific
type of events.
23. Second, it must implement methods to receive and process these notifications.
28
24. The methods that receive and pricess events are defined in a set of interfaces found in
java.awt.event.
25. For example, the MouseMotionListener interface defines two method to receive notifications when
the mouse is dragged or moved.
26. Any object may receive and process one or both of these events if it provides an implementation of
this interface.
29
EVENT CLASSES
30
Event Classes
1. The classes that represent events are at the core of Java’s event handling
mechanism.
2. At the root of the Java event class hierarchy is EventObject, which is in java.util.
3. It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
4. Here, src is the object that generates this event.
5. EventObject contains two methods: getSource() and toString().
6. The getSource() method returns the source of the event.
7. Its general form is shown here:
Object getSource()
8. As expected, toString() returns the string equivalent of the event.
9. The AWTEvent, defined within the java.awt package, is a subclass of EventObject.
10. It is the superclass of all AWT – based events used by the delegation event model.
11. Its getID() method can be used to determine the type of the event. The signature of
this method is shown here:
31
int getID()
The package java.awt.event defines several types of events that are generated by
various user interface elements.
EVENT CLASSES
DESCRIPTION
ActionEvent
Generated when a button is pressed, a list item is double - clicked, or a menu
item is selected.
AdjustmentEvent
Generated when a scroll bar is manupulated
ComponentEvent
Generated when a component is hidden, moved, resized, or becomes visible.
ContainerEvent
Generated when a component is added to or removed from a container.
FocusEvent
Generated when a component gains or loses keyboard focus.
InputEvent
Abstract super class for all component input event classes.
ItemEvent
Generated when a check box or list item is clicked; also occurs when a choice
selection is made or a checkable menu item is selected or deselecte.
KeyEvent
Generated when input is received from the keyboard.
MouseEvent
Generated when the mouse is dragged, moved, clicked, pressed, or , released;
also generated when the mouse enters or exits a component.
MouseWheelEvent
Generated when the mouse wheel is moved.
TextEvent
Generated when the value of a text area or text field is changed.
WindowsEvent
Generated when a window is activated, closed, deactivated, deiconified,
32
iconified, opened, or quit.
The ActionEvent Class
1. An ActionEvent is generated when a button is pressed, a list item is double - clicked, or a menu
item is selected.
2. The ActionEvent class defines fout integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK.
3. In addition. There is an integer constant, ACTION_PERFORMED, which can be used to identify
action events. ActionEvent has these three constructors:
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)
4. Here, src is a reference to the object that generated this event.
5. The type of the event is specified by type, and its command string is cmd.
6. The argument modifiers indicates which modifier key were pressed when the event was generated.
7. The when parameter specifies when the event occurred.
33
Action Event Example Button Click
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Button_Setnull.class" height=300 width=300>
</applet>
*/
public class Button_Setnull extends Applet implements ActionListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Button b1;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
//setTitle("Addition of Two Numbers");
setLayout(null);
34
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Addition of the Two Numbers");
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
b1 = new Button("Click Addition");
b1.setBounds(100,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(b1);
b1.addActionListener(this);
}
35
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("Click Addition"))
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
}
}
36
Action Event Example List Box item Double Click
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=“Listbox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Listbox_Setnull extends Applet implements ActionListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
List ls;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
37
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ls = new List();
ch.setBounds(100,150,150,25);
ls.add(""); ls.add("Addition"); ls.add("Subtraction");
ls.add("Multiplication"); ls.add("Division"); ls.add("Clear");
ls.add("Total No. of Item"); ls.add("Get Selected Item");
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ls);
ls.addActionListener(this);
}
38
public void actionPerformed(ActionEvent ae)
{
if(ls.getSelectedIndex() == 1)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 2)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}
39
}
if(ls.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ls.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ls.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ls.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
40
}
}
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand() method, shown here:
String getActionCommand()
For example, when a button is pressed, and action event is generated that has a command name equal to
the label on that button.
The getModifiers() method returns a value that indicates which modifier keys(ALT,CTRL,META and
SHIFT) were pressed when the event was generated. Its form is shown here:
String getModifiers()
The AdjustmentEvent Class
An AdjustementEvent is generated by a scroll bar. There are five types of adjustment events. The
AdjustementEvent class defines integer constants that can be used to identify them.
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.
TRACK – The slider was dragged.
UNIT_DECREMENT – The button at the end of the scroll bar was clicked to decrease its value
UNIT_INCREMENT – The button at the end of the scroll bar was clicked to increase its value.
41
In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED,
that indicates that a change has occurred.
Here is one AdjustmentEvent constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)
Here, src is a reference to the object that generated this event. The id equals
ADJUSTEMENT_VALUE_CHANGED. The type of the event is specified by type, and its
associated data is data.
The getAdjustable() method returns the object that generated the event. Its
form is shown here:
Adjustable getAdjustable()
The type of the adjustement event may be obtained by the getAdjustmentType() method.
It returns one of the constant defined by AdjustmentEvent. The general form is shown
here:
int getAdjustmentType()
The amount of the adjustement can be obtained from the getValue() method, shown
here
int getValue()
42
import java.applet.*; AdjustmentEvent Example Horizontal and Vertical Scrollbar Changed
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Scroll_Setnull.class" height=300 width=1000>
</applet>
*/
public class Scroll_Setnull extends Applet implements AdjustmentListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Scrollbar sbh,sbv;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
43
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
int height = Integer.parseInt(getParameter("height"));
int width = Integer.parseInt(getParameter("width"));
sbh = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,height);
sbh.setBounds(0,275,975,25);
sbv = new Scrollbar(Scrollbar.VERTICAL,0,1,0,width);
sbv.setBounds(975,0,25,300);
sbh.setUnitIncrement(50);
sbh.setBlockIncrement(50);
sbv.setUnitIncrement(20);
sbv.setBlockIncrement(20);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(sbh);
add(sbv);
sbh.addAdjustmentListener(this);
sbv.addAdjustmentListener(this);
}
44
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(sbh.getValue() == 50)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 100)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}
45
if(sbh.getValue() == 150)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 200)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(sbh.getValue() == 250)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
46
The ComponentEvent Class
A ComponentEvent is generated when the size, position, or visibility of a component is
changed. There are four types of component events. The ComponentEvent class
defines integer constants that can be used to identify them. The constant and their
meanings are shown here:
COMPONENT_HIDDEN
The component was hidden
COMPONENT_MOVED
-
The component was moved
COMPONENT_RESIZED
-
The component was resized
COMPONENT_SHOWN
-
The component became visible
ComponentEvent has this constructor
ComponentEvent(Component src, int type)
Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
ComponentEvent is the superclass either directly or indirectly
ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent.
of
The getComponent() method returns the component that generated the event.
It is shown here:
47
Component getComponent()
The ContainerEvent Class
1. A ContainerEvent is generated when a component is added to or removed from a
container.
2. There are two types of container events.
3. The ContainerEvent class defines int constants that can be used to identify them:
COMPONENT_ADDED and COMPONENET_REMOVED.
4. They indicate that a component has been added or removed form the container.
5. ContainerEvent is a subclass of ComponentEvent and has this constructor:
ContainerEvent(Component src, int type, Component comp)
Here, src is reference to the container that generated this event. The type of the event is
specified by type, and the component that has been added to or removed from the
container is comp.
You can obtain a reference to the container that generated this event by using
the getCotnainer() method, shown here:
Container getContainer()
The getChild() method returns a reference to the component that was added to
or removed from the container. Its general form is shown here:
48
Component getChild()
The FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events are
identified by the integer constants FOCUS_GAINED and FOCUS_LOST
FocusEvent is a subclass of ComponentEvent and has threse constructor:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
1. Here, src is a reference to the component that generated this event.
2. The type of the event is specified by type.
3. The argument temporaryFlag is set to true if the focus event is temporary.
4. Otherwise, it is set to false.
5. The other component involved in the focus change, called the apposite component, is passed in
other.
6. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost
focus.
7. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains
focus.
49
import java.applet.*;
FocusEvent Example Focus Gained and Focus Lost in TextBox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Focus_Event.class" height=300 width=1000>
</applet>
*/
public class Focus_Event extends Applet implements FocusListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
}
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
add(tf1);
add(tf2);
add(tf3);
tf1.addFocusListener(this);
tf2.addFocusListener(this);
50
public void focusGained(FocusEvent fe)
{
tf2.setText("Focus Gained");
}
public void focusLost(FocusEvent fe)
{
tf1.setText("Focus Lost");
}
}
51
You can determine the other component by calling getOppositeComponent(),
shown here.
Component getOppositeComponent()
The isTemporary() method indicates if this focus change is temporary. Its form
is shown here:
boolean isTemprorary()
The method returns true if the change is temporary. Otherwise, it returns false.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
MOUSE_CLICKED
-
The user clicked the mouse.
MOUSE_DRAGGED
-
The user dragged the mouse.
MOUSE_ENTERED
-
The mouse entered a component.
MOUSE_EXITED
-
The mouse exited from a component.
MOUSE_MOVED
-
The mouse moved.
MOUSE_PRESSED
-
The mouse was pressed.
MOUSE_RELEASED
-
The mouse was released.
MOUSE_WHEEL
-
The mouse wheel was moved.
52
MouseEvent is a subclass of InputEvent. Here is one of its constructor.
MouseEvent(Component src, int type, long when, int modifiers, int x,int y, int clicks, boolean triggersPopup
1. Here, src is a reference to the component that generated the event.
2. The type of the event is specified by type.
3. The system time at which the mouse event occurred is passed in when.
4. The modifiers aregument indicates which modifiers were pressed when a mouse
event occurred.
5. The coordinates of the mouse are passed in x and y.
6. The click count is passed in clicks.
7. The triggersPopup flag indicates if this event causes a pop – up menu to appear on
this platform
Methods
Description
int getX() and int getY()
These retrun the X and Y coordinates of the mouse when the event
occured
Point getPoint()
It returns a Point object that contains the X, Y coordinates in its integer
members.
getClickCount()
The methods obtains the number of mouse clicks for this event
isPopupTrigger()
53
This method tests if this event causes a pop – up menu to appear on this
platform
import java.awt.*;
MouseEvent Example
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
in Mouse
54
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="CCET";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
55
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
56
The MouseWheelEvent Class
The MouseWheelEvent class encapsulates a mouse wheel event. If a mouse has a
wheel, it is located between the left and right buttons. Mouse wheels, are used for
scrolling. MouseWheelEvent defines these two integer constants.
WHEEL_BLOCK_SCROLL
WHEEL_UNIT_SCROLL
A page – up or page – down scroll event occurred
-
-
A line – up or line – down scroll event occured
MouseWheelEvent defines the following constructor:
MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks,
boolean triggersPopup, int scrollHow, int amount, int count)
Here, src is a reference 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 argument indicates which modifiers were pressed when the event
occurred. The coordinates of the mouse are passed in x and y. The number of clicks the
wheel has rotated is passed in clicks. The triggers Popup flag indicates if this event
causes a pop – up menu to appear on this platform. The scrollHow value must be either
is passes in amount. The count parameter indicates the number of roational units that
the wheel moved.
57
Methods
Description
int getWheelRotation()
It returns the number of rotational units. If the value is positive, the wheel
moved conterclockwise. If the value is negative, the wheel moved
clockwise.
int getScrollType()
It returns either WHEEL_UNIT_SCORLL or WHEEL_BLOCK_SCROLL
int getScrollAmount()
If the scroll type is WHEEL_UNIT_SCROLL you can obtain the number of
units to scroll by calling getScrollAmount().
The InputEvent Class
1. The abstract class InputEvent is a subclass of ComponentEvent and is the
superclass for component input events.
2. Its subclasses are keyEvent and MouseEvent.InputEvent defines several integer
constants that represent any modifiers, such as the control key being pressed, that
might be assocated with the event.
3. Originally, the InputEvent class defined the following eight values to represent the
modifiers.
ALT_MASK
BUTTON2_MASK
BUTTON3_MASK
SHIFT_MASK
BUTTON1_MASK
CTRL_MASK
META_MASK
58
4. However, because of possible conflicts between the modifiers used by keyboard
events and mouse events, and other issues, Java2 version 1.4, added the following
extended modifier values.
ALT_DOWN_MASK
BUTTON2_DOWN_MASK
BUTTON3_DOWN_MASK
SHIFT_DOWN_MASK
BUTTON1_DOWN_MASK
CTRL_DOWN_MASK
META_DOWN_MASK
5. When writing new code, it is recommended that you use the new, extended modifiers
rather that the original modifiers.
6. To test if a modifier was pressed at the time an event is generated, use the
isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown()
methods.
7. The forms of these methods are shown here:
boolean isAltDown()
boolean isAltGraphDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
59
You can obtain a value that contains all of the original modifer flags by calling the
getModifiers() method. It is shown here:
int getModifiers()
You can obtain the extended modifiers by called getModifiersEx(), which is shown here:
int getModifiersEx()
The ItemEvent Class
1. An ItemEvent is generated when a check box or a list item is clicked or when a
checkable menu item is selected or deselected.
2. 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
In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that
signifies a change of state.
ItemEvent(ItemSelectable src, int type, Object entry, int state)
60
3. Here, src is a reference to the component that generated this event.
4. For example, this might be a list or choice element.
5. The type of the event is specified by type.
6. The specific item that generated the item event is passed in entry. The current state of
that item is in state.
7. The getItem() method can be used to obtain a reference to the item that generated an
event. Its signature is shown here:
Object getItem()
8. The getItemSelectable() method can be used to obtain a reference to the
ItemSelectable object that generated an event. Its general form shown here:
itemSelectable getItemSelectable()
9. Lists and choices are examples of user interface elements that implement the
ItemSelectable interface.
10. The getStateChange() method returns the state change for the event. It is shown
here:
int getStateChange()
61
import java.applet.*;
ItemEvent Example in Checkbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkbox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkbox_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Addition of the Two Numbers");
l3.setBounds(0,100,170,25);
62
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch1 = new Checkbox("Addition");
ch1.setBounds(100,150,150,25);
ch2 = new Checkbox("Subtraction");
ch2.setBounds(250,150,150,25);
ch3 = new Checkbox("Multiplication");
ch3.setBounds(400,150,150,25);
ch4 = new Checkbox("Division");
ch4.setBounds(550,150,150,25);
ch5 = new Checkbox("Clear");
ch5.setBounds(700,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1);
add(ch2); add(ch3); add(ch4); add(ch5);
ch1.addItemListener(this); ch2.addItemListener(this);
ch3.addItemListener(this); ch4.addItemListener(this);
ch5.addItemListener(this);
}
63
public void itemStateChanged(ItemEvent ie)
{
if(ch1.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ch2.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}
64
if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
65
import java.applet.*;
ItemEvent Example in CheckboxGroup
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Checkboxgroup_Setnull.class" height=300 width=1000>
</applet>
*/
public class Checkboxgroup_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Checkbox ch1,ch2,ch3,ch4,ch5;
CheckboxGroup cbg;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
cbg = new CheckboxGroup();
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
66
l3 = new Label("Compute the Two Numbers");
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch1 = new Checkbox("Addition",cbg,false);
ch1.setBounds(100,150,150,25);
ch2 = new Checkbox("Subtraction",cbg,false);
ch2.setBounds(250,150,150,25);
ch3 = new Checkbox("Multiplication",cbg,false);
ch3.setBounds(400,150,150,25);
ch4 = new Checkbox("Division",cbg,false);
ch4.setBounds(550,150,150,25);
ch5 = new Checkbox("Clear",cbg,false);
ch5.setBounds(700,150,150,25);
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1);
add(ch2); add(ch3); add(ch4); add(ch5);
ch1.addItemListener(this); ch2.addItemListener(this);
ch3.addItemListener(this); ch4.addItemListener(this);
ch5.addItemListener(this);
}
67
public void itemStateChanged(ItemEvent ie)
{
if(ch1.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
l3.setVisible(true);
tf3.setVisible(true);
}
if(ch2.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}
68
if(ch3.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y;
tf3.setText(String.valueOf(z));
}
if(ch4.getState()==true)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y;
tf3.setText(String.valueOf(z));
}
if(ch5.getState()==true)
{
tf1.setText("");
}
}
}
tf2.setText("");
tf3.setText("");
69
ItemEvent Example in Choice Box
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Choicebox_Setnull.class" height=300 width=1000>
</applet>
*/
public class Choicebox_Setnull extends Applet implements ItemListener
{
TextField tf1,tf2,tf3;
Label l1,l2,l3;
Choice ch;
int x,y,z;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
setLayout(null);
l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25);
l2 = new Label("Enter the B Value");
l2.setBounds(0,50,100,25);
l3 = new Label("Compute the Two Numbers");
70
l3.setBounds(0,100,170,25);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
ch = new Choice();
ch.setBounds(100,150,150,25);
ch.add(""); ch.add("Addition"); ch.add("Subtraction");
ch.add("Multiplication"); ch.add("Division"); ch.add("Clear");
ch.add("Total No. of Item"); ch.add("Get Selected Item");
add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch);
ch.addItemListener(this);
}
71
public void itemStateChanged(ItemEvent ie)
{
if(ch.getSelectedIndex() == 1)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x + y;
tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 2)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x - y;
tf3.setText(String.valueOf(z));
}
72
}
if(ch.getSelectedIndex() == 3)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x * y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 4)
{
x = Integer.parseInt(tf1.getText());
y = Integer.parseInt(tf2.getText());
z = x / y; tf3.setText(String.valueOf(z));
}
if(ch.getSelectedIndex() == 5)
{
tf1.setText(""); tf2.setText(""); tf3.setText("");
}
if(ch.getSelectedIndex() == 6)
{
int a = ch.getItemCount(); tf3.setText(String.valueOf(a));
}
if(ch.getSelectedIndex() == 7)
{
tf3.setText(ch.getItem(ch.getSelectedIndex()));
73
}
}
The KeyEvent Class
1. A KeyEvent is generated when keyboard input occurs.
2. There are three types of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED and KEY_TYPED.
3. The first two events are generated when any key is pressed or released.
4. The last event occurs only when a character is generated.
5. Remember, not all key presses result in characters.
6. For example, pressing the SHIFT key does not generate a character.
7. There are many other integer constants that are defined by KeyEvent.
8. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII
equivalents of the numbers and letters. Here are some others:
VK_ENTER
VK_ESCAPE
VK_CANCEL
VK_UP
VK_DOWN
VK_LEFT
VK_RIGHT
VK_PAGE_DOWN
VK_PAGE_UP
VK_SHIFT
VK_ALT
VK_CONTROL
74
9. The VK constants specify virtual key codes and are independent of any modifiers,
such as control, shift, or alt. KeyEvent is a subclass of InputEvent.
10. Here are two of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
11. Here, src is a reference to the component that generated the event.
12. The type of the event is specified by type.
13. The system time at which the key was pressed is passed in when.
14. The modifiers argument indicates which modifiers where pressed when this key
event occurred.
15. The virutal key code, such as VK_UP, VK_A, and so forth, is passed in code.
16. The character equivalent is passed in ch. If no valid character exists, then ch
contains CHAR_UNDEFINED.
17. For KEY_TYPED events, code will contain VK_UNDEFINED.
18. The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar(), which returns the character that was entered, and getKeyCode(), which
returns the key code.
75
//the key event handles
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=Key_Event.class width=300 height=100>
</applet>
*/
public class Key_Event extends Applet implements KeyListener
{
String msg="";
int x=10,y=20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
KeyEvent Example in Keyboard
76
Their general forms are shown here:
char getKeyChar()
int getKeyCode()
If not valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When
a KEY_TYPED event occurs, getKeyCode() returns VK_UNDEFINED
The TextEvent Class
Instances 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 defines the integer
constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
77
import java.applet.*;
TextEvent Example in Textbox
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Text_Event.class" height=300 width=1000>
</applet>
*/
public class Text_Event extends Applet implements TextListener
{
TextField tf1,tf2,tf3;
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
tf1 = new TextField(10);
tf1.setBounds(200,0,100,25);
tf2 = new TextField(10);
tf2.setBounds(200,50,100,25);
tf3 = new TextField(10);
tf3.setBounds(200,100,100,25);
add(tf1);
add(tf2);
add(tf3);
tf1.addTextListener(this);
tf2.addTextListener(this);
}
public void textValueChanged(TextEvent te)
{
tf3.setText(tf1.getText());
78
}
}
The WindowEvent Class
There are ten types of window events. The WindowEvent class defines integer
constants that can be used to identify them. The constant and their meanings are shown
here:
WINDOW_ACTIVATED
- The window was activate
WINDOW_CLOSED
- The window has been closed
WINDOW_CLOSING
- The user requested that the window be closed
WINDOW_DEACTIVATED
- The window was deactivated.
WINDOW_DEICONIFIED
- The window was deiconified.
WINDOW_GAINED_FOCUS
- The window gained input focus.
WINDOW_ICONIFIED
- The window was iconified.
WINDOW_LOST_FOCUS
- The window lost input focus.
WINDOW_OPENED
- The window was opened.
79
WINDOW_STATE_CHANGED
- The state of the window changed.
WindowEvent is a subclass of ComponentEvent. It defines the following constructor.
WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is
type.
The most commonly used method in this class is getWindow(). It returns the Window
object that generated the event. Its general form is shown here:
Window getWindow()
80
Event Classes
Event Listener Interfaces
Event Listener Interfaces Methods
ActionEvent
ActionListener
void actionPerformed(ActionEvent ae)
AdjustmentEvent
AdjustmentListener
void adjustmentValueChanged(AdjustmentEvent ae)
ComponentEvent
ComponentListener
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(CommonentEvent ce)
ContainerEvent
ContainerListener
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainterEvent ce)
FocusEvent
FocusListener
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemEvent
ItemListener
void itemStateChanged(ItemEvent ie)
KeyEvent
KeyListener
Void keyPressed(KeyEvent ke)
Void keyReleased(KeyEvent ke)
Void KeyTyped(KeyEvent ke)
MouseEvent
MouseListener
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
MouseMotionListener
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
InputEvent
81
Event Classes
Event Listener Interfaces
Event Listener Interfaces Methods
MouseWheelEvent
MouseWheelListener
void mouseWheelMoved(MouseWheelEvent mwe)
TextEvent
TextListener
void textChanged(TextEvent te)
WindowEvent
WindowsListener
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
WindowFocusListener
Void windowGainedFocus(WindowEvent we)
Void windowLostFocus(WindowEvent we)
82
Sources of Events
Event Source
Description
Button
Generates action events when the button is pressed.
Checkbox
Generates item event s when the check box is selected or deselected.
Choice
Generates item event s when the choice is changed.
List
Generates action event s when an item is double – clicked; generates item
event when an item is selected or deselected.
Menu Item
Generates action event swhen a menu item is selected; generates item
events when a checkable menu item is selected or deselected.
Scrollbar
Generates adjustment event when the scroll bar is manipulated.
Text components
Generates text events when the user enters a character.
Window
Generated window events when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
83
The Collection Interface
1. The Collection interface is the foundation upon which the collections framework is
built.
2. It declares the core methods that all collections will have.
3. Several of these methods can throw an UnsupportedOperationException.
4. A ClassCastException is generated when one object is incompatible with another,
such as when an attempt is made to add an incompatible object to a collection.
84
85
5. Objects are added to a collection by calling add( ).
6. Notice that add( ) takes an argument of type Object.
7. Because Object is a superclass of all classes, any type of object may be stored in a collection.
8. However, primitive types may not.
9. For example, a collection cannot directly store values of type int, char, double, and so forth.
10. You can add the entire contents of one collection to another by calling addAll( ).
11. You can remove an object by using remove( ).
12. To remove a group of objects, call removeAll( ).
13. You can remove all elements except those of a specified group by calling retainAll( ).
14. To empty a collection, call clear( ).
15. You can determine whether a collection contains a specific object by calling contains( ).
16. To determine whether one collection contains all the members of another, call containsAll( ).
17. You can determine when a collection is empty by calling isEmpty( ).
18. The number of elements currently held in a collection can be determined by calling size( ).
19. The toArray( ) method returns an array that contains the elements stored in the invoking
collection.
20. This method is more important than it might at first seem.
21. Often, processing the contents of a collection by using array-like syntax is advantageous.
22. By providing a pathway between collections and arrays, you can have the best of both worlds.
23. Two collections can be compared for equality by calling equals( ).
24. The precise meaning of “equality” may differ from collection to collection.
25. For example, you can implement equals( ) so that it compares the values of elements stored in
the collection.
26. Alternatively, equals( ) can compare references to those elements.
27. One more very important method is iterator( ), which returns an iterator to a collection.
86
The List Interface
1. The List interface extends Collection and declares the behavior of a collection that
stores a sequence of elements.
2. Elements can be inserted or accessed by their position in the list, using a zero-based
index.
3. A list may contain duplicate elements.
4. Note
again
that
several
of
these
methods
will
throw
an
UnsupportedOperationException if the collection cannot be modified, and a
ClassCastException is generated when one object is incompatible with another,
such as when an attempt is made to add an incompatible object to a collection.
5. To the versions of add( ) and addAll( ) defined by Collection, List adds the methods
add(int, Object) and addAll(int, Collection).
6. These methods insert elements at the specified index.
7. Also, the semantics of add(Object) and addAll(Collection) defined by Collection
are changed by List so that they add elements to the end of the list.
8. To obtain the object stored at a specific location, call get( ) with the index of the
object.
9. To assign a value to an element in the list, call set( ), specifying the index of the
object to be changed.
10. To find the index of an object, use indexOf( ) or lastIndexOf( ).
87
88
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());
}
}
}
89
The Set Interface
1. The Set interface defines a set.
2. It extends Collection and declares the behavior of a collection that does not allow
duplicate elements.
3. Therefore, the add( ) method returns false if an attempt is made to add duplicate
elements to a set.
4. It does not define any additional methods of its own.
public class SetDemo
{
public static void main(String[] args)
{
// Set example with implement TreeSet
Set s=new TreeSet();
s.add("b");
s.add("a");
s.add("d");
s.add("c");
Iterator it=s.iterator();
while(it.hasNext())
{
String value=(String)it.next();
System.out.println("Value :"+value);
}
}
}
90
The SortedSet Interface
1. The SortedSet interface extends Set and declares the behavior of a set sorted in ascending
order.
2. In addition to those methods defined by Set, the SortedSet interface declares the methods.
3. Several methods throw a NoSuchElementException when no items are contained in the
invoking set.
4. A ClassCastException is thrown when an object is incompatible with the elements in a set.
5. A NullPointerException is thrown if an attempt is made to use a null object and null is not
allowed in the set.
6. SortedSet defines several methods that make set processing more convenient.
7. To obtain the first object in the set, call first( ).
8. To get the last element, use last( ).
9. You can obtain a subset of a sorted set by calling subSet( ), specifying the first and last object
in the set.
10. If you need the subset that starts with the first element in the set, use headSet( ). If you want
the subset that ends the set, use tailSet( ).
91
92
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetExample {
public static void main(String[] args) {
SortedSet<String> ss=new TreeSet<String>();
ss.add("a");
ss.add("e");
ss.add("g");
ss.add("b");
ss.add("c");
Iterator it=ss.iterator();
while(it.hasNext())
{
String value=(String)it.next();
System.out.println("Value :"+value);
}
}
}
93
COLLECTION CLASSES
94
Class
Description
AbstractCollection
Implements most of the Collection interface.
AbstractList
Extends AbstractCollection and implements most
of the List interface.
AbstractSequentialList
Extends AbstractList for use by a collection that
uses sequential rather than random access of its
elements.
LinkedList
Implements a linked list by extending
AbstractSequentialList.
ArrayList
Implements a dynamic array by extending
AbstractList.
AbstractSet
Extends AbstractCollection and implements most
of the Set interface.
HashSet
Extends AbstractSet for use with a hash table.
LinkedHashSet
Extends HashSet to allow insertion-order iterations.
TreeSet
Implements a set stored in a tree. Extends
95
1. The ArrayList class extends AbstractList and implements the List interface.
2. ArrayList supports dynamic arrays that can grow as needed.
3. In Java, standard arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements an
array will hold.
4. But, sometimes, you may not know until run time precisely how large of an array you
need.
5. To handle this situation, the collections framework defines ArrayList.
6. In essence, an ArrayList is a variable-length array of object references.
7. That is, an ArrayList can dynamically increase or decrease in size.
8. Array lists are created with an initial size. When this size is exceeded, the collection
is automatically enlarged.
9. When objects are removed, the array may be shrunk.
10. ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array
list that is initialized with the elements of the collection c. The third constructor builds an
array list that has the specified initial capacity. The capacity is the size of the underlying
array that is used to store the elements. The capacity grows automatically as elements
96
are added to an array list.
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
97
The LinkedList Class
1. The LinkedList class extends AbstractSequentialList and implements the List
interface.
2. It provides a linked-list data structure. It has the two constructors, shown here:
LinkedList( )
LinkedList(Collection c)
3. The first constructor builds an empty linked list.
4. The second constructor builds a linked list that is initialized with the elements of the
collection c.
5. In addition to the methods that it inherits, the LinkedList class defines some useful
methods of its own for manipulating and accessing lists.
6. To add elements to the start of the list, use addFirst( ); to add elements to the end,
use addLast( ).
7. Their signatures are shown here:
void addFirst(Object obj)
void addLast(Object obj)
Here, obj is the item being added. To obtain the first element, call getFirst( ). To retrieve
98
the last element, call getLast( ). Their signatures are shown here:
Object getFirst( )
Object getLast( )
To remove the first element, use removeFirst( ); to remove the last element, call
removeLast( ). They are shown here:
Object removeFirst( )
Object removeLast( )
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
99
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: “ + ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: “ + ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
100
The HashSet Class
1. HashSet extends AbstractSet and implements the Set interface.
2. It creates a collection that uses a hash table for storage.
3. As most readers likely know, a hash table stores information by using a mechanism
called hashing.
4. In hashing, the informational content of a key is used to determine a unique value,
called its hash code.
5. The hash code is then used as the index at which the data associated with the key is
stored.
6. The transformation of the key into its hash code is performed automatically—you
never see the hash code itself.
7. Also, your code can’t directly index the hash table.
8. The advantage of hashing is that it allows the execution time of basic operations,
such as add( ), contains( ), remove( ), and size( ), to remain constant even for
large sets.
9. The following constructors are defined:
HashSet( )
HashSet(Collection c)
HashSet(int capacity)
101
10. The first form constructs a default hash set.
11. The second form initializes the hash set by using the elements of c.
12. The third form initializes the capacity of the hash set to capacity.
import java.util.*;
public class CollectionTest
{
public static void main(String [] args)
{
System.out.println( "Collection Example!\n" );
int size;
// Create a collection
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
Iterator iterator;
//Adding data in the collection
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
//Create a iterator
iterator = collection.iterator();
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
102
// Get size of a collection
size = collection.size();
if (collection.isEmpty())
{
System.out.println("Collection is empty");
}
else
{
System.out.println( "Collection size: " + size);
}
System.out.println();
// Remove specific data
collection.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = collection.iterator();
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size: " + size + "\n");
//Collection empty
collection.clear();
size = collection.size();
if (collection.isEmpty())
{
System.out.println("Collection is empty");
}
else
{
System.out.println( "Collection size: " + size);
103
}
}
}
}
The LinkedHashSet Class
1. Java 2, version 1.4 adds the LinkedHashSet class.
2. This class extends HashSet, but adds no members of its own.
3. LinkedHashSet maintains a linked list of the entries in the set, in the order in which
they were inserted.
4. This allows insertion-order iteration over the set.
5. That is, when cycling through a LinkedHashSet using an iterator, the elements will
be returned in the order in which they were inserted.
6. This is also the order in which they are contained in the string returned by toString( )
when called on a LinkedHashSet object.
7. To see the effect of LinkedHashSet, try substituting LinkedHashSet For HashSet in
the preceding program.
8. The output will be
[B, A, D, E, C, F]
which is the order in which the elements were inserted.
104
import java.util.LinkedHashSet;
import java.util.Iterator;
public class HashSetDemo
{
public static void main(String[] args)
{
//create object of LinkedHashSet
LinkedHashSet lhashSet = new LinkedHashSet();
//add elements to LinkedHashSet object
lhashSet.add("1");
lhashSet.add("2");
lhashSet.add("3");
//get the Iterator
Iterator itr = lhashSet.iterator();
System.out.println("LinkedHashSet contains : ");
while(itr.hasNext())
System.out.println(itr.next());
}
}
105
The TreeSet Class
1. TreeSet provides an implementation of the Set interface that uses a tree for storage.
2. Objects are stored in sorted, ascending order.
3. Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
4. The following constructors are defined:
TreeSet( )
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet ss)
5. The first form constructs an empty tree set that will be sorted in ascending order
according to the natural order of its elements.
6. The second form builds a tree set that contains the elements of c.
7. The third form constructs an empty tree set that will be sorted according to the
comparator specified by comp.
8. The fourth form builds a tree set that contains the elements of ss.
106
import java.util.*;
public class TreeSetDemo
{
public static void main(String[] args)
{
System.out.println("Tree Set Example!\n");
TreeSet tree = new TreeSet();
tree.add("12");
tree.add("23");
tree.add("34");
tree.add("45");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
107
//Check impty or not
if (tree.isEmpty())
{
System.out.print("Tree Set is empty.");
}
else
{
System.out.println("Tree Set size: " + tree.size());
}
//Retrieve first data from tree set
System.out.println("First data: " + tree.first());
//Retrieve last data from tree set
System.out.println("Last data: " + tree.last());
if (tree.remove("23"))
{
System.out.println("Data is removed from tree set");
}
else
{
System.out.println("Data doesn't exist!");
}
108
System.out.print("Now the tree set contain: ");
iterator = tree.iterator();
//Displaying the Tree set data
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
System.out.println("Now the size of tree set: " + tree.size());
//Remove all
tree.clear();
if (tree.isEmpty())
{
System.out.print("Tree Set is empty.");
}
else
{
System.out.println("Tree Set size: " + tree.size());
}
}
}
109
Using an Iterator
1. Before you can access a collection through an iterator, you must obtain one.
2. Each of the collection classes provides an iterator( ) method that returns an iterator
to the start of the collection.
3. By using this iterator object, you can access each element in the collection, one
element at a time.
4. In general, to use an iterator to cycle through the contents of a collection, follow
these steps:
a.
b.
c.
Obtain an iterator to the start of the collection by calling the collection’s
iterator( ) method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long
as hasNext( ) returns true.
Within the loop, obtain each element by calling next( ).
110
111
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
112
System.out.println();
// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
113
Working with Maps
1. A map is an object that stores associations between keys and values, or key/value
pairs.
2. Given a key, you can find its value. Both keys and values are objects.
3. The keys must be unique, but the values may be duplicated.
4. Some maps can accept a null key and null values, others cannot.
The Map Interfaces
Interface
Map
Description
Maps unique keys to values.
Map.Entry
Describes an element (a
key/value pair) in a map.
This is an inner class of Map.
SortedMap
Extends Map so that the keys are
maintained in ascending order.
114
1.
2.
3.
4.
5.
The Map interface maps unique keys to values.
A key is an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object.
After the value is stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the
invoking map.
6. A ClassCastException is thrown when an object is incompatible with the elements
in a map.
7. A NullPointerException is thrown if an attempt is made to use a null object and null
is not allowed in the map.
8. An UnsupportedOperationException is thrown when an attempt is made to change
an unmodifiable map.
9. Maps revolve around two basic operations: get( ) and put( ).
10. To put a value into a map, use put( ), specifying the key and the value.
11. To obtain a value, call get( ), passing the key as an argument. The value is returned.
12. As mentioned earlier, maps are not collections because they do not implement the
Collection interface, but you can obtain a collection-view of a map.
13. To do this, you can use the entrySet( ) method.
14. It returns a Set that contains the elements in the map.
15. To obtain a collection-view of the keys, use keySet( ).
16. To get a collection-view of the values, use values( ).
17. Collection-views are the means by which maps are integrated into the collections
framework.
115
116
The SortedMap Interface
1.
2.
3.
4.
5.
The SortedMap interface extends Map.
It ensures that the entries are maintained in ascending key order.
Several methods throw a NoSuchElementException when no items are in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object when null is not
allowed in the map.
6. Sorted maps allow very efficient manipulations of submaps (in other words, a subset of a map).
7. To obtain a submap, use headMap( ), tailMap( ), or subMap( ).
8. To get the first key in the set, call firstKey( ). To get the last key, use lastKey( ).
117
import java.util.*;
public class SortedMapExample
{
public static void main(String[] args)
{
SortedMap map = new TreeMap();
// Add some elements:
map.put("2", "Two");
map.put("1", "One");
map.put("5", "Five");
map.put("4", "Four");
map.put("3", "Three");
// Display the lowest key:
System.out.println("The lowest key value is: " + map.firstKey());
// Display the highest key:
System.out.println("The highest key value is: " + map.lastKey());
// Display All key value
System.out.println("All key value is:\n" + map);
118
// Display the headMap:
System.out.println("The head map is:\n" + map.headMap("4"));
// Display the tailMap:
System.out.println("The tail map is:\n" + map.tailMap("4"));
// keySet method returns a Set view of the keys contained in this map.
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext())
{
Object key = iterator.next();
System.out.println("key : " + key + " value :" + map.get(key));
}
}
}
119
The Map Classes
Several classes provide implementations of the map interfaces. The classes that can be
used for maps are summarized here:
Class
Description
AbstractMap
Implements most of the Map interface.
HashMap
Extends AbstractMap to use a hash table.
TreeMap
Extends AbstractMap to use a tree.
WeakHashMap
Extends AbstractMap to use a hash table
with weak keys.
LinkedHashMap
Extends HashMap to allow insertion-order
iterations.
IdentityHashMap
Extends AbstractMap and uses reference
equality when comparing documents.
120
The HashMap Class
1. The HashMap class uses a hash table to implement the Map interface.
2. This allows the execution time of basic operations, such as get( ) and put( ), to
remain constant even for large sets.
3. The following constructors are defined:
HashMap( )
HashMap(Map m)
121
HashMap(int capacity)
1.
2.
3.
4.
5.
6.
7.
The first form constructs a default hash map.
The second form initializes the hash map by using the elements of m.
The third form initializes the capacity of the hash map to capacity.
HashMap implements Map and extends AbstractMap.
It does not add any methods of its own.
You should note that a hash map does not guarantee the order of its elements.
Therefore, the order in which elements are added to a hash map is not necessarily
the order in which they are read by an iterator.
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
122
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " + hm.get("John Doe"));
}
}
123
The TreeMap Class
1. The TreeMap class implements the Map interface by using a tree.
2. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and
allows rapid retrieval.
3. You should note that, unlike a hash map, a tree map guarantees that its elements will
be sorted in ascending key order. The following TreeMap constructors are defined:
TreeMap( )
TreeMap(Comparator comp)
TreeMap(Map m)
TreeMap(SortedMap sm)
4. The first form constructs an empty tree map that will be sorted by using the natural
order of its keys.
5. The second form constructs an empty tree-based map that will be sorted by using the
Comparator comp.
6. The third form initializes a tree map with the entries from m, which will be sorted by
using the natural order of the keys.
7. The fourth form initializes a tree map with the entries from sm, which will be sorted in
124
the same order as sm.
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
// Create a tree map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
125
// Display elements
while(i.hasNext())
{
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " + tm.get("John Doe"));
}
}
The LinkedHashMap Class
1. Java 2, version 1.4 adds the LinkedHashMap class.
2. This class extends HashMap.
3. LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were
inserted.
4. This allows insertion-order iteration over the map.
5. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they
were inserted.
126
6. You can also create a LinkedHashMap that returns its elements in the order in which they were last
accessed.
LinkedHashMap defines the following constructors.
LinkedHashMap( )
LinkedHashMap(Map m)
LinkedHashMap(int capacity)
The first form constructs a default LinkedHashMap. The second form initializes the
LinkedHashMap with the elements from m. The third form initializes the capacity.
import java.util.LinkedHashMap;
public class LinkedHashMapExample
{
public static void main(String[] args)
{
//create object of LinkedHashMap
LinkedHashMap lHashMap = new LinkedHashMap();
lHashMap.put("One", new Integer(1));
lHashMap.put("Two", new Integer(2));
//retrieve value using Object get(Object key) method of Java LinkedHashMap class
Object obj = lHashMap.get("One");
System.out.println(obj);
}
}
127
Comparators
1. Both TreeSet and TreeMap store elements in sorted order.
2. However, it is the comparator that defines precisely what “sorted order” means.
3. By default, these classes store their elements by using what Java refers to as
“natural ordering,” which is usually the ordering that you would expect. (A before B, 1
before 2, and so forth.)
4. If you want to order elements a different way, then specify a Comparator object
when you construct the set or map.
5. Doing so gives you the ability to govern precisely how elements are stored within
sorted collections and maps.
6. The Comparator interface defines two methods: compare( ) and equals( ).
7. The compare( ) method, shown here, compares two elements for order:
int compare(Object obj1, Object obj2)
8. obj1 and obj2 are the objects to be compared.
9. This method returns zero if the objects are equal.
10. It returns a positive value if obj1 is greater than obj2.
11. Otherwise, a negative value is returned.
12. The method can throw a ClassCastException if the types of the objects are not
compatible for comparison.
13. By overriding compare( ), you can alter the way that objects are ordered.
128 the
14. For example, to sort in reverse order, you can create a comparator that reverses
outcome of a comparison.
import java.util.*;
// A reverse comparator for strings.
class MyComp implements Comparator
{
public int compare(Object a, Object b)
{
String aStr, bStr;
aStr = (String) a;
bStr = (String) b;
// reverse the comparison
return bStr.compareTo(aStr);
}
}
class CompDemo
{
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet(new MyComp());
129
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
// Get an iterator
Iterator i = ts.iterator();
// Display elements
while(i.hasNext())
{
Object element = i.next();
System.out.print(element + " ");
}
System.out.println();
}
}
130
The Legacy Classes and Interfaces
The legacy classes defined by java.util are shown here:
Dictionary
Hashtable
Properties
Stack
Vector
Vector
1. Vector implements a dynamic array.
2. It is similar to ArrayList, but with two differences: Vector is synchronized, and it
contains many legacy methods that are not part of the collections framework.
3. With the release of Java 2, Vector was reengineered to extend AbstractList and
implement the List interface, so it now is fully compatible with collections.
4. Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
131
5. The first form creates a default vector, which has an initial size of 10.
6. The second form creates a vector whose initial capacity is specified by size.
7. The third form creates a vector whose initial capacity is specified by size and whose
increment is specified by incr.
8. The increment specifies the number of elements to allocate each time that a vector is
resized upward. The fourth form creates a vector that contains the elements of collection
c.
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
132
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " + v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());
if(v.contains(new Integer(10)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
133
Stack
1.
2.
3.
4.
5.
6.
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack.
Stack includes all the methods defined by Vector, and adds several of its own.
To put an object on the top of the stack, call push( ).
To remove and return the top element, call pop( ).
An EmptyStackException is thrown if you call pop( ) when the invoking stack is
empty. You can use peek( ) to return, but not remove, the top object.
7. The empty( ) method returns true if nothing is on the stack.
8. The search( ) method determines whether an object exists on the stack, and returns
the number of pops that are required to bring it to the top of the stack.
import java.util.*;
class StackDemo
{
static void showpush(Stack st, int a)
{
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st)
{
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
134
public static void main(String args[])
{
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try
{
showpop(st);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");
}
}
}
135
Dictionary
1. Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map.
2. Given a key and value, you can store the value in a Dictionary object.
3. Once the value is stored, you can retrieve it by using its key.
4. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.
5. To add a key and a value, use the put( ) method.
6. Use get( ) to retrieve the value of a given key.
7. The keys and values can each be returned as an Enumeration by the keys( ) and elements( )
methods, respectively.
8. The size( ) method returns the number of key/ value pairs stored in a dictionary.
9. isEmpty( ) returns true when the dictionary is empty.
10. You can use the remove( ) method to delete a key/value pair.
136
Hashtable
1. Hashtable was part of the original java.util and is a concrete implementation of a
Dictionary.
2. However, Java 2 reengineered Hashtable so that it also implements the Map
interface.
3. Thus, Hashtable is now integrated into the collections framework.
4. It is similar to HashMap, but is synchronized.
5. Like HashMap, Hashtable stores key/value pairs in a hash table.
6. When using a Hashtable, you specify an object that is used as a key, and the value
that you want linked to that key.
7. The key is then hashed, and the resulting hash code is used as the index at which
the value is stored within the table.
8. The Hashtable constructors are shown here:
Hashtable( )
Hashtable(int size)
Hashtable(Map m)
The first version is the default constructor. The second version creates a hash table that
has an initial size specified by size. The Third version creates a hash table that is
initialized with the elements in m. The capacity of the hash table is set to twice the
137
number of elements in m.
import java.util.*;
class HTDemo
{
public static void main(String args[])
{
Hashtable balance = new Hashtable();
Enumeration names;
String str;
double bal;
balance.put("John Doe", new Double(3434.34));
balance.put("Tom Smith", new Double(123.22));
balance.put("Jane Baker", new Double(1378.00));
balance.put("Todd Hall", new Double(99.22));
balance.put("Ralph Smith", new Double(-19.08));
// Show all balances in hash table.
names = balance.keys();
while(names.hasMoreElements())
{
str = (String) names.nextElement();
System.out.println(str + ": " + balance.get(str));
}
System.out.println();
// Deposit 1,000 into John Doe's account
bal = ((Double)balance.get("John Doe")).doubleValue();
balance.put("John Doe", new Double(bal+1000));
System.out.println("John Doe's new balance: " + balance.get("John Doe"));
138
}
}
One important point: like the map classes, Hashtable does not directly support iterators.
Thus, the preceding program uses an enumeration to display the contents of balance.
However, you can obtain set-views of the hash table, which permits the use of iterators.
// Use iterators with a Hashtable.
import java.util.*;
class HTDemo2
{
public static void main(String args[])
{
Hashtable balance = new Hashtable();
String str;
double bal;
balance.put("John Doe", new Double(3434.34));
balance.put("Tom Smith", new Double(123.22));
balance.put("Jane Baker", new Double(1378.00));
balance.put("Todd Hall", new Double(99.22));
balance.put("Ralph Smith", new Double(-19.08));
// show all balances in hashtable
Set set = balance.keySet(); // get set-view of keys
// get iterator
Iterator itr = set.iterator();
139
while(itr.hasNext())
{
str = (String) itr.next();
System.out.println(str + ": " + balance.get(str));
}
System.out.println();
// Deposit 1,000 into John Doe's account
bal = ((Double)balance.get("John Doe")).doubleValue();
balance.put("John Doe", new Double(bal+1000));
System.out.println("John Doe's new balance: " +
balance.get("John Doe"));
}
}
140
Properties
1. Properties is a subclass of Hashtable.
2. It is used to maintain lists of values in which the key is a String and the value is also
a String.
3. The Properties class is used by many other Java classes.
4. For example, it is the type of object returned by System.getProperties( ) when
obtaining environmental values.
5. Properties defines the following instance variable:
Properties defaults;
This variable holds a default property list associated with a Properties object.
Properties defines these constructors:
Properties( )
Properties(Properties propDefault)
The first version creates a Properties object that has no default values. The second
creates an object that uses propDefault for its default values. In both cases, the property
list is empty. In addition to the methods that Properties inherits from Hashtable,
Properties defines the various methods. Properties also contains one deprecated
method: save( ). This was replaced by store( ) because save( ) did not handle errors
141
correctly.
142
import java.util.*;
class PropDemo
{
public static void main(String args[])
{
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while(itr.hasNext())
{
str = (String) itr.next();
System.out.println("The capital of " + str + " is " +
capitals.getProperty(str) + ".");
}
System.out.println();
// look for state not in list -- specify default
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is " + str + ".");
}
}
143
APPLET CONTROLS
144
145