URGENT - Client,UI,Observable & Observer

I have a Client who receives packets from
other Clients or the server.
This Main class for Client creates a "User Interface
class".And then the UI class creates the
"Central Class" which deals with packet handling etc.
When I receive a packet, "Central" unpacks it
and need to notify the "UI" class and send
some info(Event Object May be) for
"UI" to display it.
I read a post on Observable and Observer class.
so I can make Central Class extend Observable
so it can notify the Observer, which will be UI
BUT!!
In order to use Observable & Observer,
It is required to add Observer to Observerable
by doing addObserver(object o)
in Observable class.
But Observable class is created IN the Observer
class. So how can I pass the object for the
addObserver method?
any help is really appreciated,
thanks in advance.
<< may reply to [email protected] >>

I have a Client who receives packets from
other Clients or the server.
This Main class for Client creates a "User Interface
class".And then the UI class creates the
"Central Class" which deals with packet handling etc.
When I receive a packet, "Central" unpacks it
and need to notify the "UI" class and send
some info(Event Object May be) for
"UI" to display it.
I read a post on Observable and Observer class.
so I can make Central Class extend Observable
so it can notify the Observer, which will be UI
BUT!!
In order to use Observable & Observer,
It is required to add Observer to Observerable
by doing addObserver(object o)
in Observable class.
But Observable class is created IN the Observer
class. So how can I pass the object for the
addObserver method?
any help is really appreciated,
thanks in advance.
<< may reply to [email protected] >>
After creating the Observable try addObserver(this)

Similar Messages

  • RMI + Observable/Observer trouble

    I'm trying to develop the following:
    Local:
    A Swing JFrame object which contains some JPanels that should Observe the actions of server's BusinessLogic.java
    Both sides:
    An interface that contains the declaration of the methods in server's business logic.
    RemoteObserver.java
    RemoteObservable.java
    RemoteObserverImpl.java
    RemoteObservableImpl.java
    Server:
    One Observable class that contains the business logic and notifies some changes and implements the Interface.
    Other classes.
    I'm using the latest JDK version.
    I have some classes to do the RMI + Observable/Observer thing but I don't know how to apply them to my application.
    Here's what i've done so far:
    public class MainFrame extends JFrame {
         public static final String serviceName = "RemoteServer";
         private String host = "localhost";
         private RemoteBusinessLogicInterface remoteLogic;
         public MainFrame(String frameTitle) {
              super();
              setTitle(frameTitle);
              setSize(700, 600);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              System.setProperty("java.security.policy", "client.policy");
              setRemoteServer();
              ObserverPanel observerPanel = new ObserverPanel(
                        remoteLogic);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(observerPanel, BorderLayout.CENTER);
              this.setVisible(true);
         public void setRemoteServer(){
              try {
                   if (System.getSecurityManager() == null)
                        System.setSecurityManager(new RMISecurityManager());
                   String rmiUrl = "rmi://" + host  + "/" + serviceName;
                   remoteLogic = (RemoteBusinessLogicInterface) Naming.lookup(rmiUrl);
              } catch (ConnectException ex) {
              } catch (UnknownHostException ex) {
              } catch (Exception ex) {
         public static void main(String[] args) {
              MainFrame f = new MainFrame("Title");
    public class ObserverPanel extends JPanel{
         private DefaultListModel items;
         private JList list;
         public ObserverPanel(RemoteBusinessLogicInterface remoteLogic) {
              items = new DefaultListModel();
              list = new JList(items);
              list.setVisibleRowCount(24);
              JScrollPane scrollPane;
              scrollPane = new JScrollPane(list);
              setLayout(new BorderLayout());
              add(scrollPane,BorderLayout.CENTER);
         public void update(RemoteObservable observable, Object objektua) {
              System.out.println("Change notified");
    public interface RemoteBusinessLogicInterface extends RemoteObservable{
         public void insertData(int number, String code, Date date) throws RemoteException;
         public void submit() throws RemoteException;
         public void clear() throws RemoteException;
    class RemoteBusinessLogic extends RemoteObservableImpl implements
              RemoteBusinessLogicInterface {
         public static final String serviceName = "RemoteServer";
         public RemoteBusinessLogic() throws RemoteException {
         public void clear() throws RemoteException {
              setChanged();
              super.notifyObservers();
         public void insertData(int number, String code,
                   Date date) throws RemoteException {
              System.out.println("Something");
              setChanged();
              super.notifyObservers();
         public void submit() throws RemoteException {
              System.out.println("Something");
              setChanged();
              super.notifyObservers();
         public static void main(String[] args) {
              System.setProperty("java.security.policy", "client.policy");
              if (System.getSecurityManager() == null)
                   System.setSecurityManager(new RMISecurityManager());
              try {
                   RemoteBusinessLogic serverObject = new RemoteBusinessLogic();
                   try {
                        java.rmi.registry.LocateRegistry.createRegistry(1099);
                        Naming.rebind(serviceName, serverObject;
                        System.out.println("Server launched");
                   } catch (MalformedURLException e) {
                   } catch (Exception e) {
              } catch (RemoteException e1) {
    }RMI works OK, but I don't know how to tell the server which are his observers. I know I have to use the addObserver (RemoteObserver ro) method but I don't know how to tell the server which are the GUI instances (which are the observers) so that I can add them.
    Any help will be welcomed. Thanks.
    Bye.

    Hello Vitor,
    Simply have your clients give your observable server object a remote reference to their observer object.
    It would look something like this:
    server.addObserver(new Remote(myObserver));Your server object would keep a list of its observers, and call them whenever it wants, using some interface method like:observer.stateChanged(someData);Essentially, design it just as if the observers were local.
    John

  • Help please on Observer / Observable and Serial Communications!

    Help!
    I have a project where I need a java application to talk to some test equipment via the serial port. I have studied the java comm api and played around with the SerialDemo example which I used to model my code.
    I have a SeialConnection class which is very similar to the example except I made it to extend Observable and I have it notify observers when data is detected on the serial port.
    I created a second class which extends Obserable which communicates with the SerialConnection and implemented the observer interface. This class process the incomming and outgoing data and provides some higher level methods, like getSerialNumber(), for my application to use. The application frame is an Observer of this class so the GUI can show the status as well.
    An example method from this class:
    private String Get590AROMString() {
    SendString("EZR-V"); //Send a command to the s.p.
    serialConnection.pause(750); //Basically a sleep(750)
    return ROMVersion; //Return the data from update()
    Excerpt from update method:
    // If return from serialConnection starts with VER: parse the RV and SN.
    if(T.startsWith("VER:")) {
    ROMVersion = new String(T.substring(0,T.indexOf('~')));
    SpeciesName = new String(T.substring(T.indexOf('~')+2));
    return;
    This works great when the test equipment sends a message or when the user selects a command from the program interface. My problem is when I try to send a command to the serial port from within the update method of the observer. There are instances where a result from the serial port needs to initiate another request for information.
    Here is a fragment from the update method of the application frame:
    public void update(Observable obs, Object obj) {
    DensTalkStatus DTS;
    if( obs==DT ) {
    DTS = (DensTalkStatus)obj;
    else if(DTS.GetStatus()==DensTalkStatus.NOTIFY_ZEROOK) {
    if(FIRSTCONNECT590A) {
    GDD.GetDensimeterInfo(); // *** This is the Request
    GDD.SetDensID(EDM);
    FIRSTCONNECT590A = false;
    When I make a request for additional information from the serial port within the update method I get nothing returned and the requested data arrives later after the update method has completed.
    I do not know the fine details of how the javax.comm or observer/obserable works but it appears to me that my strategy can only process one command at a time.
    Can anyone think of a way to allow the application's frame update method to request information and wait for the data to be ready?
    Does anybody have an example of how to do this type of communications?
    I am sorry for the length of this question... Thank you for your time.
    Doug

    I have not received any suggestions yet on an alternate method for this problem, but I have come up with a solution I think will work. I am posting it here so others who have the same problem can at least see what path I followed...
    The basic problem seems to be that I am trying to have my observer ask for information that requires the same observer / observable thread to respond.. duh! :) To requst additional information from the serial port I need to move the requests out of the update() method to a different thread.
    I implemented the SerialWorker class to make the request so the observer update() method could return normally without waiting for the result of the new request.
    Doug

  • Observer-observable pattern question

    Hi all there!!
    I reckon that in the observer-observable pattern, there is an notfiyObserver(object obj) method to invoke the Observer to receive the reference instance obj, and in the observer class, as there is a method called update(observable obr, object obj2), obj is subsituted into obj2 to complete the whole process. so obj from Observable is sent to Observer as obj2. Am i right?
    Because I've tried such thing, but seems that the observer receives null object...... sorry that I'm not going to post the code here /_\!! Thank you

    Are you sure you are calling notifyObservers(Object arg) and not just notifyObservers()? Because in the later case, the "observer" would receive null as a second argument in its "update" method.
    Try to print or do some operation on your arg object before passing it in notifyObservers method to see if it's really not NULL.
    Hope this helps..

  • Observer/Observable design pattern

    Is there a way to implement the Observer/Observable pattern in a pure java FX 1.2 desktop Application?
    And if yes how ? :)

    You can use the real stuff, as shown in some threads (eg. in [Cannot bind a string array|http://forums.sun.com/thread.jspa?threadID=5425718] I show an example).
    This is necessary only to bind Java variables to JavaFX code.
    Now, as said above, in pure JavaFX code, you use binding. And the 'on replace' facility is useful too, as changes trigger actions.

  • Observer/Observable vs. EventListener

    Can anybody tell me why Observer/Observable would be used in a situation rather than implementing EventListener? On the surface they seem redundant, but I'm hoping there's an explanation as to when and why you would use one over the other.
    Thanks.
    craig

    I've been wondering the same thing myself and have been able to make the following reasonings:
    - The Java Observer-Observable mechanism is "quasi-transactional" in the sense that Observers are not strictly notified when any change is made, but rather when the Observer decides to notify its registered Observers. Observers can still inquire (via hasChanged) if the Observable has been updated, so atomicity is not guaranteed for a set of changes (short of providing a bulk mutator).
    - The EventListener pattern is littered with various support implementations for firing events. The java.beans package has support classes for its listeners, as do AWT and Swing. In general the EventListener pattern is more of a pure pattern since the implementation is not embedded (as with the Observer-Observable mechanism).
    - The Observer-Observable mechanism seems to predate the JavaBeans specification in the naming conventions. I am personally not a frequent user of IDE's, so the following statement may be way off, but is an educated guess: It's quite likely that most IDE's cannot introspect the Observer-Observable mechanism the way they can with the EventListener pattern.
    - Referrent to the previous item, it is also not possible to use the standard JavaBeans Introspector to get an EventSetDescriptor for a JavaBean that implements an Observer. (A brief examination of the sources for Introspector shows this to be the case. I suppose one could write a custom BeanInfo to make an aggregated or superclass Observer appear with an EventSetDescriptor...)
    - The notification parameter for the Observer-Observable mechanism is an Object.
    - The notification parameter for an EventListener is an EventObject with some concrete extension that is commensuate with the events processed by the EventListeners.
    As I type this, I think I've convinced myself that the EventListener mechanism is probably preferrable in general to the Observer-Observable pattern for the following reasons:
    - First-class introspection support.
    - Limited contortions to make use of the framework (refer to the countless threads asking for advice on how to use the Observer-Observable mechanism without resorting to aggregation and subclassing).
    The main contention that I'd had with EventListeners over the Observer-Observable mechanism has been the quasi-transactional nature of the latter. In particular, it's nice to sometimes bundle changes to an object before sending out change notifications, especially with GUI applications (versus an "update-model-then-update-views-some-time-later" approach.) Nevertheless, it's possible to bundle change notifications with EventListeners. I guess I was wrapped up in using a PropertyChangeListener which has a property-by-property-change-notification nature.
    Hope my musings help...

  • Notify/Wait or Observable/Observer?

    Hi,
    I have one thread process the data and store the result in a data object. Several threads access the data object to display.
    Which one to use:
    1) Have the processing thread notify the display threads when it's done? Using thread wait()/notify()?
    2) Have the data object be the observable, and the dislay threads be the observers? Using the observable/observer concept?
    Thanks

    How exactly would you code the wait/notify method calls? I had dynamic data that was used to update the data models for a JList and a JTable, and found it difficult to notify the models correctly, after the data changed.
    Somehow the object has to "post" the fact that it has changed, a job for Observer/Observable. The Thread tutorial and the various Swing tutorials don't quite describe this in a way I understand. Can somebody give an example of how to use notify/wait in this sort of situation? Thanks.

  • Are Observer/Observable still alive?

    Hello. I can't understand why one should use these classes instead of the very common event listening model, composing with, or subclassing, EventListenerList.
    I also didn't find any recent code which uses Observer/Observable?
    Enrico

    Hello. I can't understand why one should use these
    classes instead of the very common event listening
    model, composing with, or subclassing,
    EventListenerList.
    I also didn't find any recent code which uses
    Observer/Observable?
    EnricoI prefer the names of the Observer / Observable classes but I think they aren't used because Observable is a class. Since there is no multiple inheritance in Java, it's not very useful. I have found the java.beans.PropertyChangeEvent, PropertyChangeListener, and PropertyChangeSupport classes to be a good replacement.

  • Observable Observer Model

    Hi,
    I am implementing Event Service for that
    I have two classes
    1]
    One class extends Observable and another implements Observer.
    whenever i get event i put it in memory Queue which is nothing but Vector and notify observer about this change
    now my observer gets that event and checks for matching subscribers and send event to those matching subscribers
    the problem i am facing is
    whenever observable class notify observer class
    unless and until update method is finished processing in observer class , observable class has to wait
    Please help in solving problem
    Thanks in advance

    This is my observable class
    package .....
    import java.util.*;
    public class InMemoryEvents extends Observable
         private static Ve
    ctor inMemRepository = new Vector();
         public InMemoryEvents()
              addObserver(new EventsHandlerThread());
    public Document Add2Stack(Document _doc) {
              try
                   inMemRepository.addElement( _doc );
                   sendMessage(_doc);
              catch(Exception e)
                   e.printStackTrace();
                   return           }
              return dom ;
    public synchronized void sendMessage(Document _doc)
              System.out.println("IN SEND MESSAGE");
              setChanged();
              notifyObservers(_doc);
    ===============================================================
    class EventsHandlerThread implements Observer
    public EventsHandlerThread()
    public void update(Observable o,Object arg)
              message=(Document)arg;
              notify();
    bun();
              System.out.println("--------------- hello --------");
              Vector v = InMemoryEvents.getVectorInstance();
              System.out.println(v);
              message = null;
    public void bun()
                   System.out.println("----------WAITING FOR THE EVENT TO COME----------");
                        while(message==null)
                             try{
                                  wait();
    in other methods i get events from vector and find matching subscribers for it
    Explantation :
    I have a memory queue where i am putting my events in as and when they come (i.,e in Vector)
    This is my observable class
    One observer is observing on that memory
    as soon vector gets one or more events observer will be nofitied by the observable about this change
    and update method gets called
    Now when update method is going on observable is waiting on that method ( That is what i found )
    I want to avoid this situation cos events are coming in continously
    Please help me its urgent
    Post some code if u have
    Thanks i advance

  • Observable/observer nightmare

    I'm currently simulating a robot with a graphical front end linked to a model using a model-view architecture. In fact there are two views running in parallel: a graphical representation and a set of JLabels displaying parameters of the model as they change. I have recently discovered that making the model extend the Observable class and the views implement the Observer interface is the way forward.
    However, this has messed up my architecture. Before, the model was a member of both the view classes. i.e. the model does not see the views. Unfortunately, the model needs to see the views to register them as Observers. What can be done? Is there a simple example of how to use the observing techniques properly?

    You also wanted an example, so, here goes.....
    Assuming that you dont change your listeners very much (and by the sounds of it, you dont), you can do something like the following (If you do change them around quite a bit, consider using AWTEventMulticaster).
    // The model that you can watch:
    public interface RobotModel
      public void addRobotListener(RobotListener r);
      public void removeRobotListener(RobotListener r);
    // The listener
    public interface RobotListener
      /* Note: You may want to consider giving an actual
         'change event' to describe the change - but In the
         simple case, your view can query the model when
         it knows it's been updated
      public void robotModelChanged(RobotModel aModel);
    // Impl
    public class YourModel implements RobotModel
      private List mListenerList;
      public YourModel()
       mListenerList=new LinkedList;
      public void addRobotListener(RobotListener aListener)
        /* Need to sync on the list - if you add/remove quite
           a lot, consider AWTEventMulticaster instead
        synchronized(mListenerList)
          if(!mListenerList.contains(aListener))
            mListenerList.add(aListener);
      public void removeRobotListener(RobotListener aListener);
        /* Again, sync on the list  */
       synchronized(mListenerList)
          mListenerList.remove(aListener);
      protected void pNotify()
        /* Call this when you want to notify your listeners
           of a change to your model
        synchronized(mListenerList)
          Iterator anIterator=mListenerList.iterator();
          while(anIterator.hasNext())
            RobotListener aListener=(RobotListener)anIterator.next();
            // Do the notification:
            aListener.robotModelChanged(this);
      /* Example of changing something */
      public void changeSomethingInTheModel()
        // Do the change, then:
        pNotify();
    // Your view:
    public class ViewImpl implements RobotListener
      private RobotModel mModel;
      public ViewImpl(RobotModel aModel)
        // You said the view knew about the model:
        mModel=aModel;
        // register as a listener to the model:
        mModel.addRobotListener(this);
      // We receive notification of changes thru this method:
      public void robotModelChanged(RobotModel aModel)
        if(aModel!=mModel)
          // receiving dodgy notification!
          // (probably dont need this check in practice!)
        else
          // Model updated - query the model and update
          // the view!
    }Note that your model does NOT need to know about a view - it just needs to know about a RobotListener.
    Dave.

  • Observer - Observable

    I'd like to port a simple app to a MIDlet.
    However, it makes use of the java.util Observer interface and Observable class (to notify GUI that it needs to update when data has changed).
    How can I best implement this functionality in a MIDlet?

    You will have to implement the code for the classes java.util.Observer and java.util.Observable. It would be quite simple to implement the classes. You can have a look at the JDK source code.
    The only data structure you would need is a Vector of Observer
    objects inside the Observable class that you write. It would be
    rather simple to implement...really.

  • Urgent: client requirement

    Hi Sap Experts,
    when I am executing the automatic payment run system is generated 2 checks for one vendor, that vendor have two invoices each invoce amount are 10000, 20000.
    Here two invoices amount should come in one chck , when executing automatic payment run. T/code F110
    is it possible , if it is possible please give me advise.
    Thanks in advance,
    Prabhakar
    Moderator: please obeserve the [forum rules |Before you post: Rules of Engagement;- No words such as "urgent" in the thread title. Thread locked.

    Hi prabhakar,
    In FBZP TCode Click 4 th button. i.e., Payment Method in company codes.  There you select the payment method for your company code and double click. 
    In the next screen you will find a check box called, "Single Payment for marked item".  Press F1 on that and you find the below description.
    """""Indicator: One Payment per Item?
    Causes open items which contain this payment method to be paid individually.
    Use
    All items, for which the payment method so indicated is entered explicitly, are paid individually. If the payment method is not specified explicitly but is instead selected by the payment program, several items can be paid together.""""""
    The functionality of this check box is that, if you flag it and give the payment method in the invoice document, then that will be paid through a separate check.  if you dont give the payment method in the invoice document, then it will pay all the invoices together.
    Hope this helps you a lot.
    Regards,
    Sreekanth....

  • Very Urgent Client requirement in OM

    Hi Oracle Gurus,
    Clients follow below procedure while shipping the product to customer in current system:
    Ex: Receives Sales orders from customer as below:
    1-july-12 - Part:ABC 200
    3-july-12 - Part:ABC 500
    10-jul-12 Part:ABC 700
    If Qty 800 is manufactured, simply they select the orders by FIFO method and system automatically calculate Qty 800 from order 1 – 200, order -2 500 and remaining from order 3 100. No need to calculate manually.
    It will end up with 10 july 12 order as Qty 600 pending.
    Their system shows 200 – 200 shipped; 500 – 500 shipped and 700 – 100 shipped
    Is it possible to achieve this in Oracle standard system in order management or need to go for customization?
    Quick responses are highly appreciated, helpful.

    943549 wrote:
    Hi Oracle Gurus,
    Clients follow below procedure while shipping the product to customer in current system:
    Ex: Receives Sales orders from customer as below:
    1-july-12 - Part:ABC 200
    3-july-12 - Part:ABC 500
    10-jul-12 Part:ABC 700
    If Qty 800 is manufactured, simply they select the orders by FIFO method and system automatically calculate Qty 800 from order 1 – 200, order -2 500 and remaining from order 3 100. No need to calculate manually.
    It will end up with 10 july 12 order as Qty 600 pending.
    Their system shows 200 – 200 shipped; 500 – 500 shipped and 700 – 100 shipped
    Is it possible to achieve this in Oracle standard system in order management or need to go for customization?
    Quick responses are highly appreciated, helpful.I think this is a standard business process..
    what we can do in oracle OM is create 3 lines with the above schedule ship date..
    Pick release and ship confirm the lines 1 and 2..which will be fulfiled right away..and for line 3 you can ship the 100 quantity too...and the remaining quantities will be backordered as there is no on hand available to fulfill it...and oracle will split the line 3 with remaining quantites which will be in awaiting shipping...then you can fulfill the quantities when you have on hand..
    HTH
    Mahendra

  • Observer& Observable in Java

    Can any one pls give one small example of how observers and observalbe is used in java.

    Hi,
    This sounds like homework. What does your textbook say? Have you tried to google, or search the forum?
    Kaj

  • RMI Remote Observer

    Sorry for the cross-post but getting answers out of the JINI forum is like pulling teeth...
    I'm looking to improve performance of an application I wrote which has a server generating remote events and distributing them to clients who have previously signaled interest. One thing I noticed is that when one of the clients has a slow connection the whole system suffers. So I was wondering if introducing a threaded architecture would help in the following piece of code.
    currently...
    Iterator hashMapKeySetIterator = hashMap.keySet().iterator();
    while ( hashMapKeySetIterator.hasNext() )
    Object key = hashMapKeySetIterator.next();
    Observer observer = (Observer)hashMap.get(key);
    try
    observer.notify( event[] ); <-------- Thread this???????
    } catch (RemoteException re)
    try
    removeObserver( key, observer );
    }catch(Exception e)
    //handle exception
    System.out.println("Provider.notify() Error --> " + re.getMessage() );
    So, if I instead just created a new thread for each of the calls to notify(), would that improve the overall performance? Would it introduce any problem areas or would there be anything I should be concerned about? Thanks in advance.
    Dave

    Yes. Your solution seems to be the way to solve this type of problem.
    I would recommend some type of Thread pool so that you don't have as much Thread creation overhead.

Maybe you are looking for

  • How can I get 18 Localized.rsrc's out of my trash can?

    How's that for a dumb question. What happened was - I stupidly moved my Palm software to an external hard drive for a back-up of it. I had a HORRIBLE time unmounting my hard drive because of the message that it couldn't be completed because some unkn

  • Apps transfer to Macbook Pro

    I I have purchased Pages, Numbers, and Keynote for my iPhone and iPad how do I transfer that and get them on my Macbook?

  • OWSM GATEWAY VIRTUALIZED BPEL PROCESS INVOCATION PROBLEM

    Hi This is the error i am getting when i try to invoke the VIRTUALIZED BPEL process from test page of OWSM. i have created a component and added service to it. But this error surfaced when i try to invoke the service. I can see the virtualized WSDL i

  • Network Signal question- What does the "E" mean?

    I have an 8GB iPhone, with the prepaid account from AT&T- I notice that occasionally, I have a little emblem next to the phone carrier- it's a square with a capital E in it. What does that mean?

  • 6.1.3(10B329) upgrade crashes how to fix it

    Ever Sense I downloaded This upgrade I've been having problems When I browse the Internet it crashes Sometimes even when I'm playing on apps Is there a way to fix this?