|
This is a simple implementation of a Calculator. I started with some code I found in Object-Oriented Programming and Java by Danny C.C. Poo and Derek B.K. Kiong which implemented the four binary operations: + - / * and = in the class CalculatorEngine. I added the unary functions and built a Swing GUI.
Design Decisions
- CalculatorEngine
The original code returned Double.toString( value ). This worked fine
from the command line but gave me problems when I was designing the GUI; exponential
numbers were being returned.
I then tried using a JFormattedTextField in the GUI with
a DecimalFormat. This also presented difficulties. The default pattern
for DecimalFormat is "#,##0.0#". The display always showed
0.0. I only wanted to show decimal digits if the user had selected the
decimal key. I changed the pattern to #,###.#" and invoked
setDecimalSeperatorAlwaysShown( false ) but then the decimal did not
show up until the user selected another digit key and if that happened to be a zero,
in any decimal position, it was not shown until a number between 1 and 9 was selected.
In the end I gave up and decided to modify CalculatorEngine, adding the
display field, a NumberFormatter and modifying the code to
keep the value and display attributes in sync.
- Calculator
The key to the GUI is displaying the various buttons in a pleasing manner and finding
an easy way to invoke their actions. By default, each JButton's action
command is set to the value of the button label. This got me thinking about how
nice it would be if, when a user selected the cos button, the button action
listener could invoke engine.cos(). The reflection mechanism in Java
allows for just such a scenario.
I also wanted the buttons appearance to vary according to their functions: digit,
unary, binary, control. To accomplish this I created an inner class
CalcButton which implements ActionListener and then created
a number of subclasses to handle the different colour settings for each function.
All in all the whole thing came out fairly clean<g>. There is one small flaw that
I'm aware of, if the result of a unary operation such as mod is zero, the
display shows nothing when really it should show a '0'. Haven't figured out how to get
around this yet. If you have a solution, please let me know <g>
|