I'm building an Android app and a Blackberry app (same app different platforms). There is an abstract class that I am building that will handle events. For instance, I touch the "save" button on Android it posts a notif/event. The abstract class receives that event. I press the "save" button on Blackberry, it does the same thing.
What is the best way to accomplish this? I've looked at EventObject, as well as MBeans and its notification classes but they appear overly complicated. In objective-c I simply register a class instance for notifications with the objective-c notificationcenter, and then in the class that triggers the notif, at the time of trigger we do something along the lines of "postNotification". Is there anything that easy in Java? Also I need to send Objects with those notifications.
Oh at I suppose we actually can't use any MBeans classes. Not part of Blackberry Java version.
Thanks!
With BlackBerry, if you're planning on these events to be generated from UI elements (ButtonField, ListField, etc) they all come with Field.setChangeListener(FieldChangeListener) so you just have to attach a listener to that. If you want this to be something that responds to things like IO or processing, you could use the Event and EventListener classes to accomplish this. Personally I think they're a little more than what I need for simple notifications, so I generally make my own simple interfaces.
Say you have a class that extends Thread that connects to a web service to download an XML file that lists states and their capitals. and processes it. You could create an interface EventGenerator with abstract methods public void addEventHandler(EventHandler) and protected void notifyHandlers(Object obj). Inside of this you have a Vector that stores EventHandlers that your notifyHandlers() can loop through and send a call to handler.handleEvent(Object). When you are finished with processing the data, you wrap it up in an Oject (maybe Hashtable, or a custom States bean), we'll call it states, and internally call notifyHandlers(states). Now as you go through each EventHandler, you call handler.handleEvent(states). You may consider putting a try/catch around each call to it so one EventHandler doesn't prevent all of them from running.
So onto the EventHandlers. This is another interface that has the abstract method public void handleEvent(Object obj). Say you have a Screen that, after the states are retrieved, will display them in a list. This Screen will implement EventHandler and then register itself with the EventGenerator using generator.addEventHandler(this). Whenever the processing is done, this method will get called and you can do whatever you want with the Object that is returned.
An addition you can implement is changing public void handleEvent(Object obj) to public boolean handleEvent(Object obj) and, similarly to navigation methods in BB, return true if the event was handled and nothing else should try processing it.
Related
If we have a class in Java responsilbe for building interfaces (builder), it builds an interface which the user interacts with (interface 1 )and the user clicks a button which does some processing using a calculation class.
Is there anyway of knowing when this processing is complete from the builder class so it can proceed to build the second interfce and hide/close the original?
I was thinking the interface could throw an event which can be listended for in the interface builder class.
Is there a more appropriate way of doing this?
A builder class should just build.
If you need something to listen for events and react by hiding or closing something and building something else, that sounds much more like a controller in Model-View-Controller or a related pattern. This controller would likely call the builder whenever it needs to close a view and present a new view, and it would be the recipient of such events.
I'm making a game in Java, and I think I have a good idea of how to handle events. Does this sound right?
A Window class--the view. It's a representation of the World at the current moment.
There's also a Game class -- the controller. (The model's implementation is irrelevant for this question).
The Window class doesn't care about events. Therefore, the event listener simply dispatches them to the Game class (via something like game.notifyEvent(Event e);.
The Game class, upon receipt of this event, will start updating values and the like, and some variables (like the location of the player) will be changed. At this point, it uses its class variable Window w to notify it of the changes (via various methods such as w.movePlayer(Position p), etc.
SO, does this sound like something that would make sense to you?
Yes, what you're doing makes some sense. I find it much more intuitive to have the Window listen to the Game than the other way round. I've also found that Java is much more maintainable if you separate out the different areas of the GUI and pass the Game into each of them through a fine-grained interface. I normally get the GUI elements to listen to changes in the model, and request any interactions to be dealt with. This way round makes for easier unit testing, and you can replace the GUI with a fake for acceptance testing if you don't have a decent automation suite, or even just for logging.
Usually splitting up the GUI results in some panels purely listening, and some panels purely interacting. It makes for a really lovely separation of concerns. I represent the panels with their own classes extending JPanel, and let the Window pass the Game to them on construction.
So for instance, if I have two panels, one of which displays the results and one of which has an "Update" button, I can define two interfaces: INotifyListenersOfResults and IPerformUpdates. (Please note that I'm making role-based interfaces here using the IDoThisForYou pattern; you can call them whatever you like).
The Game controller then implements both these interfaces, and the two panels each take the respective interface. The Update interface will have a method called RequestUpdate and the Results interface will have AddResultsListener. Both these methods then appear on the Game class.
Regardless of whether you get the Game to listen to the Window or the Window to the Game, by separating things through interfaces this way you make it much easier to split the Game controller later on and delegate its responsibilities, once things start getting really complicated, which they always do!
I think you should implement the Observer design pattern (http://en.wikipedia.org/wiki/Observer_pattern) without using .NET's events. In my approach, you need to define a couple of interfaces and add a little bit of code. For each different kind of event, create a pair of symmetric interfaces
public interface IEventXDispatcher
{
void Register(IEventXHandler handler);
void Unregister(IEventXHandler handler) throws NotSupportedException;
}
public interface IEventXHandler
{
void Handle(Object sender, Object args);
}
X denotes the specific name of event (Click, KeyPress, EndApplication, WhateverYouWant).
Then make your observed class implement IEventDispatcher and your observer class(es) implement IEventHandler
public class Dispatcher implements IEventXDispatcher, IEventYDispatcher ...
{
private List<IEventXHandler> _XHandlers;
private List<IEventYHandler> _YHandlers;
void Register(IEventXHandler handler)
{
_XHandlers.Add(handler);
}
void Unregister(IEventHandler handler) throws NotSupportedException
{
//Simplified code
_XHandlers.Remove(handler);
}
private MyMethod()
{
[...]
for(IEventXHandler handler: _XHandlers)
handler.Handle(this, new AnyNeededClass())
[...]
}
//Same for event Y
All the code is hand-written. I have little experience with Java but I believe this pattern may help you!
Please forgive the very basic nature of this questions - but we all have to start somewhere. I've done some googling but all answers seem to relate to UI Events.
I am creating a very simple android app that will display your location on screen. I have my main class (HelloAndroid at the moment) that extends Activity and I have created a class LcoationUpdateHandler that listens for updates.
HelloAndroid holds an instance of LocationUpdateHandler so my question is how does the LocationUpdateHandler communicate with HelloAndroid.
In flex I would dispatch an event from one to the other but from the searching I have done this doesn't seem like a very java-y way of doing things?
Thanks for your help.
When your HelloAndroid instance creates an instance of LocationUpdateHandler it can pass a reference to itself in the constructor, which LocationUpdateHandler can store to use for future method calls in the case of events.
For these kinds of situations you don't really need to know what type of object instatiated LocationUpdateHandler. This is were interfaces come in, you can define an interface defining the event methods and implement that interface so that LocationUpdateHandler can keep a reference to that interface to deliver events.
If the situation is symmetrical, both classes can implement the same event interface.
It sounds like what you're looking for is the Observer pattern. The way it works is that observers register with the object that they are observing, such that they can be notified on events.
In your specific case, if you want LocationUpdateHandler to push information to HelloAndroid, it has to know about HelloAndroid. So your LocationUpdateHandler should at least contain a reference to HelloAndroid, but to generalize this, it should have a List of observers that all implement a common interface containing a callback function that would be called whenever LocationUpdateHandler has an update.
I wrote a Listener. Now I want to notify it, when a change occurs. Nothing special.
Now I'm asking myself:
Is there I standard class for Events that I can use, or do I have to write a new one by myself?
I know there ara java.awt.Event and AWTEvent. But I am not working directly at GUI level here. Furthermore we are using Swing at GUI level. So I'm not shure if it is a good idea to mix Swing and AWT.
Thx
Its ancient and simple, but you could use Observer/Obserable in java.util:
java.util
public class Observable extends Object
This class represents an observable
object, or "data" in the model-view
paradigm. It can be subclassed to
represent an object that the
application wants to have observed.
An observable object can have one or
more observers. An observer may be any
object that implements interface
Observer. After an observable instance
changes, an application calling the
Observable's notifyObservers method
causes all of its observers to be
notified of the change by a call to
their update method.
For more info, try http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html.
There's nothing special about events in Java. If your events are not GUI events, then it would be less confusing for you to use your own class and not mix them with java.awt.Events.
If you are using swing, you can take a look at EventBus:
The Event Bus is a single-process publish/subscribe event routing library, with Swing extensions. The EventBus is fully-functional, with very good API documentation and test coverage (80+%). It has been deployed in many production environments, including financial, engineering and scientific applications.
I've always used EventObject as the base class for my custom events. Here's what the JavaDoc says:
The root class from which all event state objects shall be derived.
All Events are constructed with a
reference to the object, the "source",
that is logically deemed to be the
object upon which the Event in
question initially occurred upon.
Kind of a standard solution in Swing apps is to maintain a list of event listeners in the class the event originates from. When the event occurs you iterate over the list and notify each listener of the event. So it can be something like this (I omitted the access modifiers and some of the type declarations for brevity):
class SomeClassInWhichTheEventOccurs {
List<MyListener> listeners;
void addListener(listener) { listeners.add(listener); }
void removeListener(listener) { listeners.remove(listener); }
void fireEvent(someEventParameters) {
foreach (listener in listeners) listener.eventOccured();
}
void someMethodInWhichTheEventOccurs() {
...
fireEvent(someEventParameters);
}
}
The event parameters can be just anything: you can create your own event class, reuse java.awt.Event, or pass some parameters of arbitrary types.
Swing is based upon AWT, so you have to mix it. The problem comes with mixing AWT heavyweight components with Swing lightweight components. Don't use AWT heavyweight components.
Just to be notified that something has changed javax.swing.event.ChangeListener is fine. In fact, so long as you are not using a library that assumes the beans model, you can ignore event classes and use a observer without an event object.
I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project