Presentation is loading. Please wait.

Presentation is loading. Please wait.

Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc.

Similar presentations


Presentation on theme: "Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc."— Presentation transcript:

1 Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc.

2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling GUI Principles Components: GUI building blocks –Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI –Using layout managers. Events: reacting to user input –Button presses, menu selections, etc.

3 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Elements of a frame Title Menu bar Content pane Window controls

4 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Layout managers Manage limited space for competing components (like our content pane) –FlowLayout, BorderLayout, GridLayout, BoxLayout, GridBagLayout. Manage Container objects, e.g. a content pane Each imposes its own style

5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling FlowLayout

6 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BorderLayout

7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling GridLayout

8 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling BoxLayout Note: no component resizing.

9 GridBagLayout Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling http://download.oracle.com/javase/tutorial/uiswing/examples/layout/GridBagLayoutDemoProject/src/layout/GridBagLayoutDemo.java

10 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling A message dialog private void showAbout() { JOptionPane.showMessageDialog(frame, "ImageViewer\n" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); } private void showAbout() { JOptionPane.showMessageDialog(frame, "ImageViewer\n" + VERSION, "About ImageViewer", JOptionPane.INFORMATION_MESSAGE); }

11 Layout Example: Box vs Border Copyright © 2012 Pearson Education, Inc.

12 Layout Example: Box vs Border Copyright © 2012 Pearson Education, Inc. http://docs.oracle.com/javase/7/docs/api/javax/swing/BoxLayout.html

13 Types Revisited Copyright © 2012 Pearson Education, Inc.

14 Wrapper Classes Use wrapper objects in Collections when you can’t use primitive types Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean

15 Wrapper Classes For example: Integer age = new Integer(40); Wrapper classes contain static methods to convert between types. For example, to convert a String to an int : int num = Integer.parseInt(str); Wrapper classes also contain constants such as MIN_VALUE and MAX_VALUE in the Integer class, which hold the smallest and largest int values Copyright © 2012 Pearson Education, Inc.

16 Enumerated Types Define a new data type and list all possible values: enum Season {winter, spring, summer, fall} Then the new type can be used to declare variables Season time; And then the variable can be assigned a value: time = Season.fall; The only values this variable can be assigned are the ones from the enum definition Copyright © 2012 Pearson Education, Inc. Why would we want to use enums?

17 Enumerated Types An enumerated type definition can be more interesting than a simple list of values Because they are like classes, we can add additional instance data and methods We can define an enum constructor as well Each value listed for the enumerated type calls the constructor See Season.java See SeasonTester.java Copyright © 2012 Pearson Education, Inc.

18 //******************************************************************** // Season.java Author: Lewis/Loftus // // Enumerates the values for Season. //******************************************************************** public enum Season { winter ("December through February"), spring ("March through May"), summer ("June through August"), fall ("September through November"); private String span; //----------------------------------------------------------------- // Constructor: Sets up each value with an associated string. //----------------------------------------------------------------- Season (String months) { span = months; } //----------------------------------------------------------------- // Returns the span message for this value. //----------------------------------------------------------------- public String getSpan() { return span; }

19 Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. //******************************************************************** public class SeasonTester { //----------------------------------------------------------------- // Iterates through the values of the Season enumerated type. //----------------------------------------------------------------- public static void main (String[] args) { for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); }

20 Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SeasonTester.java Author: Lewis/Loftus // // Demonstrates the use of a full enumerated type. //******************************************************************** public class SeasonTester { //----------------------------------------------------------------- // Iterates through the values of the Season enumerated type. //----------------------------------------------------------------- public static void main (String[] args) { for (Season time : Season.values()) System.out.println (time + "\t" + time.getSpan()); } Output winterDecember through February springMarch through May summerJune through August fallSeptember through November

21 Enumerated Types Every enumerated type contains a static method called values that returns a list of all possible values for that type The list returned from values can be processed using a for-each loop An enumerated type cannot be instantiated outside of its own definition A carefully designed enumerated type provides a versatile and type-safe mechanism for managing data Copyright © 2012 Pearson Education, Inc.

22 else-if & switch Copyright © 2012 Pearson Education, Inc.

23 Example: else-if Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’;

24 The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches Copyright © 2012 Pearson Education, Inc.

25 The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here Copyright © 2012 Pearson Education, Inc. A break statement can be used in a switch to jump to the end of the switch statement

