CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

32
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost

Transcript of CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

Page 1: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

CSE 501NFall ‘0920: Event Handling and Inner Classes

17 November 2009

Nick Leidenfrost

Page 2: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

2

Lecture Outline

Event Handling Mostly in the context of GUIs Mouse interaction Keyboard interaction Window interaction

Inner Classes Static inner classes Member classes Local classes Anonymous inner classes

Page 3: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

3

Events, Event Sources, and Event Listeners

User interface events include key presses, mouse moves, button clicks, and so on

Most programs don't want to be flooded by event notificationsSubscribe only to events we are interested in

A program can indicate that it only cares about certain specific events

Page 4: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

4

Events, Event Sources, and Event Listeners Event listener:

Notified when event happens Belongs to a class that is provided by the application

programmer Its methods describe the actions to be taken when an

event occurs A program indicates which events it needs to receive

by creating and registering event listener objects

Event source: … the thing that generates the event When an event occurs, the event source notifies all

event listeners

Page 5: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

5

Events, Event Sources, and Event Listeners Example: Use JButton components for buttons; attach

an ActionListener to each button

ActionListener interface:

Need to supply a class whose actionPerformed method contains instructions to be executed when button is clicked

public interface ActionListener { void actionPerformed(ActionEvent event);

}

Page 6: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

6

Events, Event Sources, and Event Listeners

event parameter contains details about the event, such as the time at which it occurredDifferent types of events hold different

information (mouse, key, action, scroll, etc.)

Construct an object of the listener and add it to the button:

// Code example

ActionListener listener = new ClickListener(); button.addActionListener(listener);

Page 7: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

11

Mouse Events Use a MouseListener to capture mouse

events Implement the MouseListener

interface:public interface MouseListener { void mousePressed(MouseEvent event); // Called when a mouse button has been pressed on a component void mouseReleased(MouseEvent event); // Called when a mouse button has been released on a component void mouseClicked(MouseEvent event); // Called when the mouse has been clicked on a component void mouseEntered(MouseEvent event); // Called when the mouse enters a component void mouseExited(MouseEvent event); // Called when the mouse exits a component

}

Page 8: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

12

Mouse Events

mousePressed, mouseReleased: called when a mouse button is pressed or released

mouseClicked: if button is pressed and released in quick succession, and mouse hasn't moved

mouseEntered, mouseExited: mouse has entered or exited the component's area

Page 9: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

13

Mouse Events

Add a mouse listener to a component by calling the addMouseListener method:

We can add a MouseListener to any Component in our GUI

// Code Example

public class MyMouseListener implements MouseListener { // Implements five required methods } MouseListener listener = new MyMouseListener(); component.addMouseListener(listener);

Page 10: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

14

Mouse Eventsclass MousePressListener implements MouseListener {

public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x, y); }

// Do-nothing methods public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }

All methods of the interface must be implemented (Undesired methods may be left empty)

Page 11: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

15

Window Listeners

Generate events when some aspect of a graphical window changesBy default, window behaviors are not

implemented

Why is one interested in window events?Useful to implement your shut down protocol

Maybe save some stuff to disk, etc.Stop your program from running

Page 12: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

16

WindowListener interface

windowActivated (WindowEvent e) windowClosed (WindowEvent e) windowClosing (WindowEvent e) windowDeactivated (WindowEvent e) windowDeiconified (WindowEvent e) windowIconified (WindowEvent e) windowOpened (WindowEvent e)

Page 13: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

17

Some shortcuts are available

JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Adapter classesSaves you from writing empty method stubs

for events you don’t want to monitor java.awt.event.MouseAdapter java.awt.event.KeyAdapter java.awt.event.WindowAdapter

// Code Examples

Page 14: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

18

Inner classes

Sometimes we define a class whose purpose is only to "help out" another class. E.g. Iterator or Node within LinkedList

In some situations, it is nice if the helper class didn't stand on its own, but instead was more closely associated with the parent class itself.

Page 15: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

19

Inner classes So far, all classes we have defined have been “top level”

classes. as far as the Java compiler is concerned, the classes are

independent and exist on there own.

We can do some things to group classes Put classes in the same file Packages

These are useful but do not imply (or allow) a very close association Use Inner Classes

Page 16: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

20

Types of Inner Classes

Nested top-level class Member class Local class Anonymous class

Let us look at each one in more detail

Page 17: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

21

Example

