Python 弾丸ツアー/Java: JavaBeans 準拠 ... step 2: ボタンを利用する
Python.use(better); Python 弾丸ツアー/Java: JFC/Swing 編
>>> JavaBeans 準拠
step 2: ボタンを利用する
《Python3.1|Jython2.5|IronPython2.6》
《著》小粒ちゃん@湘南組《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/23 ● 第4版♪2010/03/08
step 2: ボタンを利用する
《課題》日時を確認するウィンドウを表示したい。
《テストケース》 ̄次のコマンドを実行すると、
$ jython -i swingTimer.py
ウィンドウが現われます。ここで、"Click Me" とあるボタンをクリックすると、
そのときの日時が表示されます。ウィンドウを閉じると、アプリケーションが終了します。
■ Java vs. Jython
 ̄このアプリケーションを Jython で記述すると、次のようになります。
## ---------------------------------------- step1 from java.awt.event import ActionListener class Tips(JPanel, ActionListener): def __init__(self, *args, **keys): button = JButton() button.setText("Click Me") button.setPreferredSize(Dimension(200, 50)) button.addActionListener(self) self.add(button) def actionPerformed(self, e): # ActionListener comp = e.getSource() comp.setText(str(ctime())) def tips(): frame = JFrame() frame.setTitle("Timer") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) comp = Tips() frame.setContentPane(comp) frame.pack() frame.setVisible(True) tips()
 ̄これは、同じ機能を実現する Java のコードを意識したものですが、また次のように、
## ---------------------------------------- step2 class Tips(JPanel): def __init__(self, *args, **keys): button = JButton() button.text = "Click Me" button.preferredSize = (200, 50) button.actionPerformed = self.actionPerformed self.add(button) def actionPerformed(self, e): # ActionListener comp = e.source comp.text = "%s"%ctime() def tips(): frame = JFrame() frame.title = "Timer" frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE comp = Tips() frame.contentPane = comp frame.pack() frame.visible = True tips()
より簡潔で洗練された表現ができます。
↑TOP
》作業中です《