Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Objectives –Display a date and time. –Use a JPasswordField.

Similar presentations


Presentation on theme: "© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Objectives –Display a date and time. –Use a JPasswordField."— Presentation transcript:

1 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Objectives –Display a date and time. –Use a JPasswordField. –Use a Date to determine the system’s current date and time. –Use a DateFormat to format the date and time.

2 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 11.1Test Driving the Security Panel Application

3 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 3 11.1Test Driving the Security Panel Application (Cont.) Figure 11.1 Security Panel application. Keypad Output JTextArea JPasswordField

4 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 4 11.1Test Driving the Security Panel Application (Cont.) Figure 11.2 Asterisks displayed in the SecurityCode: JPasswordField. JPasswordField displays one asterisk ( * ) for each numeric key the user presses (so no one can see the actual security code entered) Enter the security code 1212 JPasswordField displays asterisks rather than the typed characters

5 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 5 11.1Test Driving the Security Panel Application (Cont.) Figure 11.3 Security Panel displaying the Access Denied message. Message indicating that an invalid security code was entered Press # to submit your security code Press C to clear your security code

6 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 6 11.1Test Driving the Security Panel Application (Cont.) Figure 11.4 Security Panel application confirming a valid security code entry. Message displayed when a valid security code is entered Enter 1006 to log on with a valid security code

7 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7 11.3Constructing the Security Panel Application When the user clicks a numeric JButton Get the JButton’s digit Append the digit to the text in the JPasswordField When the user clicks the # JButton Get the security code input by the user from the JPasswordField Clear the JPasswordField switch based on the security code variable case where access code is 7, 8 or 9 Store text “Restricted Access” in a String variable case where access code equals 1645 Store text “Technician” in a String variable case where access code equals 8345 Store text “Custodian” in a String variable case where access code equals 9998 or is in the range 1006 to 1008 Store text “Scientist” in a String variable default case where none of the preceding cases match Store text “Access Denied” in a String variable Display a message in the JTextArea with current time and the String variable’s contents

8 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 8 11.3Constructing the Security Panel Application (Cont.)

9 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 9 11.3Constructing the Security Panel Application (Cont.) Figure 11.7 Setting the securityCodeJPasswordField ’s bounds and editable properties. Echo characters (masked characters) Set character displayed using the setEchoChar method Set the bounds and editable properties of the JPasswordField

10 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 10 11.3Constructing the Security Panel Application (Cont.) Figure 11.8 Security Panel application after customizing the JPasswordField.

11 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 11.3Constructing the Security Panel Application (Cont.) Figure 11.9 Storing the access code and clearing the Security code: JPasswordField. Declare message Store the access codeClear the JPasswordField

12 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 12 11.3Constructing the Security Panel Application (Cont.) Figure 11.10 Adding a switch statement to the method. Beginning of the switch statement

13 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 13 11.3Constructing the Security Panel Application (Cont.) Figure 11.11 Adding case labels to the switch statement. Multiple case labels result in same message

14 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 14 11.3Constructing the Security Panel Application (Cont.) Figure 11.12 Finishing the switch statement. Access code 1645 for technicians Access code 8345 for custodians Access codes 9998, 1006, 1007 and 1008 for scientists

15 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 15 11.3Constructing the Security Panel Application (Cont.) Figure 11.13 Adding a default case to the switch statement. switch statements can have at most one default statement default case at the end of the switch statement

16 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 16 11.3Constructing the Security Panel Application (Cont.) Figure 11.14 Outputting the current date, the time and the message. The DateFormat object is similar to a DecimalFormat object –Allows you to output a date and time Format for the date and time Add the date and time to the message

17 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 17 11.3Constructing the Security Panel Application (Cont.) Figure 11.15 Appending a one to the end of the security code. Add 1 to the end of the security code Use the + operator to append (concatenate) String s to other String s

18 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 18 11.3Constructing the Security Panel Application (Cont.) Figure 11.16 Coding event handlers for 2 JButton and 3 JButton ; other JButton s would be similar. Add 2 to the end of the security code Add 3 to the end of the security code

19 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 19 11.3Constructing the Security Panel Application (Cont.) Figure 11.17 Clearing the Security Code: JPasswordField. Clear the security code

20 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 20 11.3Constructing the Security Panel Application (Cont.) Figure 11.18 Completed Security Panel application.

21  2003 Prentice Hall, Inc. All rights reserved. Outline 21 SecurityPanel.java (1 of 19) 1 // Tutorial : SecurityPanel.java 2 // Enable user to enter security codes specifying access privileges. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 import java.text.DateFormat; 7 import java.util.Date; 8 9 public class SecurityPanel extends JFrame 10 { 11 // JLabel and JPasswordField for user to input security code 12 private JLabel securityCodeJLabel; 13 private JPasswordField securityCodeJPasswordField; 14 15 // JButtons to represent security keypad 16 private JButton oneJButton; 17 private JButton twoJButton; 18 private JButton threeJButton; 19 private JButton fourJButton; 20 private JButton fiveJButton; 21 private JButton sixJButton; 22 private JButton sevenJButton; 23 private JButton eightJButton; 24 private JButton nineJButton; 25 private JButton clearJButton;

22  2003 Prentice Hall, Inc. All rights reserved. Outline 22 SecurityPanel.java (2 of 19) 26 private JButton zeroJButton; 27 private JButton enterJButton; 28 29 // JLabel, JTextArea and JScrollPane to display access log 30 private JLabel accessLogJLabel; 31 private JTextArea accessLogJTextArea; 32 private JScrollPane accessLogJScrollPane; 33 34 // no-argument constructor 35 public SecurityPanel() 36 { 37 createUserInterface(); 38 } 39 40 // create and position GUI components; register event handlers 41 private void createUserInterface() 42 { 43 // get content pane for attaching GUI components 44 Container contentPane = getContentPane(); 45 46 // enable explicit positioning of GUI components 47 contentPane.setLayout( null ); 48

23  2003 Prentice Hall, Inc. All rights reserved. Outline 23 SecurityPanel.java (3 of 19) 49 // set up securityCodeJLabel 50 securityCodeJLabel = new JLabel(); 51 securityCodeJLabel.setBounds( 16, 16, 90, 21 ); 52 securityCodeJLabel.setText( "Security code:" ); 53 contentPane.add( securityCodeJLabel ); 54 55 // set up securityCodeJPasswordField 56 securityCodeJPasswordField = new JPasswordField(); 57 securityCodeJPasswordField.setBounds( 114, 16, 172, 26 ); 58 securityCodeJPasswordField.setEditable( false ); 59 contentPane.add( securityCodeJPasswordField ); 60 61 // set up oneJButton 62 oneJButton = new JButton(); 63 oneJButton.setBounds( 80, 64, 50, 50 ); 64 oneJButton.setText( "1" ); 65 contentPane.add( oneJButton ); 66 oneJButton.addActionListener( 67 68 new ActionListener() // anonymous inner class 69 { 70 // event handler called when oneJButton is pressed 71 public void actionPerformed( ActionEvent event ) 72 { 73 oneJButtonActionPerformed( event ); Set the bounds and editable properties of the JPasswordField

