When handling various events, my general policy has been to create a xxxHandler class like MouseHandler, WindowHandler, etc which extends its appropriate xxxAdapter class provided by Java.
I was just going over some other text about handling events and it says that whenever you extend any EventListener interface, say ActionListener, you must call the enableEvents(AWTEvent e) method in the constructor and call the super.processXXXEvent() whenever an event is generated.
I find this approach highly confusing. These methods have the access specifier as protected so I assume that these are for internal use only ?
What exactly are those methods for ?
Are they really needed for handling events ?
Do they offer any benefits over the usual actionPerformed(), mouseMoved(), etc where you add your code to handle the events in the method definition without calling any super methods?
Help needed. Simple words are highly appreciated rather than technical mumbo-jumbo.
What exactly are those methods for?
The processEvent() method filters the types of events that comes to it. The parameter to this method is of type AWTEvent type.
After filtering, this method calls the corresponding processXYZEvent() method which takes the corresponding event object.
For example, processMouseEvent(MouseEvent)
The processXYZEvent() method notifies the corresponding listeners about the event by passing the event object to the handler.
For example, processMouseEvent(MouseEvent) notifies the registered mouse listener(s).
The enableEvents() method decides what event(s) to give to the processEvent() method. This method cannot be overrided since it is final. However this can be accessed in the sub class of the Component class to decide what type of events that the component support.
Are they really needed for handling events ?
Their role is mentioned above. This means that they are needed for handling events because you can only handle an event when an event object is created and dispatched and those methods do this.
Related
Is there a way to call a method from another class to the class where the run method is present (without creating the object of the class with the run method)? I would like to know how the method addMouseListeners() call my mouseClicked() method located in the class where the run method is present. Please answer.
I think you're asking about the callback pattern. Wiki has some information and examples you might be interested in.
In general, the callback pattern involves passing off an instance of a class which will have various methods on it called in response to some event. Your mouse listener is a callback class instance, and the container you passed it to is generating mouse events and passing them to your mouse listener.
In processing if you want to register a mouse event listener, you just need to define a function with the name "mousepressed", "mousereleased", etc. and they "magically" become event listeners. This also happens to the controlP5 library I'm using, where all the functions named after a control widget "magically" become its event handler. I'm wondering how does Java handle this kind of magic? Where can I see some source code or topic regarding this pattern. I would like to know its mechanism since I can't define the listeners in main applet.
Processing might use reflection for some stuff, but in the case of the mousePressed() functions, that's a simple matter of inheritance.
Processing contains a PApplet class, the source of which you can view here: https://github.com/processing/processing/blob/master/core/src/processing/core/PApplet.java
At the time of this answer, line 3087 of the PApplet class is the mousePressed(MouseEvent) function that is called via an Event handler, which you can read about here: http://docs.oracle.com/javase/tutorial/uiswing/events/
This mousePressed(MouseEvent) method calls the no-arg mousePressed() function, which is an empty function on line 3084.
When you write a Processing sketch, you're secretly extending PApplet. When you write a mousePressed() function in your sketch, you override the empty mousePressed() function of the PApplet class. Now when the PApplet class gets a MouseEvent from its MouseListener, it calls your mousePressed function. That's how inheritance works.
If you're asking a more specific question, please provide an MCVE that demonstrates exactly what you're talking about.
I was having problems with class design until i found out about observable (using observer design pattern) and thus created a small application using it which solved my problem. I was happy and proud that I had used a good principle to sovle a problem.
Now i am about to start my main application and have just read this
Making a JFrame and Observable Object
Why is the poster advised against the use of observable and instead told to use propertychangelistenr? Is there any issues with using observable?
Regards
Observer and Listener pattern are very similar. But Observer has a weakness: all observables are the same. You have to implement the logic that is based on instanceof and cast object to concrete type into Observable.update() method.
Listeners are different. There are a lot of listener types. For example mouse listener, keyboard listener etc. Each one has several callback methods (i.e. keyPressed(), keyReleased() etc). So, you never have to implement the logic that should answer the question "is it my event" into the event handler.
I think that this is why listener model is preferable.
DejanLekic and others have probably by now realized, that Observable is not an interface. That is the whole problem with Java.util.Observable!
The user of Observable has to inherit from it, and nothing else.
Consider Java.RMI or Listener events.
The only right answer is "it depends".
Observable is good when you don't care what changes about an object; you only want to know that something changed and update e.g. a cache of object properties. It's interface is just too coarse, but it could be a time-saver if you just have a need for such a thing.
On the other hand, as AlexR noticed, you also don't know what type of argument gets passed in before hand (it can even be a null value!). This makes it harder to do something useful with it. A proper listener class can have a richer API, but at the cost of adding a Listener interface and event class to your project.
PropertyChangeListener is a special case of the Observable pattern. That is I guess that both solution is good from a design perspective. Meanwhile as far as I remember PropertyChangeListener has some built in support hence it might require less coding. Ie. see: http://download.oracle.com/javase/1.4.2/docs/api/java/beans/PropertyChangeSupport.html.
The difference is in how you use them. Most of the time subclasses of Observable have no particular implementation - you inherit from it just to get a new type of Observable. Listeners on the other hand implement particular interface (or top level EventListener interface) and therefore MUST implement certain methods.
In an Android app (or Java more generally if it's no different), what is the best way of calling a method whenever a variable's value changes?
What you really want to do is set up event-driven model to trigger a listener when an event happen (in your case, say a variable value has changed). This is very common not only for Java, but for other programming languages as well especially in the context of UI programming (though it is not necessarily only for that)
Typically this is done by doing the following steps:
Decide the interface that the listener should implement in the case of the event is triggered. For your case, you could call it VariableChangeListener and define the interface as:
public interface VariableChangeListener {
public void onVariableChanged(Object... variableThatHasChanged);
}
You could put any argument that you think it is important for the listener to handle here. By abstracting into the interface, you have flexibility of implementing the necessary action in the case of variable has changed without tight coupling it with the class where the event is occurring.
In the class where the event occurred (again in your case, the class where the variable could change), add a method to register a listener for the event. If you call your interface VariableChangeListener then you will have a method such as
// while I only provide an example with one listener in this method, in many cases
// you could have a List of Listeners which get triggered in order as the event
// occurres
public void setVariableChangeListener(VariableChangeListener variableChangeListener) {
this.variableChangeListener = variableChangeListener;
}
By default there is no one listening to the event
In the case of event occurred (variable has changed), you will then trigger the listener, the code would look like something like
if( variableValue != previousValue && this.variableChangeListener != null) {
// call the listener here, note that we don't want to a strong coupling
// between the listener and where the event is occurring. With this pattern
// the code has the flexibility of assigning the listener
this.variableChangeListener.onVariableChanged(variableValue);
}
Again this is a very common practice in programming to basically reacts to an event or variable change. In Javascript you see this is as part of onclick(), in Android you could check the event driven model for various listener such as OnClickListener set on a Button onclick event. In your case you will just trigger the listener based on different event which is whenever the variable has changed
You can make like this.As you have not defined what you want exactly.It may work. Suppose your variable name is v.Take one variable previous_v. Make previous_v=v; . You can put in your code according to your requirement:
if(v!=previous_v){
//your stuffs
}
I having a little trouble making use out of annotations in order to invoke the method that the annotation pertains to... I will give an example:
class MyEventHandlers {
#handler(id=“1”)
public doSomething() {
...
}
#handler(id=“2”)
public doSomethingElse() {
...
}
}
....
subscribe(“event1”, new MyEventHandlers, “1”);
//or maybe a better way to do this?!
....
//later, when I detect ‘event1’ I can process the required handler:
process(new MyEventHandlers, “1”)
The idea is, I want to have a way for defining handlers to events, and then linking a events to handlers. (consider for now an event is some string literal).
In all, I am not sure, what is the best style to use for doing what I want. The above is what I think at the moment. If there is better style to achieve this, please suggest.
I suspect that what you want to do, could be more easily implemented with an AOP framework.
But since you might want to do it yourself anyway:
The key to performance is to only use reflection during setup. So when subscribeing, you create a handler descriptor and add it to the listeners for the event. A handler descriptor is basically a java.lang.reflect.Method with an instance to call it on, and some knowledge on how to get event data in i.e. what arguments the method takes.
This way you can implement event triggering by
for (HandlerDescriptor desc : subscriptionMap.get(event)) {
desc.trigger(event);
}
, which should be plenty fast. You can have different HandlerDescriptors for handlers that take event info, ...
You can also make subscribe itself faster, by caching the java.lang.reflect.Methods at a class level (by a handler id key). Such that reflection is only used, when subscribeing a method of a class, not seen before.
What I'm not discussing here (hint: it's API style)
How to name the annotations
How to get context / event data in, you could take a look at JAX-RS for this.
Basically you'll also parse that info at setup time, e.g. by looking at the argument types, so that you don't need to dispatch for this at .trigger() time.
Whether to have subscribe / unsubscribe or return an Unsubscriber from subscribe.
That's the age old event system api style question.