@Ov3rM1nD
Congratulations on getting as far as you have. First things first
Yes that’s very good.
This technique uses Java Reflection and can be a difficult topic to master but you have made an excellent start. Java Reflection allows the user to examine the source code (classes, attributes, methods etc) at runtime and is really neat. It is the main technique I use in G4P and GUI Builder.
in the constructor this code looks for our event handler and if found stores a reference to it in myEventMethod
, if it can’t find the method myEventMethod
will be initialised to null
.
myEventMethod = pa.getClass().getMethod("buttonMouseover", new Class[] { Button.class });
So in the makeEvent method you first test to make sure the method exists then the crunch comes here
myEventMethod.invoke(pa, new Object[] { this });
myEventMethod.invoke
- execute the method referenced by myEventMethod
pa
- is the object the underlying method is invoked from
new Object[] { this }
- a list or parameters to be passed to the method, in this case a single parameter of type Button
Two questions here, the first answer is do not call it from the draw() because you already have registered your button for mouse events so remove the call from draw and changeb the mouseEvent to
public void mouseEvent(MouseEvent m) {
//if (isInside() && m.getAction() == MouseEvent.PRESS) setVisible(!isVisible());
if (isInside() && m.getAction() == MouseEvent.PRESS) fillColor = 0xffFF0000;
if (isInside() && m.getAction() == MouseEvent.RELEASE) fillColor = 0xff04B4FF;
if (isInside() && visible && m.getAction() == MouseEvent.MOVE) makeEvent();
}
I would also modify this method further to use a switch statement to avoid multiple calls to isInsie and getAction like this
public void mouseEvent(MouseEvent m) {
if (isInside()) {
switch (m.getAction()) {
case MouseEvent.PRESS:
fillColor = 0xffFF0000;
break;
case MouseEvent.RELEASE:
fillColor = 0xff04B4FF;
break;
case MouseEvent.MOVE:
if (visible) makeEvent();
break;
}
}
}
It is possible to call the method makeEvent
from outside the class but it doesn’t make sense to do so and would only confuse someone reading your code.
It is a good example and the concept is called Reflection
If you google ‘java reflection tutorial’ there and lots of sites listed that might help.