SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
Jython wraps Java libraries so that any of them can be used directly or via inheritance. In addition, Python shorthand simplifies coding.
As an example, consider the HTMLButton.java example from Thinking in Java. Here is its conversion to Jython:
# Jython/PythonSwing.py # The HTMLButton.java example from "Thinking in Java" # converted into Jython. from javax.swing import JFrame, JButton, JLabel from java.awt import FlowLayout frame = JFrame("HTMLButton", visible=1, defaultCloseOperation=JFrame.EXIT_ON_CLOSE) def kapow(e): frame.contentPane.add(JLabel("<html>"+ "<i><font size=+4>Kapow!")) # Force a re-layout to # include the new label: frame.validate() button = JButton("<html><b><font size=+2>" + "<center>Hello!<br><i>Press me now!", actionPerformed=kapow) frame.contentPane.layout = FlowLayout() frame.contentPane.add(button) frame.pack() frame.size=200, 500
If you compare the Java version of the program to the above Jython implementation, you’ll see that Jython is shorter and generally easier to understand. For example, to set up the frame in the Java version you had to make several calls: the constructor for JFrame(), the setVisible() method and the setDefaultCloseOperation() method, whereas in the above code all three of these operations are performed with a single constructor call.
Also notice that the JButton is configured with an actionListener() method inside the constructor, with the assignment to kapow. In addition, Jython’s JavaBean awareness means that a call to any method with a name that begins with “set” can be replaced with an assignment, as you see above.
The only method that did not come over from Java is the pack() method, which seems to be essential in order to force the layout to happen properly. It’s also important that the call to pack() appear before the size setting.