余録

#! /usr/bin/env python
# coding: utf-8
## ----------------------------------------
##
## (C) Copyright 2000-2010, 小粒ちゃん《監修》小泉ひよ子とタマゴ倶楽部
##
## ----------------------------------------
## History: Swing Example "2010 FIFA World Cup South Africa"
##      2003/07, Java/Jython
##      2006/07, Jython
##      2008/02, Jython 2.2.1
##      2010/06, Jython 2.5.0
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
"""
>>> tips()

>>> ## ----------------------------------------
>>> None
version: #1.0.18
"""
from __init__ import *

## ----------------------------------------
## 気軽に Swing〔2〕JTextArea: 各チーム紹介
## Java.use(better,Jython=Swing) 〜 萬プログラマーのための Python 導入ガイド
## ----------------------------------------
## ----------------------------------------
## 2008/03/17《2.1》今回の課題:相手チームを知ろう
## ----------------------------------------
from os.path import dirname, exists
from sys import argv

from java.awt import BorderLayout
from java.awt import Font
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JLabel
from javax.swing import JPanel
from javax.swing import JScrollPane
from javax.swing import JSplitPane
from javax.swing import JTabbedPane
from javax.swing import JTable
from javax.swing import JTextArea
from javax.swing import ListSelectionModel
from javax.swing.table import DefaultTableModel

## ----------------------------------------
class GroupListPanel(JPanel):

    groupTabs = "ABCDEFGH"
    groups = {
        "A": [                          # Group A
            {"rsa": "South Africa"},
            {"mex": "Mexico"},
            {"uru": "Uruguay"},
            {"fra": "France"},
            ],
        "B": [                          # Group B
            {"arg": "Argentina"},
            {"nga": "Nigeria"},
            {"kor": "Korea Republic"},
            {"gre": "Greece"},
            ],
        "C": [                          # Group C
            {"eng": "England"},
            {"usa": "USA"},
            {"alg": "Algeria"},
            {"svn": "Slovenia"},
            ],
        "D": [                          # Group D
            {"ger": "Germany"},
            {"aus": "Australia"},
            {"srb": "Serbia"},
            {"gha": "Ghana"},
            ],
        "E": [                          # Group E
            {"ned": "Netherlands"},
            {"den": "Denmark"},
            {"jpn": "Japan"},
            {"cmr": "Cameroon"},
            ],
        "F": [                          # Group F
            {"ita": "Italy"},
            {"par": "Paraguay"},
            {"nzl": "New Zealand"},
            {"svk": "Slovakia"},
            ],
        "G": [                          # Group G
            {"bra": "Brazil"},
            {"prk": "Korea DPR"},
            {"civ": "Cote d'Ivoire"},
            {"por": "Portugal"},
            ],
        "H": [                          # Group H
            {"esp": "Spain"},
            {"sui": "Switzerland"},
            {"hon": "Honduras"},
            {"chi": "Chile"},
            ],
        }
    teamNames = dict*1

    ## ----------------------------------------
    def __init__(self, master, *args, **keys):
        self.teams = {}
        self.label = {}
        self.textArea = {}
        self.tab = None
        self.scores = self._scores()
        self.master = master

        self.table = {}

        def splitPane(group):
            controlPane = self._controlPane(
                group = group,
                minimumSize = (200,84),
                )
            canvasPane = self._canvasPane(
                group = group,
                minimumSize = (200,50),
                )
            return self._splitPane(
                leftComponent  = controlPane,
                rightComponent = canvasPane,
                )
        
        master.contentPane = self._tabbedPane(
            panes = dict((e, splitPane(e)) for e in self.groupTabs),
            )
        self._update("South Africa")

    ## ----------------------------------------
    def _scores(self):
        def valid(line):
            for prefix in "Group","Team","Details":
                if line.startswith(prefix):
                    return False
            else:
                return True

        scores = {}
        path = "%s/score/score.txt"%dirname(argv[-1])
        lines = open(path).readlines() if exists(path) else []
        for line in lines:
            if valid(line):
                s = line.split("\t")
                team = self.teamNames[s[0]]
                scores[team] = [int(e) for e in s[1:]]
        return scores

    ## ----------------------------------------
    def _controlPane(self, group, minimumSize, **keys):
        columnNames = "Team","MP","W","D","L","GF","GA","Pts",

        def teams(group):
            return [(k,v) for team in self.groups[group]
                for k,v in team.items()]

        def tableModel(group):
            self.teams[group] = \
            model = DefaultTableModel()
            for e in columnNames:
                model.addColumn(e)
            for k,v in teams(group):
                model.addRow([v]+list(self.scores[k]))
            return model

        def view(group):
            self.table[group] = \
            comp = JTable(
                model = tableModel(group),
                toolTipText = ",\t".join(columnNames),
                )
            comp.selectionModel.valueChanged = self

            model = comp.columnModel    ;print("model::",model)
            model.getColumn(0).preferredWidth = 100
            pass; print("getColumn(0)::",model.getColumn(0))
            for i in range(1, model.columnCount):
                model.getColumn(i).preferredWidth = 30
            return comp
        
        pane = JScrollPane(
            viewportView = view(group),
            minimumSize = minimumSize,
            )
        return pane

    ## ----------------------------------------
    def _canvasPane(self, group, minimumSize, **keys):
        comp = JPanel(
            layout = BorderLayout(),
            )
        for layout, e in [
            ("WEST"  , self._labelPane(group)            ),
            ("CENTER", self._textPane(group, minimumSize)),
            ]:
            comp.add(e, getattr(BorderLayout, layout))
        return comp

    def _labelPane(self, group, **keys):
        def view(group):
            self.label[group] = \
            comp = JLabel(
                horizontalAlignment = JLabel.CENTER,
                horizontalTextPosition = JLabel.CENTER,
                verticalTextPosition = JLabel.BOTTOM,
                preferredSize = (100,50),
                )
            comp.font = comp.font.deriveFont(Font.ITALIC)
            return comp        

        comp = view(group)
        return comp

    def _textPane(self, group, minimumSize, **keys):
        def view(group):
            self.textArea[group] = \
            comp = JTextArea(
                lineWrap = True,
                wrapStyleWord = True,
                )
            comp.font = comp.font.deriveFont(Font.ITALIC)
            return comp        

        comp = JScrollPane(
            viewportView = view(group),
            minimumSize = minimumSize,
            )
        return comp

    ## ----------------------------------------
    def _splitPane(self, **keys):
        comp = JSplitPane(
            orientation = JSplitPane.VERTICAL_SPLIT,
            oneTouchExpandable = True,
            dividerLocation = 90,
            **keys
            )
        return comp

    def _tabbedPane(self, panes, **keys):
        def stateChanged(e):
            index = e.source.selectedIndex
            self.tab = self.groupTabs[index]
            e.source.toolTipText = "group %s"%self.tab

        comp = JTabbedPane(
            stateChanged = stateChanged,
            )
        for e in self.groupTabs:
            comp.addTab(e, panes[e])
        return comp
        
    ## ----------------------------------------
    def __call__(self, e):    # ListSelectionListener.valueChanged
        row = e.source.leadSelectionIndex
        value = self.teams[self.tab].getValueAt(row, 0)
        self._update(value)

    def _update(self, value=None):
        def name(key):
            for group in self.groups.values():
                for team in group:
                    if key in team:
                        return team[key]
            else:
                return None

        def imageIcon(path):
            return ImageIcon(path) if exists(path) else None

        def update_label(tab, path):
            comp = self.label[tab]
            comp.icon = imageIcon(
                "%s/squad/%s.gif"%(path, self.teamNames[value]))
            comp.text = value
            comp.toolTipText = self.teamNames[value]

        def contents(path):
            return "".join([e for e in open(path)]) if exists(path) else None

        def update_textArea(tab, path):
            comp = self.textArea[tab]
            text = contents(
                "%s/profile/%s.txt"%(path, value))
            comp.text = text if text else "*** File not found ***"
            comp.caretPosition = 0
            comp.toolTipText = value

        def update_table(tab):
            comp = self.table[tab]
            comp.toolTipText = value

        tab = self.tab
        path = dirname(argv[-1])
        update_label(tab, path)
        update_textArea(tab, path)
        update_table(tab)

