Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handling with Jython & Swing

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?

like image 815
Joonas Pulakka Avatar asked Feb 06 '09 15:02

Joonas Pulakka


1 Answers

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()
like image 84
jfs Avatar answered Sep 30 '22 18:09

jfs