24  2003 Prentice Hall, Inc. All rights reserved. Outline 24 SecurityPanel.java (4 of 19) 74 } 75 76 } // end anonymous inner class 77 78 ); // end call to addActionListener 79 80 // set up twoJButton 81 twoJButton = new JButton(); 82 twoJButton.setBounds( 130, 64, 50, 50 ); 83 twoJButton.setText( "2" ); 84 contentPane.add( twoJButton ); 85 twoJButton.addActionListener( 86 87 new ActionListener() // anonymous inner class 88 { 89 // event handler called when twoJButton is pressed 90 public void actionPerformed( ActionEvent event ) 91 { 92 twoJButtonActionPerformed( event ); 93 } 94 95 } // end anonymous inner class 96 97 ); // end call to addActionListener 98

25  2003 Prentice Hall, Inc. All rights reserved. Outline 25 SecurityPanel.java (5 of 19) 99 // set up threeJButton 100 threeJButton = new JButton(); 101 threeJButton.setBounds( 180, 64, 50, 50 ); 102 threeJButton.setText( "3" ); 103 contentPane.add( threeJButton ); 104 threeJButton.addActionListener( 105 106 new ActionListener() // anonymous inner class 107 { 108 // event handler called when threeJButton is pressed 109 public void actionPerformed( ActionEvent event ) 110 { 111 threeJButtonActionPerformed( event ); 112 } 113 114 } // end anonymous inner class 115 116 ); // end call to addActionListener 117 118 // set up fourJButton 119 fourJButton = new JButton(); 120 fourJButton.setBounds( 80, 114, 50, 50 ); 121 fourJButton.setText( "4" ); 122 contentPane.add( fourJButton ); 123 fourJButton.addActionListener(

26  2003 Prentice Hall, Inc. All rights reserved. Outline 26 SecurityPanel.java (6 of 19) 124 125 new ActionListener() // anonymous inner class 126 { 127 // event handler called when fourJButton is pressed 128 public void actionPerformed( ActionEvent event ) 129 { 130 fourJButtonActionPerformed( event ); 131 } 132 133 } // end anonymous inner class 134 135 ); // end call to addActionListener 136 137 // set up fiveJButton 138 fiveJButton = new JButton(); 139 fiveJButton.setBounds( 130, 114, 50, 50 ); 140 fiveJButton.setText( "5" ); 141 contentPane.add( fiveJButton ); 142 fiveJButton.addActionListener( 143

27  2003 Prentice Hall, Inc. All rights reserved. Outline 27 SecurityPanel.java (7 of 19) 144 new ActionListener() // anonymous inner class 145 { 146 // event handler called when fiveJButton is pressed 147 public void actionPerformed( ActionEvent event ) 148 { 149 fiveJButtonActionPerformed( event ); 150 } 151 152 } // end anonymous inner class 153 154 ); // end call to addActionListener 155 156 // set up sixJButton 157 sixJButton = new JButton(); 158 sixJButton.setBounds( 180, 114, 50, 50 ); 159 sixJButton.setText( "6" ); 160 contentPane.add( sixJButton ); 161 sixJButton.addActionListener( 162 163 new ActionListener() // anonymous inner class 164 { 165 // event handler called when sixJButton is pressed 166 public void actionPerformed( ActionEvent event ) 167 { 168 sixJButtonActionPerformed( event ); 169 }

28  2003 Prentice Hall, Inc. All rights reserved. Outline 28 SecurityPanel.java (8 of 19) 170 171 } // end anonymous inner class 172 173 ); // end call to addActionListener 174 175 // set up sevenJButton 176 sevenJButton = new JButton(); 177 sevenJButton.setBounds( 80, 164, 50, 50 ); 178 sevenJButton.setText( "7" ); 179 contentPane.add( sevenJButton ); 180 sevenJButton.addActionListener( 181 182 new ActionListener() // anonymous inner class 183 { 184 // event handler called when sevenJButton is pressed 185 public void actionPerformed( ActionEvent event ) 186 { 187 sevenJButtonActionPerformed( event ); 188 } 189 190 } // end anonymous inner class 191 192 ); // end call to addActionListener 193

29  2003 Prentice Hall, Inc. All rights reserved. Outline 29 SecurityPanel.java (9 of 19) 194 // set up eightJButton 195 eightJButton = new JButton(); 196 eightJButton.setBounds( 130, 164, 50, 50 ); 197 eightJButton.setText( "8" ); 198 contentPane.add( eightJButton ); 199 eightJButton.addActionListener( 200 201 new ActionListener() // anonymous inner class 202 { 203 // event handler called when eightJButton is pressed 204 public void actionPerformed( ActionEvent event ) 205 { 206 eightJButtonActionPerformed( event ); 207 } 208 209 } // end anonymous inner class 210 211 ); // end call to addActionListener 212 213 // set up nineJButton 214 nineJButton = new JButton(); 215 nineJButton.setBounds( 180, 164, 50, 50 ); 216 nineJButton.setText( "9" ); 217 contentPane.add( nineJButton ); 218 nineJButton.addActionListener(

30  2003 Prentice Hall, Inc. All rights reserved. Outline 30 SecurityPanel.java (10 of 19) 219 220 new ActionListener() // anonymous inner class 221 { 222 // event handler called when nineJButton is pressed 223 public void actionPerformed( ActionEvent event ) 224 { 225 nineJButtonActionPerformed( event ); 226 } 227 228 } // end anonymous inner class 229 230 ); // end call to addActionListener 231 232 // set up clearJButton 233 clearJButton = new JButton(); 234 clearJButton.setBounds( 80, 214, 50, 50 ); 234 clearJButton.setText( "C" ); 236 contentPane.add( clearJButton ); 237 clearJButton.addActionListener( 238 239 new ActionListener() // anonymous inner class 240 {

31  2003 Prentice Hall, Inc. All rights reserved. Outline 31 SecurityPanel.java (11 of 19) 241 // event handler called when clearJButton is pressed 242 public void actionPerformed( ActionEvent event ) 243 { 244 clearJButtonActionPerformed( event ); 245 } 246 247 } // end anonymous inner class 248 249 ); // end call to addActionListener 250 251 // set up zeroJButton 252 zeroJButton = new JButton(); 253 zeroJButton.setBounds( 130, 214, 50, 50 ); 254 zeroJButton.setText( "0" ); 255 contentPane.add( zeroJButton ); 256 zeroJButton.addActionListener( 257 258 new ActionListener() // anonymous inner class 259 { 260 // event handler called when zeroJButton is pressed 261 public void actionPerformed( ActionEvent event ) 262 { 263 zeroJButtonActionPerformed( event ); 264 } 265

