interactive programs java api. terminology event—an action or occurrence, not part of a program,...

23
Interactive Interactive Programs Programs Java API

Upload: lenard-small

Post on 14-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Interactive Interactive ProgramsPrograms

Java API

Page 2: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

TerminologyTerminology

EventEvent—an action or occurrence, not —an action or occurrence, not part of a program, detected by the part of a program, detected by the program. Events can be program. Events can be user actions--clicking a mouse button, user actions--clicking a mouse button,

pressing a key, hovering mouse over text pressing a key, hovering mouse over text boxbox

system occurrences—running out of system occurrences—running out of memory, raising exceptionsmemory, raising exceptions

Event-drivenEvent-driven programprogram—responds to —responds to events, such as most programs in events, such as most programs in Windows environmentWindows environment

Page 3: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Terminology (cont.)Terminology (cont.)

Event ListenerEvent Listener— an interface (like a — an interface (like a class, but provides only methods)—class, but provides only methods)—that will detect an event. The that will detect an event. The interface provides only an outline of interface provides only an outline of the methods, and the programmer the methods, and the programmer must write the code for each must write the code for each method.method.

Event HandlerEvent Handler— code that is — code that is executed when an even is detectedexecuted when an even is detected

Page 4: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

To Make Interactive To Make Interactive ProgramProgram

Steps to make a program Steps to make a program interactive:.interactive:.

1.1. Identify components with Identify components with anticipated anticipated eventsevents (e.g., a button (e.g., a button with a button-click)with a button-click)

2.2. Associate Associate event listenersevent listeners with the with the componentscomponents

3.3. Write Write event handlersevent handlers

Page 5: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Types of EventsTypes of Events ActionAction event event

occurs when a button, check box, radio occurs when a button, check box, radio button, or text field is clicked.button, or text field is clicked.

AdjustmentAdjustment event event occurs occur when a scrollbar is adjusted occurs occur when a scrollbar is adjusted

by dragging an arrow on the bar or by dragging an arrow on the bar or clicking anywhere on the bar.clicking anywhere on the bar.

FocusFocus event event occurs when component gains or loses occurs when component gains or loses

focus on the GUI. E.g., a text field can focus on the GUI. E.g., a text field can gain a focus by clicking the mouse gain a focus by clicking the mouse anywhere inside it or by pressing the tab anywhere inside it or by pressing the tab keykey

Page 6: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Types of Events (cont.)Types of Events (cont.) KeyKey event event

occurs when a particular key is occurs when a particular key is pressed on the keyboard. An event pressed on the keyboard. An event listener can distinguish each key so listener can distinguish each key so that appropriate event handlers can that appropriate event handlers can be provided.be provided.

MouseMouse event event occurs when the mouse is clicked occurs when the mouse is clicked

over a component, when it hovers over a component, when it hovers over a component, or when it leaves over a component, or when it leaves the component's area.the component's area.

Page 7: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Event ListenerEvent Listener

Event listener—Event listener—an interface an interface corresponding to each type of event.corresponding to each type of event.

When an event listener is associated When an event listener is associated with a class, the class with a class, the class mustmust implement all methods in the event implement all methods in the event listener.listener.

Page 8: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Event Listener (cont.)Event Listener (cont.) Interface Interface ActionListenerActionListener contains method contains method

actionPerformed(), to handle action events.actionPerformed(), to handle action events. Interface Interface AdjustmentListenerAdjustmentListener contains method contains method

adjustmentValueChanged() to handle the adjustmentValueChanged() to handle the adjustment events.adjustment events.

Interface Interface FocusListenerFocusListener contains two methods: contains two methods: focusGained() and focusLost() to handle focus focusGained() and focusLost() to handle focus events.events.

Interface Interface KeyListenerKeyListener contains three methods: contains three methods: keyPressed(), keyReleased(), and keyTyped(), to keyPressed(), keyReleased(), and keyTyped(), to handle key events.handle key events.

