This is quite difficult to phrase, but I need to be able to link a specific method to an object. More specifically, I'm making a graphics-oriented GUI, and I want to be able to assign an arbitrary method as the default "action" function for an element, such as a button.
That is, I created these interfaced "graphics" objects that basically have the ability to draw themselves. I would like them to handle their own actions, so I can, for example, do something like this:
GraphicObject b1 = new Button();
GraphicObject b2 = new Button();
b1.assignDefaultAction(---some method reference here--);
b2.assignDefaultAction(---a different method reference here--);
Then, if I do something like:
b1.action();
b2.action();
Each element will call its own referenced method independently. I believe this is possible to do in C++, but I haven't seen it in Java. Is it even possible, or is there some kind of a workaround? The thing I'm trying to avoid is having to create specific abstraction for every single little thing I need to do, or litter my containing JPanel with a hundred specifications that just look messy.
Thank you for all your help.
Buttons should use
ActionListener
implementations. Stick with Swing in that particular case.Your own classes can follow suit and start with a Command pattern interface:
Or maybe a better idea is to stick with the API that the JDK provides and try Callable.
There are no method references in Java. Instead you can use pseudo-closures (aka anonymous inner classes). The only problem with this is of course, you can't reuse the functions if needed.
Beginning with Java 8 there will be easy-to-use method references and lambda expressions.
Assigning actions to buttons is actually a prime example.
or, using method references:
Normally you'd just use an ActionListener anonymous inner class to do this, and add whatever method calls you want in the actionPerformed method.
Something like: