java i lecture_6

Post on 26-May-2015

67 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Java I--Copyright © 2000 Tom Hunter

Java I--Copyright © 2000 Tom Hunter

Chapter 6

Methods

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

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

Java I--Copyright © 2000 Tom Hunter

• Teacher.asksStudent( help );

A Method Call

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

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

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

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

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

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

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.

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

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

Java I--Copyright © 2000 Tom Hunter

How Do We Build A GUI Screen?

A Container is the building block...

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?

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.

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.

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()

Java I--Copyright © 2000 Tom Hunter

Frame

“contentPane”

Button Label

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.

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

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

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.

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

• Every JApplet inherits a Container.

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

Java I--Copyright © 2000 Tom Hunter

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.

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

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.

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.

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

{

Java I--Copyright © 2000 Tom Hunter

Method getContentPane()

Container c = getContentPane();

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

d

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

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.

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.

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.”

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.

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.

Java I--Copyright © 2000 Tom Hunter

You will only remember this

process when you are practicing it...

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

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.

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

Java I--Copyright © 2000 Tom Hunter

• You can’t create a Math instance.

Math m;

Math Class Methods

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.

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

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

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

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.

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.

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?

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.

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.

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.

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

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.

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.

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.

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.

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.

Java I--Copyright © 2000 Tom Hunter

Event Delegation Model

Event Sources

transmit

ActionEvent

objects

to Event Listener(s).

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.”

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 );

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 );

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 );

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 );

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. }}

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.

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 )

...

}

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...}

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.

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.*;

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.

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.

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;

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;

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;

Java I--Copyright © 2000 Tom Hunter

Java I--Copyright © 2000 Tom Hunter

Java I--Copyright © 2000 Tom Hunter

Java I--Copyright © 2000 Tom Hunter

top related