Transcript Chapter 6
Layouts, Types, & Switches
Copyright © 2012 Pearson Education, Inc.
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
Window controls
Menu bar
Content pane
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 component
resizing.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
GridBagLayout
http://download.oracle.com/javase/tutorial/uiswing/examples/layout/GridBagLayoutDemoProject/src/layout/GridBagLayoutDemo.java
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Layout Example: Box vs Border
Copyright © 2012 Pearson Education, Inc.
Layout Example: Box vs Border
http://docs.oracle.com/javase/7/docs/api/javax/swing/BoxLayout.html
Copyright © 2012 Pearson Education, Inc.
Types Revisited
Copyright © 2012 Pearson Education, Inc.
Wrapper Classes
• Use wrapper objects in Collections when you can’t
use primitive types
Primitive Type
byte
short
Wrapper Class
Byte
Short
int
long
float
double
Integer
Long
Float
Double
char
boolean
Character
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
Why would we want
to use enums?
• 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.
//********************************************************************
// 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.
Output
winter December through February
//********************************************************************
spring March through May
// SeasonTester.java
Author: Lewis/Loftus
summer June through August
//
fall
September through November
// 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.
else-if & switch
Copyright © 2012 Pearson Education, Inc.
Example: else-if
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’;
Copyright © 2012 Pearson Education, Inc.
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
and
case
are
reserved
words
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
If expression
matches value2,
control jumps
to here
A break statement can be used in a switch to jump to the
end of the switch statement
Copyright © 2012 Pearson Education, Inc.
The switch Statement
• An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Copyright © 2012 Pearson Education, Inc.
Example: else-if vs switch
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’;
}
If no other case value matches, the optional default case
Copyright © 2012 Pearson Education, Inc.
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
• 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
break;
case 9:
System.out.println
break;
case 8:
System.out.println
break;
case 7:
System.out.println
break;
case 6:
System.out.println
System.out.println
("a perfect score. Well done.");
("well above average. Excellent.");
("above average. Nice job.");
("average.");
("below average. You should see the");
("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.
Copyright © 2012 Pearson Education, Inc.
Templates
While Loop Index Template:
While Loop Sentinel Template:
initialize index
while (condition){
statements to be repeated
update index
}
get input value
while (input != end condition){
statements to be repeated
get input value
}
Example switch:
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
}
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