Sep 181 Example Program Dem .

31
Sep 18 1 Example Program Example Program DemoTranslateEnglishGUI.java

description

Sep 183 Java Events When a user types characters or uses the mouse, Java’s window manager sends a notification to the program that an event has occurred E.g., when the user presses a key on the keyboard, a key pressed event occurs There are many, many kinds of events (e.g., key pressed, key released, key typed) Many are of no interest Some are of great interest

Transcript of Sep 181 Example Program Dem .

Page 1: Sep 181 Example Program Dem .

Sep 18 1

Example ProgramExample ProgramDemoTranslateEnglishGUI.java

Page 2: Sep 181 Example Program Dem .

Sep 18 2

Java’s Event Class Java’s Event Class Hierarchy Hierarchy

EventObject

AWTEvent

ActionEvent ComponentEvent

InputEvent WindowEvent

MouseEvent KeyEventUsed in example program

Note: this diagram is not complete. It just shows the most common event classes

Page 3: Sep 181 Example Program Dem .

Sep 18 3

Java EventsJava Events

When a user types characters or uses the mouse, Java’s window manager sends a notification to the program that an event has occurred

E.g., when the user presses a key on the keyboard, a key pressed event occurs

There are many, many kinds of events (e.g., key pressed, key released, key typed)Many are of no interestSome are of great interest

Page 4: Sep 181 Example Program Dem .

Sep 18 4

Java Events (2)Java Events (2)To receive notification of events of interest, a program must install event listener objectsIt is not enough to simply know that an event has occurred; we need to know the event source

E.g., a key was pressed, but in which of several text fields in the GUI was the key pressed?

So, an event listener must be installed for particular components that may generate the event

Page 5: Sep 181 Example Program Dem .

Sep 18 5

import ...

public class NameOfProgram{

public static void main(String[] args){

}}

public class NameOfProgramFrame{

}

Identify packages containing classes used in the program

1. Construct the GUI frame2. Give it a title3. Show it4. Done!!!!

Naming convention (just add “Frame” to name of program)

All the work is done here

Page 6: Sep 181 Example Program Dem .

Sep 18 6

import ...

public class NameOfProgram{

public static void main(String[] args){

}}

public class NameOfProgramFrame extends JFrame{

}Our GUI frame class is actually a JFrame – extended and modified to suit our needs

Page 7: Sep 181 Example Program Dem .

Sep 18 7

JFrameJFrameClass in the javax.swing packageSun’s Swing toolkit is Java’s most advanced toolkitLife before Swing…

AWT (abstract windowing toolkit)AWT used “native” UI components (unique to local system)This creates inconsistencies across platforms

UI components of AWT are now obsoleteAWT still used for drawing, images,etc.

Swing paints the components itselfPro: code is consistent across platformsCon: results in “big” programs (lots of memory!)

Swing still uses many features of AWT

Page 8: Sep 181 Example Program Dem .

Sep 18 8

import ...

public class NameOfProgram{

public static void main(String[] args){

}}

public class NameOfProgramFrame extends Jframeimplements KeyListener{

} Our GUI class implements the methods of the KeyListener listener

Page 9: Sep 181 Example Program Dem .

Sep 18 9

...public class NameOfProgramFrame extends Jframeimplements KeyListener{

public ...private ...

public class NameOfProgramFrame() {}

public void keyPressed(KeyEvent ke) {}public void keyReleased(KeyEvent ke) {}public void keyTyped(KeyEvent ke) {}

public ...private ...

}

Declare variables (“fields”, “attributes”)

Constuctor

Must implement all three KeyListener methods, even though just one is used.Other methods

Page 10: Sep 181 Example Program Dem .

Sep 18 10

Frame ConstructorFrame Constructor

Must…Create and configure the GUI componentsInstall (“add”) listeners

Listeners are not just installed, they must be associated with particular GUI components

Arrange components in panel(s)Get the JFrame’s content paneAdd panel(s) to content pane

