Solved

creating events.

Posted on 2001-08-16
7
204 Views
Last Modified: 2012-08-14
i would create an event to a class.I think this will be happen with some listener but all listener that java have is only for swing or awt.i would create an event ex when a variable change.My project is that. I have a shoket to communicate with some other pc's .To make connection i use some buffereader and input streame objects.I like to take an event when the data have some prices example 23 or "password:23".

If you have some idea who i can make a non grafical event tell me.Thanks you very much!
0
Comment
Question by:tzelve
7 Comments
 
LVL 92

Expert Comment

by:objects
ID: 6395096
You need to add support to your class for for adding PropertyChangeListeners.
You'll need to create an addPropertyChangeListener and removePropertyChangeListener methods.
And when a property change occurs in your object then you'll need to send a PropertyChangeEvent to each registered listener.
0
 
LVL 3

Expert Comment

by:Sendoh
ID: 6395340
listening...:)
0
 
LVL 9

Accepted Solution

by:
Ovi earned 50 total points
ID: 6395759
To follow the Java specifications, when you want to create custom events and listeners, you must follow this rules :

- the listener interface must extend java.util.EventListener;
- the event specific to the listener must extend java.util.EventObject;

Why this? For the case when you want to use the virtual machine event thread, in other words, when you want to propagate your custom events like any other java event. Of course this requirement must be followed in the above case. Any way, in principle you just create an listener interface and the coresponding event class.

***************************************************
import java.util.*;

public interface MyListener extends EventListener {
  public void processMyEvent(MyEvent me);
}
***************************************************

***************************************************
import java.util.*;

public class MyEvent extends EventListener {
  public static final int ACTION1 = 1;
  public static final int ACTION2 = 2;
  public static final int ACTION3 = 3;
  public static final int ACTION4 = 4;
  private int eventID;

  public MyEvent(Object source, int id) {
    super(source);
    eventID = id;
  }
 
  public int getEventID() {return(eventID);}
}
****************************************************
import java.util.Vector;

public class A {
  private Vector listeners = new Vector();
 
  public void addMyListener(MyListener ml) {
    listeners.addElement(ml);
  }

  public void removeMyListener(MyListener ml) {
    listeners.removeElement(ml);
  }
  protected void fireMyEvent(MyEvent me) {
    for(int idx = 0; idx<listeners.size(); idx++)
      ((MyListener)listeners.elementAt(idx)).processMyEvent(me);
  }

  protected void calculus() {
    //some tests which require the event generation
    MyEvent me = new MyEvent(this, MyEvent.ACTIONx);// an action
    fireMyEvent(me); // so the listeners get notified
  }
}
*******************************************************

*******************************************************
public class B implements MyListener {
  private A eventGenerator = new A();
 
  public B() {
    //registering as a listener to the class A
    eventGenerator.addMyListener(this);
  }

  public void processMyEvent(MyEvent me) {
    //process all incomming events from the class A
    switch(me.getEventID) {
      case MyEvent.ACTION1:
        // process action 1
        break;
      case MyEvent.ACTION2:
        // process action 2
        break;
      case MyEvent.ACTION3:
        // process action 3
        break;
      case MyEvent.ACTION4:
        // process action 4
        break;
    }
  }
}

Note :

MyEvent - class which implements the custom event
MyListener - the listener interface for the event
A       - the class which generates events of type MyEvent
B       - the class which listen for events of type MyEvent

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 1

Expert Comment

by:dviji
ID: 6397502
Ovi,
    This is another way to solve this problem by using Observer/Observable pattern..... ;-))
 
tzelve,
 If there is an state change you have to notify some other object then you have to use Observer/Observable pattern. In java 1.1 & 1.2 event handling is based on this pattern only.
 
  In AWT all the Events (i.e WindowEvent,ActionEvent.. ) class are Observable which will tell the all observers (itnterested parties) that the state of the object was changed. (All the Listeners are Observers)

  In java by using Oberver and Observable class in java.util Package we will achive it.

  Some days back I grabbed this code form net. Go through this you will get some ideas about Observer/Observable pattern.

----------------------------------------------------------
The Observer/Observable pattern may be appropriate in the situation where you have need to update a set of objects based on a change in another. At least two objects are needed, one which extends the Observable class and represents the changeable 'data' or 'model' and one that implements the Observer interface and is the class whose interest is registered with the Observable. The following is a short demo - the only code of real import is the implementation of the update() method by the Observer, and the use of the three methods addObserver(),setChanged(), and notifyObservers() [the minimum that must be used] by the Observable.

Example:-
 A change in the state of a String in the Observable will notify the Observer, which will in turn output a message to that effect to the console:


import java.util.*;
import java.io.*;

public class Actor extends Observable {

    private String stateString = "idle";

    public Actor() {
     addObserver(new Watcher());
    }

    public String getState() {
     return stateString;
    }

    public void setState(String s)  {
     if( ! (s.equals(stateString) ) ) {
         setChanged();
         notifyObservers("State changed");
     }
     stateString = s;
    }
   
    public static void main(String[] args) {
     String s;
     Actor actor = new Actor();
     BufferedReader reader =
         new BufferedReader(
          new InputStreamReader(System.in));
     try {
         System.out.println("Enter a state (" +
          actor.getState(
           ) + " is the current state): ");
         while((s = reader.readLine()) != null) {
          actor.setState(s);
          System.out.println("Current state: " +
            actor.getState());
         }
     }
     catch(Exception e) {
         System.out.println("Program terminated.");
     }
    }
}


class Watcher implements Observer {
  public void update(Observable o, Object arg) {
   System.out.println("Observable object " +
    o + " has changed state.");
    }
}
-----------------------------------------------------------

....dviji
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6399649
Hi,

I agree with objects that PropertyChangeEvent/Listener is correct way to reflect variable change. Note that package is java.beans. Look at java.beand.ProperyChangeSupport class--it does a lot of work for listener notification and registering.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
0
 

Author Comment

by:tzelve
ID: 6401144
Your example is simple dviji, but i have this problem:
If the variable is backround changable?
My project is that i use a Socket object to communicate with some other pc and i want to listen datas, when the datas are equal with costand value to call an event.in your example you must run the notifyObservers() method to work.
Help me if you can...
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6450071
To tzelve : Thanks for the points


To dviji :  I use the Observer/Observable pattern only and only in implementing the MVC pattern (model-view-controller). Will work of course in the case of SIMULATING the event notification but is not a pure solution. I believe SOME TIME the things must be used for what they have been created for. Any way thanks for details.

http://www.google.com/search?hl=en&safe=off&q=MVC+applet
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now