例題で学ぶ Jython/Swing フレームワーク #6: JList

記事一覧

Java.use(better, Jython=Swing)《Jython2.5.0》
#6: JList

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

概要

Swing によるオブジェクト指向プログラミングへの扉を開きます。
Java で作成した例題を、Jython で再構成しました。


》こちらに移動中です《
》こちらに移動中です《

事例:モジュールを起動する

$ jython2.5.0 -i swing_tips.py 
>>> ex()
 0: step00 -- from javax.swing import JFrame
 1: step01 -- from javax.swing import JButton
 2: step02 -- class TIPS()
 3: step03 -- from javax.swing import JPanel
 4: step04 -- def command(self, *args)
 5: step05 -- from random import randint
 6: step06 -- from javax.swing import JList
 7: step07 -- from javax.swing import DefaultListModel
 8: step08 -- from javax.swing import JScrollPane
 9: step09 -- class Command(object)
10: step10 -- def addElement(self, obj)
11: step11 -- from java.awt import GridLayout
12: step12 -- from javax.swing import JLabel
>>> do(5)

モジュールを起動すると、次のようなウィンドウが現れます。


  • ボタンを押すたびに、3桁の乱数(100〜999)が出力されます。
>>> do(5)
>>> 923
121
793

事例:コードの解説

from random import randint

def step05():
    class TIPS():
        def __init__(self, master):
            self.create_controller(                             #1:
                master = master,
                text = "random",
                command = self.command,
                )
            
        def create_controller(self, master, text, command):     #2:
            panel = JPanel()
            master.add(panel)
            comp = JButton(
                text = text,
                actionPerformed = command,     # ActionListener
                )
            panel.add(comp)

        def command(self, *args):                               #3:
            print(randint(100,999))
        
    ## ----------------------------------------
    frame = JFrame(
        title = "swing: step05",
        size = (180,100),
        )
    TIPS(master=frame)    
    frame.visible = True
■ #1,2: リファクタリング
            self.create_controller(                             #1:
                master = master,
                text = "random",
                command = self.command,
                ...            
        def create_controller(self, master, text, command):     #2:

メソッド create_controller の本体では、

  • ボタンに表示するテキスト text
  • ボタンの選択に呼応するイベントリスナー command

に依存しない、抽象表現が可能になります。これらの具体的な情報は、メソッド呼び出しの実引数を指定するまで、確定しません。

》こちらに移動中です《
TOP


関連記事

Last updated♪2009/10/18