26 The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement: Copyright © 2012 Pearson Education, Inc.

27 Example: else-if vs switch Copyright © 2012 Pearson Education, Inc. int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; if (grade > 89) letter = ‘A’; else if (grade > 79) letter = ‘B’; else if (grade > 69) letter = ‘C’; else if (grade > 59) letter = ‘D’; else letter = ‘F’; int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } int grade = 85; char letter = ‘’; switch (grade) { case 100: case 99: case 98: … case 90: letter = ‘A’; break; case 89: … default: letter = ‘F’; } If no other case value matches, the optional default case will be executed (if present)

28 The switch Statement The type of a switch expression must be integers, characters, or enumerated types Why? 109.54 == 109.542 Copyright © 2012 Pearson Education, Inc. As of Java 7, a switch can also be used with strings You cannot use a switch with floating point values The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement (i.e., > or <)

29 Copyright © 2012 Pearson Education, Inc. //******************************************************************** // GradeReport.java Author: Lewis/Loftus // // Demonstrates the use of a switch statement. //******************************************************************** import java.util.Scanner; public class GradeReport { //----------------------------------------------------------------- // Reads a grade from the user and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { int grade, category; Scanner scan = new Scanner (System.in); System.out.print ("Enter a numeric grade (0 to 100): "); grade = scan.nextInt(); category = grade / 10; System.out.print ("That grade is "); continue

30 Copyright © 2012 Pearson Education, Inc. continue switch (category) { case 10: System.out.println ("a perfect score. Well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. You should see the"); System.out.println ("instructor to clarify the material " + "presented in class."); break; default: System.out.println ("not passing."); } Sample Run Enter a numeric grade (0 to 100): 91 That grade is well above average. Excellent.

31 Templates While Loop Index Template: initialize index while (condition){ statements to be repeated update index } For Loop Template: for(initialize index; condition; update index){ statements to be repeated } For Each Loop Template: for (ElementType elementName : collection){ statements to be repeated } While Loop Sentinel Template: get input value while (input != end condition){ statements to be repeated get input value } Example switch: switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; }

32 The Conditional Operator The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression Example: char pf = grade > 59 ? ‘P’ : ‘F’; Copyright © 2012 Pearson Education, Inc.

33 The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger ; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands Copyright © 2012 Pearson Education, Inc.

34 The Conditional Operator Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); Copyright © 2012 Pearson Education, Inc.

35 Quick Check Copyright © 2012 Pearson Education, Inc. Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println("It is not greater than 10."); else System.out.println("It is greater than 10."); System.out.println("It is" + ((val <= 10) ? " not" : "") + " greater than 10.");

36 The do Statement A do statement has the following syntax: do { statement-list; } while (condition); The statement-list is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false Copyright © 2012 Pearson Education, Inc.

37 Logic of a do Loop true condition evaluated statement false Copyright © 2012 Pearson Education, Inc.

38 The do Statement An example of a do loop: The body of a do loop executes at least once See ReverseNumber.java int count = 0; do { count++; System.out.println (count); } while (count < 5); Copyright © 2012 Pearson Education, Inc.

39 //******************************************************************** // ReverseNumber.java Author: Lewis/Loftus // // Demonstrates the use of a do loop. //******************************************************************** import java.util.Scanner; public class ReverseNumber { //----------------------------------------------------------------- // Reverses the digits of an integer mathematically. //----------------------------------------------------------------- public static void main (String[] args) { int number, lastDigit, reverse = 0; Scanner scan = new Scanner (System.in); continue

40 Copyright © 2012 Pearson Education, Inc. continue System.out.print ("Enter a positive integer: "); number = scan.nextInt(); do { lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } while (number > 0); System.out.println ("That number reversed is " + reverse); } Sample Run Enter a positive integer: 2896 That number reversed is 6982

41 Comparing while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop Copyright © 2012 Pearson Education, Inc.

42 Create a CeilingFan Class Step 1: Create the class, fields, & constructors –Add a Speed enum {off, low, medium, high} –Store the fan’s current speed –Create a default constructor Step 2: Create the following methods –changeSpeed that changes the speed w/ no parameters using a switch statement –changeSpeed with 1 parameter (the number of times to change it) that uses the first changeSpeed() method & a loop

43

44


Download ppt "Layouts, Types, & Switches Copyright © 2012 Pearson Education, Inc."

Similar presentations


Ads by Google