~/home_Jython/berry_py/worldCup/ex02/wc02b_JTable.py

INDEX Java.use(better, Jython)

》作業中です《

#! /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.29
"""
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((v,k) for group in groups.values()
                     for team in group for k,v in team.items())
    """
Group A
Team	MP	W	D	L	GF	GA	Pts
Uruguay	2	1	1	0	3	0	4
Mexico	2	1	1	0	3	1	4
France	2	0	1	1	0	2	1
South Africa	2	0	1	1	1	4	1

Group B
Team	MP	W	D	L	GF	GA	Pts
Argentina	2	2	0	0	5	1	6
Korea Republic	2	1	0	1	3	4	3
Greece	2	1	0	1	2	3	3
Nigeria	2	0	0	2	1	3	0

Group C
Team	MP	W	D	L	GF	GA	Pts
Slovenia	1	1	0	0	1	0	3
USA	1	0	1	0	1	1	1
England	1	0	1	0	1	1	1
Algeria	1	0	0	1	0	1	0

Group D
Team	MP	W	D	L	GF	GA	Pts
Germany	2	1	0	1	4	1	3
Ghana	1	1	0	0	1	0	3
Serbia	2	1	0	1	1	1	3
Australia	1	0	0	1	0	4	0

Group E
Team	MP	W	D	L	GF	GA	Pts
Netherlands	1	1	0	0	2	0	3
Japan	1	1	0	0	1	0	3
Cameroon	1	0	0	1	0	1	0
Denmark	1	0	0	1	0	2	0

Group F
Team	MP	W	D	L	GF	GA	Pts
Paraguay	1	0	1	0	1	1	1
Italy	1	0	1	0	1	1	1
New Zealand	1	0	1	0	1	1	1
Slovakia	1	0	1	0	1	1	1

Group G
Team	MP	W	D	L	GF	GA	Pts
Brazil	1	1	0	0	2	1	3
Côte d'Ivoire	1	0	1	0	0	0	1
Portugal	1	0	1	0	0	0	1
Korea DPR	1	0	0	1	1	2	0

