Event handling with Jython & Swing

我的未来我决定 提交于 2019-12-08 17:06:06

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/520615/event-handling-with-jython-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!