lecture six – a simple...

37
1 1 Lecture Six Lecture Six A Simple Calculator A Simple Calculator More about More about IDEs IDEs Review of what you know Review of what you know Taking a detour Taking a detour Event driven programming Event driven programming Program Development Phases Program Development Phases Requirement Analysis Requirement Analysis A Simple Calculator A Simple Calculator Design Phase Design Phase Draw the interface Draw the interface Implementing the Graphic User Interface Implementing the Graphic User Interface Ten steps to a GUI Ten steps to a GUI Drill 6 Drill 6

Upload: others

Post on 17-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

11

Lecture Six Lecture Six –– A Simple CalculatorA Simple Calculator

�� More about More about IDEsIDEs

�� Review of what you knowReview of what you know

�� Taking a detourTaking a detour

�� Event driven programmingEvent driven programming

�� Program Development PhasesProgram Development Phases

�� Requirement Analysis Requirement Analysis –– A Simple CalculatorA Simple Calculator

�� Design Phase Design Phase –– Draw the interfaceDraw the interface

�� Implementing the Graphic User InterfaceImplementing the Graphic User Interface

�� Ten steps to a GUITen steps to a GUI

�� Drill 6Drill 6

Page 2: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

22

More about More about IDEsIDEs

�� We discussed We discussed IDEsIDEs earlier, and I promised some earlier, and I promised some more instruction on how to use more instruction on how to use JCreatorJCreator..

�� Mrs. Dianne Mrs. Dianne RisterRister, an outstanding computer , an outstanding computer science teacher at Consolidated High School in science teacher at Consolidated High School in College Station, has provided a lesson on how to College Station, has provided a lesson on how to download and use download and use JCreatorJCreator, and I have posted it , and I have posted it to the Web Site. to the Web Site.

�� Use it if you like, it will make programming a lot Use it if you like, it will make programming a lot easier, or as we mentioned earlier, if you have easier, or as we mentioned earlier, if you have another IDE you would rather use, feel free to do another IDE you would rather use, feel free to do so.so.

Page 3: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

33

What You Know So FarWhat You Know So Far

�� So far you know So far you know �� How to enter an run a basic program in javaHow to enter an run a basic program in java

�� How to import library packagesHow to import library packages

�� How to use How to use JOptionPaneJOptionPane for input and Outputfor input and Output

�� How to use primitive types and StringsHow to use primitive types and Strings

�� How to use basic operatorsHow to use basic operators

�� How to use if, switch, and the while and for loopsHow to use if, switch, and the while and for loops

�� How to use arraysHow to use arrays

�� Some things you don’t know yet Some things you don’t know yet �� Graphic User InterfacesGraphic User Interfaces

�� The use of methods (although you have seen the main method)The use of methods (although you have seen the main method)

�� Writing and using constructorsWriting and using constructors

�� We will discuss these things in detail later, but we are We will discuss these things in detail later, but we are going to go ahead and use them in this lesson.going to go ahead and use them in this lesson.

Page 4: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

44

Let’s Take a DetourLet’s Take a Detour

�� Let’s jump ahead and make a GUI Let’s jump ahead and make a GUI

(Graphic User Interface)(Graphic User Interface)

�� This code is going to use methods and This code is going to use methods and

constructors. constructors.

�� Don’t be concerned about this, we will Don’t be concerned about this, we will

discuss methods and constructors in detail discuss methods and constructors in detail

in a later lesson.in a later lesson.

Page 5: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

55

Graphic User InterfacesGraphic User Interfaces�� What are they?What are they?

�� A GUI is the kind of interface that you are used to using on A GUI is the kind of interface that you are used to using on

a computera computer

�� You have a screen with buttons and entry fields.You have a screen with buttons and entry fields.

�� You indicate what you want done, by entering data and You indicate what you want done, by entering data and

clicking on buttons.clicking on buttons.

�� Why are they important?Why are they important?

�� This is the kind of interface that people expectThis is the kind of interface that people expect

�� Java and Windows are designed to facilitate graphic user Java and Windows are designed to facilitate graphic user

interfacesinterfaces

�� If you are not programming with GUIs, you are not taking If you are not programming with GUIs, you are not taking

advantage of the capability of Javaadvantage of the capability of Java

�� And besides, GUIs are fun!And besides, GUIs are fun!

Page 6: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

66

Event Driven ProgrammingEvent Driven Programming

�� Previous interfacesPrevious interfaces�� provide questions and instructions for the user to follow provide questions and instructions for the user to follow in a linear sequencein a linear sequence

