layouts, types, & switches copyright © 2012 pearson education, inc
TRANSCRIPT
Layouts, Types, & Switches
Copyright © 2012 Pearson Education, Inc.
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.
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
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
FlowLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
BorderLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
GridLayout
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
BoxLayout
Note: no componentresizing.
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
Layout Example: Box vs Border
Copyright © 2012 Pearson Education, Inc.
Layout Example: Box vs Border
Copyright © 2012 Pearson Education, Inc.
http://docs.oracle.com/javase/7/docs/api/javax/swing/BoxLayout.html
Types Revisited
Copyright © 2012 Pearson Education, Inc.
Wrapper Classes• Use wrapper objects in Collections when you can’t
use primitive types
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
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.
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?Why would we want to use enums?
Copyright © 2012 Pearson Education, Inc.
//********************************************************************// 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; }
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()); }}
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()); }}
Outputwinter December through Februaryspring March through Maysummer June through Augustfall September through November
else-if & switch
Copyright © 2012 Pearson Education, Inc.
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’;
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.
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 ...
}
switchandcaseare
reservedwords
If expressionmatches value2,control jumpsto here
Copyright © 2012 Pearson Education, Inc.
A break statement can be used in a switch to jump to the end of the switch statement
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.
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)
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 <)
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
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): 91That grade is well above average. Excellent.
TemplatesWhile Loop Index Template:
initialize indexwhile (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 valuewhile (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;}
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