Top Banner
Java I--Copyright © 2000 Tom Hunter
80
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Page 2: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Chapter 6

Methods

Page 3: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• A Method is invoked by a method call.

• The Syntax is as follows:

object.method(arguments);

A Method Call

spill

Page 4: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Usually, we start with an instance of an object.

• The object hands the method some information (arguments) and asks that method to perform a task based on that information.

• When the the task is done, the method returns information back to the object that called it.

return = object.method(arguments);

A Method Call

Page 5: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Teacher.asksStudent( help );

A Method Call

Page 6: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Teacher.asksStudent( help );

• The OBJECT (Teacher) does not need to know how the method (student) accomplished the request.

• Maybe the men’s room was empty and the student had to go get towels from the ladies room.

A Method Call

Page 7: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Maybe the custodian was filling up the dispenser, and he had to ask the custodian to give him some towels.

• I--the Object--don’t need to know how he accomplished the method.

• I made a request and got back results.

A Method Call

Page 8: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Teacher.asksStudent( help );

• When we’re writing software, one object is independent of another.

• How any object implements its own methods is hidden from the outside world.

• That way, once your method works,nobody can mess it up.

A Method Call

Page 9: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Hiding the implementation of a method promotes good software engineering.

• If you can’t change how an object performs its methods, then you can’t introduce errors.

• You have to live with the way it works now.

A Method Call

Page 10: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• A Method can receive as many arguments as you wish.

• A Method can only return ONE thing.

A Method Call

method

Page 11: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• A Method Always Receives A Copy Of Its Arguments

• Since a Method Only Receives a duplicate, it can

NEVER change the original copy

of the parameter it received.

A Method Call

Page 12: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.Container;import javax.swing.*;

public class SquareInt extends JApplet{ public void init() {

String output = "";JTextArea oArea = new JTextArea( 10, 20 );Container c = getContentPane();c.add( oArea );int result;for( int x = 1; x <= 10; x++ ){ result = square( x ); output += ”Square of " + x +

" is " + result + "\n";}outputArea.setText( output );

}

public int square( int y ) {

return y * y; }}

Notice this syntax:We are inside method init(),

yet we’re calling to anothermethod square() without

referring to an object.“Methods in a class definition

are allowed to invoke allother methods in the same class

this way.”Inherited methods can

be called this sameway.

Page 13: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.Container;import javax.swing.*;

public class SquareInt extends JApplet{ public void init() {

String output = "";JTextArea oArea = new JTextArea( 10, 20 );Container c = getContentPane();c.add( oArea );int result;for( int x = 2; x <= 10; x++ ){ result = square( x ); output += ”Square of " + x +

" is " + result + "\n";}outputArea.setText( output );

}

public int square( int y ) {

return y * y; }}

x2

Result?

y2

Page 14: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Result?

import java.awt.Container;import javax.swing.*;

public class SquareInt extends JApplet{ public void init() {

String output = "";JTextArea oArea = new JTextArea( 10, 20 );Container c = getContentPane();c.add( oArea );int result;for( int x = 1; x <= 10; x++ ){ result = square( x ); output += ”Square of " + x +

" is " + result + "\n";}outputArea.setText( output );

}

public int square( int y ) {

return y * y; }}

Result4

x2

y2

Page 15: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

How Do We Build A GUI Screen?

A Container is the building block...

Page 16: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()import java.awt.Container;import javax.swing.*;