�� Each line of code is basically executed in sequence, or Each line of code is basically executed in sequence, or controlled by selection (if statements) or repetition controlled by selection (if statements) or repetition (while and for loops)(while and for loops)

�� Event driven Programming Event driven Programming �� The Program displays a window with a picture of the The Program displays a window with a picture of the graphic user interfacegraphic user interface

�� Execution is driven by the occurrence of an event, such Execution is driven by the occurrence of an event, such as the clicking of a button by the user.as the clicking of a button by the user.

�� GUIs are an example if event driven programmingGUIs are an example if event driven programming

Page 7: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

77

A Simple ExampleA Simple Example

Page 8: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

88

Development phasesDevelopment phases

�� Phase 1. Analyze the requirement.Phase 1. Analyze the requirement.

�� Identify what your program is required to doIdentify what your program is required to do

�� Phase 2. Design the ProgramPhase 2. Design the Program

�� Determine how the program will meet the requirementsDetermine how the program will meet the requirements

�� Phase 3. Implement the designPhase 3. Implement the design

�� Write the codeWrite the code

�� Phase 4. Test your program.Phase 4. Test your program.

�� Make sure it works for all legal entriesMake sure it works for all legal entries

Page 9: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

99

Analyze the RequirementsAnalyze the Requirements�� In this phase the analyst must identify what the In this phase the analyst must identify what the

program is required to do. This should be done prior program is required to do. This should be done prior

to writing any code.to writing any code.

�� Initial requirement typically comes from a user who is Initial requirement typically comes from a user who is

paying for the program developmentpaying for the program development

�� The program analyst must expand on the requirement The program analyst must expand on the requirement

analysis to insure it is analysis to insure it is completecomplete (does every thing the (does every thing the

user needs) and user needs) and necessarynecessary (it does not have extraneous (it does not have extraneous

capabilities that are not required by the user)capabilities that are not required by the user)

Page 10: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1010

The Requirements for our ProgramThe Requirements for our Program

�� 1. Write a program with a Graphic User Interface1. Write a program with a Graphic User Interface……

�� 2. Include the name 2. Include the name ““Simple CalculatorSimple Calculator”” in the title bar in the title bar of the GUI windowof the GUI window

�� 3. Provide fields for the user to enter two numbers and a 3. Provide fields for the user to enter two numbers and a field for the sum.field for the sum.

�� 4. Provide an ADD button, which displays the sum of 4. Provide an ADD button, which displays the sum of the values in the sum field.the values in the sum field.

�� 5. Provide an X icon in the title bar to terminate the 5. Provide an X icon in the title bar to terminate the program program

Page 11: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1111

Design the InterfaceDesign the Interface

�� Draw a picture of the interfaceDraw a picture of the interface

�� Include all sub windowsInclude all sub windows

�� Show customer and discuss the designShow customer and discuss the design

�� Old Programmer ProverbOld Programmer Proverb

Programmer who analyzes and Programmer who analyzes and

designs on the fly, will get a lot designs on the fly, will get a lot

more programming practice !!!more programming practice !!!

Page 12: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1212

Draw the InterfaceDraw the InterfaceThe interface provides the “Look and Feel” of the program

Page 13: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1313

Implement the DesignImplement the Design

�� In the next several slides we will go through 10 In the next several slides we will go through 10 steps for implementing the steps for implementing the Simple Calculator Simple Calculator GUI ProgramGUI Program..

�� Follow along and write the program as we go.Follow along and write the program as we go.

�� Afterward you can expand and modify this GUI Afterward you can expand and modify this GUI to create GUIs of your own.to create GUIs of your own.

�� Once you have written one, you can use it as a Once you have written one, you can use it as a model to do whatever you want.model to do whatever you want.

�� It is always easier to rewrite than to start with It is always easier to rewrite than to start with a blank screena blank screen

Page 14: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1414

10 steps to writing our GUI based program10 steps to writing our GUI based program

Step 1. Step 1. Import library packages.Import library packages.Step 2. Step 2. Open the class Open the class SimpleCalcSimpleCalcStep 3. Step 3. Declare the components. Declare the components. Step 4. Step 4. Write the Write the ‘‘mainmain’’ method.method.Step 5. Step 5. Begin the constructor method.Begin the constructor method.Step 6. Step 6. Select and set a layout manager.Select and set a layout manager.Step 7. Step 7. Add components to the layout.Add components to the layout.Step 8. Step 8. Add listeners to button and window.Add listeners to button and window.Step 9. Step 9. Write the Write the ‘‘actionPerformedactionPerformed’’ method.method.Step 10. Step 10. Complete the Complete the ‘‘WindowListenerWindowListener’’

