例題で学ぶデザインパターン #12: DefaultMutableTreeNode を利用する

前の記事記事一覧次の記事

例題で学ぶ Jython/Swing デザインパターン《Jython2.5》
DefaultMutableTreeNode を利用する

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

■ 概要

例題により、アプリケーションを作成する過程を通して、Jython/Swing によるデザインパターンを習得します。

この課題では、Swing/GUI を使って階層構造を持つ情報を提示します。〈GoF〉Composite/Iterator/Visitor/Command パターンを導入すると、if/for 文によるコードの汚染、配列の境界問題が解消されるので、要求仕様の変更にも柔軟に対処でき、簡潔で見通しの良いコードを記述できるようになります。

《Note》JPython1.1.x/Jython2.1.x 用に作成したセミナー課題を、Jython2.5 で再構成しました。

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

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

$ jython2.5b3 -i step11/TreeEx.py

 
 
JTree を頂点とするツリー/colors を頂点とする部分ツリー/violet ノード

ボタン〔Tree〕を押すと、選択したノードを頂点とする部分ツリーが、新たなウィンドウに表示されます。
》作業中です《

事例:コードの解説

■ モジュール:TreeModel.py

新たに作成したモジュール TreeModel では、

from javax.swing.tree import DefaultMutableTreeNode
from TreeComposite import Node

class Model(object):
    def __init__(self, path, **keys):
        self.root = DefaultMutableTreeNode(Node(path))
        self.createNodes(path, self.root)

引数 path を頂点とする、部分ツリーを作成します。コンストラクター DefaultMutableTreeNode の引数には、各ノードに情報を提供するモデル Node を指定します。

    def createNodes(self, path, parent):
        for e in path.children():
            child = DefaultMutableTreeNode(Node(e))
            parent.add(child)
            if not e.leaf:
                self.createNodes(e, child)

各ノードが葉でない not e.leaf なら、新たに child を頂点とする、部分ツリーを作成します。

■ モジュール:TreeView.py
from TreeModel import Model

class View(JPanel):
    ...
    def actionPerformed(self, e):
        path = self.tree.selectionPath.lastPathComponent
        global                              Xmodel; Xmodel = \
        model = Model(path)
        view = JTree(model.root)
        view = JScrollPane(view)

        window = PopWindow(
            title = str(path),
            )
        window.contentPane.add(view)
        window.open()

コンストラクター JTree の引数には、ツリーの頂点となるノード model.root を指定します。

■ モジュール:TreeComposite.py
class Node(object):
    ...
    def __repr__(self):
        return str(self.node)

特殊 __repr__ メソッドは、ツリーの各ノードに表示される文字列を規定します。

Tips

》作業中です《

Last updated♪09/06/11