Swing – Why does Jython refuse to find the Java package

jythonswing

I know it's something silly, but for some reason Jython refuses to find javax.swing. I'm using Java 1.6.0_11. This is my start-up script:

@echo off

"%JAVA_HOME%\bin\java" -Xmx1024M -classpath ".;c:\Projects\Jython2.5.1\jython.jar" org.python.util.jython 

My output looks like:

Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_10
Type "help", "copyright", "credits" or "license" for more information.
>>> import javax.swing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named swing
>>> import javax
>>> dir(javax)
['__name__']
>>>

Best Answer

Most likely Jython is not scanning your packages. On startup, Jython tries to go through the jars and class files on its path and scan for Java packages. This is necessary because there is no way to look for Java packages by reflection. Package scanning can be deliberately turned off, or you could lack write privileges where it wants to write the cached information out see http://wiki.python.org/jython/PackageScanning for more. The best way to import Java classes is to do so explicitly class by class, like so:

from javax.swing import JFrame

This method should always work, even if package scanning is off or otherwise unable to work, and is the recommended approach (though it can be a bit tedious). If you do want to import packages (or if you want to do "from javax.swing import *" which also depends on package scanning - but is discouraged) you will need to figure out why your package scanning isn't working.

Related Topic