Group H
Team	MP	W	D	L	GF	GA	Pts
Chile	1	1	0	0	1	0	3
Switzerland	1	1	0	0	1	0	3
Honduras	1	0	0	1	0	1	0
Spain	1	0	0	1	0	1	0
    """
    scores = {
        # Group A
        "uru": (2, 1, 1, 0, 3, 0, 4),
        "mex": (2, 1, 1, 0, 3, 1, 4),
        "fra": (2, 0, 1, 1, 0, 2, 1),
        "rsa": (2, 0, 1, 1, 1, 4, 1),
        # Group B
        "arg": (2, 2, 0, 0, 5, 1, 6),
        "kor": (2, 1, 0, 1, 3, 4, 3),
        "gre": (2, 1, 0, 1, 2, 3, 3),
        "nga": (2, 0, 0, 2, 1, 3, 0),
        # Group C
        "svn": (1, 1, 0, 0, 1, 0, 3),
        "usa": (1, 0, 1, 0, 1, 1, 1),
        "eng": (1, 0, 1, 0, 1, 1, 1),
        "alg": (1, 0, 0, 1, 0, 1, 0),
        # Group D
        "ger": (2, 1, 0, 1, 4, 1, 3),
        "gha": (1, 1, 0, 0, 1, 0, 3),
        "srb": (2, 1, 0, 1, 1, 1, 3),
        "aus": (1, 0, 0, 1, 0, 4, 0),
        # Group E
        "ned": (1, 1, 0, 0, 2, 0, 3),
        "jpn": (1, 1, 0, 0, 1, 0, 3),
        "cmr": (1, 0, 0, 1, 0, 1, 0),
        "den": (1, 0, 0, 1, 0, 2, 0),
        # Group F
        "par": (1, 0, 1, 0, 1, 1, 1),
        "ita": (1, 0, 1, 0, 1, 1, 1),
        "nzl": (1, 0, 1, 0, 1, 1, 1),
        "svk": (1, 0, 1, 0, 1, 1, 1),
        # Group G
        "bra": (1, 1, 0, 0, 2, 1, 3),
        "civ": (1, 0, 1, 0, 0, 0, 1),
        "por": (1, 0, 1, 0, 0, 0, 1),
        "prk": (1, 0, 0, 1, 1, 2, 0),
        # Group H
        "chi": (1, 1, 0, 0, 1, 0, 3),
        "sui": (1, 1, 0, 0, 1, 0, 3),
        "hon": (1, 0, 0, 1, 0, 1, 0),
        "esp": (1, 0, 0, 1, 0, 1, 0),
        }

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

        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 _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():
            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():
            comp = JTable(
                model = tableModel(),
                )
            comp.selectionModel.valueChanged = self

            model = comp.columnModel
            model.getColumn(0).preferredWidth = 100
            for i in range(1, model.columnCount):
                model.getColumn(i).preferredWidth = 30
            return comp
        
        pane = JScrollPane(
            viewportView = view(),
            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():
            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()
        return comp

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

        comp = JScrollPane(
            viewportView = view(),
            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]

        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

        def contents(path):
            return "".join([e for e in open(path)]) if exists(path) else None
##            return u"".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.text = unicode(text) if text else "*** File not found ***"
            comp.caretPosition = 0

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

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.pack()
    frame.show()

## ========================================
## ----------------------------------------
def tips2():
    frame = JFrame(
        title = "Color",
        size = (350,120),
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
        locationRelativeTo = None,
        )
    TIPS(master = frame)
    frame.visible = True

## ----------------------------------------
from pawt import colors
class TIPS():
    columnNames = "name","red","green","blue",
    colorNames = [e for e in dir(colors) if not e.startswith("_")]

    def __init__(self, master, *args, **keys):
        canvasPane = self._canvasPane(
            minimumSize = (50,100),
            )
        controlPane = self._controlPane(
            columnNames = self.columnNames,
            colorNames = self.colorNames,
            valueChanged = Command(self),
            minimumSize = (80,100),
            )
        self.splitPane = self._splitPane(
            leftComponent = canvasPane,
            rightComponent = controlPane,
            )
        master.contentPane = self.splitPane

    def _canvasPane(self, **keys):
        comp = JPanel(**keys)
        self.canvas = comp
        return comp

    def _controlPane(self, columnNames, colorNames, valueChanged, **keys):
        def _tableModel():
            model = DefaultTableModel()
            for e in columnNames:
                model.addColumn(e)
            for e in colorNames:
                c = getattr(colors, e)
                model.addRow([e, c.red, c.green, c.blue])
            return model

        def _table():
            self.table = \
            comp = JTable(
                model = _tableModel(),
                )
            # addListSelectionListener
            comp.selectionModel.valueChanged = valueChanged
##            comp.columnModel.selectionModel.valueChanged = valueChanged
            column = comp.columnModel.getColumn(0)
            column.preferredWidth = 200
            return comp
        
        pane = JScrollPane(
            viewportView = _table(),
            **keys
            )
        return pane

    def _splitPane(self, **keys):
        pane = JSplitPane(
            orientation = JSplitPane.HORIZONTAL_SPLIT,
            dividerLocation = 100,
            **keys
            )
        return pane        

    def _update(self, value):
        self.canvas.background = getattr(colors, value)

## ----------------------------------------
class Command:
    def __init__(self, client):
        self.client = client
        
    def __call__(self, e):                  # ListSelectionListener
        table = self.client.table
        row = table.selectionModel.leadSelectionIndex
##        column = table.columnModel.selectionModel.leadSelectionIndex
        value = table.getValueAt(row, 0)    # getValueAt(row, column)
        self.client._update(value)

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

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

## ========================================