CookXml Jython Extension



Support This Project


stats counter


Logo Logo IntelliJ IDEA

This extension basically adds a <jython> tag, which supports Jython in CookXml. Each time this tag is used, a new instance of PythonInterpreter is created. Objects created using XML can be referenced using their id.

Personally I am not a big fan of scripting inside XML, since excessive use of scripts instead of actual Java code is meaningless in terms of developemental efforts and performance. However, from time to time I do find myself wishing to have extra flexibilities in designing certain aspects of GUI using XML. See the demo offered below to see what I mean.


To add <jython> to your existing tag library, say CookSwing, add the following code:

		CookJythonLib.setupTags (CookSwing.getSwingTagLibrary ());

There are three attributes associated with the tag.

Attribute Description
return Since Python does not have a way of returning a value outside functions, what you can do is to assign the return value to a variable in Python, then specify the variable in XML using this attribute.
class In most cases, the return value's Java class type can be automatically generated. If not, then you can explicitly specify the Java class object to be generated from the Python code.
src Jython code can be inserted in two ways: inside the tag, or in another resource/file specified using "src" attribute.

Note that Python interpreter is sensitive to indentations, so make sure you do it correctly in XML.

	<button text="Button 1">
		<jython return="action" func="addActionListener">
from java.awt.event import ActionListener

class ExitAction (ActionListener):
	def actionPerformed(self, e):
		statusBar.setText (e.getSource ().getText () + " Pressed");

action = ExitAction ()
	<button text="Button 2">
		<!-- calling an external Jython code (identical to the Jython code above) -->
		<jython func="addActionListener" src="examples/cookjython/" return="action"/>


Try the Java Web Start demo for some simple demos.

Note that Jython has trouble loading Java classes that are not in the same jar file as Jython in Java Web Start. Therefore, if you intend to write a Java Web Start applicationi using Jython, I would suggest you to repackage Jython, CookXml and other Java classes that you will ever need in Python codes into a single big jar file named jython.jar.

(c) Copyright 2004-2007 Heng Yuan. All rights reserved.

Valid XHTML 1.0! Valid CSS!