Clojure ActionListener Interop

(See my full list of Clojure Swing examples and tutorials at Clojure Swing Interop)

When working with UI elements in Clojure Swing, your “go to” event handler is the ActionListener  found in the java.awt.event  package. This is a one-size-fits-all handler that works for many general situations where you just need to know **something** happened.

The fist hurdle to overcome is what Clojure technique should you use to implement the ActionListener  interface? The correct answer is reify .

Reify gives you an anonymous implementation of an interface. It is perfect for implementing Java event interfaces that are rarely named once created. Reify takes the interface name followed by method implementations as it’s arguments. The one trick that may throw off seasoned Java programmers implementing methods in Clojure’s reify, is that the first argument to functions used to implement methods is always an explicit this . this  is usually hidden in Java implementations of methods. It’s there, just not visible.

For example, here is reify implementing an ActionListener for a typical JButton  called my-button .

Here’s an example of a JFrame containing a JButton that prints “Clicked” to the console when clicked.

JFrame with JButton running in Clojure
JFrame with JButton running in Clojure

Here is the full source code.

 

Leave a Reply

Your email address will not be published.