Java Observer and Observable not working properly between applications
-
28-10-2019 - |
Question
I have an application with a main JFrame that contains a default list model. I want that if I modify something on these records, the second running application is automatically updated.
So far I have a MainController class which implements the listener and overwrites the update method:
public class MainController implements ActionListener, Observer {
public void update(Observable o, Object o1) {}
}
and a simple class that extends Observable
public class Comanda extends Observable{}
My problem is that if I delete one record from the first application, the second list doesn't update. The program is deleting the record from the text file but is not updating the default list model. Same problem with edit or add.
I tried adding "reloadList()" in the update method, but that doesn't work. Ideas?
Solution
Have you called addObserver
on Comanda
and added the MainController
as an Observer
? Also, when the change occurs are you calling setChanged
and notifyObservers
?
Looking at the code you have posted I can see that you have not wired the Observer
and Observable
Objects together. As I said, you have to call addObserver
on your Observable
object, then within your Observable
Object, whenever a change is made you need to call setChanged
then notifyObservers
. Only when notifyObservers
is called will the update
method of any Observer
s that have been added be called.
You said in your question that when you delete one record the list doesn't update, which makes me think that Comanda
is probably not the Object
that you want to Observe
. Whichever Object it is that holds the List
of records is the one that should be the Observable
.
Have a look at this for some more information on the Observer/Observable pattern.
OTHER TIPS
What you are trying to to is called "interprocess communication" - sending data from one application to another. There are various ways to do it; a Google search would give you more information. Observable
only works within a single application.