Created
July 21, 2010 11:25
-
-
Save apg/484357 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from javax.swing import JFrame, JLabel, JTextField, JButton, JOptionPane | |
from java.awt import FlowLayout | |
from java.awt.event import ActionListener, MouseAdapter | |
import math | |
TO_CEL = u"→" | |
TO_FAHR = u"←" | |
class TempConverter(JFrame): | |
def __init__(self): | |
super(TempConverter, self).__init__() | |
self._fahr = JTextField(3) | |
self._cel = JTextField(3) | |
self._cel.setEditable(False) | |
self._switcher = JButton(TO_CEL) | |
self._switcher.addActionListener(ButtonHandler(self)) | |
self._fahr.addActionListener( | |
Handler(self._cel, | |
lambda x: int(math.floor((x - 32) * 5/9.0)))) | |
self._cel.addActionListener( | |
Handler(self._fahr, | |
lambda x: int(math.floor((9/5.0 * x) + 32)))) | |
content = self.getContentPane() | |
content.setLayout(FlowLayout()) | |
for n in [JLabel(u"Fahrenheit:"), self._fahr, self._switcher, | |
JLabel(u"Celsius:"), self._cel]: | |
content.add(n) | |
self.setSize(350, 60) | |
self.setResizable(False) | |
self.setVisible(True) | |
class ButtonHandler(ActionListener): | |
def __init__(self, conv): | |
self._converter = conv | |
def actionPerformed(self, event): | |
if self._converter._switcher.getText() == TO_CEL: | |
self._converter._switcher.setText(TO_FAHR) | |
self._converter._fahr.setEditable(False) | |
self._converter._cel.setEditable(True) | |
else: | |
self._converter._switcher.setText(TO_CEL) | |
self._converter._fahr.setEditable(True) | |
self._converter._cel.setEditable(False) | |
self._converter._fahr.setText(u"") | |
self._converter._cel.setText(u"") | |
class Handler(ActionListener): | |
def __init__(self, target, converter): | |
self._target = target | |
self._converter = converter | |
def actionPerformed(self, event): | |
value = event.getActionCommand() | |
if value.isdigit(): | |
self._target.setText(str(self._converter(int(value)))) | |
else: | |
JOptionPane.showMessageDialog(self._target, | |
u"Invalid temperature. Please only use integers.", u"Error", | |
JOptionPane.ERROR_MESSAGE) | |
self._target.setText(u"") | |
if __name__ == '__main__': | |
b = TempConverter() | |
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment