Events and Applet AWT & Swing Generics Collections

Java Programming II – Review
Events and Applet
AWT & Swing
Generics
Collections
How to use Eclipse
Java Programming II
1
Contents
 Events
and Applet
 AWT and Swing
 Generics
 Collection
Java Programming II
2
Event Class Hierarchy
Object
EventObject
AWTEvent
ActionEvent
FocusEvent
ComponentEvent
InputEvent
KeyEvent
ItemEvent
TextEvent
WindowEvent
MouseEvent
Java Programming II
3
Event Handling (Old Model)

Using the action method. It needs some code to identify
an event source and to do action for the event.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public void paint(Graphics g) {
g.drawString(message, 20, 70);
}
/*
<APPLET CODE=EventHandlingOld.class
WIDTH=400 HEIGHT=200>
</APPLET>
*/
public class EventHandlingOld extends Applet {
String message = "";
Button button1 = new Button("Label Set"),
button2 = new Button("OK");
public void init() {
add(button1);
add(button2);
}
/* Old Model for Event Handling */
public boolean action (Event e, Object arg) {
if ( e.target instanceof Button ) {
if(e.target.equals(button1))
message = "Label Set Button Clicked!";
else if(e.target.equals(button2))
message = "OK Button Clicked!";
repaint();
}
return true;
}
/* end of code for event handling */
} // End of the EventHandlingOld Class
Java Programming II
4
The Delegation Event Model



The model provides a standard
mechanism for a source to
generate an event and send it to
a set of listeners
A source generates events.
Three responsibilities of a
Source
source:



To provide methods that allow
listeners to register and unregister
for notifications about a specific type
of event
To generate the event
To send the event to all registered
listeners.
Java Programming II
Listener
container
events
Listener
Listener
5
MouseListener (Low-Level Listener)
import java.awt.*;
import java.awt.event.*;

The MouseListener
interface defines the
methods to receive mouse
events.





class MLF extends Frame implements MouseListener {
MLF()
{
super("Example: MouseListener");
addMouseListener(this);
setSize(250,100);
}
public void mouseClicked(MouseEvent me) {
}
mouseClicked(MouseEvent me)
mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
A listener must register to
receive mouse events
public void mouseReleased(MouseEvent me) {
System.out.println(me);
}
public static void main(String[] args) {
new MLF().setVisible(true);
}
}
Mouse click
MouseEvent
Java Programming II
6
Semantic Event Listener

The semantic events relate to operations on the components in the
GUI. There are three semantic event classes: ActionEvent,
ItemEvent, and AdjustmentEvent.

An ActionEvent is generated when there was an action performed on a
component such as clicking on a menu item or a button.
―

An ItemEvent occurs when a component is selected or deselected.
―

Produced by Objects of Type: Buttons, Menus
An AdjustmentEvent is produced when an adjustable object, such as a scrollbar,
is adjusted.
―

Produced by Objects of Type: Buttons, Menus, Text
Produced by Objects of Type: Scrollbar
Semantic Event Listeners



Listener Interface: ActionListener, Method: void actionPerformed(ActionEvent e)
Listener Interface: ItemListener, Method: void itemStateChanged (ItemEvent e)
Listener Interface: AdjustmentListener, Method: void adjustmentValueChanged
(AdjustmentEvent e)
Java Programming II
7
Using the ActionListener

Stages for Event Handling by ActionListener
 First, import event class
import java.awt.event.*;
Button Click
Event
 Define an overriding class of event type (implements
ActionListener)
①
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Write what to be done. . .
label.setText(“Hello World!”);
}
}
 Create an event listener object
ButtonListener
action
addActionListener
②
ButtonListener bt = new ButtonListener();
 Register the event listener object