public class Animation extends Component {

public Animation(....){...addMouseListener( new AnimationRequestHandler() ); ...

}

public void beginAnimation() {// To be called when component is clicked...

}

}

Page 18: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

22

Nested Top Level Class

This is a class defined as a static class member. It’s still really a top-level class, but from

outside its name is prefixed with the name of the containing class separated by a dot:

Access to the class can be controlled through protection modifiers.

LinkedList.Node node;

Page 19: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

23

Examplepublic class Animation extends Component{

public Animation(....){... addMouseListener( new AnimationRequestHandler() ); ....

}

public void beginAnimation() {...

}

private static class AnimationRequestHandler extends MouseAdapter{

public void mouseClicked (MouseEvent e){Animation anim = (Animation)e.getSource();anim.beginAnimation();

}}

}

Page 20: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

24

Example beginAnimation() must be public because

AnimationRequestHandler is a top level class and has no special access to methods in Animation,

The inner class AnimationRequestHandler can access only public methods and public instance variables of the Animation class (like any other class), not private ones.

Just like with any other method, you must use objectName.methodName() notation for beginAnimation().

Page 21: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

25

Member Classes These are not top level classes

They are declared inside the class body like instance variables and methods (not static)

Each instance of a member class has a corresponding instance of the containing class (an implicit link to an instance of its parent class - usually the instance that created it)

Instances of member classes have access to the instance variables and methods of the containing class (and vice versa), as well as other member class instance variables and methods created by the original class.

Page 22: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

26

Example

public class Animation extends Component {

public Animation(....){...addMouseListener( new AnimationRequestHandler() ); ...

} void beginAnimation () {

...}

private class AnimationRequestHandler extends MouseAdapter {  public void mouseClicked(MouseEvent e){

beginAnimation();}

}}

Page 23: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

27

Example beginAnimation() does not need to be public because AnimationRequestHandler is member class and has access to methods in Animation the member class AnimationRequestHandler can access

any method or instance variable of the Animation class.

This time beginAnimation() can be called without a source because there is only one object it could belong to.

Technical Note: Member classes can't contain any static members and they can't have the same name as any containing class or package.

Page 24: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

28

Local Classes These are similar to member classes

The have access to all class members

Local classes are different than member classes in that They are declared within a method or constructor They also have access to final local variables within the scope

in which they are declared They are only visible and usable within the scope of their

containing method / constructor

Local classes have the same restrictions as member classes: local classes can't contain any static members and they can't

have the same name as any containing class or package.

Page 25: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

29

Examplepublic class Animation extends Component {

public Animation(....){  

class AnimationRequestHandler extends MouseAdapter{  

public void mouseClicked(MouseEvent e){  beginAnimation();

}} ...addMouseListener( new AnimationRequestHandler() ); ...

}

void beginAnimation () {...

}}

Page 26: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

30

Anonymous Inner Classes

These are similar to local classes, except they have no names. Instead, they are defined within the expression that instantiates them.

Anonymous classes must either extend a class, or implement an interface (and extend Object) Why? We need some named way to access a defined API.

Page 27: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

31

Example

public class Animation extends Component {

public Animation(....){... addMouseListener( new MouseAdapter(){

public void mouseClicked(MouseEvent e){beginAnimation();

}}); ...

}

void beginAnimation () {...

}}

Page 28: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

32

Notes on Anonymous Classes MouseAdapter is the name of the class being extended or interface being implemented.

Any parameters to the constructer for MouseAdapter need to be included.

An anonymous class inherits its constructor because it is never given the chance to define its own.

An anonymous class has no name.

An anonymous class has no protection modifiers - it has no name, so you can't access it from outside anyway.

Page 29: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

33

Inner Classes as Listeners

Example: investment viewer program; whenever button is clicked, interest is added, and new balance is displayed

Page 30: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

34

Processing Text Input

Use JTextField components to provide space for user input

Place a JLabel next to each text field

Supply a button that the user can press to indicate that the input is ready for processing

int FIELD_WIDTH = 10; // In charactersJTextField rateField = new JTextField(FIELD_WIDTH);

JLabel rateLabel = new JLabel(“Interest Rate: ");

Page 31: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

35

Processing Text Input The button's actionPerformed method

reads the user input from the text fields (use getText)

class AddInterestListener implements ActionListener {

public void actionPerformed (ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); . . . } }

Page 32: CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.

36

Conclusion

Questions? In Lab Now