Sie sind auf Seite 1von 59

Programming in Java

Calculator Project - Introduction

2011 BlueSignet LLC. All rights reserved.

Wow! You are awesome!

We will be building our first full scale GUI application Think of where you came from! This is a crucial point in your maturity as a software developer

2011 BlueSignet LLC. All rights reserved.

What are we going to make?

A calculator class that will perform the basic arithmetic functions We will build the class using a console application first After testing is complete, we will apply this class to a GUI

2011 BlueSignet LLC. All rights reserved.

This is the end product

2011 BlueSignet LLC. All rights reserved.

This is the end product

Jframe GUI container


Contains all the graphical elements of our program
2011 BlueSignet LLC. All rights reserved.

This is the end product

JButtons
Allow the user to interact with the calculator backend class

2011 BlueSignet LLC. All rights reserved.

This is the end product

JTextField
Present the backend class output to the user

2011 BlueSignet LLC. All rights reserved.

This is the end product

JPanels
Sets out the layout for the GUI controls

2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Programming in Java
Calculator Project - Planning

2011 BlueSignet LLC. All rights reserved.

How will the calculator work?

Imagine what a calculator does and how it works There are several conditions that must be accounted for Keep in mind, there are an unlimited number of ways to get a calculator to function

Everyone has their own opinion

2011 BlueSignet LLC. All rights reserved.

Class Overview
CalculatorBase (Interface) Calculator (Abstract Class) WiBitCalculator
(Implementing Class)

2011 BlueSignet LLC. All rights reserved.

Process Flow
Start

Storage Queue (Array) Queue Index (Integer) Display (String) Just Calculated (Boolean) Sent Operator (Boolean)

Present User interface

Button Pressed?

Press Button

2011 BlueSignet LLC. All rights reserved.

Process Flow
Yes

Append Display

Press Button

Is Digit?

Anything else?

Perform square root on current value Store result in Queue Storage Index 0 Update Display Set Queue Index to 1

Value > 0

Multiply value in Storage Queue Index 0 by -1 Update Display Set Queue Index to 1

Return

Just Calculated?

Yes

Press Button (c)

Append Display (<p>)


Process Operator

Clear Storage Queue Array Set Queue Index to 0 Clear Display Set Just Calculated to False Set Sent Operator to False Queue Index == 2?

Sent Operator?

Yes Yes Clear Display Set Sent Operator to False


Display blank? OR Sent Operator is True

Perform Arithmetic

Return
Yes

Append passed value to display

Append Display (0)

Append Display (.)

Store result in Storage Queue Index 0 Update Display Set Queue Index = 1 Set Just Calculated to True

Return

Display contains .?

No

2011 BlueSignet LLC. All rights reserved.

Process Flow
Process Operator
Set Storage Queue Index 0 = Display Value Set Storage Queue Index 1 = Operator Passed Set Storage Queue Index = 2 Set Sent Operator = True

Queue Index is 0

Yes

Queue Index is 1

Yes

Set Storage Queue Index 1 = Operator Passed Set Sent Operator = True Set Just Calculated = False

Return

Queue Index is 2 AND Sent Operator is False

Yes

Append Display (=)

Append Display (<p>)

2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Programming in Java
Calculator Project Abstract Class

2011 BlueSignet LLC. All rights reserved.

CalculatorBase.java public interface CalculatorBase { public void pressButton(char buttonValue); public void setDisplay(String value); public void setDisplay(double value); public void appendDisplay(char value); public double getDisplayValue(); public String getDisplay(); }

2011 BlueSignet LLC. All rights reserved.

