Solved

creating events.

Posted on 2001-08-16
7
244 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How  can  i  resolve  HTTP Status 404 -? 8 78
Convert from a json string array to a Java object 3 80
glassfish admin console 1 47
Bitwise and to sum elements 2 52
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

732 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