32  2003 Prentice Hall, Inc. All rights reserved. Outline 32 SecurityPanel.java (11 of 19) 241 // event handler called when zeroJButton is pressed 242 public void actionPerformed( ActionEvent event ) 243 { 244 zeroJButtonActionPerformed( event ); 245 } 246 247 } // end anonymous inner class 248 249 ); // end call to addActionListener 250 251 // set up clearJButton 252 clearJButton = new JButton(); 253 clearJButton.setBounds( 80, 214, 50, 50 ); 254 clearJButton.setText( "C" ); 255 contentPane.add( clearJButton ); 256 clearJButton.addActionListener( 257 258 new ActionListener() // anonymous inner class 259 { 260 // event handler called when clearJButton is pressed 261 public void actionPerformed( ActionEvent event ) 262 { 263 clearJButtonActionPerformed( event ); 264 } 265

33  2003 Prentice Hall, Inc. All rights reserved. Outline 33 SecurityPanel.java (12 of 19) 266 } // end anonymous inner class 267 268 ); // end call to addActionListener 269 270 // set up enterJButton 271 enterJButton = new JButton(); 272 enterJButton.setBounds( 180, 214, 50, 50 ); 273 enterJButton.setText( "#" ); 274 contentPane.add( enterJButton ); 275 enterJButton.addActionListener( 276 277 new ActionListener() // anonymous inner class 278 { 279 // event handler called when enterJButton is pressed 280 public void actionPerformed( ActionEvent event ) 281 { 282 enterJButtonActionPerformed( event ); 283 } 284 285 } // end anonymous inner class 286 287 ); // end call to addActionListener 288

34  2003 Prentice Hall, Inc. All rights reserved. Outline 34 SecurityPanel.java (13 of 19) 289 // set up accessLogJLabel 290 accessLogJLabel = new JLabel(); 291 accessLogJLabel.setBounds( 16, 285, 100, 16 ); 292 accessLogJLabel.setText( "Access log:" ); 293 contentPane.add( accessLogJLabel ); 294 295 // set up accessLogJTextArea 296 accessLogJTextArea = new JTextArea(); 297 298 // set up accessLogJScrollPane 299 accessLogJScrollPane = new JScrollPane( accessLogJTextArea ); 300 accessLogJScrollPane.setBounds( 16, 309, 270, 95 ); 301 contentPane.add( accessLogJScrollPane ); 302 303 // set properties of application's window 304 setTitle( "Security Panel" ); // set window's title 305 setSize( 310, 450 ); // set window's size 306 setVisible( true ); // display window 307 308 } // end method createUserInterface 309 310 // append 1 to the security code 311 private void oneJButtonActionPerformed( ActionEvent event ) 312 {

35  2003 Prentice Hall, Inc. All rights reserved. Outline 35 SecurityPanel.java (14 of 19) 313 securityCodeJPasswordField.setText( String.valueOf( 314 securityCodeJPasswordField.getPassword() ) + "1" ); 315 316 } // end method oneJButtonActionPerformed 317 318 // append 2 to the security code 319 private void twoJButtonActionPerformed( ActionEvent event ) 320 { 321 securityCodeJPasswordField.setText( String.valueOf( 322 securityCodeJPasswordField.getPassword() ) + "2" ); 323 324 } // end method twoJButtonActionPerformed 325 326 // append 3 to the security code 327 private void threeJButtonActionPerformed( ActionEvent event ) 328 { 329 securityCodeJPasswordField.setText( String.valueOf( 330 securityCodeJPasswordField.getPassword() ) + "3" ); 331 332 } // end method threeJButtonActionPerformed 333 334 // append 4 to the security code 335 private void fourJButtonActionPerformed( ActionEvent event ) 336 { Append the numeric JButton value "1" to the password stored in the JPasswordField Append the numeric JButton value "2" to the password stored in the JPasswordField Append the numeric JButton value "3" to the password stored in the JPasswordField

36  2003 Prentice Hall, Inc. All rights reserved. Outline 36 SecurityPanel.java (15 of 19) 337 securityCodeJPasswordField.setText( String.valueOf( 338 securityCodeJPasswordField.getPassword() ) + "4" ); 339 340 } // end method fourJButtonActionPerformed 341 342 // append 5 to the security code 343 private void fiveJButtonActionPerformed( ActionEvent event ) 344 { 345 securityCodeJPasswordField.setText( String.valueOf( 346 securityCodeJPasswordField.getPassword() ) + "5" ); 347 348 } // end method fiveJButtonActionPerformed 349 350 // append 6 to the security code 351 private void sixJButtonActionPerformed( ActionEvent event ) 352 { 353 securityCodeJPasswordField.setText( String.valueOf( 354 securityCodeJPasswordField.getPassword() ) + "6" ); 355 356 } // end method sixJButtonActionPerformed 357 358 // append 7 to the security code 359 private void sevenJButtonActionPerformed( ActionEvent event ) 360 { Append the numeric JButton value "4" to the password stored in the JPasswordField Append the numeric JButton value "5" to the password stored in the JPasswordField Append the numeric JButton value "6" to the password stored in the JPasswordField

37  2003 Prentice Hall, Inc. All rights reserved. Outline 37 SecurityPanel.java (16 of 19) 361 securityCodeJPasswordField.setText( String.valueOf( 362 securityCodeJPasswordField.getPassword() ) + "7" ); 363 364 } // end method sevenJButtonActionPerformed 365 366 // append 8 to the security code 367 private void eightJButtonActionPerformed( ActionEvent event ) 368 { 369 securityCodeJPasswordField.setText( String.valueOf( 370 securityCodeJPasswordField.getPassword() ) + "8" ); 371 372 } // end method eightJButtonActionPerformed 373 374 // append 9 to the security code 375 private void nineJButtonActionPerformed( ActionEvent event ) 376 { 377 securityCodeJPasswordField.setText( String.valueOf( 378 securityCodeJPasswordField.getPassword() ) + "9" ); 379 380 } // end method nineJButtonActionPerformed 381 382 // append 0 to the security code 383 private void zeroJButtonActionPerformed( ActionEvent event ) 384 { Append the numeric JButton value "7" to the password stored in the JPasswordField Append the numeric JButton value "8" to the password stored in the JPasswordField Append the numeric JButton value "9" to the password stored in the JPasswordField

38  2003 Prentice Hall, Inc. All rights reserved. Outline 38 SecurityPanel.java (17 of 19) 385 securityCodeJPasswordField.setText( String.valueOf( 386 securityCodeJPasswordField.getPassword() ) + "0" ); 387 388 } // end method zeroJButtonActionPerformed 389 390 // clears the securityCodeJPasswordField 391 private void clearJButtonActionPerformed( ActionEvent event ) 392 { 393 securityCodeJPasswordField.setText( "" ); 394 395 } // end method clearJButtonActionPerformed 396 397 // gets access code and determines level of clearance 398 private void enterJButtonActionPerformed( ActionEvent event ) 399 { 400 String message; // displays access status of users 401 402 // stores access code entered 403 int accessCode = Integer.parseInt( String.valueOf( 404 securityCodeJPasswordField.getPassword() ) ); 405 406 securityCodeJPasswordField.setText( "" ); 407 408 switch ( accessCode ) // check access code input 409 { Append the numeric JButton value "0" to the password stored in the JPasswordField Clear the JPasswordField Get password property Using a switch statement to determine user access level String for message to display Clear the JPasswordField

