Tags

, , ,

My Simple example with 4 classes for understanding how event and eventListener work together.

------------------------------
package myevents;
import java.util.EventObject;

public class MyEvent extends EventObject {

 private static final long serialVersionUID = 5736098458773344230L;
 private Object data;

 public MyEvent(Object source, Object _data)    {
   super(source);
   data = _data;
 }

 public Object getData()    {
   return data;
 }
}
-------------------------------
package myevents;
import java.util.EventListener;

public interface MyEventListener extends EventListener    {
  public void myEventHappend(MyEvent e);
}
------------------------------
package myevents;
public class PracticalInterface implements MyEventListener    {

 @Override
 public void myEventHappend(MyEvent e) {
    System.out.println((String) e.getData());
 }
}
------------------------------
package myevents;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class AppProgram extends JFrame {

private Vector listeners = new Vector();
private JTextArea _tar  = new JTextArea(22,40);
private JButton _bt1    = new JButton("Yeah");
private JButton _bt2    = new JButton("Yoo");

public AppProgram()    {
super("Application");
setLayout(new FlowLayout());
_bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
shootEvent("Yeah !!");
}
});
_bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
shootEvent("Yoo !?");
}
});
this.add(_tar);
this.add(_bt1);
this.add(_bt2);
}

public void addListener(MyEventListener l)    {
listeners.add(l);
}

public void removeListener(MyEventListener l)    {
listeners.remove(l);
}

public void shootEvent(String text)    {
MyEvent me = new MyEvent(this, text);
if (listeners.size() > 0)    {
((MyEventListener)listeners.firstElement()).myEventHappend(me);
}
}

public static void main(String[] args) {
AppProgram app = new AppProgram();
PracticalInterface lis = new PracticalInterface();
app.addListener(lis);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(400,600);
app.setVisible(true);
}

}
------------------------------
Hope you like it :)
------------------------------
Advertisements