Java Event Handling

Here's an example of Java event handling in Jython. It does the same thing the example in the previous section did but in the Java (Jython) way.

>>> from javax.swing import JFrame, JButton
>>> from java.awt.event import ActionListener
>>> class hello(ActionListener):
...   def actionPerformed(self, event):
...           print "Hello"
...
>>> f = JFrame()
>>> b = JButton("Hello from Java Events")
>>> hi = hello()
>>> b.addActionListener(hi)
>>> f.getContentPane().add(b)
>>> f.pack()
>>> f.visible = 1

I think you'll prefer the more Pythonesque way of doing things because it's brief and easy. Unfortunately, however, you need to know the Java way to understand the Jython way. For example, the only way to know that JButton supports an event ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.