Page 15: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1515

Step 1. Import library packagesStep 1. Import library packages

�� Use the Use the ““importimport”” command to provide command to provide access to Java Library Packages.access to Java Library Packages.

�� The abstract windowing toolkit (The abstract windowing toolkit (awtawt) is ) is required to implement GUIrequired to implement GUI’’s in Java.s in Java.

�� Swing provides improved graphic Swing provides improved graphic components under Java version 2.components under Java version 2.

�� The The awt.eventawt.event classes allow our GUI to classes allow our GUI to interact with events.interact with events.

Page 16: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1616

Step 1. Import library packagesStep 1. Import library packages

import import java.awtjava.awt.*;.*;

import import javax.swingjavax.swing.*;.*;

import import java.awt.eventjava.awt.event.*;.*;

Page 17: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1717

Step 2. Declare the class Step 2. Declare the class SimpleCalcSimpleCalc

�� Declare Declare SimpleCalcSimpleCalc as a public class that as a public class that extends extends JFrameJFrameand and implements implements ActionListenerActionListener and and WindowListenerWindowListener..

�� JFrameJFrame provides the window for our GUI. The provides the window for our GUI. The SimpleCalcSimpleCalcclassclass is going to is going to extend extend JFrameJFrame. In other words, it will be a . In other words, it will be a subclass of the subclass of the JFrameJFrame classclass from the library. This is called from the library. This is called inheritance and will be discussed more in a future lesson.inheritance and will be discussed more in a future lesson.

�� ActionListenerActionListener and and WindowListenerWindowListener are implemented by are implemented by the program, which means that they provide or allow the program, which means that they provide or allow something to be done by the program.something to be done by the program.

Page 18: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1818

Step 2. Declare the class Step 2. Declare the class SimpleCalcSimpleCalc

import import java.awtjava.awt.*;.*;

import import javax.swingjavax.swing.*;.*;

import import java.awt.eventjava.awt.event.*;.*;

public class public class SimpleCalcSimpleCalc extends extends JFrameJFrame implements implements ActionListenerActionListener, , WindowListenerWindowListener