39  2003 Prentice Hall, Inc. All rights reserved. Outline 39 SecurityPanel.java (18 of 19) 410 // access code is 7, 8 or 9 411 case 7: 412 case 8: 413 case 9: 414 message = "Restricted Access"; 415 break; // done processing case 416 417 // access code equal to 1645 418 case 1645: 419 message = "Technician"; 420 break; // done processing case 421 422 // access code equal to 8345 423 case 8345: 424 message = "Custodian"; 425 break; // done processing case 426 427 // access code equal to 9998 or between 1006 and 1008 428 case 9998: 429 case 1006: 430 case 1007: 431 case 1008: 432 message = "Scientist"; 433 break; // done processing case 434 Three case labels result in the same message Terminate switch statement and continue execution with next statement after switch Access code 1645 for Technicians Access code 8345 for Custodians Access codes 9998, 1006, 1007, and 1008 for Scientists

40  2003 Prentice Hall, Inc. All rights reserved. Outline 40 SecurityPanel.java (19 of 19) 435 // if no other case is true 436 default: 437 message = "Access Denied"; 438 439 } // end switch statement 440 441 // display time and message in access log JTextArea 442 DateFormat formatter = DateFormat.getDateTimeInstance(); 443 accessLogJTextArea.append( formatter.format( new Date() ) + 444 " " + message + "\n" ); 445 446 } // end method enterJButtonActionPerformed 447 448 // main method 449 public static void main( String[] args ) 450 { 451 SecurityPanel application = new SecurityPanel(); 452 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 453 454 } // end method main 455 456 } // end class SecurityPanel Default case executes if no other case s match Right brace ends the switch statement Append the current date and time to the message

41 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 41 12.1Test Driving the Enhanced Wage Calculator Application

42 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 42 12.1Test Driving the Enhanced Wage Calculator Application (Cont.) Figure 12.1 Wage Calculator executing. Enter 10 in the Hourly wage: JTextField Enter 45 in the Hours worked: JTextField Click the Calculate JButton

43 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 43 12.3Method Declarations (Cont.) Figure 12.3 Running the Hypotenuse Calculator application.

44 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 44 12.3Method Declarations (Cont.) Figure 12.4 Hypotenuse Calculator template code. Lengths for sides A and B Message dialog displays if negative value (or zero) is entered

45 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 45 12.3Method Declarations (Cont.) Figure 12.5 Declaring method square. Method name: square Return type: double Parameter list: A double named side Method headerA right brace marks the end of a method declaration

46 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 46 12.3Method Declarations (Cont.) Figure 12.7 Hypotenuse Calculator application updated.

47 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 47 12.3Method Declarations (Cont.) Figure 12.8 Invoking the square method. Call a method by using the method name followed by a set of parentheses containing the method’s argument ( sideA and sideB ) Calling method square for each side

48 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 48 12.3Method Declarations (Cont.) Figure 12.9 Completing the calculateJButtonActionPerformed method. Format and display the length of the hypotenuse Calling Math method sqrt The Math.sqrt method returns the square root of its argument

49 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 49 12.3Method Declarations (Cont.) Figure 12.10 Running the completed Hypotenuse Calculator application.

50 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 50 12.4Finishing the Maximum Application Figure 12.11 Maximum application executing.

51 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 51 12.4Finishing the Maximum Application (Cont.) Figure 12.12 Invoking the determineMaximum method. Store user input Calling method determineMaximum

52 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 52 12.4Finishing the Maximum Application (Cont.) Figure 12.13 Declaring the determineMaximum method. Empty method determineMaximum Arguments: three values of which to determine maximum Return value: double containing maximum value

53 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 53 12.4Finishing the Maximum Application (Cont.) Figure 12.14 Math.max returns the larger of its two arguments. Return maximum of all three values Calling Math.max twice to determine the maximum of three values Use the Math.max method

54 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 54 12.4Finishing the Maximum Application (Cont.) Figure 12.15 Maximum application executing.

55 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 55 12.5Using Methods in the Wage Calculator Application Figure 12.16 calculateJButtonActionPerformed calls the calculatePay method. Format and display the total wage Store user input Call to method calculatePay

56 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 56 12.5Using Methods in the Wage Calculator Application (Cont.) Figure 12.17 Declaring the calculatePay method. Method headerReturn wages for the week Calculate gross wages based on the number of hours worked

57 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 57 12.5Using Methods in the Wage Calculator Application (Cont.) Figure 12.18 Wage Calculator application executing.

58  2003 Prentice Hall, Inc. All rights reserved. Outline 58 WageCalculator.java (1 of 7) 1 // Tutorial 12: WageCalculator.java 2 // This application inputs the hourly wage and number of hours 3 // worked for an employee, then calculates the employee's gross 4 // wages (with overtime for hours worked over 40 hours). 5 import java.awt.*; 6 import java.awt.event.*; 7 import javax.swing.*; 8 import java.text.*; 9 10 public class WageCalculator extends JFrame 11 { 12 // JLabel and JTextField for wage per hour 13 private JLabel hourlyWageJLabel; 14 private JTextField hourlyWageJTextField; 15 16 // JLabel and JTextField for hours worked in a week 17 private JLabel hoursWorkedJLabel; 18 private JTextField hoursWorkedJTextField; 19 20 // JLabel and JTextField for gross wages 21 private JLabel grossWagesJLabel; 22 private JTextField grossWagesJTextField; 23 24 // JButton to initiate wage calculation 25 private JButton calculateJButton;

59  2003 Prentice Hall, Inc. All rights reserved. Outline 59 WageCalculator.java (2 of 7) 26 27 // no-argument constructor 28 public WageCalculator() 29 { 30 createUserInterface(); 31 } 32 33 // create and position GUI components; register event handlers 34 public void createUserInterface() 35 { 36 // get content pane for attaching GUI components 37 Container contentPane = getContentPane(); 38 39 // enable explicit positioning of GUI components 40 contentPane.setLayout( null ); 41 42 // set up hourlyWageJLabel 43 hourlyWageJLabel = new JLabel(); 44 hourlyWageJLabel.setBounds( 16, 16, 90, 21 ); 45 hourlyWageJLabel.setText( "Hourly wage:" ); 46 contentPane.add( hourlyWageJLabel ); 47

