《Jython2.5》The Swing Tutorial, TextDemoProject

記事一覧

The Swing Tutorial《Jython2.5.0》
《事例》 TextDemoProject

《著》小粒ちゃん《監修》小泉ひよ子とタマゴ倶楽部
第1版♪2003/05/23 ● 第2版♪2009/04/03

概要

Swing によるオブジェクト指向プログラミングへの扉を開きます。
※ 公式サイト《The Java™ Tutorials》で公開されている例題を、Jython で再構成しました。

タマゴ倶楽部のスタッフが作成した例題(サンプル集)を公開します。原則として、オリジナル版の趣旨を尊重しつつ、Jython の特徴を活かすように改編しています。なお、プログラムの不具合については「小粒ちゃん」にお問い合わせください。


事例:モジュールの起動

$ jython -i TextDemo.py 
>>> tips()

事例:コードの解説

#! /usr/bin/env python
# coding: utf-8

## ----------------------------------------
##package components

##/* TextDemo.java requires no other files. */

from java.awt import GridBagConstraints
from java.awt import GridBagLayout
from java.awt.event import ActionListener
from javax.swing import JFrame
from javax.swing import JPanel
from javax.swing import JScrollPane
from javax.swing import JTextArea
from javax.swing import JTextField

## ----------------------------------------
class TextDemo(JPanel, ActionListener):
    newline = "\n"

    def __init__(self):
        super(self.__class__,self).__init__(GridBagLayout())

        self.textField = JTextField(
            20,
            actionPerformed = self,     #addActionListener
            )

        self.textArea = JTextArea(
            5, 20,
            editable = False,
            )
        scrollPane = JScrollPane(self.textArea)

        ##Add Components to this panel.
        c = GridBagConstraints()
        c.gridwidth = GridBagConstraints.REMAINDER

        c.fill = GridBagConstraints.HORIZONTAL
        self.add(self.textField, c)

        c.fill = GridBagConstraints.BOTH
        c.weightx = 1.0
        c.weighty = 1.0
        self.add(scrollPane, c)

    def __call__(self, evt):     #actionPerformed
        text = self.textField.text
        self.textArea.append(text + self.newline)
        self.textField.selectAll()

        ##Make sure the new text is visible, even if there
        ##was a selection in the text area.
        self.textArea.caretPosition = self.textArea.document.length

    """
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
    """
    @staticmethod
    def createAndShowGUI():
        ##Create and set up the window.
        frame = JFrame("TextDemo")
        frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE

        ##Add contents to the window.
        frame.add(TextDemo())

        ##Display the window.
        frame.pack()
        frame.visible = True

def tips():
    ##Schedule a job for the event dispatch thread:
    ##creating and showing this application's GUI.
    TextDemo.createAndShowGUI()
  • リスナー actionPerformed= として、インスタンスオブジェクト self を指定します。

》作業中です《
TOP


関連記事

  • INDEX《Swing》JTextField

Last updated♪2009/10/17