Page 11: Sep 181 Example Program Dem .

Sep 18 11

ListenersListeners

Java’s listener classes are actually interfaces (not classes)What is an interface?

Page 12: Sep 181 Example Program Dem .

Sep 18 12

Interfaces vs. ClassesInterfaces vs. Classes

The definition of a class includes both the design of the class and its implementationSometimes it is desirable only to design a class, leaving the implementation for laterThis is accomplished through an interface An interface contains only the design of a class

Includes signatures for its members (methods and fields)No implementation is provided

Page 13: Sep 181 Example Program Dem .

Sep 18 13

Characteristics of Characteristics of InterfacesInterfaces

Interfaces…Do not have instance variables

You cannot instantiate an object of an interfaceInclude only abstract methods

Methods have a signature (i.e., a name, parameters, and return type)Methods do not have an implementation (i.e., no code)

Include only public methods and fieldsDoes not make sense to define private members if the public members that could potentially use them are themselves not implemented

Page 14: Sep 181 Example Program Dem .

Sep 18 14

Listeners (revisited)Listeners (revisited)

The signature of our extended JFrame class includes the clause implements KeyListenerThis means our class must include definitions for the methods of the KeyListener listenerThus…

Our implementation includes the code we want executed when a key is pressed, released, and/or typed

public void keyPressed(KeyEvent ke) {}public void keyReleased(KeyEvent ke) {}public void keyTyped(KeyEvent ke) {}

Page 15: Sep 181 Example Program Dem .

Sep 18 15

Installing ListenersInstalling ListenersIt is not enough simply to implement the methods of a listenerThe listener must also be “installed” (aka “registered”, “added”)Furthermore, it must be installed for the component to which the listener methods are to be associatedThus (from our example program)

enterArea.addKeyListener(this);

Component to which the listener methods are to be associated

An object of a class that implements the listener methods

Page 16: Sep 181 Example Program Dem .

Sep 18 16

Installing Listeners (2)Installing Listeners (2)

Consider the method addKeyListenerFact #1: addKeyListener is a method of the Component class (check the API Spec)Fact #2: enterArea (from our example) is an object (instance variable) of the JTextArea classFact #3: Through inheritance, a JTextArea object is a Component objectConclusion: the addKeyListener method can be invoked on enterArea

Page 17: Sep 181 Example Program Dem .

Sep 18 17

Installing Listeners (3)Installing Listeners (3)Signature for the addKeyListener method:

Description:

In our example, we used this as the “specified key listener”Indeed, the current instance of our extended JFrame class (“this”) is a key listener because it implements the key listener methodsResult: when a key pressed event occurs on the enterArea component, the keyPressed method in our extended JFrame class will execute!

public void addKeyListener(KeyListener)

Adds the specified key listener to receive key events from this component.

Page 18: Sep 181 Example Program Dem .

Sep 18 18

Let’s Say That Again…Let’s Say That Again…

When a key pressed event occurs on the enterArea component, the keyPressed method in our extended JFrame class will execute!

Page 19: Sep 181 Example Program Dem .

Sep 18 19

Processing EventsProcessing EventsSignature for the keyPressed method:

When our keyPressed method executes, it receives a KeyEvent object as an argumentWe use the KeyEvent object to

Determine which key was pressed, usinggetKeyChar, getKeyCode, etc.

Determine the source of the event, usinggetSource

“Determine the source of the event” is important if there is more than one component registered to receive key events (not the case in our example program)

public void keyPressed(KeyEvent ke)

Page 20: Sep 181 Example Program Dem .

Sep 18 20

Event SourcesEvent SourcesJava’s event classes are all subclasses of EventObject (see earlier slide)EventObject includes the getSource method:

Didn’t need this in our example program, because only one object (enterArea) was registered to generate key eventsSo, when the keyPressed method executes we know it is because a key was pressed in enterAreaBut, if we have two JTextArea components…

public Object getSource()

Page 21: Sep 181 Example Program Dem .

Sep 18 21