60  2003 Prentice Hall, Inc. All rights reserved. Outline 60 WageCalculator.java (3 of 7) 48 // set up hourlyWageJTextField 49 hourlyWageJTextField = new JTextField(); 50 hourlyWageJTextField.setBounds( 120, 16, 90, 21 ); 51 hourlyWageJTextField.setHorizontalAlignment( 52 JTextField.RIGHT ); 53 contentPane.add( hourlyWageJTextField ); 54 55 // set up hoursWorkedJLabel 56 hoursWorkedJLabel = new JLabel(); 57 hoursWorkedJLabel.setBounds( 16, 56, 90, 21 ); 58 hoursWorkedJLabel.setText( "Hours worked:" ); 59 contentPane.add( hoursWorkedJLabel ); 60 61 // set up hoursWorkedJTextField 62 hoursWorkedJTextField = new JTextField(); 63 hoursWorkedJTextField.setBounds( 120, 56, 90, 21 ); 64 hoursWorkedJTextField.setHorizontalAlignment( 65 JTextField.RIGHT ); 66 contentPane.add( hoursWorkedJTextField ); 67 68 // set up grossWagesJLabel 69 grossWagesJLabel = new JLabel(); 70 grossWagesJLabel.setBounds( 16, 96, 90, 21 ); 71 grossWagesJLabel.setText( "Gross wages:" ); 72 contentPane.add( grossWagesJLabel );

61  2003 Prentice Hall, Inc. All rights reserved. Outline 61 WageCalculator.java (4 of 7) 73 74 // set up grossWagesJTextField 75 grossWagesJTextField = new JTextField(); 76 grossWagesJTextField.setBounds( 120, 96, 90, 21 ); 77 grossWagesJTextField.setHorizontalAlignment( 78 JTextField.RIGHT ); 79 grossWagesJTextField.setEditable( false ); 80 contentPane.add( grossWagesJTextField ); 81 82 // set up calculateJButton 83 calculateJButton = new JButton(); 84 calculateJButton.setBounds( 120, 136, 90, 24 ); 85 calculateJButton.setText( "Calculate" ); 86 contentPane.add( calculateJButton ); 87 calculateJButton.addActionListener( 88 89 new ActionListener() // anonymous inner class 90 { 91 // event handler called when calculateJButton clicked 92 public void actionPerformed ( ActionEvent event ) 93 { 94 calculateJButtonActionPerformed( event ); 95 } 96 97 } // end anonymous inner class

62  2003 Prentice Hall, Inc. All rights reserved. Outline 62 WageCalculator.java (5 of 7) 98 99 ); // end call to addActionListener 100 101 // set properties of application's window 102 setTitle( "Wage Calculator" ); // set title bar string 103 setSize( 230, 200 ); // set window size 104 setVisible( true ); // display window 105 106 } // end method createUserInterface 107 108 // get user input and call displayPay 109 private void calculateJButtonActionPerformed( ActionEvent event ) 110 { 111 // get hourly wage 112 double hourlyWage = 113 Double.parseDouble( hourlyWageJTextField.getText() ); 114 115 // get number of hours worked this week 116 double hoursWorked = 117 Double.parseDouble( hoursWorkedJTextField.getText() ); 118 119 // gross wages for week; returned from method calculatePay 120 double totalWages = calculatePay( hoursWorked, hourlyWage ); 121 Calling method calculatePay Initializing variables

63  2003 Prentice Hall, Inc. All rights reserved. Outline 63 WageCalculator.java (6 of 7) 122 // specify output format 123 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 124 125 // display gross wages 126 grossWagesJTextField.setText( dollars.format( totalWages ) ); 127 128 } // end method calculateJButtonActionPerformed 129 130 // calculate and display wages in grossWagesJTextField 131 private double calculatePay( double hours, double wages ) 132 { 133 // gross wages for week; calculated in if...else statement 134 double total; 135 136 // constant for maximum hours employee can 137 // work before being paid for overtime 138 final double HOUR_LIMIT = 40.0; // declare constant 139 140 // determine gross wages 141 if ( hours <= HOUR_LIMIT ) 142 { 143 // regular wages for HOUR_LIMIT (40) hours or less 144 total = wages * hours; 145 } Formatting and displaying value returned from the calculatePay method Method calculatePay takes two double parameters, returns a double Variable total will contain user’s wages for the week Overtime for more than 40 hours worked Calculate standard pay

64  2003 Prentice Hall, Inc. All rights reserved. Outline 64 WageCalculator.java (7 of 7) 146 else // worked more than HOUR_LIMIT (40) hours 147 { 148 // wages for first 40 hours with time and a half added 149 total = ( wages * HOUR_LIMIT ) + ( hours - HOUR_LIMIT ) * 150 ( 1.5 * wages ); 151 } 152 153 return total; 154 155 } // end method calculatePay 156 157 // main method 158 public static void main( String[] args ) 159 { 160 WageCalculator application = new WageCalculator(); 161 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 162 163 } // end method main 164 165 } // end class WageCalculator Calculate overtime pay Return total to calling method Closing brace ends method body

65 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 65 Objective –Create an event handler. –Understand how objects are used to represent events. –Handle the ChangeEvent which is generated when the value in a JSpinner is changed.

66 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 66 13.1 Test-Driving the Enhanced Interest Calculator Application

67 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 67 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) Figure 13.1 Running Interest Calculator application.

68 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 68 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) Enter values in the components Figure 13.2 Entering values in the running Interest Calculator application.

69 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 69 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) JTextArea is cleared Figure 13.3 Clearing the output.

70 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 70 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) Figure 13.4 Calculating the new account balance. Output is cleared

71 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 71 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) Figure 13.5 Changing the value in a JSpinner. Output is clearedNumber of years is changed

72 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 72 13.1 Test-Driving the Enhanced Interest Calculator Application (Cont.) Figure 13.6 Clearing the Interest Calculator application. JTextField s are cleared and JSpinner is set to 1 JTextArea is clearedClear the components and reset the year to 1

73 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 73 13.2 Event Handlers When the user clicks the Calculate JButton Get the values for the principal, interest rate and years Display a header in the JTextArea to label the output For each year, starting at 1 and ending with the number of years entered, Calculate and display the year Calculate and display the current value of the investment When the user changes the value in the Years: JSpinner Clear the JTextArea When the user types in the Principal: JTextField Clear the JTextArea When the user types in the Interest rate: JTextField Clear the JTextArea When the user clicks the Clear JButton Clear the JTextArea Clear the JTextFields Reset the JSpinner to the default value

74 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 74 13.2 Event Handlers (Cont.)

75 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 75 13.2 Event Handlers (Cont.) Event driven application –Waits for certain actions (or events) –These actions generate event objects in response –Event handlers (e.g. actionPerformed methods) are then called by the event objects

76 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 76 13.2 Event Handlers (Cont.) Declaration of event handler actionPerformed Figure 13.8 Examining calculateJButton ’s actionPerformed event handler. Event objects –ActionEvent generated when a user clicks a JButton –KeyEvent and MouseEvent are other types of event objects Access modifier –keyword public allows objects of other classes to access this event handler

77 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 77 13.2 Event Handlers (Cont.) Figure 13.9 Finishing calculateJButton ’s actionPerformed event handler. Call programmer- declared method

