3.2 OOP in JAVA
3.2 OOP in JAVA
: 60
---------------------------------------------------------
-
Total
: 100
Course Objectives
1. Understand fundamentals of
programming such as variables, conditional
and iterative execution, methods, etc.
2. Understand fundamentals of object-
oriented programming in Java, including
defining classes, invoking methods, using
class libraries, etc.
3. Be able to use the Java SDK environment
to create, debug and run simple Java
programs.
Course Outcomes
At the end of this course Students will be able to:
1. Understand fundamentals and constructs of basic
Java Programming.
2. Understand and implement constructs of Object
Oriented Programming using Java
3. Understand and implement Multithreading and
Exception Handling in Java.
4. Understand and implement Java packages and
graphical constructs.
5. Understand and implement file handling and I/O
event handling.
Java - An Introduction
Java - The new programming language
from Sun Microsystems
Java -Allows anyone to publish a web
page with Java code in it
Java - CPU Independent language
Created for consumer electronics
Java - James , Arthur Van , and others
Oak -The predecessor of Java
Java is “C++ -- ++ “
Java is...
Simple and Powerful
Object Oriented
Portable
Architecture Neutral
Distributed
Multi-threaded
Robust, Secure/Safe
Interpreted
High Performance
Dynamic programming
language/platform.
Java as Object Oriented
“Objects all the way down”
Simple and Familiar: “C++ Lite”
No Pointers!
Garbage Collector
Dynamic Binding
Single Inheritance with “Interfaces”
Java as Portable
Unlike other language compilers, Java
complier generates code (byte codes) for
Universal Machine.
Java Virtual Machine (JVM): Interprets
bytecodes at runtime
Architecture Neutral
Higher Level Portable Features: AWT,
Unicode
Total Platform Independence
JAVA (translator)
COMPILER
JAVA INTERPRETER
(one for each different system)
Just in
Java
Time
Interpreter Java
Java Compiler
Java Bytecodes Virtual
Compiler move locally machine
or through
network Runtime System
Java
Bytecod Operating System
e
(.class )
Hardware
Java Development Kit
javac - The Java Compiler
java - The Java Interpreter
jdb- The Java Debugger
appletviewer -Tool to run the applets
<HTML>
<TITLE> Hello Worlds Applet </TITLE>
<APPLET code=“HelloWorld.class” width=500
height=500>
</APPLET>
</HTML>
Example
Example.java
Execution of Applets
2 4 5
1 3
APPLET hello.class Create Accessing The browser
Development Applet from creates
AT C-DAC’S a new
“hello.java” WEB tag in CRAY Corp.
HTML (USA) window and
AT SERVER
document a new thread
CDAC-India and
then runs the
code
Hello Java
<app=
“Hello”> The Internet
Hello
Rich Object Environment
Core Classes
language
Utilities
Input / Output
Low-Level Networking
Abstract Graphical User Interface
Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
Java versions
J2SE
J2EE
J2ME
J2SE
JDK 1.1.4 (Sparkler) September 12, 1997
JDK 1.1.5 (Pumpkin) December 3, 1997
JDK 1.1.6 (Abigail) April 24, 1998
JDK 1.1.7 (Brutus) September 28, 1998
JDK 1.1.8 (Chelsea) April 8, 1999
J2SE 1.2 (Playground) December 4, 1998
J2SE 1.2.1 (none) March 30, 1999
J2SE 1.2.2 (Cricket) July 8, 1999
J2SE 1.3 (Kestrel) May 8, 2000
J2SE 1.3.1 (Ladybird) May 17, 2001
J2SE 1.4.0 (Merlin) February 13, 2002
J2SE 1.4.1 (Hopper) September 16, 2002
J2SE 1.4.2 (Mantis) June 26, 2003
J2SE 5.0 (1.5.0) (Tiger) September 29, 2004
Java SE 6 (1.6.0) (Mustang) December 11, 2006
Java SE 7 (1.7.0) (Dolphin) anticipated for 2008
Main Packages
java.lang
java.util
java.io
java.awt
java.awt.image
java.applet
java.net
Java Constructs
What is Java, basic constructs, including
classes and objects
constructors,
this and super keywords,
inheritance,
abstract classes, interfaces,
inner classes,
exceptions.
Data Types
Eight basic types
4 integers (byte, short, int, short) [ int a; ]
2 floating point (float, double) [double a;]
1 character (char) [ char a; ]
1 boolean (boolean) [ boolean a; ]
Everything else is an object
String s;
Example
Example2.java
Java program structure
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Definitions
}
Editors used
DOS editor
Jcreator
Eclipse
Netbeans
Textpad
GNU editor
Emacs
Java tokens
Identifiers
Keywords
Literals
Operators
Separators
Keywords
Abstract boolean break byte byvalue*
Escape Meaning
\n New Line
\t Tab
\b Backspace
\r Carriage Return
\\ Back slash
\’ Single quote
\” Double quote
Separators
Separator Name
() Parenthesis
{} Curly Braces
[] Square brackets
; Semicolon
, Comma
. Dot/Period
Data types
Integer data type
Typ
Size Minimum Value Maximum Value
e
shor
Two bytes -32,768 32,767
t
Four
int -2,147,483,648 2,147,483,647
bytes
-
Real data types
Value Value
bytes
e bytes
Default values
Type of Default
variable value
boolean False
byte zero : 0
short zero : 0
int zero : 0
long zero : 0L
float 0.0f
double 0.0d
From To
float double
Free form language
System.out.println(“Welcome to Java”);
Can also be written as,
System.out.println
(“Welcome to Java”);
Or even as,
System.
out
.
println(“Welcome to Java”);
Decision making
statements
if
if-else
Nested if-else
else-if ladder
switch-case
Loop statements
for loop
while loop
do-while loop
Nested loops
Example
BlockTest.java
break statement
Jumping out of switch-case.
Breaking loop statements
Specialized form of goto
break as goto
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t)
break second;
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
continue statement
It is useful to force the early iteration of
the loop.
When we want to continue the next
iteration of the loop by skipping some
part inside it, the ‘continue’ statement
can be used. It is also associated with the
condition
Example
ContinueLabel.java
Class definition
class class-name
{
data-type instance-variable1;
data-type instance-variable2;
- - - - -;
data-type instance-variableN;
data-type method-name1(parameter-list)
{
//body of the method1
}
data-type method-name2(parameter-list)
{
//body of the method2
}
- - - - -;
data-type method-nameN(parameter-list)
{
//body of the methodN
}
}
Example: class
class Country
{
long population;
float currencyRate;
int noOfStates;
}
Creating objects
Country japan; // declaration
Or (combined)
System.out.println(“Population:”+population);
System.out.println(“No of
states:”+noOfStates);
}
}
Constructor overloading
class Box
{
int height, depth, length;
Box() {
height = depth = length = 10;
}
Box(int x,int y) {
height = x; depth = y;
}
Box(int x, int y, int z) {
height = x; depth = y; length = z;
}
}
Example
BoxDemo7.java
The ‘this’ keyword
Used to refer the instance variables and
methods of the same class where it is
used.
Used to call a constructor from another
constructor.
The ‘this’ keyword
class Box
{
int height;
int depth;
int length;
Box(int height, int depth, int length)
{
this.height = height;
this.depth = depth;
this.length = length;
}
}
Examples
This-Example1.txt
This-Example with
Constructor.txt
Method overloading
It is possible to define two or more
methods within the same class that are
having the same name, but their
parameter declarations are different.
In the case, the methods are said to be
overloaded, and the process is referred to
as method overloading.
Method overloading is one of the ways of
Java implementation of polymorphism.
Example
int add(int z) //version1
{
cal = z + 10;
return(cal);
}
float add(float x, float y) //version2
{
val = x + y;
return(val);
}
Example
Overload.java
Overload1.java
Static members
In some cases it is necessary to define
a member that is common to all the
objects and accessed without using a
particular object.
That is, the member belongs to the
class as a whole rather than the
objects created from the class. Such
members can be created by preceding
them with the keyword static.
Example: static
static int cal;
static float min = 1;
static void display(int x)
‘static’ restrictions
Restrictions over static methods
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any
way.
Example: static
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Calling methods
Call by value
Call by reference
Call by Value & reference
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " +
ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " +
ob.b);
}
Recursion
int fact(int n)
{
if(n==1)
return 1; //statement1
else
return(n*fact(n-1));
}
Nested classes
It is possible to define a class within
another class; such classes are known as
nested classes.
The scope of a nested class is bounded
by the scope of its enclosing class.
Types-
Static
Non-static
Static nested class
A static nested class is one which has the
static modifier applied.
Because it is static, it must access the
members of its enclosing class through
an object.
That is, it cannot refer to members of its
enclosing class directly.
Because of this restriction, static nested
classes are rarely used.
Non-static nested class
An inner class is a non-static nested
class.
It has access to all of the variables and
methods of its outer class and may refer
to them directly in the same way that
other non-static members of the outer
class do.
Thus, an inner class is fully within the
scope of its enclosing class.
Example
InnerClassDemo.java
Inheritance
The reusability can be obtained by creating
new classes and reusing the properties of
the existing one.
The mechanism of deriving a new class from
existing one is called as inheritance. The old
class or existing class is known as super
class and new class is known as subclass.
Thus, a subclass is specialized version of
super class. We can call super class as base
class or parent class and subclass as derived
class or child class.
Inheritance types
Single Inheritance (only one super and subclass)
Hierarchical Inheritance (one super class with
many subclasses)
Multilevel Inheritance (subclass is super class of
another class)
Hybrid Inheritance (combination of above three
types)
Creating inheritance
class subclassname extends
superclassname
{
//Body of the class;
}
Example
class Super
{
int i, j;
void show()
{
System.out.print("i and j: ");
System.out.println( + i + " " + j);
}
}
class Sub extends Super
{
int k;
void display()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
Example
SimpleInheritance.java
The ‘super’ keyword
The keyword ‘super’ has specially been
added for inheritance.
Whenever the subclass needs to refer to
its immediate super class, ‘super’
keyword is used. There are two different
applications of the ‘super’. That are,
Accessing members from super class that has
been hidden by members of the subclass
Calling super class constructor
Example
DemoSuper.java
UseSuper.java
Multilevel hierarchy
class A
{
…….
…….
…….
}
class B extends A
{
…….
…….
…….
}
class C extends B
{
…….
…….
…….
}
Sequence of constructor
call
class GrandFather class Child extends Father
{ {
GrandFather() Child()
{ {
System.out.println("This is GrandFather");
System.out.println("This is
} Child");
}
}
class Father extends GrandFather
}
{
class CallConstructor
Father()
{ {
System.out.println("This is Father"); public static void main(String
} args[])
} {
Child roger = new Child();
}
}
Method overriding
A method in a subclass has the same
name and type signature as a method in
its superclass.
Compiler will always refer to the version
of that method defined by the subclass.
Example
Override.java
Override1.java
Dynamic method dispatch
Method overriding forms the basis for one
of Java’s most powerful concepts:
dynamic method dispatch.
Dynamic method dispatch is the
mechanism by which a call to an
overridden method is resolved at run
time, rather than compile time.
Dynamic method dispatch is important
because this is the only way in which Java
implements run-time polymorphism.
Example
Dispatch.java
Abstract class
In some situations, it may be required to define
a super class that declares the structure of a
given abstraction without providing a complete
implementation of every method.
That is, sometimes we may want to create a
super class that only defines a generalized form
that will be shared by all of its subclasses by
leaving it to each subclass to fill in the details.
Such a class determines the nature of the
methods that the subclasses must implement.
This can be done by creating a class as an
abstract.
Abstract class and
methods
abstract datatype
methodname(parameters);
Allocate space
• a = new int [7];
• c = new int [7][11];
Arrays have length
used to retrieve the size of an array
• int a [ ] = new int [7]; // 1-dim
System.out.println(a.length); will print
‘7’
java.util.Vector v = new
java.util.Vector(10);
Creating package
Include a package command as the first
statement in a Java source file.
Then any classes declared within that file
will automatically belong to the specified
package.
The package statement defines a name
space in which classes are stored. If we
omit the package statement, the class
names are put into the default package,
which has no name.
Package statement
package pkg;
package myPackage;
public class MyClass
{
//body of the class
}
Package hierarchy
We can create a hierarchy of packages
also. For this, we have to separate each
package name from the one above it by
use of a dot operator.
The general form of a multileveled
package statement is shown here:
package pkg1[.pkg2[.pkg3]];
System.out.println("Population:"+pop);
}
}
Executing the program
Save this file with name SimplePack.java, and
put it in a directory called myPack. Next,
compile the file. This can be compiled by
following command:
javac myPack\SimplePack.java
java myPack.SimplePack
Visibility control
Same package no
No Yes Yes Yes
subclass
Different package
No No Yes Yes
subclass
Different package no
No No No Yes
subclass
Example
Packages.txt
Hiding classes
package myPack;
public class A
{
//body of A
}
class B
{
//body of B
}
Static import
import static java.lang.Math.sqrt;
import static java.lang.Character.isUpperCase;
import static java.lang.System.out;
class StaticImport
{
public static void main(String args[])
{
double x = sqrt(52); //method1
out.print("Square root of 52: ");
out.println(x); //method2
char ch = 'D';
if(isUpperCase(ch)) //method3
out.println(ch+" is uppercase");
}
}
interface
Interface is Java’s abstract class
implementation. They can not be
instantiated.
That is, using interface, we can specify what
a class must do, but not how it does it.
Interfaces are syntactically similar to
classes, but they do not have instance
variables, and their methods are declared
without having any body.
This means that we can define interfaces
which don’t make assumptions about how
they are implemented.
interface
Once the interface is defined, any number of
classes can implement an interface. Also,
one class can implement any number of
interfaces.
To implement an interface, a class must
create the complete set of methods defined
by the interface. However, each class can
define the methods with different
definitions.
By providing the interface keyword, Java
allows us to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Interfaces are designed to support dynamic
Defining an interface
access interface InterfaceName
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
.......
data-type final-varname1 = value;
data-type final-varname2 = value;
.......
return-type method-nameN(parameter-list);
data-type final-varnameN = value;
}
Example
interface College
{
int studs = 120;
void play();
int countUp(int x);
}
Implementing an interface
access class ClassName [extends
superclass]
[implements interface
[,interface...]]
{
// class-body
}
Example
class Sitrc implements College
{
public void play( )
{
System.out.println(“Let’s play !!!”);
}
public int countUp(int x)
{
x++;
return(x);
}
}
Implementation
interface Mango class MyInterface
{ {
void display( ); public static void main(String args[ ])
{
}
Mango m = new Summer( ); //statement
class Summer implements Mango Winter n = new Winter( );
{ m.display( );
public void display( ) m = n; //assigning the reference
{ m.display( );
System.out.println("First Display method... }
"); }
}
}
class Winter implements Mango
{
public void display( )
{
System.out.println("Second Display
method...");
}
}
Partial implementation
error
interface Mango
{
void display();
void show();
}
class Summer implements Mango
{
public void display()
{
System.out.println("Display method");
}
}
Example
TestIface2.java
Partial-interface.txt
Implementing multiple inheritance
Nesting of interfaces
class CPU
{
public interface MicroProcessor
{
boolean isMultiCore(int core);
}
}
class Computer implements CPU.MicroProcessor
{
public boolean isMultiCore(int core)
{
if(core>1)
return true;
else
return false;
}
}
Interface variables
interface Constants
{
double PI = 3.14;
String unit = " sq.cm";
}
interface Values
{
int cir = 2;
}
public class InterfaceVar implements Constants
{
public static void main(String args[])
{
double rad = 5.83;
System.out.print("Area of circle: ");
System.out.println(PI * rad * rad + unit);
System.out.print("Perimeter of circle: ");
System.out.println(Values.cir*PI*rad);
}
}
Interface inheritance
interface SEIT
{
int strength = 74;
void displaySecond();
}
interface TEIT extends SEIT
{
int strength = 66;
void displayThird();
void displayAll();
}
class InfoTech implements TEIT
{
int total;
Example
IFExtend.java
Interface versus abstract class
Methods of a Java interface are implicitly abstract and cannot
have implementations. A Java abstract class can have instance
methods that implements a default behavior.
Variables declared in a Java interface is by default final. An
abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java
abstract class can have the usual flavors of class members like
private, protected, etc..
Java interface should be implemented using keyword
“implements”; A Java abstract class should be extended using
keyword “extends”.
An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java
interfaces.
A Java class can implement multiple interfaces but it can extend
only one abstract class.
Interface is absolutely abstract and cannot be instantiated; A
Java abstract class also cannot be instantiated, but can be
invoked if a main() exists.
Multithreading
Java thread model
Java thread states
Newborn state
Runnable state
Running state
Blocked state
Dead state
The Thread class methods
Method Meaning
running
time
The main thread
All the Java programs are at least single
threaded programs.
When a Java program starts up, one thread
begins running immediately. This is usually
called the main thread of the program, because
it is the one that is executed when our program
begins.
The main thread is important for two reasons:
It is the thread from which other “child” threads can be
initiated
Generally it must be the last thread to finish execution
because it performs various shutdown actions.
Using main thread
class CurrentThread
{
public static void main(String args[]) throws
InterruptedException
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// changing the name of the thread
t.setName("Prime Thread");
System.out.println("After name change: " + t);
Thread.sleep(3000);
System.out.println("End of main thread & Program");
}
}
Creation of thread in Java
Implementing Runnable interface
Extending the Thread class
Example
ThreadDemo.java
ExtendThread.java
Implementing Runnable interface
void start( )
NORM_PRIORITY
MAX_PRIORITY
MIN_PRIORITY
Thread synchronization
Needed for execution of multiple threads.
Two ways-
synchronized methods
synchronized blocks
MultiThreadDemo.java
Applets
The Applet
The Applet skeleton
import java.awt.*; public void stop( )
import java.applet.*; {
public class MyApplet extends // suspends
Applet execution
{ }
public void init( ) public void destroy( )
{ {
// initializes // perform
applet shutdown activities
} }
public void start( ) public void paint (Graphics g)
{ {
// start or // redisplay
resume execution contents of window
} }
}
The Applet method calls
Life cycle of applet
Life cycle of applet
init: This method is intended for whatever initialization is
needed for your applet.
start: This method is automatically called after the browser calls
the init method. It is also called whenever the user returns to the
page containing the applet after having gone off to other pages.
stop: This method is automatically called when the user moves
off the page on which the applet sits. It can, therefore, be called
repeatedly in the same applet.
destroy: This method is only called when the browser shuts
down normally. Because applets are meant to live on an HTML
page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also
any time the applet needs to repaint itself in the browser. The
paint() method is actually inherited from the java.awt.
A simple applet
import java.awt.*;
import java.applet.*;
/*
<applet code = "HelloApplet" width = 200 height = 100>
</applet>
*/
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello",100,50);
}
}
Colors
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
Label( )
Label(String str)
Label(String str, int how)
Button
A push button is a component that
contains a label and that generates an
event when it is pressed. Push buttons
are objects of type Button. Button defines
these two constructors:
Button( )
Button(String str)
CheckBox
A check box is a control that is used to turn an
option on or off. It consists of a small box that
can either contain a check mark or not. There is
a label associated with each check box that
describes what option the box represents.
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup
cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean
on)
CheckboxGroup
It is possible to create a set of mutually
exclusive check boxes in which one and
only one check box in the group can be
checked at any one time.
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox wh)
Dimension class
This class encapsulates the ‘width’
and ‘height’ of a component (in
integer precision) in a single object.
The class is associated with certain
properties of components. Several
methods defined by the Component class
and the LayoutManager interface return a
Dimension object.
Choice
The Choice class is used to create a pop-
up list of items from which the user may
choose.
Thus, a Choice control is a form of menu.
When inactive, a Choice component takes
up only enough space to show the
currently selected item.
Choice methods
int getItemCount( )
void select(int index)
void select(String name)
String getSelectedItem( )
int getSelectedIndex( )
void add(String name)
String getItem(int index)
List
The List class provides a compact,
multiple-choice, scrolling selection list.
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
void add(String name)
void add(String name, int index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
Scrollbar
Scroll bars are used to select continuous
values between a specified minimum and
maximum. Scroll bars may be oriented
horizontally or vertically.
A scroll bar is actually a composite of
several individual parts. Each end has an
arrow that we can click to move the
current value of the scroll bar one unit in
the direction of the arrow
Scrollbar methods
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int iValue, int tSize, int min, int
max)
void setValues(int iValue, int tSize, int min, int
max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)
TextComponent
TextComponent
TextArea TextField
TextField
The TextField class implements a single-
line text-entry area, usually called an edit
control.
Text fields allow the user to enter strings
and to edit the text using the arrow keys,
cut and paste keys, and mouse selections
Constructor and methods
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
String getText( )
void setText(String str)
String getSelectedText( )
void select(int startIndex, int endIndex)
boolean isEditable( )
void setEditable(boolean canEdit)
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
TextArea
Sometimes a single line of text input is
not enough for a given task.
To handle these situations, the AWT
includes a simple multiline editor called
TextArea.
TextArea
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int
sBars)
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
void append(String str)
void insert(String str, int index)
LayoutManager
A layout manager is an instance of any
class that implements the
LayoutManager interface.
The layout manager is set by the
setLayout( ) method. If no call to
setLayout( ) is made, then the default
layout manager is used.
Whenever a container is resized (or sized
for the first time), the layout manager is
used to position each of the components
within it.
LayoutManager
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
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.
BorderLayout
BorderLayout( )
BorderLayout(int horz, int vert)
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
void add(Component compObj, Object
region);
Insets
Sometimes we want to leave a small
amount of space between the container
that holds our components and the
window that contains it.
For doing this, we have to override the
getInsets( ) method that is defined by
Container.
Insets
Insets(int top, int left, int bottom, int
right)
Insets getInsets( )
Example:
public Insets getInsets()
{
return new Insets(10, 10, 10, 10);
}
GridLayout
GridLayout lays out components in a two-
dimensional grid. When we instantiate a
GridLayout, we define the number of
rows and columns.
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int
horz, int vert)
Menus
A top-level window can have a menu bar
associated with it.
A menu bar displays a list of top-level
menu choices.
Each choice is associated with a drop-
down menu. This concept is implemented
in Java by the following classes:
MenuBar, Menu, and MenuItem.
Creating menus on Frame
Create Add
Menu
Menubar MenuItems to
Objects
Object Menu
Add Menubar
to Applet
Menu
Menu( )
Menu(String optionName)
Menu(String optionName, boolean
removable)
MenuItem
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName,
MenuShortcut keyAccel)
Method of Menubar-
Menu add(Menu menu)
Delegation Event Model
Event
In the delegation model, 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 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.
Event Source
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.
Object getSource( )
Event Objects
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT
events that are handled by the
delegation event model.
Events
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
MouseEvent
MouseWheelEvent
TextEvent
WindowEvent
Events
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 manipulated.
ComponentEvent- Generated when a
component is hidden, moved, resized, or
becomes visible.
Events
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
Events
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.
WindowEvent- Generated when a window is
activated, closed, deactivated, deiconified,
iconified, opened, or quit.
ActionEvent
An ActionEvent is generated when a
button is pressed, a list item is double-
clicked, or a menu item is selected.
String getActionCommand( )
AdjustmentEvent
An AdjustmentEvent is generated by a
scroll bar. There are five types of
adjustment events.
The AdjustmentEvent class defines
integer constants that can be used to
identify them. The constants and their
meanings are shown here:
AdjustmentEvent
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
int getValue( )
ComponentEvent
A ComponentEvent is generated when the
size, position, or visibility of a component
is changed. There are four types of
component events.
ComponentEvent
InputEvent
KeyEvent MouseEvent
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:
int getStateChange( )
KeyEvent
A KeyEvent is generated when keyboard
input occurs.
There are three types of key events,
which are identified by these integer
constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED.
The first two events are generated when
any key is pressed or released. The last
event occurs only when a character is
generated.
KeyEvents
KeyEvent constants:
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
char getKeyChar( )
int getKeyCode( )
MouseEvent
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.
MouseEvent
int getX( )
int getY( )
Point getPoint( )
void translatePoint(int x, int y)
int getClickCount( )
Event Listeners
The delegation event model has two
parts: sources and listeners.
Listeners are created by implementing
one or more of the interfaces defined by
the java.awt.event package.
When an event occurs, the event source
invokes the appropriate method defined
by the listener and provides an event
object as its argument.
Listener Interfaces
ActionListener Interface
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
void
adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Interface
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
Listener Interfaces
ItemListener Interface
void itemStateChanged(ItemEvent ie)
KeyListener Interface
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Interface
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Listener interfaces
MouseMotionListener Interface
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
TextListener Interface
void textChanged(TextEvent te)
Examples
MouseEvents.java
SimpleKey.java
ButtonDemo.java
References
Herbert Schildt, “The Complete
Reference: Java”, 5th Edition, Tata McGraw
Hill.