lecture six – a simple...
TRANSCRIPT
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
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.
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.
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.
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!
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
77
A Simple ExampleA Simple Example
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
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)
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
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 !!!
1212
Draw the InterfaceDraw the InterfaceThe interface provides the “Look and Feel” of the program
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
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’’
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.
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.*;.*;
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.
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.
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.
2020
A Simple ExampleA Simple Example
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;;
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
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);
}}
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.
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");");
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.
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););
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.
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 ););
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””))
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
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.
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 ) );
}}
}}
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.
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 ) { }
} }
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.
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.