## ----------------------------------------
def tips():
    frame = JFrame(
        title = u"2010 FIFA World Cup South Africa™",
        size = (350,300),
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
        locationRelativeTo = None,
        )
    GroupListPanel(frame)
    frame.show()

## ----------------------------------------
from doctest import testmod

if __name__=='__main__':
    inform()
    testmod()

*1:v,k) for group in groups.values() for team in group for k,v in team.items(

Jython/Swing《余録》JButton: 開催日&試合結果

記事一覧Java.use(better, Jython=Swing)《Jython2.5》《復刻改訂版》
Java プログラマーのための Python 導入ガイド -- 2010 FIFA World Cup South Africa™

《余録》JButton: 開催日&試合結果

《著》伊藤うさぎ、森こねこ《監修》小粒ちゃん@湘南組、小粒ちゃん@博多組
第1版♪2003/12/29 ● 第2版♪2006/10/02 ● 第3版♪2010/06/11

2010 FIFA World Cup の開催を機に、Jython2.5 で再構成しました。


課題:開催日と試合結果

要求仕様

予選リーグに出場した全32チームの個別情報をグループ別に表示したい。

  • モジュールを起動すると、
$ jython -i wc02c_JTableFile.py
>>> 

グループEのタブを選択したので、日本チーム Japan (jpn) に関する情報が表示されます。


以下の公式サイトから得られる情報をもとに、

その内容を反映したテキストファイル score/score.txt から各チームの戦績を読み込んで、テーブル JTable 内に表示します。

% cat score/score.txt
Group A
Team	MP	W	D	L	GF	GA	Pts
Uruguay	3	2	1	0	4	0	7
Mexico	3	1	1	1	3	2	4
South Africa	3	1	1	1	3	5	4
France	3	0	1	2	1	4	1
DetailsNewsAnalysisMatches
Group B
Team	MP	W	D	L	GF	GA	Pts
Argentina	3	3	0	0	7	1	9
Korea Republic	3	1	1	1	5	6	4
Greece	3	1	0	2	2	5	3
Nigeria	3	0	1	2	3	5	1
DetailsNewsAnalysisMatches
...

TOP
》作業中です《


関連記事

Last updated♪2010/06/25