Event Sources (2)Event Sources (2)

public void keyPressed(KeyEvent ke){

if (ke.getSource() == enterArea1){

// code for enterArea1 key pressed events}else if (ke.getSource() == enterArea2){

// code for enterArea2 key pressed events}

}

Page 22: Sep 181 Example Program Dem .

Sep 18 22

Back to the Example Back to the Example Program…Program…

...public class NameOfProgramFrame extends Jframeimplements KeyListener{

...

private class WindowCloser extends WindowAdapter{

public void windowClosing(WindowEvent we){

System.exit(0);}

}}

Page 23: Sep 181 Example Program Dem .

Sep 18 23

Adapter ClassesAdapter Classes

What is an adapter class?A class provided as a convenience in the Java APIAn adapter class includes an empty implementation of the methods in a listenerProgrammers extend the adapter class and implement the methods of interest, while ignoring methods of no interest

Page 24: Sep 181 Example Program Dem .

Sep 18 24

WindowAdapterWindowAdapter

public abstract class WindowAdapter implements WindowListener{

void windowActivated(WindowEvent we) {}void windowClosed(WindowEvent we) {}void windowClosing(WindowEvent we) {}void windowDeactivated(WindowEvent we) {}void windowDeiconified(WindowEvent we) {}void windowIconified(WindowEvent we) {}void windowOpened(WindowEvent we) {}

}

Page 25: Sep 181 Example Program Dem .

Sep 18 25

Using the Using the WindowAdapter ClassWindowAdapter ClassDefine an inner class that extends the WindowAdapter class

Implement the listener methods of interestIgnore other listener methods

In the frame constructor, use the appropriate “add” method to add an object of the extended WindowAdapter classIn our example program…this.addWindowLisener(new WindowCloser());

Page 26: Sep 181 Example Program Dem .

Sep 18 26

Examples of Listeners and Examples of Listeners and AdaptersAdapters

Listeners (# methods) AdaptersKeyListener (3) KeyAdapterWindowListener (7) WindowAdapterMouseListener (5) MouseAdapterMouseMotionListener (2) MouseMotionAdapterMouseInput Listener (7) MouseInputAdapterActionListener (1) -ItemListener (1) -FocusListener (2) FocusAdapter

(Note: MouseInputListener combines MouseListener and MouseMotionListener)

Page 27: Sep 181 Example Program Dem .

Sep 18 27

Extending Adapters vs. Extending Adapters vs. Implementing ListenersImplementing Listeners

Largely a matter of personal choiceOur example program does both

The KeyListener methods were implementedThe WindowAdapter class was extended

Could have done the opposite, i.e.,Extend the KeyAdapter classImplement the WindowListener methods

Note: a Java class can implement many listeners, but it can extend only one class

Java does not include multiple inheritance (unlike C++ or Eiffel)

Page 28: Sep 181 Example Program Dem .

Sep 18 28

Pros and ConsPros and ConsUsing adapter classes

AdvantageOnly the listener methods needed are defined

DisadvantageA bit complicated to setupNeed to define an inner class, then instantiate an object of the inner class to pass to the appropriate “add” method

Implementing listener methodsAdvantage

A class can implement many different listenersDisadvantage

Must implement all the methods defined in the listener (even those not used)

Page 29: Sep 181 Example Program Dem .

Sep 18 29

The Good, The Bad, and The Good, The Bad, and The ArcaneThe Arcane

Do you like creating code that mere mortals find incomprehensible? If so, you’ll like this one.Delete the inner class definition…

and replace this…

with this…this.addWindowListener(new WindowCloser());

private class WindowCloser extends WindowAdapter{ public void windowClosing(WindowEvent we)

{ System.exit(0);}

}

this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0);}

});

Page 30: Sep 181 Example Program Dem .

Sep 18 30

Example ProgramExample Program

DemoKeyEvents2.java

Page 31: Sep 181 Example Program Dem .

Sep 18 31

Example ProgramExample Program

DemoMouseEvents.java