Calculator.java
public abstract class Calculator implements CalculatorBase { private double[] _calcQueue = new double[3]; private int _queueIndex = 0; protected String _displayValue = ""; private boolean _justCalculated = false; private boolean _sentOperator = false; /* ********************************* */ // Method that processes a single button being pressed on the calculator public void pressButton(char buttonValue) { } /* ********************************* */ // Sets the display text on the calculator public void setDisplay(String value) { } /* ********************************* */ // Sets the display text on the calculator when a numerical value is passed public void setDisplay(double value) { } /* ********************************* */ // Appends text to the display. public void appendDisplay(char value) { } /* ********************************* */ // Returns numerical display value public double getDisplayValue() { } /* ********************************* */ }
2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
public void pressButton(char buttonValue) { // IF number button is pressed if(Character.isDigit(buttonValue)) appendDisplay(buttonValue); ...

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF period character is pressed else if(buttonValue == '.') { // IF no buttons have been pressed... if(_displayValue.equals("") || _sentOperator) { // Send characters '0' and '.' appendDisplay('0'); appendDisplay('.'); } // IF buttons have been pressed... else if(!_displayValue.contains(".")) appendDisplay(buttonValue); } ...
2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF operator button was pressed... else if(buttonValue == '+' || buttonValue =='-' || buttonValue == '*' || buttonValue == '/') { // IF storage queue is empty if(_queueIndex == 0) { _calcQueue[_queueIndex] = getDisplayValue(); // Store the data that is in the display to the storage queue _calcQueue[++_queueIndex] = (double)buttonValue; // Add the sent operator to the middle queue location _calcQueue[++_queueIndex] = 0.0; // Set the last value of the queue to zero _sentOperator = true; } // IF storage queue has performed an operation else if(_queueIndex == 2 && !_sentOperator) { pressButton('='); // Perform equal operation pressButton(buttonValue); // Send manually press the operator button } // IF one value is stored in queue else if(_queueIndex == 1) { _calcQueue[_queueIndex++] = (double)buttonValue; // Store the operator button _justCalculated = false; // Remove the justCalculated flag. This helps make the calculator perform more accurately _sentOperator = true; } } ...
2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF equals operation is sent else if(buttonValue == '=') // Equals { if(_queueIndex == 2) // IF one number, and one operator was previously sent (traditional situation) { _calcQueue[2] = getDisplayValue(); // Store the value in the display into the storage queue switch((int)_calcQueue[1]) // Switch on the stored operation { case 43: // + _calcQueue[0] = _calcQueue[0] + _calcQueue[2]; // Perform addition break; case 45: // _calcQueue[0] = _calcQueue[0] - _calcQueue[2]; // Perform subtraction break; case 42: // * _calcQueue[0] = _calcQueue[0] * _calcQueue[2]; // Perform multiplication break; case 47: // / if((int)_calcQueue[2] == 0) { System.err.println("Illegal division by zero."); _calcQueue[0] = 0; } else _calcQueue[0] = _calcQueue[0] / _calcQueue[2]; // Perform division break; default: break; // Unknown operation... Do nothing } setDisplay(_calcQueue[0]); // Store the operation outcome in the display _justCalculated = true; // Tell the application that a calculation just occurred. This is used later to make sure the calculator behaves proper _calcQueue[1] = 0.0; // Reset operator value to zero _calcQueue[2] = 0.0; // Reset second value to zero _queueIndex = 1; // Set queue index to the center value. This means the calculator can accept a compound operation (Ex: 1+2=+2= would equal 5) } } ...

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF clear operation is requested else if(buttonValue == 'c') { for(int i = 0; i < _calcQueue.length; i++) _calcQueue[i] = 0.0; // Clear storage queue _queueIndex = 0; setDisplay(""); _justCalculated = false; _sentOperator = false; } ... // // // // Set queue index back to the begining Clear display Reset justCalculated flag Reset sentOperator flag

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF negative operation is requested (multiply whatever the current value is by -1) else if(buttonValue == 'n') { _calcQueue[0] = getDisplayValue() * -1; // Store the current display value multiplied by -1 setDisplay(_calcQueue[0]); // Set the display with the new value _queueIndex = 1; // Set the queue index to the middle. } ...

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: pressButton
... // IF Square Root operation is requested else if(buttonValue == 's') { if(getDisplayValue() > 0) // Make sure the value is positive { _calcQueue[0] = Math.sqrt(getDisplayValue());// Perform square root // store outcome in the first //queue storage index setDisplay(_calcQueue[0]); // Reset the display to the outcome _queueIndex = 1; // Set the queue index to the middle. } } }

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: setDisplay

public void setDisplay(String value) { _displayValue = value; } public void setDisplay(double value) { setDisplay(Double.toString(value)); }
2011 BlueSignet LLC. All rights reserved.

Calculator.java :: appendDisplay
// Appends text to the display. public void appendDisplay(char value) { // IF the justCalculated flag is set if(_justCalculated) pressButton('c'); // Clear calculator. Example: 1+1=2+2= else if(_sentOperator) { setDisplay(""); _sentOperator = false; } // Append to display value _displayValue += Character.toString(value); }

2011 BlueSignet LLC. All rights reserved.

Calculator.java :: appendDisplay

public double getDisplayValue() { // Return numerical value of the display if(_displayValue.equals("")) return 0.0; return Double.parseDouble(_displayValue); }

2011 BlueSignet LLC. All rights reserved.

WiBitCalculator.java
import java.text.*; public class WiBitCalculator extends Calculator { public void processString(String calcInput) { for(int i = 0; i < calcInput.length(); i++) pressButton(calcInput.charAt(i)); } public String getDisplay() { if(_displayValue.equals("")) return "0"; else return new String(_displayValue); } }
2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Programming in Java
Calculator Project Class Testing

2011 BlueSignet LLC. All rights reserved.

MainClass.java
import java.io.*; public class MainClass { public static void main(String[] args) throws Exception { WiBitCalculator calc = new WiBitCalculator(); String inputValue = ""; while(1 == 1) { System.out.print("MATH:>"); inputValue = readLine(); if(inputValue.toLowerCase().equals("exit")) break; calc.processString(inputValue); System.out.println(calc.getDisplayValue()); } } public static String readLine() throws Exception { InputStreamReader inStream = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inStream); return br.readLine(); } }
2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Programming in Java
Calculator Project GUI Class

2011 BlueSignet LLC. All rights reserved.

Look what we have done!


CalculatorBase (Interface) Calculator (Abstract Class) WiBitCalculator
(Implementing Class)

2011 BlueSignet LLC. All rights reserved.

Wow! Thats a lot of code files!

You could easily simplify this code We are trying to use different concepts to expose you to the full spectrum of the Java development Many built-in Java classes use the interface/abstract class inheritance structure Now lets code the GUI!

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CalculatorGui { private JFrame _calculatorFrame = null; private WiBitCalculator _calculatorProcessor = null; private JTextField _textFieldDisplay = new JTextField(); private int _numberButtonWidth = 60, _numberButtonHeight = 60; private int _frameWidth = 345, _frameHeight = 440; private int _bottonButtomY = _frameHeight - (_numberButtonHeight * 2) + 10; public CalculatorGui() { } private void setOnClick(JButton button) { } private void buildUserInterface() { } public void showDialog() { } }
2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: setOnClick
private void setOnClick(JButton button) { button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent a) { if(a.getActionCommand().equals("Clear")) _calculatorProcessor.processString("c"); else if(a.getActionCommand().equals("X")) _calculatorProcessor.processString("*"); else if(a.getActionCommand().equals("Sqrt")) _calculatorProcessor.processString("s"); else _calculatorProcessor.processString(a.getActionCommand()); _textFieldDisplay.setText(_calculatorProcessor.getDisplay()); } }); }
2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: CalculatorGui constructor


public CalculatorGui() { _calculatorFrame = new JFrame("WiBit.Net Java GUI Calculator"); _calculatorProcessor = new WiBitCalculator(); _calculatorFrame.setLayout(null); _calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _calculatorFrame.setSize(_frameWidth, _frameHeight); _calculatorFrame.setLocationRelativeTo(null); buildUserInterface(); }

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
private void buildUserInterface() { //*************************************************** // INIT BUTTONS JButton[] buttonNumbers = new JButton[10]; for(int i = 0; i < buttonNumbers.length; i++) buttonNumbers[i] = new JButton(Integer.toString(i)); JButton buttonPlus = new JButton("+"); JButton buttonEqual = new JButton("="); JButton buttonClear = new JButton("Clear"); JButton JButton JButton JButton JButton ... buttonDot = new JButton("."); buttonSubtract = new JButton("-"); buttonSquareRoot = new JButton("Sqrt"); buttonMultiply = new JButton("X"); buttonDivide = new JButton("/");

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
... //*************************************************** // SET BUTTON SIZES for(int i = 0; i < buttonNumbers.length; i++) { if(i == 0) buttonNumbers[i].setPreferredSize(new Dimension(_numberButtonWidth * 2 + 5, _numberButtonHeight)); else buttonNumbers[i].setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); } buttonDot.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); buttonSubtract.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); buttonSquareRoot.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); buttonMultiply.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); buttonDivide.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight)); buttonPlus.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight * 2 + 5)); buttonEqual.setPreferredSize(new Dimension(_numberButtonWidth, _numberButtonHeight * 2 + 5)); buttonClear.setPreferredSize(new Dimension(_numberButtonWidth * 2 + 5, _numberButtonHeight)); ...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
... //*************************************************** // SET ON CLICK for(int i = 0; i < buttonNumbers.length; i++) setOnClick(buttonNumbers[i]); setOnClick(buttonPlus); setOnClick(buttonEqual); setOnClick(buttonClear); setOnClick(buttonDot); setOnClick(buttonSubtract); setOnClick(buttonSquareRoot); setOnClick(buttonMultiply); setOnClick(buttonDivide); ...
2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // INIT DISPLAY TEXTFIELD _textFieldDisplay.setPreferredSize(new Dimension(_numberButtonWidth * 5 + 20, _numberButtonHeight)); _textFieldDisplay.setFont(new Font("Courier New", Font.PLAIN, 35)); _textFieldDisplay.setHorizontalAlignment(JTextField.RIGHT); _textFieldDisplay.setEditable(false); _textFieldDisplay.setText("0");

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // LEVEL 1 PANEL JPanel panelNumbersBottom = new JPanel(); panelNumbersBottom.setLayout(new FlowLayout(FlowLayout.LEFT)); panelNumbersBottom.add(buttonNumbers[0]); panelNumbersBottom.add(buttonDot); panelNumbersBottom.setBounds(0, _bottonButtomY, _numberButtonWidth * 3 + 15, _numberButtonHeight + 5);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // LEVEL 2 PANEL JPanel panelNumbersMiddle = new JPanel(); panelNumbersMiddle.add(buttonNumbers[1]); panelNumbersMiddle.add(buttonNumbers[2]); panelNumbersMiddle.add(buttonNumbers[3]); panelNumbersMiddle.setLayout(new FlowLayout(FlowLayout.LEFT)); panelNumbersMiddle.setBounds(0, _bottonButtomY - (_numberButtonHeight + 5), _numberButtonWidth * 3 + 15, _numberButtonHeight + 5);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
... //*************************************************** // LEVEL 3 PANEL JPanel panelNumbersTopMiddle = new JPanel(); panelNumbersTopMiddle.add(buttonNumbers[4]); panelNumbersTopMiddle.add(buttonNumbers[5]); panelNumbersTopMiddle.add(buttonNumbers[6]); panelNumbersTopMiddle.setLayout(new FlowLayout(FlowLayout.LEFT)); panelNumbersTopMiddle.setBounds(0, _bottonButtomY - (_numberButtonHeight * 2 + 10), _numberButtonWidth * 3 + 15, _numberButtonHeight + 5); ...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // LEVEL 4 PANEL JPanel panelNumbersTop = new JPanel(); panelNumbersTop.add(buttonNumbers[7]); panelNumbersTop.add(buttonNumbers[8]); panelNumbersTop.add(buttonNumbers[9]); panelNumbersTop.setLayout(new FlowLayout(FlowLayout.LEFT)); panelNumbersTop.setBounds(0, _bottonButtomY - (_numberButtonHeight * 3 + 15), _numberButtonWidth * 3 + 15, _numberButtonHeight + 5);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // + = PANEL JPanel panelPlusEquals = new JPanel(); panelPlusEquals.add(buttonPlus); panelPlusEquals.add(buttonEqual); panelPlusEquals.setLayout(new FlowLayout(FlowLayout.LEFT)); panelPlusEquals.setBounds(_numberButtonWidth * 3 + 15, _bottonButtomY - (_numberButtonHeight + 5), _numberButtonWidth * 2 + 10, _numberButtonHeight * 2 + 10);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // - Sqrt PANEL JPanel panelSubtractSquareRoot = new JPanel(); panelSubtractSquareRoot.add(buttonSubtract); panelSubtractSquareRoot.add(buttonSquareRoot); panelSubtractSquareRoot.setLayout( new FlowLayout(FlowLayout.LEFT) ); panelSubtractSquareRoot.setBounds(_numberButtonWidth * 3 + 15, _bottonButtomY - (_numberButtonHeight * 2 + 10), _numberButtonWidth * 2 + 10, _numberButtonHeight * 2 + 10);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // * / PANEL JPanel panelMultiplyDivide = new JPanel(); panelMultiplyDivide.add(buttonMultiply); panelMultiplyDivide.add(buttonDivide); panelMultiplyDivide.setLayout(new FlowLayout(FlowLayout.LEFT)); panelMultiplyDivide.setBounds(_numberButtonWidth * 3 + 15, _bottonButtomY - (_numberButtonHeight * 3 + 15), _numberButtonWidth * 2 + 10, _numberButtonHeight * 2 + 10);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // Clear PANEL JPanel panelClear = new JPanel(); panelClear.add(buttonClear); panelClear.setLayout(new FlowLayout(FlowLayout.LEFT)); panelClear.setBounds(_numberButtonWidth * 3 + 15, _bottonButtomY - (_numberButtonHeight * 4 + 20), _numberButtonWidth * 2 + 10, _numberButtonHeight * 2 + 10);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
...
//*************************************************** // Display PANEL JPanel panelDisplay = new JPanel(); panelDisplay.add(_textFieldDisplay); panelDisplay.setLayout(new FlowLayout(FlowLayout.LEFT)); panelDisplay.setBounds(0, _bottonButtomY - (_numberButtonHeight * 5 + 25), _numberButtonWidth * 5 + 25, _numberButtonHeight + 5);

...

2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface
... //*************************************************** // Add Controls to Frame _calculatorFrame.add(panelNumbersBottom); _calculatorFrame.add(panelNumbersMiddle); _calculatorFrame.add(panelNumbersTopMiddle); _calculatorFrame.add(panelNumbersTop); _calculatorFrame.add(panelPlusEquals); _calculatorFrame.add(panelSubtractSquareRoot); _calculatorFrame.add(panelMultiplyDivide); _calculatorFrame.add(panelClear); _calculatorFrame.add(panelDisplay); } ...
2011 BlueSignet LLC. All rights reserved.

CalculatorGui.java :: buildUserInterface

... public void showDialog() { _calculatorFrame.setVisible(true); } }

2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Programming in Java
Calculator Project Main Class

2011 BlueSignet LLC. All rights reserved.

MainClass.java
import java.io.*; public class MainClass { public static void main(String[] args) throws Exception { CalculatorGui calc = new CalculatorGui(); calc.showDialog(); } }

2011 BlueSignet LLC. All rights reserved.

The End?
Thank You For Watching!

2011 BlueSignet LLC. All rights reserved.

Das könnte Ihnen auch gefallen