78 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 78 13.2 Event Handlers (Cont.) Figure 13.10 Running the updated Interest Calculator application.

79 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 79 13.3 Event Handler Registration Event handler registration –Each event handler must be registered with its corresponding component

80 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 80 13.3 Event Handler Registration (Cont.) Figure 13.11 Completing the clearJButton event handler. Call programmer- declared method

81 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 81 13.3 Event Handler Registration (Cont.) Figure 13.12 Event handler registration for the clearJButton. Register event handler for clearJButton Method addActionListener –registers the actionPerformed event handler

82 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 82 13.3 Event Handler Registration (Cont.) Figure 13.13 Event handler registration for the calculateJButton. Register event handler for calculateJButton

83 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 83 13.3 Event Handler Registration (Cont.) Figure 13.14 Declaring method clearJButtonActionPerformed. Declare method to clear the values of the components and reset the JSpinner to 1

84 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 84 13.3 Event Handler Registration (Cont.) Figure 13.15 Clearing the values in the components. Clear components and reset the JSpinner to 1 The setValue method –Sets the value property of the JSpinner to an Integer object representing the value 1

85 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 85 13.3 Event Handler Registration (Cont.) Figure 13.16 Running the updated Interest Calculator application. Output is cleared

86 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 86 13.4 Handling a ChangeEvent Figure 13.17 Event handler stateChanged for a ChangeEvent. Event handler stateChanged Event object ChangeEvent –Generated by changing the value in a JSpinner Event handler stateChanged –Called as a result of a new ChangeEvent

87 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 87 13.4 Handling a ChangeEvent (Cont.) Figure 13.18 Calling the programmer-declared method yearJSpinnerStateChanged from event handler stateChanged. Call programmer- declared method from event handler

88 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 88 13.4 Handling a ChangeEvent (Cont.) Figure 13.19 Registering the event handler stateChanged to handle ChangeEvent s. Call method addChangeListener

89 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 89 13.4 Handling a ChangeEvent (Cont.) Figure 13.20 Clearing the accountJTextArea. Clear the JTextArea

90 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 90 13.4 Handling a ChangeEvent (Cont.) Figure 13.21 Completed Interest Calculator application responding to ChangeEvent by clearing JTextArea.

91  2003 Prentice Hall, Inc. All rights reserved. Outline 91 Interest- Calculator.java (1 of 11) 1 // Tutorial 13: InterestCalculator.java 2 // Calculate the total value of an investment. 3 import java.text.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 import javax.swing.*; 7 import javax.swing.event.*; 8 9 public class InterestCalculator extends JFrame 10 { 11 // JLabel and JTextField for principal 12 private JLabel principalJLabel; 13 private JTextField principalJTextField; 14 15 // JLabel and JTextField for interest rate 16 private JLabel rateJLabel; 17 private JTextField rateJTextField; 18 19 // JLabel and JSpinner for years 20 private JLabel yearsJLabel; 21 private JSpinner yearsJSpinner; 22

92  2003 Prentice Hall, Inc. All rights reserved. Outline 92 Interest- Calculator.java (2 of 11) 23 // JLabel, JTextArea and JScrollPane for yearly balances 24 private JLabel accountJLabel; 25 private JTextArea accountJTextArea; 26 private JScrollPane accountJScrollPane; 27 28 // JButton to calculate the yearly balances 29 private JButton calculateJButton; 30 31 // JButton to clear the components 32 private JButton clearJButton; 33 34 // no-argument constructor 35 public InterestCalculator() 36 { 37 createUserInterface(); 38 } 39 40 // create and position GUI components; register event handlers 41 private void createUserInterface() 42 { 43 // get content pane and set layout to null 44 Container contentPane = getContentPane(); 45 contentPane.setLayout( null ); 46

93  2003 Prentice Hall, Inc. All rights reserved. Outline 93 Interest- Calculator.java (3 of 11) 47 // set up principalJLabel 48 principalJLabel = new JLabel(); 49 principalJLabel.setText( "Principal:" ); 50 principalJLabel.setBounds( 16, 16, 56, 24 ); 51 contentPane.add( principalJLabel ); 52 53 // set up principalJTextField 54 principalJTextField = new JTextField(); 55 principalJTextField.setHorizontalAlignment( JTextField.RIGHT ); 56 principalJTextField.setBounds( 96, 16, 104, 24 ); 57 contentPane.add( principalJTextField ); 58 principalJTextField.addKeyListener( 59 60 new KeyAdapter() // anonymous inner class 61 { 62 // event handler called when principalJTextField 63 // is edited 64 public void keyPressed( KeyEvent event ) 65 { 66 principalJTextFieldKeyPressed( event ); 67 } 68 69 } // end anonymous inner class 70 71 ); // end call to addKeyListener

94  2003 Prentice Hall, Inc. All rights reserved. Outline 94 Interest- Calculator.java (4 of 11) 72 73 // set up rateJLabel 74 rateJLabel = new JLabel(); 75 rateJLabel.setText( "Interest rate:" ); 76 rateJLabel.setBounds( 16, 56, 80, 24 ); 77 contentPane.add( rateJLabel ); 78 79 // set up rateJTextField 80 rateJTextField = new JTextField(); 81 rateJTextField.setHorizontalAlignment( JTextField.RIGHT ); 82 rateJTextField.setBounds( 96, 56, 104, 24 ); 83 contentPane.add( rateJTextField ); 84 rateJTextField.addKeyListener( 85 86 new KeyAdapter() // anonymous inner class 87 { 88 // event handler called when rateJTextField is edited 89 public void keyPressed( KeyEvent event ) 90 { 91 rateJTextFieldKeyPressed( event ); 92 } 93 94 } // end anonymous inner class 95 96 ); // end call to addKeyListener

95  2003 Prentice Hall, Inc. All rights reserved. Outline 95 Interest- Calculator.java (5 of 11) 97 98 // set up yearsJLabel 99 yearsJLabel = new JLabel(); 100 yearsJLabel.setText( "Years:" ); 101 yearsJLabel.setBounds( 16, 96, 48, 24 ); 102 contentPane.add( yearsJLabel ); 103 104 // set up yearsJSpinner 105 yearsJSpinner = new JSpinner( 106 new SpinnerNumberModel( 1, 1, 10, 1 ) ); 107 yearsJSpinner.setBounds( 96, 96, 104, 24 ); 108 contentPane.add( yearsJSpinner ); 109 yearsJSpinner.addChangeListener( 110 111 new ChangeListener() // anonymous inner class 112 { 113 // event handler called when value in 114 // yearsJSpinner changes 115 public void stateChanged( ChangeEvent event ) 116 { 117 yearsJSpinnerStateChanged( event ); 118 } 119 120 } // end anonymous inner class 121 Calling programmer- declared method from event handler Calling method addChangeListener Event handler stateChanged

