|
|||||
Web
Design & Development CS506
VU
Lesson
13
Problem
in Last Code
Example
Problem
We were interested
in windowClosing()
method
only
But
have to provide definitions of all the
methods, Why?
Because
a class implementing an interface
has to provide definitions of
all methods
present
in that interface.
Solution
To
avoid giving implementations of
all methods of an interface
when we are not using
these
methods
we use Event Adapter
classes
Adapter
Classes
·
For
listener interfaces containing more than
one event handling methods,
jdk defines adapter
classes.
Examples are
For
WindowListener Æ WindowAdapter
For
MouseMotionListener Æ
MouseMotionAdapter
and many
more
·
Adapter
classes provide definitions
for all the methods
(empty bodies) of their
corresponding
Listener
interface
·
It
means that WindowAdapter
class implements WindowListener interface
and provide the
definition
of all methods inside that
Listener interface
·
Consider the
following example of MouseMotionAdapter and
its corresponding
MouseMotionListener
interface
public
interface MouseMotionListener
{
public
void mouseDragged (MouseEvent
me);
public
void mouseMoved (MouseEvent
me);
}
public
class MouseMotionAdapter
implements MouseMotionListener{
public
void mouseDragged (MouseEvent
me) { }
public
void mouseMoved (MouseEvent
me) { }
}
104
Web
Design & Development CS506
VU
Available
Adapter classes
How to
use Adapter
Classes
Previously
handler class need to
implement interface
public
class EventsEx implements
MouseMotionListener{...}
Therefore
it has to provide definitions of
all the methods inside that
interface
Now
our handler class will
inherit from adapter
class
public
class EventsEx extends
MouseMotionAdapter{...}
Due
to inheritance, all the methods of the
adapter class will be available
inside our handler
class
Since
adapter classes has already
provided definitions with
empty bodies.
We do
not have to provide implementations of
all the methods again
We
only need to override our
method of interest.
Example
Code 13.1: Handling Window
Events using Adapter
Classes
Here
we are modifying the window
event code in the last example to show
the use of
WindowAdapter
instead of WindowListener. Code related to
MouseMotionListener is deleted to
avoid
cluttering of code.
1.
import
java.awt.*;
2.
import
javax.swing.*;
3.
import
java.awt.event.*;
4.
public
class EventsEx extends WindowAdapter
{
5.
JFrame
frame;
6.
JLabel
coordinates;
// setting
layout
7.
public
void initGUI ( ) {
105
Web
Design & Development CS506
VU
// creating event
generator
8.
frame =
new JFrame();
9.
Container
cont = frame.getContentPane();
10.
cont.setLayout(new
BorderLayout( ) );
11.
coordinates
= new JLabel ();
12.
cont.add(coordinates,
BorderLayout.NORTH);
// registering
window handler with
generator
13.
frame.addWindowListener(this);
14.
frame.setSize(350,
350);
15.
frame.setVisible(true);
16.
} //
end initGUI method
//default
constructor
17.
public
EventsEx ( ) {
18.
initGUI();
19.
}
// As
you can see that we
have only implemented
//
our required method
20.
public
void windowClosing (WindowEvent we)
{
21.
JOptionPane.showMessageDialog(null,
"Good Bye");
22.
System.exit(0);
23.
}
24.
public
static void main(String
args[]) {
25.
EventsEx ex = new
EventsEx();
26.
}
27.
} //
end class
Problem
in Last Code
Example
We have
inherited from
WindowAdapter
What
if we want to use MouseMotionAdpater as
well ? or what if our class
already inherited
form
some
other class ?
Problem
--
Java allows single
inheritance
Solution
--
Use Inner
classes
106
Web
Design & Development CS506
VU
Inner
Classes
A
class defined inside another
class
Inner
class can access the
instance variables and
members of outer
class
It
can have constructors, instance variables
and methods, just like a
regular class
Generally
used as a private utility
class which does not
need to be seen by others
classes
Example
Code13.2: Handling Window
Event with Inner
Class
Here
we are modifying the window
event code in the last example to show
the use of
WindowAdapter
as an inner class.
1.
import
java.awt.*;
2.
import
javax.swing.*;
3.
import
java.awt.event.*;
4.
public
class EventEx {
5.
JFrame
frame;
6.
JLabel
coordinates;
7.
// setting
layout
8.
public
void initGUI ( ) {
9.
frame =
new JFrame();
10.
Container
cont = frame.getContentPane();
11.
cont.setLayout(new
BorderLayout( ));
12.
coordinates
= new JLabel ();
13.
cont.add(coordinates,
BorderLayout.NORTH);
/* Creating an
object of the class which is handling
our
window
events and registering it with
generator */
107
Web
Design & Development CS506
VU
14.
WindowHandler
handler = new Window Handler
();
15.
frame.addWindowListener(handler);
16.
frame.setSize(350, 350);
17.
frame.setVisible(true);
18. }
// end initGUI
//default
constructor
19.
public EventEx ( ) {
20.
initGUI();
21.
}
/*
Inner class implementation of
window adapter. Outer
class
is free to inherit from any other
class. */
22.
private
class WindowHandler extends
WindowAdapter {
//
Event Handler for
WindowListener
23.
public
void windowClosing (WindowEvent we)
{
24.
JOptionPane.showMessageDialog(null,
"Good Bye");
25.
System.exit(0)
26.
}
27.
} //
end of WindowHandler
class
28.
public static void
main(String args[]) {
29.
EventEx e = new
EventEx();
30.
}
31.}
// end class
Example
Code 13.3: Handling Window
and Mouse Events with
Inner Class
Here
we are modifying the window
event code of the last example to
handle window and mouse
events
using
inner classes. The diagram
given below summarizes the
approach.
Outer
class for GUI and other
code
108
Web
Design & Development CS506
VU
Inner
class
Handling
Window
1.
import
java.awt.*;
2.
import
javax.swing.*;
3.
import
java.awt.event.*;
4.
public
class EventEx {
5.
JFrame
frame;
6.
JLabel
coordinates;
7.
// setting
layout
8.
public
void initGUI ( ) {
9.
frame = new
JFrame();
10.
Container cont =
frame.getContentPane();
11.
cont.setLayout(new
BorderLayout( ) );
12.
coordinates
= new JLabel ();
13.
cont.add(coordinates,
BorderLayout.NORTH);
/*
Creating an object of the class
which is handling our
window
events and registering it with
generator */
14.
WindowHandler
whandler = new WindowHandler
();
15.
frame.addWindowListener(whandler);
/* Creating an
object of the class which is handling
our
MouseMotion
events & registering it with
generator */
16.
MouseHandler
mhandler = new MouseHandler
();
17.
frame.addMouseMotionListener(mhandler);
18.
frame.setSize(350, 350);
19.
frame.setVisible(true);
20.
}
//default
constructor
21.
public EventEx ( ) {
22.
initGUI();
23.
}
/*
Inner class implementation of
WindowAdapter. Outer class
is free to
inherit from any other
class. */
24.
private
class WindowHandler extends
WindowAdapter {
//
Event Handler for
WindowListener
25.
public
void windowClosing (WindowEvent we)
{
26.
JOptionPane.showMessageDialog(null,
"Good Bye");
27.
System.exit(0)
109
Web
Design & Development CS506
VU
28.
}
29.
} //
end of WindowHandler
//Inner
class implementation of
MouseMotionAdapter
30.
private
class MouseHandler extends
MouseMotionAdapter {
//
Event Handler for mouse
motion events
31.
public
void mouseMoved (MouseEvent
me) {
32.
int x =
me.getX();
33.
int y =
me.getY();
34.
coord.setText("Moved
at [" + x + "," + y + "]" );
35.
}
36.
} //
end of MouseHandler
37.
public static void
main(String args[]) {
38.
EventEx e = new
EventEx();
39.
}
40.}
// end class
Example
Code: Making Small Calculator
using Inner
classes
User
enters numbers in the provided
fields
On
pressing "+" button, sum
would be displayed in the answer
field
On
pressing "*" button, product
would be displayed in the answer
field
1.
import java.awt.*;
2.
import javax.swing.*;
3.
import java.awt.event.*;
110
Web
Design & Development CS506
VU
4.
public class SmallCalcApp implements
ActionListener{
5.
JFrame
frame;
6.
JLabel
firstOperand, secondOperand,
answer;
7.
JTextField
op1, op2, ans;
8.
JButton
plus, mul;
9. // setting
layout
10.
public void initGUI ( )
{
11.
frame = new
JFrame();
12.
firstOperand = new
JLabel("First Operand");
13.
secondOperand
= new JLabel("Second Operand");
14.
answer
= new
JLabel("Answer");
15.
op1 =
new JTextField (15);
16.
op2 =
new JTextField (15);
17.
ans =
new JTextField (15);
18.
plus = new
JButton("+");
19.
plus.setPreferredSize(new
Dimension(70,25));
20.
mul =
new JButton("*");
21.
mul.setPreferredSize(new
Dimension(70,25));
22.
Container
cont = frame.getContentPane();
23.
cont.setLayout(new
FlowLayout());
24.
cont.add(firstOperand);
25.
cont.add(op1);
26.
cont.add(secondOperand);
27.
cont.add(op2);
28.
cont.add(plus);
29.
cont.add(mul);
30.
cont.add(answer);
31.
cont.add(ans);
/* Creating an
object of the class which is
handling
button
events & registering it with
generators */
32.
ButtonHandler
bHandler = new ButtonHandler();
33.
plus.addActionListener(bHandler);
34.
mul.addActionListener(bHandler);
35.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
36.
frame.setSize(200,
220);
37.
frame.setVisible(true);
38.
}
111
Web
Design & Development CS506
VU
39.
//constructor
40.
public
SmallCalcApp ( ) {
41.
initGUI();
42.
}
//Inner
class implementation of
ActionListener
43.
private class ButtonHandler implements
ActionListener{
44.
public void
actionPerformed(ActionEvent event)
{
45.
String
oper, result;
46.
int
num1, num2, res;
47.
if
(event.getSource() == plus) {
48.
oper =
op1.getText();
49.
num1 =
Integer.parseInt(oper);
50.
oper =
op2.getText();
51.
num2 =
Integer.parseInt (oper);
52.
res =
num1+num2;
53.
result =
res+"";
54.
ans.setText(result);
55
}
56.
else
if (event.getSource() == mul) {
57.
oper =
op1.getText();
58.
num1 =
Integer.parseInt(oper);
59.
oper =
op2.getText();
60.
num2 =
Integer.parseInt (oper);
61.
res =
num1*num2;
62.
result =
res+"";
63.
ans.setText(result);
64
}
65.
} //
end actionPerformed
method
66. }
// end inner class
ButtonHandler
67.
public
static void main(String
args[]) {
68.
SmallCalcApp
scApp = new SmallCalcApp();
69.
}
70.
}// end class
112
Web
Design & Development CS506
VU
Anonymous
Inner Classes
Has
no name
Same
as inner class in
capabilities
much
shorter
difficult
to understand
Named
vs. Anonymous
Objects
Named
String
s = "hello"; System.out.println(s);
"hello"
has a named reference s.
Anonymous
System.out.println("hello");
We
generally use anonymous object when
there is just a one time
use of a particular object
but in
case
of a repeated use we generally
used named objects and use
that named reference to use
that objects
again
and again.
Example
Code 13.4 Handling Window
Event with Anonymous Inner
Class
Here
we are modifying the window
event code of 13.3 to show
the use of anonymous inner
class.
28.
import
java.awt.*;
29.
import
javax.swing.*;
30.
import
java.awt.event.*;
31.
public
class EventsEx extends WindowAdapter
{
32.
JFrame
frame;
33.
JLabel
coordinates;
// setting
layout
34.
public
void initGUI ( ) {
// creating event
generator
35.
frame =
new JFrame();
36.
Container cont =
frame.getContentPane();
37.
cont.setLayout(new
BorderLayout( ) );
38.
coordinates
= new JLabel ();
39.
cont.add(coordinates,
BorderLayout.NORTH);
// registering
event handler (anonymous inner
class)
//
with generator by using
113
Web
Design & Development CS506
VU
40.
frame.addWindowListener (
41.
new
WindowAdapter ( ) {
42.
public
void windowClosing (WindowEvent we)
{
43.
JOptionPane.showMessageDialog(null,
"Good Bye");
44.
System.exit(0);
45.
} //
end window closing
46.
} // end WindowAdapter
47. );
// end of addWindowListener
48.
frame.setSize(350, 350);
49.
frame.setVisible(true);
50. }
// end initGUI method
//default
constructor
51.
public EventsEx ( ) {
52.
initGUI();
53.
}
54.
public static void
main(String args[]) {
55.
EventsEx ex = new EventsEx();
56.
}
57. }
// end class
Summary
of Approaches for Handling
Events
1. By implementing
Interfaces
2. By
extending from Adapter
classes
To
implement the above two techniques we can
use
Same
class
·
putting
event handler & generator in one
class
Separate
class
1.
Outer class
·
Putting
event handlers & generator in two
different classes
3.
Inner classes
3.
Anonymous Inner
classes
References
Java
A Lab Course by Umair
Javed
114
Table of Contents:
|
|||||