b1 = new Button(“Show”);
b1.addActionListener(bt);
Java Programming II
8
A Hello Example Using Button Listener
import java.awt.*;
import java.awt.event.*;
public class HelloAWT extends Frame {
Label contents;
Button dispbutton;
// Using Frame
public HelloAWT() { // Constructor
setLayout(new FlowLayout(FlowLayout.CENTER, 50, 50));
contents = new Label("
"); // Create Label object
add(contents); // Add the label to this Frame
dispbutton = new Button("Show"); // Create Button object
dispbutton.addActionListener(new DispButtonListener()); // Add Event Listener
add(dispbutton); // Add the button object to this Frame
}
class DispButtonListener implements ActionListener { // Event Listener
public void actionPerformed(ActionEvent e) { // What to do when the button is
clicked
contents.setText("Hello World!");
}
}
public static void main (String[] args) {
HelloAWT f = new HelloAWT(); // Create Hello GUI
f.setTitle("Hello!");
f.setSize(400,150);
f.setVisible(true);
}
} // end of “HelloAWT.java”
Java Programming II
Run:
Java HelloAWT
9
Using Images
import java.applet.*;
import java.awt.*;
/*
<applet code="DrawImage" width=280 height=280>
<param name="file" value="kids2.jpg">
</applet>
*/
 getImage() Methods
public class DrawImage extends Applet {
Image image;
Image getImage(URL url)
Image getImage(URL base, String fileName)
public void init() {
image = getImage(getDocumentBase(),
getParameter("file"));
}
 drawImage() Methods
abstract boolean drawImage(Image img, int x, int y, I
mageObserver io)
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
Java Programming II
10
Using Threads
update() and repaint() Methods
repaint() : request an update of the applet
display
update() : clears the applet display with the
background color and then invokes the paint()
method
public class Counter extends Applet
implements Runnable {
int counter;
Thread t;
public void run() {
try {
while(true) {
// Request a repaint
repaint();
//Sleep before displaying next count
Thread.sleep(1000);
//Increment counter
++counter;
}
}
catch(Exception e) { }
}
public void paint(Graphics g) {
// Set Font
g.setFont(new Font("Serif", Font.BOLD, 36));
public void init() {
// Initialize counter
counter = 0;
}
// Get font metrics
FontMetrics fm = g.getFontMetrics();
// Start thread
t = new Thread(this);
t.start();
}
}
// Display counter
String str = "" + counter;
Dimension d = getSize();
int x = d.width / 2 - fm.stringWidth(str) / 2;
g.drawString(str, x, d.height / 2);
Java Programming II
11
Double Buffering (No Double Buffering)
Double Buffering can be used to avoid display “flicker” in applets.
import java.applet.*;
import java.awt.*;
/*
<applet code="NoDoubleBuffer" width=300
height=100>
</applet>
*/
// Request a repaint
repaint();
//Sleep before update
Thread.sleep(100);
public class NoDoubleBuffer extends Applet
implements Runnable {
int x = 0;
Thread t;
}
public void paint(Graphics g) {
public void init() {
}
// Draw filled circle
Dimension d = getSize();
g.fillOval(x, d.height / 4, 50, 50);
// Start thread
t = new Thread(this);
t.start();
public void run() {
try {
while(true) {
}
}
catch(Exception e) {
}
}
}
// Increment x
x += 5;
if (x + 50 > d.width)
x = 0;
Java Programming II
12
Double Buffering (With Double Buffering)
import java.applet.*;
import java.awt.*;
/*
<applet code="DoubleBuffer" width=300 height=100>
</applet>
*/
}
public class DoubleBuffer extends Applet
implements Runnable {
int x = 0;
Thread t;
Image buffer;
Graphics bufferg;
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
public void init() {
//Get graphics object for buffer
if (bufferg == null)
bufferg = buffer.getGraphics();
// Start thread
t = new Thread(this);
t.start();
}
// Sleep before update
Thread.sleep(100);
}
}
catch(Exception e) {
}
//Draw to buffer
Dimension d = getSize();
bufferg.setColor(Color.white);
bufferg.fillRect(0, 0, d.width, d.height);
bufferg.setColor(Color.black);
bufferg.fillOval(x, d.height / 4, 50, 50);
// Create buffer
Dimension d = getSize();
buffer = createImage(d.width, d.height);
public void run() {
try {
while(true) {
//Update screen
g.drawImage(buffer, 0, 0, this);
//Request a repaint
repaint();
}
}
//Increment x
x += 5;
if (x + 50 > d.width)
x = 0;
Java Programming II
13
Swing Components (Java Look and Feel)
JButton
JCheckBox
JList
JComboBox
JSlider
JRadioButton
JMenu
JSpinner
JTextField
Java Programming
JPasswordField
14
Button


A Button is a component
that simulates the
appearance of a push
button
When the user presses
the mouse inside a button
an ActionEvent is
generated
import java.awt.*;
import java.awt.event.*;
class BTN extends Frame {
BTN()
{
super("Example: Button");
final Button b = new Button("Press me!");
Anonymous
Class
b.addActionListener(new ActionListener() {
// the event handler
public void actionPerformed(ActionEvent ae) {
b.setLabel("Thank you!");
}
});
add(b);
setSize(200,100);
}
public static void main(String[] args)
{
new BTN().setVisible(true);
}
}
Mouse click
ActionEvent
Java Programming
15
Panel
Panel is the simplest
container class
 A panel provides
space in which an
application can attach
any other component,
including other panels
 The default layout
manager for a panel
is the FlowLayout
manager

import java.awt.*;
import java.awt.event.*;
class PNL extends Frame {
PNL()
{
super("Example: Panel");
final Panel p = new Panel();
p.add(new Button("1"));
p.add(new Button("2"));
p.add(new Button("3"));
add(p);
setSize(250,100);
}
public static void main(String[] args)
{
new PNL().setVisible(true);
}
}
Java Programming
16
Creating New Window Frame
public static void main (String args[]) {
CreatNewFrame f = new CreatNewFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{System.exit(0);}
});
// Dialog Box
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreatNewFrame extends JFrame
{
JLabel client_title;
JButton create_button;
f.setTitle("Create New Frame");
f.setSize(200,150);
f.setVisible(true);
}
} // end of CreatNewFrame
public CreatNewFrame() {
class NewFrame extends JFrame {
JLabel label;
getContentPane().setLayout(new GridLayout(1,0));
create_button = new JButton("Create");
create_button.addActionListener(new ButtonListener());
getContentPane().add(create_button);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
NewFrame nf = new NewFrame();
nf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
}
public NewFrame() {
getContentPane().setLayout(new FlowLayout());
label = new JLabel("Another New Frame");
getContentPane().add(label);
} // NewFrame constructor
} // end of NewFrame class
nf.setTitle("New Window Frame");
nf.setSize(200,150);
nf.setVisible(true);
}
Button clicked
Java Programming
17
Dialogs