Interface Interface MouseListenerMouseListener contains five methods: contains five methods: moustClicked(), mouseEntered(), mouseExited(), moustClicked(), mouseEntered(), mouseExited(), moustPressed(), and mouseReleased() to handle moustPressed(), and mouseReleased() to handle the mouse events.the mouse events.

Page 9: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Event Listener (cont.)Event Listener (cont.)NameName Method(s)Method(s)

ActionListenerActionListener actionPerformed()actionPerformed()

AdjustmentListenAdjustmentListenerer

adjustmentValueChanged()adjustmentValueChanged()

FocusListenerFocusListener focusGained(); focusLost()focusGained(); focusLost()

KeyListenerKeyListener keyPressed(); keyPressed(); keyReleased(); keyTyped()keyReleased(); keyTyped()

MouseListenerMouseListener mouseClicked(); mouseClicked(); mouseEntered();mouseEntered();mouseExited(); mouseExited(); moustPressed(); moustPressed(); mouseReleased()mouseReleased()

Page 10: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

ImplementingImplementing Interface Interface

To make use of the methods in an event To make use of the methods in an event listener interface in a class, it is listener interface in a class, it is implementedimplemented , instead of extended, by the , instead of extended, by the class. class.

If there are more than one interface to be If there are more than one interface to be brought in, they can be listed one after brought in, they can be listed one after another with commas separating them. another with commas separating them.

The following code segment involves The following code segment involves interfaces ActionListener and interfaces ActionListener and FocusListener in the EventDemo class.FocusListener in the EventDemo class.

Page 11: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Implementing Interface Implementing Interface (cont.)(cont.)