96  2003 Prentice Hall, Inc. All rights reserved. Outline 96 Interest- Calculator.java (6 of 11) 122 ); // end call to addChangeListener 123 124 // set up calculateJButton 125 calculateJButton = new JButton(); 126 calculateJButton.setText( "Calculate" ); 127 calculateJButton.setBounds( 216, 16, 100, 24 ); 128 contentPane.add( calculateJButton ); 129 calculateJButton.addActionListener( 130 131 new ActionListener() // anonymous inner class 132 { 133 // event handler called when calculate button is clicked 134 public void actionPerformed( ActionEvent event ) 135 { 136 calculateJButtonActionPerformed( event ); 137 } 138 139 } // end anonymous inner class 140 141 ); // end call to addActionListener 142 Call programmer- declared method from event handler Registering event handler for calculateJButton Event handler actionPerformed

97  2003 Prentice Hall, Inc. All rights reserved. Outline 97 Interest- Calculator.java (7 of 11) 143 // set up clearJButton 144 clearJButton = new JButton(); 145 clearJButton.setBounds( 216, 56, 100, 24 ); 146 clearJButton.setText( "Clear" ); 147 contentPane.add( clearJButton ); 148 clearJButton.addActionListener( 149 150 new ActionListener() // anonymous inner class 151 { 152 // event handler called when clearJButton is clicked 153 public void actionPerformed( ActionEvent event ) 154 { 155 clearJButtonActionPerformed( event ); 156 } 157 158 } // end anonymous inner class 159 160 ); // end call to addActionListener 161 162 // set up accountJLabel 163 accountJLabel = new JLabel(); 164 accountJLabel.setText( "Yearly account balance:" ); 165 accountJLabel.setBounds( 16, 136, 150, 24 ); 166 contentPane.add( accountJLabel ); 167 Call programmer- declared method from event handler Registering event handler for clearJButton Event handler actionPerformed

98  2003 Prentice Hall, Inc. All rights reserved. Outline 98 Interest- Calculator.java (8 of 11) 168 // set up accountJTextArea 169 accountJTextArea = new JTextArea(); 170 accountJTextArea.setEditable( false ); 171 172 // set up accountJScrollPane 173 accountJScrollPane = new JScrollPane( accountJTextArea ); 174 accountJScrollPane.setBounds( 16, 160, 300, 88 ); 175 contentPane.add( accountJScrollPane ); 176 177 // set properties of application’s window 178 setTitle( "Interest Calculator" ); // set title bar text 179 setSize( 340, 300 ); // set window size 180 setVisible( true ); // show window 181 182 } // end method createUserInterface 183 184 // clear the accountJTextArea 185 private void rateJTextFieldKeyPressed( KeyEvent event ) 186 { 187 accountJTextArea.setText( "" ); 188 189 } // end method rateJTextFieldKeyPressed 190

99  2003 Prentice Hall, Inc. All rights reserved. Outline 99 Interest- Calculator.java (9 of 11) 191 // clear the accountJTextArea 192 private void principalJTextFieldKeyPressed( KeyEvent event ) 193 { 194 accountJTextArea.setText( "" ); 195 196 } // end method principalJTextFieldKeyPressed 197 198 // calculate yearly values of investment 199 private void calculateJButtonActionPerformed( ActionEvent event ) 200 { 201 // declare variables to store user input 202 double principal = Double.parseDouble( 203 principalJTextField.getText() ); 204 double rate = Double.parseDouble( rateJTextField.getText() ); 205 Integer integerObject = ( Integer ) yearsJSpinner.getValue(); 206 int year = integerObject.intValue(); 207 208 accountJTextArea.setText( "Year\tAmount on Deposit" ); 209 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 210

100  2003 Prentice Hall, Inc. All rights reserved. Outline 100 Interest- Calculator.java (10 of 11) 211 // calculate the total value for each year 212 for ( int count = 1; count <= year; count++ ) 213 { 214 double amount = principal * 215 Math.pow( ( 1 + rate / 100 ), count ); 216 accountJTextArea.append( "\n" + count + "\t" + 217 dollars.format( amount ) ); 218 219 } // end for 220 221 } // end method calculateJButtonActionPerformed 222 223 // clear GUI components 224 private void clearJButtonActionPerformed( ActionEvent event ) 225 { 226 // clear the JTextFields 227 principalJTextField.setText( "" ); 228 rateJTextField.setText( "" ); 229 230 // clear the JTextArea 231 accountJTextArea.setText( "" ); 232 233 // reset the value of the JSpinner 234 yearsJSpinner.setValue( new Integer( 1 ) ); 235 Programmer- declared method Clear JTextField s Reset JSpinner to original value Clear JTextArea

101  2003 Prentice Hall, Inc. All rights reserved. Outline 101 Interest- Calculator.java (11 of 11) 236 } // end method clearJButtonActionPerformed 237 238 // clear the JTextArea 239 private void yearsJSpinnerStateChanged( ChangeEvent event ) 240 { 241 accountJTextArea.setText( "" ); 242 243 } // end method yearsJSpinnerStateChanged 244 245 // main method 246 public static void main( String args[] ) 247 { 248 InterestCalculator application = new InterestCalculator(); 249 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 250 251 } // end method main 252 253 } // end class InterestCalculator Programmer- declared method Clear JTextArea

102 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 102 14.1 Test-Driving the Fund Raiser Application

103 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 103 14.1 Test-Driving the Fund Raiser Application (Cont.) Figure 14.1 Running the completed Fund Raiser application.

104 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 104 14.1 Test-Driving the Fund Raiser Application (Cont.) Figure 14.2 Fund Raiser application with first donation entered.

105 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 105 14.1 Test-Driving the Fund Raiser Application (Cont.) Figure 14.3 Making further donations. Total of all donations (minus expenses)

106 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 106 14.2 Constructing the Fund Raiser Application When the user changes the current donation amount in the JTextField Clear the JTextField that displays the current donation after expenses When the user clicks the Donate JButton Obtain the current donation from the JTextField Calculate and display the current donation after expenses Update and display the total amount raised for the charity

107 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 107 14.2 Constructing the Fund Raiser Application (Cont.)

108 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 108 14.3 Conversions (Cont.) Figure 14.9 Displaying the donation amount after operating expenses are deducted. Display the donation amount after expenses are subtracted

109 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 109 14.3 Conversions (Cont.) Figure 14.10 Updating and displaying the total amount raised for charity. Update instance variableDisplay total amount raised for charity

110 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 110 14.3 Conversions (Cont.) Figure 14.11 Clearing the After Expenses: JTextField.

111 © Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 111 14.3 Conversions (Cont.) Figure 14.12 Running the completed application.