{{

// // ActionListenerActionListener allows each desired action to be associated withallows each desired action to be associated with

// a specific button in the GUI.// a specific button in the GUI.

// // WindowListenerWindowListener allows the user to close the window by clickingallows the user to close the window by clicking

// on the X button in the title bar.// on the X button in the title bar.

Page 19: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

1919

Step 3. Declare the componentsStep 3. Declare the components

�� Declare the components for the GUI. Declare the components for the GUI.

�� This is why we drew the interface. Look at the drawing This is why we drew the interface. Look at the drawing

to identify all of the necessary GUI components.to identify all of the necessary GUI components.

�� This includes two data fields for entering values and one This includes two data fields for entering values and one

for displaying the sum, three labels to identify the data for displaying the sum, three labels to identify the data

fields, and an ADD button to make the program work.fields, and an ADD button to make the program work.

Page 20: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2020

A Simple ExampleA Simple Example

Page 21: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2121

Step 3. Declare the componentsStep 3. Declare the components

{{

private private JLabelJLabel enterALabelenterALabel;;

private private JTextFieldJTextField AFieldAField;;

private private JLabelJLabel enterBLabelenterBLabel;;

private private JTextFieldJTextField BFieldBField;;

private private JLabelJLabel sumLabelsumLabel;;

private private JTextFieldJTextField sumFieldsumField;;

private private JButtonJButton addButtonaddButton;;

Page 22: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2222

Step 4. Write the Step 4. Write the ‘‘mainmain’’ methodmethod

�� In the main method In the main method instantiateinstantiate (create an (create an

instance of) an object of the class instance of) an object of the class SimpleCalcSimpleCalc

and assign it to a and assign it to a JFrameJFrame called called frame.frame.

�� Now call Now call JFrameJFrame methodsmethods

�� setSizesetSize to set the size of the GUI windowto set the size of the GUI window

�� setTitlesetTitle to put the name in the title barto put the name in the title bar

�� setVisiblesetVisible to display the GUI on theto display the GUI on the

monitor screenmonitor screen

Page 23: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2323

Step 4. Write the Step 4. Write the ‘‘mainmain’’ methodmethod

public static void main(String[] public static void main(String[] argsargs))

{{

JFrameJFrame frame = new frame = new SimpleCalcSimpleCalc( );( );

frame.setSizeframe.setSize ( 250, 150 );( 250, 150 );

frame.setTitle("Simpleframe.setTitle("Simple Calculator");Calculator");

frame.setVisibleframe.setVisible (true);(true);

}}

Page 24: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2424

Step 5. Begin the Step 5. Begin the ‘‘constructorconstructor’’

methodmethod�� A constructor is a special method used to A constructor is a special method used to

initialize the data in an object of a class.initialize the data in an object of a class.

�� In the constructor, first initialize each of the In the constructor, first initialize each of the

GUI components.GUI components.

�� assign text strings to the labels, assign text strings to the labels,

�� assign initial values to the data fields and assign initial values to the data fields and

establish their size, establish their size,

�� and assign a name to the button.and assign a name to the button.

Page 25: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2525

Step 5. Begin the Step 5. Begin the ‘‘constructorconstructor’’

methodmethodpublic public SimpleCalcSimpleCalc( )( )

{{

enterALabelenterALabel = new = new JLabelJLabel ("Enter first value: a = ");("Enter first value: a = ");

AFieldAField = new = new JTextFieldJTextField ( "0", 6); ( "0", 6); //initial value = 0, width = 6//initial value = 0, width = 6

enterBLabelenterBLabel = new = new JLabelJLabel ("Enter second value: b = ");("Enter second value: b = ");

BFieldBField = new = new JTextFieldJTextField ( "0", 6);( "0", 6);

sumLabelsumLabel = new = new JLabelJLabel (" The Sum is a + b = ");(" The Sum is a + b = ");

sumFieldsumField = new = new JTextFieldJTextField ( "0", 6);( "0", 6);

addButtonaddButton = new = new JButton("AddJButton("Add");");

Page 26: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2626

Step 6. Select and set a Step 6. Select and set a

layout managerlayout manager�� There are several layout managers in Java for There are several layout managers in Java for controlling placement of components in a GUI frame.controlling placement of components in a GUI frame.

�� We will use the simplest in this case, called We will use the simplest in this case, called ‘‘FlowLayoutFlowLayout’’. Later you will learn about additional . Later you will learn about additional layout managers.layout managers.

�� Read the section on Flow Layout Manager Read the section on Flow Layout Manager –– pg 113pg 113

�� Declare Declare FlowlayoutFlowlayout layout and instantiate it.layout and instantiate it.

�� Create a container, we will call it Create a container, we will call it ‘‘windowwindow’’

�� Set Set ‘‘layoutlayout’’ to window.to window.

Page 27: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2727

Step 6. Select and set a layout Step 6. Select and set a layout

managermanager

FlowLayoutFlowLayout layout = new layout = new FlowLayoutFlowLayout ( );( );

Container window = Container window = getContentPanegetContentPane( );( );

window.setLayout(layoutwindow.setLayout(layout););

Page 28: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2828

Steps 7. Add the components to Steps 7. Add the components to

the layoutthe layout

While we are still in the constructor method:While we are still in the constructor method:

add the add the labels, labels,

fields, fields,

and button to the layoutand button to the layout

use use window.addwindow.add method to do this. method to do this.

Page 29: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

2929

Steps 7. Add the components Steps 7. Add the components

to the layoutto the layout

window.addwindow.add ( ( enterALabelenterALabel ););

window.add ( window.add ( AFieldAField););

window.add ( window.add ( enterBLabelenterBLabel ););

window.add ( window.add ( BFieldBField ););

window.add ( window.add ( sumLabelsumLabel ););

window.add ( window.add ( sumFieldsumField ););

window.add ( window.add ( addButtonaddButton ););

Page 30: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3030

Steps 8. Add listeners to the Steps 8. Add listeners to the

button and the windowbutton and the window

Use Use ‘‘addActionListeneraddActionListener’’ and and

‘‘addWindowListeneraddWindowListener’’ to associate the to associate the

button and the window to listeners. button and the window to listeners.

In this case the only listener is the application In this case the only listener is the application

itself, which we can reference as itself, which we can reference as ““thisthis”” (more (more

later on the keyword later on the keyword ““thisthis””))

Page 31: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3131

Steps 8. Add listeners to button Steps 8. Add listeners to button

and windowand window

window.addwindow.add ( ( enterALabelenterALabel ););

window.add ( window.add ( AFieldAField););

window.add ( window.add ( enterBLabelenterBLabel ););

window.add ( window.add ( BFieldBField ););

window.add ( window.add ( sumLabelsumLabel ););

window.add ( window.add ( sumFieldsumField ););

window.add ( window.add ( addButtonaddButton ););

addButton.addActionListeneraddButton.addActionListener (this);(this);

addWindowListeneraddWindowListener (this);(this);

}} // close the constructor// close the constructor

Page 32: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3232

Step 9. Write the Step 9. Write the

‘‘actionPerformedactionPerformed’’ methodmethod�� A method is like a small program that provides some A method is like a small program that provides some

kind of activity in the class. kind of activity in the class.

�� You will have a whole lesson on methods You will have a whole lesson on methods –– lesson 9lesson 9

�� The The actionPerformedactionPerformed method is where the programmethod is where the program’’s s work is done. In this case, adding the two values to work is done. In this case, adding the two values to get the sum.get the sum.

�� Since the data fields operate with strings, the strings Since the data fields operate with strings, the strings must be converted to integers, added together, and must be converted to integers, added together, and then the sum must be converted back to a string for then the sum must be converted back to a string for display.display.

Page 33: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3333

Step 9. Write the Step 9. Write the

‘‘actionPerformedactionPerformed’’ methodmethod

public void public void actionPerformedactionPerformed ((ActionEventActionEvent e )e )

{{

String String tempStringtempString;;

intint a, b, sum;a, b, sum;

if( if( e.getSourcee.getSource( ) = = ( ) = = addButtonaddButton ))

{{

tempStringtempString = = AField.getTextAField.getText ( ).trim ( );( ).trim ( );

a = (new Integer ( a = (new Integer ( tempStringtempString ) ) .) ) .intValueintValue( );( );

tempStringtempString = = BField.getTextBField.getText ( ).trim ( );( ).trim ( );

b = (new Integer ( b = (new Integer ( tempStringtempString ) ) .) ) .intValueintValue( );( );

sum = a + b;sum = a + b;

sumField.setTextsumField.setText ( ( tempString.valueOftempString.valueOf ( sum ) );( sum ) );

}}

}}

Page 34: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3434

Step 10. Complete the Step 10. Complete the

‘‘WindowListenerWindowListener’’

�� The The actionPerformedactionPerformed by the by the windowClosingwindowClosing

event is to close the window and end the program. event is to close the window and end the program.

�� This is accomplished with the codeThis is accomplished with the code

System.exit ( 0 );System.exit ( 0 );

indicating that the program terminated properly.indicating that the program terminated properly.

�� Other potential window events that we are not Other potential window events that we are not

using must be called with empty execution bodies using must be called with empty execution bodies

to avoid generating errors.to avoid generating errors.

Page 35: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3535

Step 10. Complete the Step 10. Complete the

‘‘WindowListenerWindowListener’’

public void public void windowClosingwindowClosing ((WindowEventWindowEvent e )e )

{{

System.exit ( 0 );System.exit ( 0 );

}}

public void public void windowActivatedwindowActivated ( ( WindowEventWindowEvent e ) { }e ) { }

public void public void windowClosedwindowClosed ( ( WindowEventWindowEvent e ) { }e ) { }

public void public void windowDeactivatedwindowDeactivated ( ( WindowEventWindowEvent e ) { }e ) { }

public void public void windowIconifiedwindowIconified ( ( WindowEventWindowEvent e ) { }e ) { }

public void public void windowDeiconifiedwindowDeiconified ( ( WindowEventWindowEvent e ) { }e ) { }

public void public void windowOpenedwindowOpened ( ( WindowEventWindowEvent e ) { }e ) { }

} }

Page 36: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3636

You have your first GUIYou have your first GUI

�� Congratulations Congratulations –– if you have followed if you have followed

along and not made any errors, you along and not made any errors, you

should have a working GUI.should have a working GUI.

�� This is a super simple GUI, but it can be This is a super simple GUI, but it can be

expanded indefinitely to become whatever expanded indefinitely to become whatever

kind of GUI you can imagine.kind of GUI you can imagine.

Page 37: Lecture Six – A Simple Calculatorfaculty.cs.tamu.edu/hammond/resources/java/brandon/Web_Lecture_6.pdf · Lecture Six – A Simple Calculator More about IDEs Review of what you know

3737

DrillDrill

1. Modify the 1. Modify the SimpleCalcSimpleCalc program, adding buttons program, adding buttons to subtract, multiply, and divideto subtract, multiply, and divide

2. Write a GUI based program called 2. Write a GUI based program called CtoFCtoF that that converts from degrees Centigrade to degrees converts from degrees Centigrade to degrees Fahrenheit Fahrenheit

3. Modify the 3. Modify the CtoFCtoF program to make a newprogram to make a new

program called program called TempConvertTempConvert that will convert in that will convert in either direction.either direction.

4. Write a GUI based program called Conversion 4. Write a GUI based program called Conversion that will make at least 4 different weight and that will make at least 4 different weight and measurement conversions of your choice.measurement conversions of your choice.