A dialog is a special window to
convey a message or provides
a special function
Every dialog is dependent on a
frame – when that frame is
destroyed, so are its
dependent dialogs
A modal dialog blocks user
input to all other windows in
the program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DLG extends JFrame {
DLG()
{
super("Example: Swing Dialog");
final JFrame jf = this;
final JButton jb = new JButton("Show a message
dialog!");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(jf,"This is a
simple message dialog");
}
});
add(jb);
setSize(250,100);
}
public static void main(String[] args)
{
new DLG().setVisible(true);
}
}
Java Programming
18
FileChooser


File choosers provide a
GUI for navigating the file
system or open a file
To display a file chooser,
use the JFileChooser API
to show a modal dialog
containing the file
chooser
import javax.swing.*;
class FCH extends JFrame {
final JLabel jl = new JLabel();
FCH()
{
super("Example: Swing FileChooser");
add(jl);
setSize(300,50);
}
public static void main(String[] args)
{
final FCH fch = new FCH();
final JFileChooser jfc = new JFileChooser();
fch.setVisible(true);
final int val = jfc.showOpenDialog(fch);
if(val == JFileChooser.APPROVE_OPTION)
fch.jl.setText("You chose to open this file: " +
jfc.getSelectedFile().getName());
}
}
Java Programming
19
Anonymous Inner Classes
Extend a class or
implement an
interface
 They are defined at
the same time when
instantiated with new,
as part of a statement
 They cannot have
explicit constructors
because they have no
name

import static java.lang.System.*;
public class EnclosingClass {
int x = 55;
public void anotherMethod2() {
out.println(new Object() {
private int x = 17;
public String toString() {
return "Inner x: " + x +
" Enclosing x: " + EnclosingClass.this.x;
}
} );
}
}
→ Inner x: 17 Enclosing x: 55
Programming Java
20
Another Example: Box
public class BoxDemo2 {
public class Box {
public static void main(String[] args) {
private Object object;
// ONLY place Integer objects into this box!
Box integerBox = new Box();
public void add(Object object) {
this.object = object;
}
// Imagine this is one part of a large
application
// modified by one programmer.
integerBox.add("10"); // note how the type is
now String
public Object get() {
return object;
}
}
// ... and this is another, perhaps written
// by a different programmer
Integer someInteger =
(Integer)integerBox.get();
Exception!
System.out.println(someInteger);
public class BoxDemo1 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
}
integerBox.add(new Integer(10));
Integer someInteger =
(Integer)integerBox.get();
System.out.println(someInteger);
}
}
}
Java Programming II
21
Another Example: Generic Type Box
**
* Generic version of the Box class.
*/
public class Box<T> {
private T t; // T stands for "Type"



public void add(T t) {
this.t = t;
}
public T get() {
return t;
}

Generic Type Invocation
Box<Integer> integerBox;
Instantiation of the class
integerBox = new Box<Integer>();
The entire statement on one line
Box<Integer> integerBox = new
Box<Integer>();
Type Parameter Naming
Conventions

}