112  2003 Prentice Hall, Inc. All rights reserved. Outline 112 FundRaiser.java (1 of 8) 1 // Tutorial 14: FundRaiser.java 2 // Calculates the amount of a donation after expenses and then 3 // totals repeated donations. 4 import java.awt.*; 5 import java.awt.event.*; 6 import java.text.*; 7 import javax.swing.*; 8 9 public class FundRaiser extends JFrame 10 { 11 // JLabel and JTextField to hold donation 12 private JLabel donationJLabel; 13 private JTextField donationJTextField; 14 15 // JLabel and JTextField to display amount after expenses 16 private JLabel afterExpensesJLabel; 17 private JTextField afterExpensesJTextField; 18 19 // JLabel and JTextField to display total amount raised 20 private JLabel totalRaisedJLabel; 21 private JTextField totalRaisedJTextField; 22 23 // JButton to allow user to enter donation 24 private JButton donateJButton; 25

113  2003 Prentice Hall, Inc. All rights reserved. Outline 113 FundRaiser.java (2 of 8) 26 // instance variable stores total raised for charity 27 private double totalNetDonations = 0.00; 28 29 // no-argument constructor 30 public FundRaiser() 31 { 32 createUserInterface(); 33 } 34 35 // create and position GUI components; register event handlers 36 private void createUserInterface() 37 { 38 // get content pane for attaching GUI components 39 Container contentPane = getContentPane(); 40 41 // enable explicit positioning of GUI components 42 contentPane.setLayout( null ); 43 44 // set up donationJLabel 45 donationJLabel = new JLabel(); 46 donationJLabel.setBounds( 16, 16, 80, 20 ); 47 donationJLabel.setText( "Donation:" ); 48 contentPane.add( donationJLabel ); 49 Declaring instance variable

114  2003 Prentice Hall, Inc. All rights reserved. Outline 114 FundRaiser.java (3 of 8) 50 // set up donationJTextField 51 donationJTextField = new JTextField(); 52 donationJTextField.setBounds( 122, 16, 120, 21 ); 53 donationJTextField.setHorizontalAlignment( JTextField.RIGHT ); 54 contentPane.add( donationJTextField ); 55 donationJTextField.addKeyListener( 56 57 new KeyAdapter() // anonymous inner class 58 { 59 // event handler called when donationJTextField is edited 60 public void keyPressed( KeyEvent event ) 61 { 62 donationJTextFieldKeyPressed( event ); 63 } 64 65 } // end anonymous inner class 66 67 ); // end call to addKeyListener 68 69 // set up afterExpensesJLabel 70 afterExpensesJLabel = new JLabel(); 71 afterExpensesJLabel.setBounds( 16, 48, 98, 20 ); 72 afterExpensesJLabel.setText( "After expenses:" ); 73 contentPane.add( afterExpensesJLabel ); 74

115  2003 Prentice Hall, Inc. All rights reserved. Outline 115 FundRaiser.java (4 of 8) 75 // set up afterExpensesJTextField 76 afterExpensesJTextField = new JTextField(); 77 afterExpensesJTextField.setBounds( 122, 48, 120, 20 ); 78 afterExpensesJTextField.setText( "$0.00" ); 79 afterExpensesJTextField.setEditable( false ); 80 afterExpensesJTextField.setHorizontalAlignment( 81 JTextField.RIGHT ); 82 contentPane.add( afterExpensesJTextField ); 83 84 // set up totalRaisedJLabel 85 totalRaisedJLabel = new JLabel(); 86 totalRaisedJLabel.setBounds( 16, 80, 88, 20 ); 87 totalRaisedJLabel.setText( "Total raised:" ); 88 contentPane.add( totalRaisedJLabel ); 89 90 // set up totalRaisedJTextField 91 totalRaisedJTextField = new JTextField(); 92 totalRaisedJTextField.setBounds( 122, 80, 120, 20 ); 93 totalRaisedJTextField.setText( "$0.00" ); 94 totalRaisedJTextField.setEditable( false ); 95 totalRaisedJTextField.setHorizontalAlignment( 96 JTextField.RIGHT ); 97 contentPane.add( totalRaisedJTextField ); 98

116  2003 Prentice Hall, Inc. All rights reserved. Outline 116 FundRaiser.java (5 of 8) 99 // set up donateJButton 100 donateJButton = new JButton(); 101 donateJButton.setBounds( 63, 112, 122, 24 ); 102 donateJButton.setText( "Donate" ); 103 contentPane.add( donateJButton ); 104 donateJButton.addActionListener( 105 106 new ActionListener() // anonymous inner class 107 { 108 // event handler called when donateJButton is clicked 109 public void actionPerformed( ActionEvent event ) 110 { 111 donateJButtonActionPerformed( event ); 112 } 113 114 } // end anonymous inner class 115 116 ); // end call to addActionListener 117 118 // set properties of application’s window 119 setTitle( "Fund Raiser" ); // set title bar string 120 setSize( 263, 174 ); // set window size 121 setVisible( true ); // display window 122 123 } // end method createUserInterface

117  2003 Prentice Hall, Inc. All rights reserved. Outline 117 FundRaiser.java (6 of 8) 124 125 // returns donation amount after operating expenses 126 private double calculateDonation( int donatedAmount ) 127 { 128 final double NET_PERCENTAGE = 0.83; 129 130 // calculate amount of donation for charity 131 return NET_PERCENTAGE * donatedAmount; 132 133 } // end method calculateDonation 134 135 // calculate the donation and fill the JTextFields 136 private void donateJButtonActionPerformed( ActionEvent event ) 137 { 138 // get donation amount 139 int grossDonation = 140 Integer.parseInt( donationJTextField.getText() ); 141 142 // obtain donation amount after operating expenses deduction 143 double netDonation = calculateDonation( grossDonation ); 144 145 // specify display format 146 DecimalFormat dollars = new DecimalFormat( "$0.00" ); 147 Declaring the method calculateDonation Obtaining the donation amount Calling method calculateDonation to obtain donation amount after deducting operating expenses

118  2003 Prentice Hall, Inc. All rights reserved. Outline 118 FundRaiser.java (7 of 8) 148 // display amount of donation after expenses 149 afterExpensesJTextField.setText( 150 dollars.format( netDonation ) ); 151 152 // update total amount of donations received 153 totalNetDonations += netDonation; 154 155 // display total amount collected for charity 156 totalRaisedJTextField.setText( 157 dollars.format( totalNetDonations ) ); 158 159 } // end method donateJButtonActionPerformed 160 161 // clear afterExpensesJTextField 162 private void donationJTextFieldKeyPressed( KeyEvent event ) 163 { 164 // clear afterExpensesJTextField 165 afterExpensesJTextField.setText( "" ); 166 167 } // end method donationJTextFieldKeyPressed 168 Displaying the donation amount Displaying the total amount of donations to the charity after expenses Clearing afterExpenses- JTextField Updating the total amount of donations received

119  2003 Prentice Hall, Inc. All rights reserved. Outline 119 FundRaiser.java (8 of 8) 169 // main method 170 public static void main( String args[] ) 171 { 172 FundRaiser application = new FundRaiser(); 173 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 174 175 } // end method main 176 177 } // end class FundRaiser


Download ppt "© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Objectives –Display a date and time. –Use a JPasswordField."

Similar presentations


Ads by Google