public class EventDemo extends JFramepublic class EventDemo extends JFrame implements implements ActionListener, FocusListener ActionListener, FocusListener {{ ... // code for EventDemo class... // code for EventDemo class}}

Page 12: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: EventDemo.javaEventDemo.java

The following is an interactive program that The following is an interactive program that displays a message in a text field, whose displays a message in a text field, whose background color can be changed by the background color can be changed by the user clicking one of the three buttons. user clicking one of the three buttons.

In addition, the text style of the message In addition, the text style of the message is changed to italic when the field gains is changed to italic when the field gains focus and returns to plain style when it focus and returns to plain style when it loses focus. (The screen shot shows the loses focus. (The screen shot shows the window after the "cyan" button is clicked. window after the "cyan" button is clicked. Note that the text style is plain because the Note that the text style is plain because the text field has lost its focus to the "cyan" text field has lost its focus to the "cyan" button.)button.)

Page 13: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: EventDemo.javaEventDemo.java (cont.)(cont.)

Go to an Applet version of EventDemo

Page 14: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: EventDemo.javaEventDemo.java (cont.)(cont.)

NoteNote In the class declaration, ActionListener and In the class declaration, ActionListener and

FocusListener are FocusListener are implemented.implemented. Objects—buttons and textfield—are declared Objects—buttons and textfield—are declared

as instance variables (global to the class).as instance variables (global to the class). In constructor In constructor EventDemo(),EventDemo(),

buttons are associated with event buttons are associated with event listeners. E.g.,listeners. E.g., green.addActionListener(this);green.addActionListener(this);

Here, this refers the current class which Here, this refers the current class which will do the listening—like the “ear”will do the listening—like the “ear”

Page 15: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: EventDemo.javaEventDemo.java (cont.)(cont.)

Buttons are added to a containerButtons are added to a container Buttons must be associated with event Buttons must be associated with event

listeners listeners beforebefore the buttons are added to a the buttons are added to a container.container.

Method Method actionPerformed()actionPerformed() is is event handler.event handler. Kind of object receiving the event is checked.Kind of object receiving the event is checked. Action is performed depending on the kind of Action is performed depending on the kind of

object receiving the event.object receiving the event. Method Method main()main() simply instantiates the simply instantiates the

EventDemoEventDemo class and makes the object visible. class and makes the object visible.

Page 16: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: DistanceConverterDistanceConverter

Program Program DistanceConverterDistanceConverter attaches some attaches some calculation steps to event handlers. Its calculation steps to event handlers. Its interface consists of two labels, two text interface consists of two labels, two text fields, and four buttons. fields, and four buttons.

Go to an Applet version of EventDemo

Page 17: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: DistanceConverter (cont.)DistanceConverter (cont.)

Text boxesText boxes For inputting distancesFor inputting distances

ButtonsButtons ““To Meter”—when clicked, converts feet To Meter”—when clicked, converts feet

value to meter value and displays in value to meter value and displays in appropriate boxappropriate box

"To Feet"—when clicked, converts meters "To Feet"—when clicked, converts meters to feet value and displays in appropriate to feet value and displays in appropriate box.box.

"Clear“—clears text fields"Clear“—clears text fields "Instructions“—pops up a message box "Instructions“—pops up a message box

with a short explanation of the program. with a short explanation of the program.

Page 18: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: DistanceConverter (cont.)DistanceConverter (cont.)

Here is the Here is the source code for source code for DistanceConverter.javaDistanceConverter.java

Note that:Note that: In constructor In constructor DistanceConvert()DistanceConvert()

super()super() is an invocation to a constructor is an invocation to a constructor of the frame's super class.of the frame's super class.

setdefaultCloseOperation()setdefaultCloseOperation() calls a calls a method inherited from JFramemethod inherited from JFrame

Container Container panepane uses a uses a gridgrid layout of 4 layout of 4 rows by 2 columnsrows by 2 columns

Page 19: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: DistanceConverter (cont.)DistanceConverter (cont.)

In event handler In event handler actionPerformed()actionPerformed() With interface With interface ActionListenerActionListener, this is the , this is the

only method that needs to be only method that needs to be implementd.implementd.

After the statementAfter the statement Object src = e.getSource()Object src = e.getSource()depending on the identity of depending on the identity of srcsrc, , different actions are performed.different actions are performed.

To check for valid input, note the use of To check for valid input, note the use of strFeet.equals(""),strFeet.equals(""), and not and not strFeet == "",strFeet == "", because because strFeetstrFeet is a reference, or a is a reference, or a pointer. pointer.

Page 20: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Example: Example: DistanceConverter (cont.)DistanceConverter (cont.)

In the statementIn the statementtxtMeter.setText(decForm.format(numMeter)+" ")txtMeter.setText(decForm.format(numMeter)+" ")

decFormdecForm is a formatting object which was is a formatting object which was instantiated from the instantiated from the DecimalFormat classDecimalFormat class, , at the top of this method. at the top of this method.

The pattern in its constructor-- "#.00"--The pattern in its constructor-- "#.00"--specifies two decimal points. Thus, specifies two decimal points. Thus, expression expression decForm.format(numMeter)decForm.format(numMeter) will will return a string of digits with two decimal return a string of digits with two decimal points. points.

Page 21: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

ExerciseExercise Recall a simple java program created in the last Recall a simple java program created in the last

chapter—GUI--named chapter—GUI--named GUIDemo,javaGUIDemo,java, which , which consisted of consisted of labelslabels for first & last names, for first & last names, textboxestextboxes for first & last names, and for first & last names, and buttonsbuttons to to start and quit the program.start and quit the program.

Modify the program as follows:Modify the program as follows: Arrange the components using the grid layout manager. Arrange the components using the grid layout manager.

(3, 2)(3, 2) Associate an event handler to the Associate an event handler to the startstart button so that button so that

when it is clicked, a message box when it is clicked, a message box (showMessageDialog()) outputs a greeting. The greeting (showMessageDialog()) outputs a greeting. The greeting is of the form “Welcome to Hawaii, Charles Chang”, is of the form “Welcome to Hawaii, Charles Chang”, where “Charles” and “Chang” are contents of the two where “Charles” and “Chang” are contents of the two text boxes.text boxes.

Page 22: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Exercise (cont.)Exercise (cont.)

Associate an event with the quit button Associate an event with the quit button so that when it is clicked, the program so that when it is clicked, the program ends. (System.exit(0))ends. (System.exit(0))

Page 23: Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action

Exercise (cont.)Exercise (cont.)

GuiDemo.java code