Instance Variables The JOptionPane Class The JOptionPane Class - - PowerPoint PPT Presentation
Instance Variables The JOptionPane Class The JOptionPane Class - - PowerPoint PPT Presentation
Instance Variables The JOptionPane Class The JOptionPane Class displays a dialog for user information and interaction... ... it is part of the javax.swing package and must be imported before you can use it. import
The JOptionPane Class
- The JOptionPane Class displays a dialog for user information and
interaction...
- ... it is part of the javax.swing package and must be imported before you
can use it.
import javax.swing.JOptionPane; public class Test { public static void main( String[] args ) { JOptionPane.showMessageDialog( null, "Hello World" ); } }
showMessageDialog
This method displays a message and an OK button.
void JOptionPane.showMessageDialog( parent, message ) parent This is the parent window for the dialog; for us it will always be null. message The message to display. public static void main( String[] args ) { JOptionPane.showMessageDialog( null, "Hello World" ); }
showInputDialog (1)
Invoked as shown below, this method displays a message, OK and Cancel buttons, and a place for a user to enter input. Input from the user is returned to the caller.
String JOptionPane.showInputDialog( parent, message ) parent: This is the parent window for the dialog; for us it will always be null. message: The message to display. Returns: OK button selected: the user's input; Cancel button selected: null JOptionPane.showInputDialog( null, message );
showInputDialog (1) Example
import javax.swing.JOptionPane; public class Test { public static void main( String[] args ) { String message = "Please enter your name"; String name = JOptionPane.showInputDialog( null, message ); if ( name != null ) System.out.println( "The user's name is: " + name ); else System.out.println( "no name entered" ); } }
showInputDialog (2)
This form of the showInputDialogMethod displays a message, OK and Cancel buttons, and allows you to specify the title and type of the dialog.
String JOptionPane.showInputDialog(parent, message, title, type ) JOptionPane.showInputDialog( null, message, "Missing Data", JOptionPane.WARNING_MESSAGE );
showInputDialog (2) Detail
title: This string will be displayed in the dialog’s title bar. type: This integer must be a constant from the JOptionPane class:
- JOptionPane.ERROR_MESSAGE,
- JOptionPane.INFORMATION_MESSAGE,
- JOptionPane.WARNING_MESSAGE,
- JOptionPane.QUESTION_MESSAGE
- JOptionPane.PLAIN_MESSAGE
JOptionPane.showInputDialog( null, message, "Missing Data", JOptionPane.WARNING_MESSAGE );
showInputDialog (2) Example
import javax.swing.JOptionPane; public class Test { public static void main( String[] args ) { String message = "You must enter your name to continue"; String name = JOptionPane.showInputDialog( null, message, "Missing Data", JOptionPane.WARNING_MESSAGE ); if ( name == null ) System.out.println( "Dialog canceled" ); else if ( name.equals( "" ) ) System.out.println( "no name entered" ); else System.out.println( "The user's name is: " + name ); } }
showConfirmDialog
This form of the showConfirmDialogMethod displays a message, yes, no and cancel buttons, and allows you to specify the title and type of the dialog.
String JOptionPane.showConfirmDialog(parent, message ) parent: This is the parent window for the dialog; for us it will always be null. message: The message to display. Returns: JOptionPane.YES_OPTION, JOptionPane.NO_OPTION or JOptionPane.CANCEL_OPTION JOptionPane.showConfirmDialog( null, message );
showConfirmDialog Example
import javax.swing.JOptionPane; public class Test { public static void main( String[] args ) { String message = "Are you sure you want to do this?"; int response = JOptionPane.showConfirmDialog( null, message ); if ( response == JOptionPane.YES_OPTION ) System.out.println( "the user is sure" ); else if ( response == JOptionPane.NO_OPTION ) System.out.println( "the user is not sure" ); else if ( response == JOptionPane.CANCEL_OPTION ) System.out.println( "the user has cancelled" ); else System.out.println( "the user selected no option" ); } }
JOptionPane Documentation
For complete documentation of the many JOptionPane alternatives, see the javax.swing documentation.
Exercises
- 1. Textbook, Chapter 4, page 4‐5
Exercise 4.1
Instance Variables
- An instance variable is used by an object to store a value unique to that
- bject.
- Instance variables are declared at the class level.
- Instance variables are almost always private.
public class Name { private String firstName_ = null; // instance variable private String lastName_ = null; // instance variable public void someMethod() { ... } }
Instance Variables Example (1)
Below are some of the instance variable declarations for Turtle objects.
public class Turtlet extends Object { private double heading = 0; // heading initially east private double xcor; // current x position of Turtle private double ycor; // current position of Turtle private Color currColor; // current color of Turtle ... }
Every Turtle you create has a unique set of these variables.
Instance Variables Example (2)
public class Test { public static void main( String[] args ) { Turtle fred = new Turtle(); Turtle wilma = new Turtle(); fred.move( 135, 128 * Math.sqrt( 2 ) ); fred.switchTo( Turtle.RED ); wilma.move( -45, 128 * Math.sqrt( 2 ) ); wilma.switchTo( Turtle.GREEN ); fred.fillBox( 64,64 ); wilma.fillCircle( 128 ); } } Wilma: xco = 128 yco = -128 color = green Fred: xco = -128 yco = 128 color = red
Accessor Methods (1)
public class Name { private String firstName_ = null; private String lastName_ = null; public void setFirstName( String name ) { firstName_ = name; } public String getFirstName() { return firstName_; } // public void setLastName( String name ) // public String getLastName( String name ) ...
When instance variables are private, you often employ accessors to set and/or get their values.
Accessor Methods (2)
... public void setName( String first, String last ) { firstName_ = first; lastName_ = last; } public String getName() { return lastName_ + ", " + firstName_; } }
Sometimes accessors are created just for convenience.
Using Accessor Methods
public class Test { public static void main( String[] args ) { Name person1 = new Name(); person1.setFirstName( "george" ); person1.setLastName( "washington" ); Name person2 = new Name(); person2.setName( "thomas", "jefferson" ); System.out.println( person2.getFirstName() ); System.out.println( person2.getLastName() ); System.out.println( person1.getName() ); } }
Output: thomas jefferson washington, george
Exercises
- 1. Implement the name class as shown in the slides; you will have to write the code
for setLastName and getLastName.
- 2. To the name class add a string instance variable to hold a title (such as Mr. and
Ms.). Write accessors for the new variable.
Basic Game
The BasicGame is a class that may serve as the core of many different games. We will start by implementing a simple guessing game. It has two instance variables, one for holding the word to guess, and one for holding the user’s guess.
public class BasicGame { private String secretWord_ = "duck"; private String usersGuess_ = "none"; . . .
Basic Game: playOneGame
The playOneGame method: 1. Asks the player’s first guess. 2. If the guess is correct, displays a congratulatory message and stops. 3. If the guess is wrong, displays an error message and returns to step 2.
. . . public void playOneGame() { askUsersFirstChoice(); while ( shouldContinue() ) { showUpdatedStatus(); askUsersNextChoice(); } showFinalStatus(); } . . .
Basic Game: playManyGames
The playManyGames method: 1. Plays one game. 2. Asks the user if she wants to play another. 3. Plays another game if the user says yes, otherwise stops.
. . . public void playManyGames() { int again = 0; do { playOneGame(); again = JOptionPane.showConfirmDialog( null, "again?" ); } while ( again == JOptionPane.YES_OPTION ); } . . .
Basic Game: askUsersFirstChoice
The askUsersFirstChoice method: 1. Asks the user to enter a string, which is stored in the object’s usersGuess_ instance variable.
. . . public void askUsersFirstChoice() { usersGuess_ = JOptionPane.showInputDialog( null, "Guess the secret word" ); } . . .
Basic Game: askUsersNextChoice
The askUsersNextChoice method: 1. Just calls askUsersFirstChoice.
. . . public void askUsersNextChoice() { askUsersFirstChoice(); } . . .
Basic Game: shouldContinue
The askUsersNextChoice method: 1. Compares the user's guess with the secret word. If they are not equal it returns true, otherwise it returns false.
. . . public boolean shouldContinue() { boolean rval = !secretWord_.equals( usersGuess_ ); return rval; } . . .
If the user guesses right we don’t want to continue, so return false.
Basic Game: showUpdatedStatus
The showUpdatedStatus method: 1. Displays an error message, and gives the user a hint about the correct answer.
. . . public void showUpdatedStatus() { String message = "That was wrong. Hint: it quacks."; JOptionPane.showMessageDialog( null, message ); } . . .
Basic Game: showFinalStatus
The showFinalStatus method: 1. Displays a congratulatory message.
. . . public void showFinalStatus() { String message = "That was right, congratulations."; JOptionPane.showMessageDialog( null, message ); } . . .
Basic Game: Running The Program
public class TestBasicGame { public static void main( String[] args ) { BasicGame game = new BasicGame(); game.playManyGames(); } }
Basic Game: Code
The complete BasicGame class can be found on the class web page under Sample Code.
Exercises
- 1. Enter and test the code for the BasicGame class.
- 2. Textbook, Chapter 4, page 4‐8
Exercise 4.3 – 4.6
Identifying Methods
Java identifies a method according to: 1. Its name; 2. The number and type of its parameters. The following are all different methods even though they have the same name: This is called the method signature.
private static int hitMe( int param ) private static double hitMe( double param ) private static String hitMe( int param1, int param2 )
Note: the method signature does NOT include the return type.
Overriding Methods
Suppose: 1. Class A has the method showMessage( String ). 2. Class B extends A, and also has the method showMessage( String ). In this case the method in class B overrides the method in class A.
Note: an overriding method must have a return type that is “compatible” with the method you are overriding.
Overriding Methods Example 1
// dog.java public class Dog { public void showMessage( String msg ) { String str = "woof woof, " + msg; JOptionPane.showMessageDialog( null, str); } } // poodle.java public class Poodle extends Dog { public void showMessage( String msg ) { String str = "yip, yip, yap, " + msg; JOptionPane.showMessageDialog( null, str); } }
This method:
- verrides this one:
continued on next slide
Overriding Methods Example 1
// test.java public class Test { public static void main( String[] args ) { Dog woofer = new Dog(); Poodle yipper = new Poodle(); woofer.showMessage( "Bark" ); yipper.showMessage( "Bark" ); bark( yipper ); } private static void bark( Dog param ) { param.showMessage( "Bark" ); } }
continued
Even though the parameter is type Dog the method in Poodle will be executed.
Overriding Methods Example 2
public class TodTheTurtle extends Turtle { public static void main( String[] args ) { TodTheTurtle tod = new TodTheTurtle(); tod.paint( 90, 256 ); } public Turtlet paint( double angle, double distance ) { say("Tod the Turtle doesn't feel like painting now."); return this; } }
The Super Keyword
The super keyword allows a subclass to directly access elements in its
- superclass. This makes it easy for an overriding method to utilize the
- verridden method in its superclass.
public class TodTheTurtle extends Turtle { public static void main( String[] args ) { TodTheTurtle tod = new TodTheTurtle(); tod.paint( 90, 256 ); } public Turtlet paint( double angle, double distance ) { say("If you insist..."); Turtlet rval = super.paint( angle, distance ); say("Happy now?"); return rval; } }
Constructors
- A constructor is a special kind of method that is called when an object is
created.
- A constructor has the same name as the class that it belongs to.
- A constructor doesn't explicitly list its return type or have a return
statement.
- Every class has a constructor; if you don’t write one, Java will provide a
default constructor for you.
public class TodTheTurtle extends Turtle { public TodTheTurtle() { System.out.println( “A new TodTheTurtle is born.” ); } }
Constructors:
- same name as class
- no return type listed
- no explicit return
The Default Constructor
- The default constructor looks like this:
// default constructor for class Fish public Fish() { }
- Java will provide you with a default constructor if a class has no other
constructors.
- You can also write the default constructor yourself.
Overloaded Constructors
- Through the use of overloading, a class can have many constructors:
public class BoxTurtle extends Turtle { public static void main(String[] args) { // BoxTurtle boxy = new BoxTurtle( 64 ); BoxTurtle boxy = new BoxTurtle( 64, RED ); } public BoxTurtle( int side ) { fillBox( side, side ); } public BoxTurtle( int side, java.awt.Color color ) { switchTo( color ); fillBox( side, side ); } }
Exercises (page 1 of 2)
- 1. Create a subclass of Turtle named TwistedTurtle with a constructor that takes a
single argument; the argument tells the Turtle instance to face a new direction. For example:
// Start with a turtle facing West TwistedTurtle bob = new TwistedTurtle( 180 );
Test your work.
- 2. Add a constructor to TwistedTurtle that tells the Turtle instance to turn at an angle
and move to a new position. For example:
// Start with a turtle facing North 128 pixels // above the center of the window. TwistedTurtle bob = new TwistedTurtle( 90, 128 );
Test your work.
Exercises (page 2 of 2)
- 3. Write a tester that contains this line of code in the main method:
TwistedTurtle sam = new TwistedTurtle();
Does this compile? Why not?
- 4. Fix the code from the previous exercise so that it compiles (you will need to add a
new constructor to TwistedTurtle).
Instance Variables
The Person class has two instance variables:
public class Person { private String firstName_; private String lastName_; }
Instance Variables
The default constructor for the Person class:
public class Person { private String firstName_; private String lastName_; public Person() { firstName_ = "none"; lastName_ = "none"; } }
Instance Variables
The constructor( String, String ) for the Person class:
public class Person { ... public Person( String firstName, String lastName ) { firstName_ = firstName; lastName_ = lastName; } } What would you do if the constructor parameters had the same names as the instance variables?
Instance Variables
Accessors for firstName_ in the Person class:
public class Person { ... public void setFirstName( String name ) { firstName_ = name; } public String getFirstName() { return firstName_; } }
Instance Variables
Overriding the toString() method in the Person class:
public class Person { ... public String toString() { String name = lastName_ + ", " + firstName_; return name; } } The Object class has a toString() method; this is
- verriding it.
Exercises
- 1. Enter and compile the code for the Person class *** but don’t code the toString()
method yet ***.
- 2. Add accessors to the Person class for lastName_.
- 3. Perform the following tests:
- a. Try these lines of code in a test program:
Person zilla = new Person( "George", "Washington" ); System.out.println( zilla );
Can you explain the output of your test program?
- b. Add the toString() method to the Person class. Run your test program again
and explain why you get different output.
Instance Variables
The ImportantPerson class adds one instance variable to the Person class:
public class ImportantPerson extends Person { private String birthday_; } Because firstName_ and lastName_ are private in the Person class, they cannot be accessed directly by the code in the ImportantPerson class.
Super‐Constructors
The ImportantPerson class will have several constructors...
- ... one of them will be the default constructor...
- ... another will be a (String, String) constructor which must initialize
firstName_ and lastName_ in the Person class:
public ImportantPerson() { birthday_ = "none"; } public ImportantPerson( String first, String last ) { super( first, last ); birthday_ = "none"; }
Use the super keyword to access a specific constructor in a superclass.
Overriding To‐String
The ImportantPerson class overrides the toString method in the Person class:
public String toString() { String name = super.toString() + ": " + birthday_; return name; } Use super to access the overridden method in the super class.
Exercises
1. Enter and compile the code for the ImportantPerson class as shown in the slides. 2. Add accessors to the ImportantPerson class for birthday_. 3. Add to ImportantPerson a method for setting firstName_, lastName_ and birthday_:
public void setName( String first, String last, String birthday ) { ... }
To set firstName_ and lastName_ utilize the setName method in the Person class. 4. Add to ImportantPerson a method for setting just firstName_ and lastName_; explicitly set birthday_ to “none”:
public void setName( String first, String last ) { ... }
To set firstName_ and lastName_ utilize the setName method in the Person class.
Instance Variables
The Time class has two instance variables:
public class Time { private int hour_ = 0; private int min_ = 0; }
Instance Variables
The Time class has a constructor( int, int ) that initializes its instance variables:
public class Time { private int hour_ = 0; private int min_ = 0; public Time( int hour, int min ) { super(); hour_ = hour; for ( min_ = min ; min_ < 0 ; min_ = min_ + 60 ) hour_--; } }
This is from your
- textbook. It
converts, for example, 185 minutes into 3 hours and 5 minutes.
Instance Variables
The Time class has a constructor that takes another Time instance as an argument:
public Time( Time time ) { hour_ = time.hour_; min_ = time.min_; }
This is called a copy constructor because the properties for the new object are copied from the argument.
Instance Variables
The Time class overrides the toString method:
public String toString() { String time = "" + hour_ + min_; if ( hour_ < 10 ) time = "0" + time; return time; } This is supposed to format the time in military format, for example 0930, but there’s a bug in it.
Instance Variables
The Time class an add method. It adds two times and stores the result in a third time object:
public Time add( Time toAdd ) { int newHour = ? int newMin = ? Time result = new Time( newHour, newMin ); return result; } Can you identify the three time
- bjects?
Instance Variables
This is an example of using the add method in the time class:
public class Test { public static void main( String[] args ) { Time time1 = new Time( 13, 30 ); Time time2 = new Time( 12, 45 ); Time time3 = time1.add( time2 ); System.out.println( time1.toString() ); System.out.println( time2.toString() ); System.out.println( time3.toString() ); } }
Exercises
- 1. Textbook, Chapter 4, page 4‐15
Exercise 4.11 Exercise 4.13 ‐ 4.20
The Random Class
- The Random Class resides in java.util.
- Use the nextInt() method to generate a pseudorandom number between
‐2.1 billion and +2.1 billion.
- Use nextInt( num ) to generate a pseudorandom number between 0 and
num ‐ 1 (num must be positive).
- See the complete documentation in the java.util reference.
Note: java.util.Random is a very convenient class, but it is not used on the AP Computer Science test. See instead Math.rand().
Using The Random Class
import java.util.Random; public class Test { public static void main( String[] args ) { Random rand = new Random(); System.out.println( rand.nextInt() ); System.out.println( rand.nextInt() ); System.out.println( rand.nextInt() ); System.out.println( rand.nextInt( 4 ) ); System.out.println( rand.nextInt( 4 ) ); System.out.println( rand.nextInt( 4 ) ); System.out.println( rand.nextInt( 4 ) ); } }
Integer.parseInt( String )
Numeric input is often received as a string. To use the data numerically the string has to be parsed.
public class Test { public static void main( String[] args ) { String resp = JOptionPane.showInputDialog( "Enter an integer" ); int inx = Integer.parseInt( resp ) + 5; System.out.println( resp + " + 5 = " + inx ); } }
Recall that 5 is an integer and “5” is a string, not a number.
Note: if resp isn’t a valid integer your program will crash.
The Guess‐Number Class
GuessNumber is an extension of BasicGame. It has three instance variables:
public class GuessNumber extends BasicGame { private Random rand_; private int secretNumber_; private int usersNumber_; ...
The Guess‐Number Constructor
GuessNumber has one constructor which is used to initialize the random number generator:
public class GuessNumber extends BasicGame { ... public GuessNumber() { super(); rand_ = new Random(); } ...
The askUsersFirstChoice Method
GuessNumber overrides askUsersFirstChoice in BasicGame:
public class GuessNumber extends BasicGame { ... public void askUsersFirstChoice() { secretNumber_ = rand_.nextInt( 100 ) + 1; askUsersNextChoice(); } ...
Generates an integer between 1 and 100, inclusive.
The askUsersNextChoice Method
GuessNumber overrides askUsersNextChoice in BasicGame:
public class GuessNumber extends BasicGame { ... public void askUsersNextChoice() { String msg = "Guess a number from 1 to 100:"; String str = JOptionPane.showInputDialog( null, msg ); if ( str != null && !str.equals( "" ) ) usersNumber_ = Integer.parseInt( str ); else usersNumber_ = -1; } ...
The shouldContinue Method
GuessNumber overrides shouldContinue in BasicGame:
public class GuessNumber extends BasicGame { ... public boolean shouldContinue() { boolean rval = usersNumber_ != secretNumber_; return rval; } ...
Remember: shouldContinue returns true if the user’s guess is wrong.
The showUpdatedStatus Method
GuessNumber overrides showUpdatedStatus in BasicGame:
public class GuessNumber extends BasicGame { ... public void showUpdatedStatus() { if ( usersNumber_ > secretNumber_ ) JOptionPane.showMessageDialog( null, "Too high" ); else JOptionPane.showMessageDialog( null, "Too low" ); } ...
Inherited Methods
GuessNumber inherits these methods from BasicGame:
- playManyGames
- playOneGame
- showFinalStatus
Exercises
- 1. Enter and compile the code for GuessNumber. If you wish, the file can be
downloaded from the Sample Code page of the class website.
- 2. Textbook, Chapter 4, page 4‐19
Exercise 4.21, 4.22 Exercise 4.24 ‐ 4.27
Method Signature
Java recognizes methods by their signature: name + number of parameters + type of parameters:
move( double, double ) // move + double + double say( String ) // say + String Time( int, int ) // Time + int + int
Method Overloading
Two or more methods that have the same name but different parameters are said to be overloads of each other:
setName( String ) // overload of setName setName( String, String ) // overload of setName setName() // overload of setName
Method Overriding
When a method in a subclass has the same signature as a method in its superclass the method in the subclass is said to override the method in the superclass:
Turtle.paint( double, double ) // overriden method TodTheTurtle.paint( double, double ) // overriding method
Method Overriding Example
public class TodTheTurtle extends Turtle { public static void main( String[] args ) { TodTheTurtle tod = new TodTheTurtle(); tod.paint( 90, 256 ); } public Turtlet paint( double angle, double distance ) { say( “Tod doesn’t feel like painting right now...“ ); return rval; } }
Executing An Overriden Method
An overriding method can invoke its overridden method using the super keyword:
public class TodTheTurtle extends Turtle { public Turtlet paint( double angle, double distance ) { say("If you insist..."); Turtlet rval = super.paint( angle, distance ); say("Happy now?"); return this; } }
Polymorphism
- The term polymorphism applies to the ability of a method to handle
different types or forms of data.
- In java, overloading and overriding create polymorphic methods.
Overriding: processing the same data differently depending on the type of the class doing the processing. Overloading: processing different data using methods with the same name in the same class.
Exercises
Note: if you’re comfortable with the double (real‐number) type use that instead of int for all numbers. 1. Write a class called Temperature which has one instance variable that stores temperature in Celsius. 2. Give Temperature two constructors:
– public Temperature( int temp )
Assume temp is in Celsius; use it to initialize your instance variable
– public Temperature( int temp, String scale )
If scale is “C”, assume temp is Celsius; if scale is anything else assume temp is
- Fahrenheit. Use temp to initialize your instance variable.
3. Add accessors to the Temperature class:
– public int getCelsius() // gets temperature in Celsius – public int getFahrenheit() // gets temperature in Fahrenheit – public void setCelsius( int temp ) // temp is Celsius – public void setFahrenheit( int temp ) // temp is Fahrenheit
4. In the temperature class override the toString() method; it should return a string consisting
- f the temperature concatenated with “C”.