views:

825

answers:

1

I'm making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just set

JButton("Push me", actionPerformed = nameOfFunctionToCall)

However, trying same thing inside a class gets difficult. Naively trying

JButton("Push me", actionPerformed = nameOfMethodToCall)

or

JButton("Push me", actionPerformed = nameOfMethodToCall(self))

from a GUI-construction method of the class doesn't work, because the first argument of a method to be called should be self, in order to access the data members of the class, and on the other hand, it's not possible to pass any arguments to the event handler through AWT event queue. The only option seems to be using lambda (as advised at http://www.javalobby.org/articles/jython/) which results in something like this:

JButton("Push me", actionPerformed = lambda evt : ClassName.nameOfMethodToCall(self))

It works, but the elegance is gone. All this just because the method being called needs a self reference from somewhere. Is there any other way around this?

+3  A: 
JButton("Push me", actionPerformed=self.nameOfMethodToCall)

Here's a modified example from the article you cited:

from javax.swing import JButton, JFrame

class MyFrame(JFrame):
    def __init__(self):
        JFrame.__init__(self, "Hello Jython")
        button = JButton("Hello", actionPerformed=self.hello)
        self.add(button)

        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(300, 300)
        self.show()

    def hello(self, event):
        print "Hello, world!"

if __name__=="__main__":
    MyFrame()
J.F. Sebastian
Wow, that was simple! Thanks. This approach seems to send both self reference and event to the method, and it thus needs to be defined like:def nameOfMethodToCall(self, evt)which is fine!
Joonas Pulakka