Event Listener and Event Source in the different class
Event Listener is implemented in the different class than where we have components. In this case to apply the listener, we have to pass the object of that class. so that whenever event occurs JRE can call the method of Listener.
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 Listener class.
- View and Controller part can be separated which is a good practice.
- All the methods must be defined in our newly created class. Blank definition is to be given even if we don’t want to use it.
Code:
import java.awt.*; import java.applet.*; import java.awt.event.*; public class EventDemo2 extends Applet { Button btn; static Label lbl; public void init() { btn = new Button("Click Me!"); lbl = new Label(" "); add(btn); add(lbl); myListenerClass myobj = new myListenerClass(); btn.addMouseListener(myobj); } } class myListenerClass implements MouseListener { public void mouseClicked(MouseEvent e) { EventDemo2.lbl.setText("Clicked!"); } public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseReleased(MouseEvent e){} } /* <applet code="EventDemo2" width="500" height="50"></applet> */
Recent Comments