E - Element (used extensively by the
Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
Java Programming II
22
Generic Type Declarations
The declaration Store<T> is a generic type
declaration
 Store is a generic class, and T is the type
parameter
 Store<String> is a specific i.e. parameterized
type and String is a specific type argument
 The use of a parameterized type is known as a
generic type invocation
 A generic type declaration can contain multiple
type parameters separated by commas (e.g.
Store<A,B>, Store<A,B,C>)

Java Programming II
23
Generic Methods
public class Box<T> {
private T t; // T stands for "Type"
public void add(T t) {
this.t = t;
}
Generic
public T get() {
Method
return t;
}
public <U> void inspect(U u) {
System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new
Box<Integer>();
integerBox.add(new Integer(10));
integerBox.inspect("some text");
}
}
Result:
T: java.lang.Integer
U: java.lang.String
Generic method can
allow the String type.

It does not be restrictive to the
type of the generic class. The
generic method can accept any
type of parameter.

Another example
Look at the “/home/course/java2/code/
GenericType/GenericMethods.java”.
Java Programming II
24
Generic Methods
class AA<E> {
// restrictive method
E[] method1(E[] arr) {
for (E e: arr)
out.println("m1: " + e.toString());
return arr;
}
public class GenericMethods {
public static void main(String[] args) {
AA<Number> aa = new AA<Number>();
Object[] a1 = aa.method1(new Integer[]
{ 1,2 });
// Object[] a2 = aa.method1(new Object[] { 1,2 });
// Object[] a2 = aa.method1(new String[]
{ "First","Second" });
Object[] a3 = aa.method2(new Object[] { 1,2 });
Object[] a4 = aa.method2(new Object[]
{ "First","Second" });
Error!
// generic method
<T> T[] method2(T[] arr) {
for (T e: arr)
out.println("m2: " + e.toString());
return arr;
}
}


for(Object i: a1)
out.println("In main, a1 element: " + i);
The restrictive method (m1)
just allows the type of the type
parameter of the class.
The generic method (m2)
allows any type of parameter.
for(Object i: a3)
out.println("In main, a3 element: " + i);
for(Object i: a4)
out.println("In main, a4 element: " + i);
}
}
Java Programming II
25
Bounded Type Parameters

When restrict the kinds of types
that are allowed to be passed to a
type parameter
public class Box<T> {
private T t;
public void add(T t) { this.t = t;
public T get() { return t; }
}
public <U extends Number> void inspect(U
u){
System.out.println("T: " +
t.getClass().getName());
System.out.println("U: " +
u.getClass().getName());
}

Compilation will now fail, since our
invocation of inspect still includes a
String:
Box.java:21: <U>inspect(U) in
Box<java.lang.Integer> cannot
be applied to (java.lang.String)
integerBox.inspect("10");
^
1 error

To specify additional interfaces
that must be implemented, use the
‘&’ character
<U extends Number & MyInterface>
public static void main(String[] args) {
Box<Integer> integerBox = new
Box<Integer>();
integerBox.add(new Integer(10));
integerBox.inspect("some text"); // error:
this is still String!
}
}
Java Programming II
26
Subtyping
class Animal { // Animal Super Class
private String name;
private int age;
Animal(String n, int a) { name = n;
age = a; }
public String toString() {
return new String("Name= " + name +
", age= " + age);
}
}
class Lion extends Animal { // Lion Class
public Lion(String n, int a)
{ super(n,a); }
}
class Butterfly extends Animal {
Butterfly Class
public Butterfly(String n, int a)
{ super(n,a); }
//

Subtyping
Animal
Lion
Butterfly
Animal animal = new Animal();
Lion lion1 = new Lion();
Butterfly butterfly1 = new Butterfly();
animal = lion1;
animal = butterfly1;

However, can it be applied to the
generic type either?
}
Java Programming II
27
Subtyping

It's possible to assign an object of
one type to an object of another
type provided that the types are
compatible.
public void someMethod(Number n){
// method body omitted
}
someMethod(new Integer(10)); // OK
someMethod(new Double(10.1)); // OK

