Web_Lecture_6

Reviews
Shared by:
Anonymous
Categories
Tags
Stats
views:
125
downloads:
3
rating:
not rated
reviews:
0
posted:
11/12/2007
language:
pages:
0
Lecture Six – A Simple Calculator More about IDEs Review of what you know Taking a detour Event driven programming Program Development Phases Requirement Analysis – A Simple Calculator Design Phase – Draw the interface Implementing the Graphic User Interface Ten steps to a GUI Drill 6 1 More about IDEs We discussed IDEs earlier, and I promised some more instruction on how to use JCreator. Mrs. Dianne Rister, an outstanding computer science teacher at Consolidated High School in College Station, has provided a lesson on how to download and use JCreator, and I have posted it to the Web Site. Use it if you like, it will make programming a lot easier, or as we mentioned earlier, if you have another IDE you would rather use, feel free to do so. 2 What You Know So Far So far you know How to enter an run a basic program in java How to import library packages How to use JOptionPane for input and Output How to use primitive types and Strings How to use basic operators How to use if, switch, and the while and for loops How to use arrays Some things you don’t know yet Graphic User Interfaces The use of methods (although you have seen the main method) Writing and using constructors We will discuss these things in detail later, but we are going to go ahead and use them in this lesson. 3 Let’s Take a Detour Let’s jump ahead and make a GUI (Graphic User Interface) This code is going to use methods and constructors. Don’t be concerned about this, we will discuss methods and constructors in detail in a later lesson. 4 Graphic User Interfaces What are they? A GUI is the kind of interface that you are used to using on a computer You have a screen with buttons and entry fields. You indicate what you want done, by entering data and clicking on buttons. Why are they important? This is the kind of interface that people expect Java and Windows are designed to facilitate graphic user interfaces If you are not programming with GUIs, you are not taking advantage of the capability of Java And besides, GUIs are fun! 5 Event Driven Programming Previous interfaces provide questions and instructions for the user to follow in a linear sequence Each line of code is basically executed in sequence, or controlled by selection (if statements) or repetition (while and for loops) Event driven Programming The Program displays a window with a picture of the graphic user interface Execution is driven by the occurrence of an event, such as the clicking of a button by the user. GUIs are an example if event driven programming 6 A Simple Example 7 Development phases Phase 1. Analyze the requirement. Identify what your program is required to do Phase 2. Design the Program Determine how the program will meet the requirements Phase 3. Implement the design Write the code Phase 4. Test your program. Make sure it works for all legal entries 8 Analyze the Requirements In this phase the analyst must identify what the program is required to do. This should be done prior to writing any code. Initial requirement typically comes from a user who is paying for the program development The program analyst must expand on the requirement analysis to insure it is complete (does every thing the user needs) and necessary (it does not have extraneous capabilities that are not required by the user) 9 The Requirements for our Program 1. Write a program with a Graphic User Interface… 2. Include the name “Simple Calculator” in the title bar of the GUI window 3. Provide fields for the user to enter two numbers and a field for the sum. 4. Provide an ADD button, which displays the sum of the values in the sum field. 5. Provide an X icon in the title bar to terminate the program 10 Design the Interface Draw a picture of the interface Include all sub windows Show customer and discuss the design Old Programmer Proverb Programmer who analyzes and designs on the fly, will get a lot more programming practice !!! 11 Draw the Interface The interface provides the “Look and Feel” of the program 12 Implement the Design In the next several slides we will go through 10 steps for implementing the Simple Calculator GUI Program. Follow along and write the program as we go. Afterward you can expand and modify this GUI to create GUIs of your own. Once you have written one, you can use it as a model to do whatever you want. It is always easier to rewrite than to start with a blank screen 13 10 steps to writing our GUI based program Step 1. Step 2. Step 3. Step 4. Step 5. Step 6. Step 7. Step 8. Step 9. Step 10. Import library packages. Open the class SimpleCalc Declare the components. Write the ‘main’ method. Begin the constructor method. Select and set a layout manager. Add components to the layout. Add listeners to button and window. Write the ‘actionPerformed’ method. Complete the ‘WindowListener’ 14 Step 1. Import library packages Use the “import” command to provide access to Java Library Packages. The abstract windowing toolkit (awt) is required to implement GUI’s in Java. Swing provides improved graphic components under Java version 2. The awt.event classes allow our GUI to interact with events. 15 Step 1. Import library packages import java.awt.*; import javax.swing.*; import java.awt.event.*; 16 Step 2. Declare the class SimpleCalc Declare SimpleCalc as a public class that extends JFrame and implements ActionListener and WindowListener. JFrame provides the window for our GUI. The SimpleCalc class is going to extend JFrame. In other words, it will be a subclass of the JFrame class from the library. This is called inheritance and will be discussed more in a future lesson. ActionListener and WindowListener are implemented by the program, which means that they provide or allow something to be done by the program. 17 Step 2. Declare the class SimpleCalc import java.awt.*; import javax.swing.*; import java.awt.event.*; public class SimpleCalc extends JFrame implements ActionListener, WindowListener { // ActionListener allows each desired action to be associated with // a specific button in the GUI. // WindowListener allows the user to close the window by clicking // on the X button in the title bar. 18 Step 3. Declare the components Declare the components for the GUI. This is why we drew the interface. Look at the drawing to identify all of the necessary GUI components. This includes two data fields for entering values and one for displaying the sum, three labels to identify the data fields, and an ADD button to make the program work. 19 A Simple Example 20 Step 3. Declare the components { private JLabel private JTextField private JLabel private JTextField private JLabel private JTextField private JButton enterALabel; AField; enterBLabel; BField; sumLabel; sumField; addButton; 21 Step 4. Write the ‘main’ method In the main method instantiate (create an instance of) an object of the class SimpleCalc and assign it to a JFrame called frame. Now call JFrame methods setSize to set the size of the GUI window setTitle to put the name in the title bar setVisible to display the GUI on the monitor screen 22 Step 4. Write the ‘main’ method public static void main(String[] args) { JFrame frame = new SimpleCalc( ); frame.setSize ( 250, 150 ); frame.setTitle("Simple Calculator"); frame.setVisible (true); } 23 Step 5. Begin the ‘constructor’ method A constructor is a special method used to initialize the data in an object of a class. In the constructor, first initialize each of the GUI components. assign text strings to the labels, assign initial values to the data fields and establish their size, and assign a name to the button. 24 Step 5. Begin the ‘constructor’ method public SimpleCalc( ) { enterALabel = new JLabel ("Enter first value: a = "); AField = new JTextField ( "0", 6); //initial value = 0, width = 6 enterBLabel = new JLabel ("Enter second value: b = "); BField = new JTextField ( "0", 6); sumLabel = new JLabel (" The Sum is a + b = "); sumField = new JTextField ( "0", 6); addButton = new JButton("Add"); 25 Step 6. Select and set a layout manager There are several layout managers in Java for controlling placement of components in a GUI frame. We will use the simplest in this case, called ‘FlowLayout’. Later you will learn about additional layout managers. Read the section on Flow Layout Manager – pg 113 Declare Flowlayout layout and instantiate it. Create a container, we will call it ‘window’ Set ‘layout’ to window. 26 Step 6. Select and set a layout manager FlowLayout layout = new FlowLayout ( ); Container window = getContentPane( ); window.setLayout(layout); 27 Steps 7. Add the components to the layout While we are still in the constructor method: add the labels, fields, and button to the layout use window.add method to do this. 28 Steps 7. Add the components to the layout window.add ( enterALabel ); window.add ( AField); window.add ( enterBLabel ); window.add ( BField ); window.add ( sumLabel ); window.add ( sumField ); window.add ( addButton ); 29 Steps 8. Add listeners to the button and the window Use ‘addActionListener’ and ‘addWindowListener’ to associate the button and the window to listeners. In this case the only listener is the application itself, which we can reference as “this” (more later on the keyword “this”) 30 Steps 8. Add listeners to button and window window.add ( enterALabel ); window.add ( AField); window.add ( enterBLabel ); window.add ( BField ); window.add ( sumLabel ); window.add ( sumField ); window.add ( addButton ); addButton.addActionListener (this); addWindowListener (this); } // close the constructor 31 Step 9. Write the ‘actionPerformed’ method A method is like a small program that provides some kind of activity in the class. You will have a whole lesson on methods – lesson 9 The actionPerformed method is where the program’s work is done. In this case, adding the two values to get the sum. Since the data fields operate with strings, the strings must be converted to integers, added together, and then the sum must be converted back to a string for display. 32 Step 9. Write the ‘actionPerformed’ method public void actionPerformed (ActionEvent e ) { String tempString; int a, b, sum; if( e.getSource( ) = = addButton ) { tempString = AField.getText ( ).trim ( ); a = (new Integer ( tempString ) ) .intValue( ); tempString = BField.getText ( ).trim ( ); b = (new Integer ( tempString ) ) .intValue( ); sum = a + b; sumField.setText ( tempString.valueOf ( sum ) ); } } 33 Step 10. Complete the ‘WindowListener’ The actionPerformed by the windowClosing event is to close the window and end the program. This is accomplished with the code System.exit ( 0 ); indicating that the program terminated properly. Other potential window events that we are not using must be called with empty execution bodies to avoid generating errors. 34 Step 10. Complete the ‘WindowListener’ public void windowClosing (WindowEvent e ) { System.exit ( 0 ); } public void windowActivated ( WindowEvent e ) { } public void windowClosed ( WindowEvent e ) { } public void windowDeactivated ( WindowEvent e ) { } public void windowIconified ( WindowEvent e ) { } public void windowDeiconified ( WindowEvent e ) { } public void windowOpened ( WindowEvent e ) { } } 35 You have your first GUI Congratulations – if you have followed along and not made any errors, you should have a working GUI. This is a super simple GUI, but it can be expanded indefinitely to become whatever kind of GUI you can imagine. 36 Drill 1. Modify the SimpleCalc program, adding buttons to subtract, multiply, and divide 2. Write a GUI based program called CtoF that converts from degrees Centigrade to degrees Fahrenheit 3. Modify the CtoF program to make a new program called TempConvert that will convert in either direction. 4. Write a GUI based program called Conversion that will make at least 4 different weight and measurement conversions of your choice. 37

premium docs