Swing Programming with Jython

  1. download and install a remotely recent J2SE JRE (1.4.2 or newer)
  2. download and install Jython 2.2.1 from: http://jython.sf.net/

run jython:

from javax.swing import JFrame
f = JFrame("Hello, Jython!")
f.show()

You have a little frame showing!

from javax.swing import JButton
b = JButton("Click me!")
f.contentPane.add(b)
f.validate()

Your frame now has a button! But clicking it does nothing. Let's make it print "I was clicked!", shall we?

There is a bit of nastiness (also niceness) here because neither Jython (or Python) has the ability of creating inline anonymous classes, so you can't do something akin to the Java:

a = new ActionListener() { public void actionPerformed(ActionEvent e) { ... } }

Leaving us holding our hands with something like:

from java.awt.event import ActionListener
class MyAction (ActionListener):
  def actionPerformed(e):
    print "I was clicked!"
b.addActionListener(MyAction())

Ick. But there is a nifty Jython slot for this, allowing niceties like:

def wasClicked(e): print 'I was clicked!'
b.actionPerformed = wasClicked

How about simply using a lambda? Well, lambda expressions (Jython or Python) can't contain the built-in non-function print, so we have to do a bit of ugliness for this "print a line" example:

import sys
b.actionPerformed = lambda x: sys.stdout.write('I was clicked!')

This is all said much better at:

http://www.oreilly.com/catalog/jythoness/chapter/ch01.html

and:

http://www.javalobby.org/articles/jython/

changed November 14, 2007