The same is also true with generics
Box<Number> box = new Box<Number>();
box.add(new Integer(10)); // OK
box.add(new Double(10.1)); // OK
Now consider the following method:
public void boxTest(Box<Number> n){
// method body omitted
}
Is it possible to pass Box<Integer> or
Box<Double> ?  NO! Why?


Cage interface
interface Cage<E> extends Collection<E>;

Let’s consider the followings:
interface Lion extends Animal {}
Lion king = ...;
Animal a = king; // OK

A lion can, of course, be put into a lion cage:
Cage<Lion> lionCage = ...;
lionCage.add(king); // OK
•
and,
interface Butterfly extends Animal {}
Butterfly monarch = ...;
Cage<Butterfly> butterflyCage = ...;
butterflyCage.add(monarch); // OK

What about an “animal cage? “ :
Cage<Animal> animalCage = …;
animalCage.add(king); // OK
animalCage.add(monarch); // OK

But, does this mean that Cage<Lion> a subtype
of Cage<Animal>?“  No!

Neither cage can be considered an "allanimal" cage:
animalCage = lionCage;
// compile-time error
animalCage = butterflyCage; // compile-time error
Java Programming II
28
Wildcards

Not for any kind of animal, but
rather for some kind of animal
whose type is unknown. In generics,
an unknown type is represented by
the wildcard character "?"
Cage<? extends Animal> someCage = ...;
A bounded wildcard
Read "? extends Animal" as "an
unknown type that is a subtype of
Animal, possibly Animal itself", which
boils down to "some kind of animal".
someCage = lionCage; // OK
someCage = butterflyCage; // OK

"Can you add butterflies and lions
directly to someCage?"  NO
someCage.add(king);
// compilertime error
someCage.add(monarch); // compiler-time
error


A way for putting some cage:
void feedAnimals(Cage<? extends Animal>
someCage) {
for (Animal a : someCage)
a.feedMe();
}
 Invocation:
feedAnimals(lionCage);
feedAnimals(butterflyCage);
 Arrays of elements that are of a specific
type produced from a generic type are not
allowed.
Vector<String>[] v = new Vector<String>[10];
 But, we can define arrays of elements of a
generic type where the element type is
the result of an unbounded wildcard type
argument.
Vector<?>[] vs= {new Vector<String>(), new
Vector<Integer>()}; or
Vector<?>[] vs= new Vector<?>[5];
Java Programming II
29
Type Erasure

When a generic type is instantiated,
the compiler translates those types
by a technique called type erasure
— a process where the compiler
removes all information related to
type parameters and type
arguments within a class or method.
Box<String> -- translate  Box
Raw type

