Extending Adapter Class
As we all know that: Java do not support multiple inheritance we cannot derive our Applet/Frame/JFrame based classes by any other class at the same time. In that case what can be done is: we can create a new class and that class will be derived from Adapter class. And our newly derived Adapter class can be used as an argument of addXYZListener() method.
Characteristics:
- Components/Event Sources cannot be easily accessed from Listener methods. We must have object of base class(where we have components) in the Listener class(where we have Listener methods)
- Event can be applied to a component by passing object of newly created adapter class which extends built in adapter class.
- View and Controller part can be separated which is a good practice.
- Not compulsory to define all the methods. No need to write Blank definition if not required.
Code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class EventDemo5 extends Applet
{
Button btn;
static Label lbl;
public void init()
{
btn = new Button("Click Me!");
lbl = new Label(" ");
add(btn);
add(lbl);
myAdapterClass myObj = new myAdapterClass();
btn.addMouseListener(myObj);
}
}
class myAdapterClass extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
EventDemo5.lbl.setText("Clicked!");
}
}
/*
<applet code="EventDemo5" width="500" height="50"></applet>
*/




Recent Comments