public class SquareInt extends JApplet{ public void init() {

JTextArea oArea = new JTextArea( 10, 20 );

Container c = getContentPane();c.add( oArea );

• What is a Container?• What is happening in these two statements?

Page 17: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

• A Container is something that can contain other objects.

• For example, JApplet is a container that can hold buttons, labels and other things that are also themselves objects.

Page 18: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

• Swing gives us three top-level Container classes:JApplet,JFrame andJDialog

• As you see here, the Frame (not a JFrame) is the largest unit.

Page 19: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Included within a Frame is a content pane.

• You can’t just drop a button or a label on a Frame--you have to put any smaller component--what we call a button or a label--on the content pane first.

Method getContentPane()

Page 20: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Frame

“contentPane”

Button Label

Page 21: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Let’s do some research:

• getContentPane() is a method of the JApplet class.

• getContentPane() is a method of the JFrame class.

• getContentPane() is a method of the JDialog class.

Page 22: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• When this method [getContentPane() ] executes, it returns an object of type Container. JApplet

Page 23: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

•Therefore, it makes sense that we could declare a Container variable c and use getContentPane() to initialize it.

Page 24: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Every JApplet inherits a Container.

Page 25: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import javax.swing.*;import java.awt.Container;public class TestApp extends JApplet{ public void init() {

JTextArea tst = new JTextArea( 10, 5 );tst.setText( " Hello " );

Container c = getContentPane();c.add( tst );

}}

Container cContent Pane

JTextArea tst

Page 26: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Page 27: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• A frame is the main window.

• A frame is the top-level container. It exists mainlyto give us a place for other swing components to paint themselves.

• But you can never place any objects directly on a frame.Instead, you place them on the content pane.

Page 28: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Applets and Dialogs can serve the same purpose a frame can--as the main window other things paint

themselves on.

Note:Applet != JAppletDialog != JDialogFrame != JFrame

Page 29: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• A button and label are the atomic components. The parts don’t get any smaller

than buttons and labels.They are the end of theline. No other object is

ever placedon these.

Page 30: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• A panel is the middle container. A panel gives us a place to put buttons and labels.

Page 31: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Consider this window:It starts with a JFrame,then gets the content pane in the middle, layers a JPanel on that, and finally lays on the JButton and JLabel.

d

{

Page 32: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• A JPanel object is a simple container object with no fancy additions.

d

Page 33: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• A pane is the middle area used for building.

• A layered pane

• A split pane

• A tabbed pane

Page 34: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Note: to view the “containment hierarchy” of any frame or dialog, click its border to select it, then press:Ctrl-Shift-1. A list of the containment hierarchy will be printed on the console.

Page 35: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• So, what is a Container?

• Every top-level container contains an intermediate container known as a content pane.

Page 36: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• The content pane contains all of the visible components in a window’s GUI.• Only the menu bar is not included within the content pane.• So, the statement abovemeans: “Give me the visible portion of my applet. I want to put something there.”

Page 37: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

JTextArea oArea = new JTextArea( 10, 20 );Container c = getContentPane();c.add( oArea );

• So, I execute the JApplet’s method “getContentPane()” and it returns to me a container object c.

Page 38: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

JTextArea oArea = new JTextArea( 10, 20 );Container c = getContentPane();c.add( oArea );

• Into this Containerobject, I add anythingthat is a component.In this case, I add the component JTextArea.

Page 39: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

You will only remember this

process when you are practicing it...

Page 40: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Found in java.lang.Math

• Automatically imported.

Math Class Methods

Math.sqrt( 900.0 )

30.0 = Math.sqrt( 900.0 )

Type double

Page 41: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Work from the Inside Out

• First Math.sqrt() is performed.

Math Class Methods

System.out.println( Math.sqrt( 900.0 ) );

System.out.println( 30.0 );

• The return value of Math.sqrt is the argument for the println method.

Page 42: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• You can never make an instance of the Math library.

• For the sake of Contrast:

Graphics g;

g.drawString( “Calling A Method” );

Math Class Methods

Making an instance of the Graphics class. This instance is called “g”.

Now, this instance will call its method drawString

Page 43: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• You can’t create a Math instance.

Math m;

Math Class Methods

Page 44: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• All the methods in the Math class are declared

static--which means the class can’t be instantiated.

Math Class Methods

• When we declare a method static, it means only the class itself can ever call the method. No extra instances of it can be made.

Page 45: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A Method Name All by itself, such as

d = square( x );

• We don’t refer to the object where this method originates.

Math Class Methods

Page 46: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A Reference to an object we have instantiated

followed by the dot . operator and the method name:

Graphics g

g.drawString

Math Class Methods

Page 47: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

• Review all the ways to call a method:

A class name followed by a method:

Integer.parseInt()

This is only used for static methods that can’t be instantiated.

Math Class Methods

Page 48: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

More About Methods• Recall the all variables declared inside a method are local variables.

• Local variables must be initialized.

• They live only while the method is being executed.

• Local variables vanish after the method is done.

Page 49: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

More About Methods

public double sum( double x, double y){

double sum = 0;

sum = x + y;return sum;

}

• In this example, all three variables are local. The variables x and y declared as parameters in the header, and the variable sum declared in the body of the method.

Page 50: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Methods: Coercion of Arguments

public double sum( double x, double y){

double sum = 0;

sum = x + y;return sum;

}

• What would happen if--when we called this method--we passed it integers, rather than the doubles it expects?

Page 51: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Methods: Coercion of Arguments

• If it was able to, the compiler would attempt to convert or “coerce” the arguments into the right type.

• If I passed it an integer and it expected a double, the conversion would be no problem--converting an integer into a double doesn’t lose any information.

Page 52: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Methods: Coercion of Arguments

• However, if I passed it a double and it was expecting an integer, the conversion from double to integer WOULD lose information, so the compiler would complain.

• The compiler would complain unless I used an explicit cast operator to force the argument into the right type.

Page 53: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Methods: Duration of Identifiers• The duration of an identifier is the lifetime of the identifier.

• Identifiers declared locally in a method are called automatic.

• Automatic variables exist only while the block they are declared in executes.

• Static variables exist from the time the class that defines them is loaded into memory until the program terminates.

Page 54: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Methods: Scope Rules• The scope for an identifier is the portion of the program in which the identifier can be referenced.

• The scopes for an identifier are:

• class

• block

• method

Page 55: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Method Overloading• Method overloading allows a method name to be re-used.

• To overload a method--or to create another version of a method that already exists--the argument lists for the methods must differ in:

• number of arguments

• type of arguments

• order of arguments

• The return type of the method is NOT considered.

Page 56: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Unlike many other languages--such as Visual Basic--when the Java programmer wishes to program responses to an event--such as the enter key being pressed, the event must be entirely programmed.

Page 57: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Consider this analogy to the event model:

> Fred decides he wants a bodyguard.

> Somebody punches Fred--that’s a problem.

> Vinnie--the bodyguard--notices Fred was punched.

> Vinnie reacts to the problem.

Page 58: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• The same thing with specifics attached:

> A Button decides it wants an ActionListener.

> A Button is pressed--an event happens:

> The ActionListener notices the Button was pressed.

> The Listener reacts to the event.

Page 59: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Fully described in Java Terms

> A Button adds an ActionListener.

> A Button is pressed--an event happens:

> The method actionPerformed is executed,

receiving an ActionEvent object.

> The Listener reacts to the event.

Page 60: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

Event Sources

transmit

ActionEvent

objects

to Event Listener(s).

Page 61: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Summarized

• An event source is an object that can register listener* objects and send those listeners event objects.

• In practice, the event source can send out event objects to all registered listeners when that event occurs.

• The listener object(s) will then use the details in the event object to decide how to react to the event.

* A “Listener Object” [an instance of a class] implements a special interface called a “listener interface.”

Page 62: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• When you ask the listener object to pay attention to your event source, that is called registering the listener object with the source object.

• You do that with the following lines of code:

eventSourceObject.addEventListener( eventListenerObject );

Page 63: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Now, the panel object is notified whenever an “action event” occurs in the button.

• When you click on a button, the panel object hears about it.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 64: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Code like this requires that the class the panel comes from to implement the appropriate interface.

• In this case, class MyPanel must implement the ActionListener interface.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 65: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• To implement the ActionListener interface, the listener class must have a method called

actionPerformed( actionPerformed( ActionEventActionEvent ee ) )

that receives an ActionEvent object as a parameter.

MyPanel panel = new MyPanel(); JButton button = new JButton( “Clear” ); button.addActionListener( panel );

Page 66: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

• Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls panel.actionPerformed, passing that event object.

public class MyPanel extends JPanelimplement ActionListener

{ public void actionPerformed( ActionEvent e ) { // appropriate code to react to event

// goes here. }}

Page 67: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Which Button Was Clicked?

• A closer look at the object that is passed, the ActionEvent object:

• The method getSource() will tell us which object created and sent the ActionEvent object.

Page 68: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Which Button Was Clicked?

• Responding to a button:

We start with a panel and some buttons on it.

• A listener object ( namely, the panel itself ) registers itself with the buttons so that it can listen to them.

public void actionPerformed( ActionEvent e )

{

if ( e.getSource() == button )

...

}

Page 69: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Every event handler requires 3 bits of code:

1. Code that says the class implements a listener interface:

public class MyClass implements ActionListener

2.Code that registers a listener on one or more components.

someComponent.addActionListener( MyClass ); 3.Code that implements the methods in the listener interface.

public void actionPerformed(ActionEvent e){ ...//code that reacts to the action...}

Page 70: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model: Another Example

• In code, this is how you react to an event:

JButton roll = new JButton( “Roll Dice” );

roll.addActionListener( this );

// call method play when button is pressed.

Public void actionPerformed( ActionEvent e )

{

do something

}

• When the JButton roll is clicked, the method actionPerformed receives an ActionEvent object that tells it the details of the event.

Page 71: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;

import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

First, to respond to events, we must import theevent class API:

java.awt.event.*;

Page 72: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

This is the first time we have seen a class that “implements” another class. This is called an interface. You see, although we are directly inheriting from the class JApplet, we are getting some functions through the interface from the class ActionListener. We will

learn more about interfaces later.

Page 73: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Here are 3 different kinds of GUI “components.” Remember, a

component is something we place on the content pane.

Page 74: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 75: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 76: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

import java.awt.*;import java.awt.event.*;import javax.swing.*;

public class Craps extends JApplet implements ActionListener{

final int WON = 0, LOST = 1, CONTINUE = 2;

boolean firstRoll = true; int sumOfDice = 0; int myPoint = 0; int gameStatus = CONTINUE;

// GUI components.JLabel die1Label,

die2Label,sumLabel,pointLabel;

JTextField firstDie, secondDie, sum, point;

JButton roll;

Page 77: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Page 78: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Page 79: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter

Page 80: Java i lecture_6

Java I--Copyright © 2000 Tom Hunter