What happens when using an older
API that operates on raw types?
public class WarningDemo {
public static void main(String[] args){
Box<Integer> bi;
bi = createBox();
/** * Pretend that this method is part of an old library,
* written before generics. It returns
* Box instead of Box<T>. * **/
static Box createBox(){
return new Box();
}
}
public class MyClass<E> {
public static void myMethod(Object item) {
if (item instanceof E) { //Compiler error
...
}

What happens when using an older API that
E item2 = new E(); //Compiler error
Recompiling with -Xlint:unchecked reveals the
E[] iArray = new E[10]; //Compiler error
following additional information:
E obj = (E)new Object(); //Unchecked cast
WarningDemo.java:4: warning: [unchecked]
warning
unchecked conversion
}
found : Box
}
required: Box<java.lang.Integer>

The operations shown in bold are
bi = createBox();
meaningless at runtime because the
compiler removes all information about the
^
actual type argument (represented by the
1 warning
type parameter E) at compile time.
Java Programming II
30
Nested Classes
A class can be defined inside another class
 Benefits:



to structure and scope members
to connect logically related objects
A nested class is considered a part of its
enclosing class
 They share a trust relationship, i.e. everything is
mutually accessible
 Nested types could be:



static – allows simple structuring of types
nonstatic – defines a special relationship between a
nested object and an object of the enclosing class
Java Programming II
31
Inner Class
 Class
in the Class
Provide the method to define the object type
to use in the class
 Solve the class name conflict to restrict the
reference scope of class
 Information hiding

class OuterClass {
// ...
class InnerClass {
// ...
}
}
32
Inner Class

Name Reference


OuterClass inside : Use InnerClass Simple name
OuterClass outside : OuterClass.InnerClass
public static void main(String[] args) {
OuterClass outObj = new OuterClass();
OuterClass.InnerClass inObj = outObj.new InnerClass();
}


Access Modifier


public, private, protected
Inner class cannot have static variable
33
Static Inner Class


Can refer without creating
object
Can use static variable
Result:
... without creating Outer-class
object
call static method
call static method

class OuterClass {
static class InnerClass {
static String str;
InnerClass(String s) {
str = s;
}
void print() {
staticPrint(str);
}
static void staticPrint(String s) {
str = s;
System.out.println(s);
}
} // end of InnerClass
} // end of OuterClass
public class StaticInnerClass {
public static void main(String[] args) {
String s = "... without creating Outer-class object";
OuterClass.InnerClass p = new
OuterClass.InnerClass(s);
p.print();
OuterClass.InnerClass.staticPrint("call static
method");
p.print();
}
}
Java Programming II
34
Inner Classes






Inner classes are associated with
instances of a class
Inner classes cannot have static
members including static nested
types
Inner classes can have final static
fields that are constant
Inner classes can extend any
other class, implement any
interface, or be extended
When an inner class object is
created inside a method of the
enclosing class the current object
this is automatically associated
with it
The name of the reference to the
enclosing object is this preceded
by the enclosing class name – a
form known as qualified–this
public class BankAccount {
private long number;
private static long bankID;
public Permissions permissionsFor(Person who) {
Permissions p = new Permissions();
// equal to
this.new Permissions();
p.method();
return p;
}
public class Permissions {
public boolean canDeposit;
public boolean canWithdraw;
void method() {
long bid = bankID;
long num = number;
in scope
num = BankAccount.this.number; // qualified-this
}
}
public static void main(String[] args) {
BankAccount ba = new BankAccount();
Permissions p = ba.new Permissons();
}
}
Java Programming II
35
Extended Inner Classes
An inner class can be
extended
 Objects of the
extended class must
remain associated
with objects of the
original enclosing
class or a subclass

class Outer {
class Inner {
}
}
class ExtendOuter extends Outer {
class ExtendInner extends Inner {
}
Inner ref = new ExtendInner();
}
class Unrelated extends Outer.Inner {
Unrelated(Outer ref) {
ref.super();
}
}
Java Programming II
36
Local Inner Classes




Can be defined in code blocks
and they are local and
accessible to that block
They do not have access
modifiers (e.g. private, public)
and cannot be static
They are not members of the
class to which the block
belongs
A local inner class can access
all the variables in that block,
and static variables, but a local
variable or method parameter
must be declared as final
import static java.lang.System.*;
public class EnclosingClass {
int x = 55;
public void enclosingMethod(final int a) {
int z = 44;
final int q = 32;
class LocalInner {
private int x = 17;
public void innerMethod() {
out.println(x);
// → 17
out.println(q);
// → 32
out.println(a);
// → 99
out.println(this.x); // → 17
out.println(EnclosingClass.this.x); // → 55
}
} // end of LocalInner
LocalInner li = new LocalInner();
li.innerMethod();
}
public static void main(String[] args) {
new EnclosingClass().enclosingMethod(99);
}
}
Java Programming II
37
Anonymous Inner Classes
Extend a class or
implement an
interface
 They are defined at
the same time when
instantiated with new,
as part of a statement
 They cannot have
explicit constructors
because they have no
name

import static java.lang.System.*;
public class EnclosingClass {
int x = 55;
public void anotherMethod2() {
out.println(new Object() {
private int x = 17;
public String toString() {
return "Inner x: " + x +
" Enclosing x: " + EnclosingClass.this.x;
}
} );
}
}
→ Inner x: 17 Enclosing x: 55
Java Programming II
38
Collections of Objects
 Three Main Types of Collections
 Sets
 Sequences
 Maps
 Sets
 The simple kinds of collection
 The objects are not ordered in any particular way.
 The objects are simply added to the set without any control over where
they go.
Java Programming II
Hashtable (Before 1.5)
class HashtableDemo {
Key
public static void main(String args[]) {
Hashtable hashtable = new Hashtable();
hashtable.put("apple", "red");
hashtable.put("strawberry", "red");
hashtable.put("lime", "green");
hashtable.put("banana", "yellow");
hashtable.put("orange", "orange");
Enumeration e = hashtable.keys();
while(e.hasMoreElements()) {
Object k = e.nextElement();
Object v = hashtable.get(k);
System.out.println("key = " + k +
"; value = " + v);
}
System.out.print("¥nThe color of an apple is: ");
Object v = hashtable.get("apple");
System.out.println(v);
}
Value
The Hashtable<k,V> class inherits from
the Dictionary class, and implement the
Map interface. All methods of it are
synchronized, unlike HashMap.
Result :
Result #2
key = lime; value = green
key = strawberry; value = red
The color of an apple is: red
Here, you will meet warning message
of unchecked type. How can we solve
this?
}
Java Programming II
Hashtable<K,V> (1.5)
import java.util.*;
class HashtableDemoGen {
public static void main(String args[]) {
Hashtable<String,String> hashtable = new
Hashtable<String,String>();
hashtable.put("apple", "red");
hashtable.put("strawberry", "red");
hashtable.put("lime", "green");
hashtable.put("banana", "yellow");
hashtable.put("orange", "orange");
for (Enumeration<String> e = hashtable.keys() ;
e.hasMoreElements() ;) {
String k = e.nextElement();
String v = hashtable.get(k);
System.out.println("key = " + k +
"; value = " + v);
}
Parameterized Type
The Hashtable<k,V> class
inherits from the Dictionary
class, and implement the Map
interface. All methods of it are
synchronized, unlike HashMap.
System.out.print("¥nThe color of an apple is: ");
String v = hashtable.get("apple");
System.out.println(v);
}
}
Java Programming II
Iterable and Iterator Interface, and Creating
Iterable Class



Iterable<T> interface
 T iterator()
Iterator<E> interface
 E next()
 boolean hasNext()
 void remove()
class Cage<T> implements Iterable<T> {
fields and methods for the Cage class
public Iterator<T> iterator() {
return new SomeIterator();
}
}
To create an “Iterable Class”
 An Iterable class implements
the “Iterable” interface
 The “iterator” method should
be implemented in the class
 An Iterator class should be
provided for the iterator. The
Iterator class has 3 methods,
hasNext, next, and remove to
access elements of the class
class SomeIterator implements Iterator<T>
{
public T next() {
// body of the next method
}
public boolean hasNext() {
// body of the hasNext method
}
public void remove() {
// body of the remove method
}
Java Programming
II
}
Writing Iterator Implementations
“ShortStrings.java”
import java.util.*;
public class ShortStrings implements Iterator<String>
{
private Iterator<String> strings ; // source for strings
private String nextShort; // null if next not known
private final int maxLen; // only return strings <=
public ShortStrings(Iterator<String> strings, int maxLen)
{
this.strings = strings;
this.maxLen = maxLen;
nextShort = null;
}
public boolean hasNext() {
if (nextShort != null) // found it already
return true;
while (strings.hasNext()) {
nextShort = strings.next();
if (nextShort.length() <= maxLen) return true;
}
nextShort = null; // did not find one
return false;
}
Result:
Short String = First String
Short String = Second Second String
Short String = Third Third Third String
public String next() {
if (nextShort == null && !hasNext())
throw new NoSuchElementException();
String n = nextShort; // remember nextShort
nextShort = null;
return n;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
“ShortStringsTest.java”
import java.util.*;
public class ShortStringsTest {
public static void main(String[] args) {
LinkedList<String> myList = new LinkedList<String>();
myList.add("First String");
myList.add("Second Second String");
myList.add("Third Third Third String");
myList.add("Fourth Fourth Fourth Fourth String");
myList.add("Fifth Fifth Fifth Fifth Fifth String");
ShortStrings myShort = new ShortStrings(myList.iterator(),
25);
// for (String val : myShort) // Why not able ?
while(myShort.hasNext()) {
System.out.println("Short String = " + myShort.next());}
}}
}
Java Programming
II
Sortable Class: TryManSortable Example
class SortableMen implements
import java.util.Arrays;
Comparable<SortableMen> {
public class TryMenSort {
private String name;
public static void main(String[] args) {
private Integer age;
SortableMen[] srtm = {
public SortableMen (String n, Integer a)
new SortableMen("Man D",25),
{ name = n; age = a; }
new SortableMen("Man A",25),
public String getName() { return name; }
new SortableMen("Man A",30),
public Integer getAge() { return age; }
new SortableMen("Man B",25)
public String toString() { return new
};
StringBuffer(128).append("Name:
System.out.println("Original Order: ");
").append(name).append(", Age:
for (SortableMen m : srtm)
").append(age.toString()).toString();
System.out.println(m);
}
Arrays.sort(srtm);
public void setName(String n) { name =
System.out.println("¥nOrder after sorting
n; }
using Comparable method: ");
public void setAge(Integer a) { age =
for (SortableMen m : srtm)
a; }
System.out.println(m);
public int compareTo(SortableMen v)
}
{ int result;
}
result =
name.compareTo(v.getName());
return result == 0 ?
age.compareTo(v.getAge()) : result ;
}
Java Programming II
}
How to use Eclipse
Java Programming
45
Start
 Some

Introductions on the Web
Eclipse IDE Tutorial by Lars Vogel
http://www.vogella.com/articles/Eclipse/article.html

Getting Started Using Eclipse by Laurie Williams,
Dright Ho, Ben Smith and Sarah Heckman
http://agile.csc.ncsu.edu/SEMaterials/tutorials/eclipse/eclipse_
tutorial_3.3.html

Getting started with the Eclipse Platform by David
Gallardo
http://www.ibm.com/developerworks/library/os-ecov/

Start Command on Unix
% eclipse <enter>
Java Programming
46
Start (Workspace Setting)
 Inputting Workspace
The workspace is the place where you store your Java projects
Select an empty directory and press Ok.
Directory for workspace
Java Programming
47
Start with creating project
 Create Project
Select from the menu
File → New → Java
Project.
 Enter a project
name (Ex:
"FirstHello"). Select
the flag "Create
separate folders for
sources and class
files ".
Java Programming
48
Create A New Package (With package)
 Create Package
Select the folder src, right click on it and select New->Package
(A good convention is to use the same name for the top package and the project.)
Java Programming
49
Create Java Class (With Package)
 Create Java Class
Right click on your package and select New->Class
Java Programming
50
Write Java Code
 Create Java Class (With Package)
Write the Java Code in the created Java file.
Java Programming
51
Run your project in Eclipse
 Run the project in Eclipse
Right click on your Java class and select Run-As -> Java Application
Result
Java Programming
52
Create Java Class (Without Package)
 Create Java Class (Without Package) – After creating a Project
Right click on the folder src of your project and select New->Class
Java Programming
53
Write Java Code
 Create Java Class (Without package) and running the project
Write the Java Code in the created Java file.
Java Programming
54
Handling Packages and Jar Files
// file UsageDemoPackage.java in
// file ClassOne.java in the directory
// /home/s111111/java/Ex08/demopackage // the directory
// /home/s111111/java/Ex08/packagetest
package demopackage;
package packagetest;
public class ClassOne {
import demopackage.*;
public void methodClassOne() {
class UsageDemoPackage {
System.out.println("methodClassOne");
public static void main(String[] args) {
}
ClassOne v1 = new ClassOne();
}
ClassTwo v2 = new ClassTwo();
// file ClassTwo.java in the directory
v1.methodClassOne();
// /home/s111111/java/Ex08/demopackage
v2.methodClassTwo();
package demopackage;
}
public class ClassTwo {
When we add these..
}
public void methodClassTwo() {
System.out.println("methodClassTwo");  Compilation:
}
javac UsageDemoPackage.java
}


Compilation:
javac *.java
Run:
java UsageDemoPackage
Java Programming
55
Handling Packages and Jar Files
// Making Jar files and executing using them.
 Compile the sources: [directory in a package]
% mkdir classes
% javac [-classpath [jar libraries]] -d classes *.java
 Create Jar file [directory in a package]
% jar -cvf JarFileNameYouWant.jar -C classes . <enter>
 Execute Main method [directory where all the jar files exist including main class file]
% java –classpath mylib1.jar;mylib2.jar;..;main.jar packagenames.MainClassRun <enter>
 Example (There are two packages in working directory: demopackage and packagetest)
In “demopackage” directory
% mkdir classes
% javac –d classes *.java
% jar -cvf PackageClasses.jar -C classes .
% mv PackageClasses.jar ..
% jar -cvf MainClass.jar -C classes .
% mv MainClass.jar ..
In the working directory where are the two
jar files.
In Windows, use ‘;’ .
<To run>
In “packagetest” directory
% java –classpath
% mkdir classes
PackageClasses.jar:MainClass.jar
% javac –cp ../PackageClasses.jar –d
packagetest.UsageDemoPackage <enter>
classes *.java
Java Programming
56