Docsity

Event-driven Programming with Java: Understanding Mouse and Keyboard Events - Prof. Jennif, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 10—Event-driven Programs
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Event-driven Programs
C H A P T E R 1 0
I claim not to have controlled events, but confess plainly that
events have controlled me.
—Abraham Lincoln, letter to Albert Hodges, 1864
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
The Java Event Model
• Graphical applications often make it possible for the user to
control the action of a program by using an input device such
as a mouse. Programs that support user control are called
interactive programs.
• User actions such as clicking the mouse are called events.
Programs that respond to events are said to be event-driven.
• In event-driven programs, user input may not occur at
predictable times. A running program may not tell the user
when to click the mouse. The user decides when to click the
mouse, and the program responds. Because events are not
controlled by the program, they are said to be asynchronous.
• When you write an event-driven program, you indicate the
events to which you wish to respond by designating an object
as a listener for that event. When the event occurs, a
message is sent to the listener, triggering a response.
Event Types
• Java events come in many different types. The event types
used in this book include the following:
–Mouse events, which occur when the user moves or clicks the mouse
–Keyboard events, which occur when the user types on the keyboard
–Action events, which occur in response to user-interface actions
• Each event type is associated with a set of methods that
specify how listeners should respond. These methods are
defined in a listener interface for each event type.
• As an example, one of the methods in the mouse listener
interface is mouseClicked. As you would expect, Java calls
that method when you click the mouse.
• Listener methods like mouseClicked take a parameter that
contains more information about the event. In the case of
mouseClicked, the argument is a MouseEvent indicating
the location at which the click occurred.
Event-Driven Program
import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;
/** Draws a circle anywhere the user clicks the mouse */
public class DrawSplatMap extends GraphicsProgram {
public static final int RING_SIZE = 20;
public void init() {
this.addMouseListeners();
}
public void mouseClicked(MouseEvent e) {
GOval circle = new GOval(RING_SIZE,RING_SIZE);
circle.setFilled(true);
this.add(circle, e.getX(), e.getY());
}
public static void main (String[] args) {
new DrawSplatMap().start();
}
}
Responding to Mouse Events
• The most common mouse events are shown in the following
table, along with the name of the appropriate listener method:
mouseClicked( e)
mousePressed( e)
mouseReleased(e)
mouseMoved(e)
mouseDragged(e)
Called when the user clicks the mouse
Called when the mouse button is pressed
Called when the mouse button is released
Called when the user moves the mouse
Called when the mouse is dragged with the button down
The parameter e is a MouseEvent object, which provides
more data about the event, such as the location of the mouse.
• You can make programs respond to mouse events by
following these general steps:
1. Define a run or init method that calls
this.addMouseListeners().
2. Write new definitions of any listener methods you need.
A Simple Line-Drawing Program
Drawing a line using this program requires three actions: pressing
the mouse button at the starting point of the line, dragging the
mouse to the desired end point, and then releasing the mouse.
The mousePressed method responds to that event by creating a
new zero-length line that begins and ends at the current mouse
position.
Dragging the mouse results in a series of mouseDragged calls
that come in rapid succession each time the computer reads the
mouse position. Each call simply resets the end point of the line.
The effect of this strategy is that the user sees the line as it grows,
providing the necessary visual feedback to position the line
correctly.
As you drag the mouse, the line will stretch, contract, and change
direction as if the two points were connected by an elastic band.
This technique is therefore called rubber-banding.
public class DrawLines extends GraphicsProgram {
/* Initializes the program by enabling the mouse listeners */
public void init() {
addMouseListeners();
}
/* Called on mouse press to create a new line */
public void mousePressed(MouseEvent e) {
line = new GLine(e.getX(), e.getY(), e.getX(), e.getY());
add(line);
}
/* Called on mouse drag to extend the endpoint */
public void mouseDragged(MouseEvent e) {
line.setEndPoint(e.getX(), e.getY());
}
/* Private instance variables */
private GLine line;
}
In all likelihood, you have at some point used an application that
allows you to draw lines with the mouse. In Java, that program
takes less than a page of code.
public class DrawLines extends GraphicsProgram {
/* Initializes the program by enabling the mouse listeners */
public void init() {
this.addMouseListeners(};
}
/* Called on mouse press to create a new line */
public void mousePressed(MouseEvent e) {
line = new GLine(e.getX(), e.getY(), e.getX(), e.getY());
this.add(line);
}
/* Called on mouse drag to extend the endpoint */
public void mouseDragged(MouseEvent e) {
line.setEndPoint(e.getX(), e.getY());
}
/* Private instance variables */
private GLine line;
}main method and import
statements not shown
pf3
pf4
pf5

Partial preview of the text

Download Event-driven Programming with Java: Understanding Mouse and Keyboard Events - Prof. Jennif and more Study notes Computer Science in PDF only on Docsity!

Chapter 10—Event-driven Programs The Art and Science of An Introduction

ERIC S. ROBERTS^ Java^ to Computer Science

Event-driven Programs

C H A P T E R 1 0 I claim not to have controlled events, but confess events have controlled me. plainly that —Abraham Lincoln, letter to Albert Hodges, 1864

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

The Java Event Model

  • Graphical applications often make it possible for the user to control the action of a program by using an input device such as a mouse. Programs that support user control are called interactive programs.
  • User actions such as clicking the mouse are called events. Programs that respond to events are said to be event-driven.
  • In event-driven programs, user input may not occur at predictable times. A running program may not tell the user when to click the mouse. The user decides when to click the mouse, and the program responds. Because events are not controlled by the program, they are said to be asynchronous.
  • When you write an event-driven program, you indicate the events to which you wish to respond by designating an object as a listener for that event. When the event occurs, a message is sent to the listener, triggering a response.

Event Types

  • Java events come in many different types. The event types used in this book include the following: - Mouse events , which occur when the user moves or clicks the mouse - Keyboard events , which occur when the user types on the keyboard - Action events , which occur in response to user-interface actions
  • Each event type is associated with a set of methods that specify how listeners should respond. These methods are defined in a listener interface for each event type.
  • As an example, one of the methods in the mouse listener interface is mouseClicked. As you would expect, Java calls that method when you click the mouse.
  • Listener methods like mouseClicked take a parameter that contains more information about the event. In the case of mouseClicked , the argument is a MouseEvent indicating the location at which the click occurred.

Event-Driven Program

import acm.program.; import acm.graphics.; import java.awt.event.; /* Draws a circle anywhere the user clicks the mouse / public class DrawSplatMap extends GraphicsProgram { public static final int RING_SIZE = 20; public void init() { this.addMouseListeners(); } public void mouseClicked(MouseEvent e) { GOval circle = new GOval(RING_SIZE,RING_SIZE); circle.setFilled(true); this.add(circle, e.getX(), e.getY()); } public static void main (String[] args) { new DrawSplatMap().start(); } }*

Responding to Mouse Events

  • The most common mouse events are shown in the following table, along with the name of the appropriate listener method: mouseClicked( e ) mousePressed( e ) mouseReleased( e ) mouseMoved( e ) mouseDragged( e ) Called when the user clicks the mouse Called when the mouse button is pressed Called when the mouse button is released Called when the user moves the mouse Called when the mouse is dragged with the button down The parameter e is a MouseEvent object, which provides more data about the event, such as the location of the mouse.
  • You can make programs respond to mouse events by following these general steps: 1. Define a run or init method that calls this.addMouseListeners(). 2. Write new definitions of any listener methods you need.

A Simple Line-Drawing Program

Drawing a line using this program requires three actions: pressing the mouse button at the starting point of the line, dragging the mouse to the desired end point, and then releasing the mouse. The mousePressed method responds to that event by creating a new zero-length line that begins and ends at the current mouse position. Dragging the mouse results in a series of mouseDragged calls that come in rapid succession each time the computer reads the mouse position. Each call simply resets the end point of the line. The effect of this strategy is that the user sees the line as it grows, providing the necessary visual feedback to position the line correctly. As you drag the mouse, the line will stretch, contract, and change direction as if the two points were connected by an elastic band. This technique is therefore called rubber-banding. public class DrawLines extends GraphicsProgram { / Initializes the program by enabling the mouse listeners / public addMouseListeners(); void init() { } / Called on mouse press to create a new line / public void mousePressed(MouseEvent e) { line = new GLine(e.getX(), e.getY(), e.getX(), e.getY()); }^ add(line); / Called on mouse drag to extend the endpoint / public void mouseDragged(MouseEvent e) { line.setEndPoint(e.getX(), e.getY()); } / Private instance variables / private GLine line; } In all likelihood, you have at some point used an application that allows you to draw lines with the mouse. In Java, that program takes less than a page of code. public class DrawLines extends GraphicsProgram { / Initializes the program by enabling the mouse listeners / public void init() { this.addMouseListeners(}; } / Called on mouse press to create a new line / public void mousePressed(MouseEvent e) { line = new GLine(e.getX(), e.getY(), e.getX(), e.getY()); }^ this.add(line); / Called on mouse drag to extend the endpoint / public void mouseDragged(MouseEvent e) { line.setEndPoint(e.getX(), e.getY()); } / Private instance variables / private GLine line; } main method and import statements not shown

Dragging Objects on the Canvas

DragObjects

  • Pressing the mouse button selects an object.
  • Dragging the mouse moves the selected object.
  • Repeating these steps makes it possible to drag other objects.
  • Clicking the mouse moves the selected object to the front. The DragObjects program on the next slide uses mouse events to drag objects around the canvas. import acm.graphics.;* import acm.program.;* import java.awt.;* import java.awt.event.;* / This class displays a mouse-draggable rectangle and oval /* public class DragObjects extends GraphicsProgram { / Initializes the program / public void init() { GRect rect = new GRect(100, 100, 150, 100); rect.setFilled(true); rect.setColor(Color.RED); this.add(rect); GOval oval = new GOval(300, 115, 100, 70); oval.setFilled(true); oval.setColor(Color.GREEN); this.add(oval); this.addMouseListeners(); }

The DragObjects Program

page 1 of 2 skip code main method not shown import acm.graphics.; import acm.program.; import java.awt.; import java.awt.event.; /** This class displays a mouse-draggable rectangle and oval / public class DragObjects extends GraphicsProgram { / Initializes the program / public void init() { GRect rect = new GRect(100, 100, 150, 100); rect.setFilled(true); rect.setColor(Color.RED); add(rect); GOval oval = new GOval(300, 115, 100, 70); oval.setFilled(true); oval.setColor(Color.GREEN); add(oval); addMouseListeners(); } / Called on mouse press to record the coordinates of the click / public void mousePressed(MouseEvent e) { this.last = new GPoint(e.getPoint()); this.gobj = getElementAt(this.last); } / Called on mouse drag to reposition the object / public void mouseDragged(MouseEvent e) { if (this.gobj != null) { this.gobj.move(e.getX()-this.last.getX(), e.getY()-this.last.getY()); this.last = new GPoint(e.getPoint()); } } / Called on mouse click to move this object to the front / public void mouseClicked(MouseEvent e) { if (this.gobj != null) this.gobj.sendToFront(); } / Private instance variables / private GObject gobj; / The object being dragged / private GPoint last; / The last mouse position / }*

The DragObjects Program

page 2 of 2 skip code

Responding to Keyboard Events

  • The most common key events are: keyPressed( e ) keyReleased( e ) keyTyped( e ) Called when the user presses a key Called when the key comes back up Called when the user types (presses and releases) a key In these methods, e is a KeyEvent object, which indicates which key is involved along with additional data to record which modifier keys (SHIFT, CTRL, and ALT) were down at the time of the event.
  • The general strategy for responding to keyboard events is similar to that for mouse events, even though the events are different. Once again, you need to take the following steps: 1. Call addKeyListeners from the constructor 2. Write new definitions of any listener methods you need.

Identifying the Key

  • The process of determining which key generated the event depends on the type of key event you are using.
  • If you are coding the keyTyped method, the usual strategy is to call getKeyChar on the event, which returns the character generated by that key. The getKeyChar method takes account of modifier keys, so that typing the a key with the SHIFT key down generates the character 'A'.

Creating a Simple GUI

  • In addition to mouse and keyboard events, application programs may include a graphical user interface or GUI (pronounced gooey ) consisting of buttons and other on-screen controls. Collectively, these controls are called interactors.
  • Java defines many types of interactors, most of which are part of a collection called the Swing library , described in section 10.6. You create a GUI by constructing the Swing interactors you need and then arranging them appropriately in the program window.
  • The text outlines two strategies for arranging interactors on the screen. The simple approach is to use a control strip along one of the edges of the window, as described on the next slide. You can, however, create other GUI layouts by using Java’s layout managers, as described in section 10.7.

Adding Features to DrawSplatMap

  • To illustrate the JButton Swing interactor, we'll add a Jbutton to the DrawSplatMap application. First, we'll add a Clear button that erases the screen.
  • Adding the button is accomplished in the init method: public void init() { this.add(new JButton("Clear"), SOUTH); this.addActionListeners(); }
  • The response to the button appears in actionPerformed : public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Clear")) { this.removeAll(); } }

Exercise: Interactive Stoplight

Using the Stoplight class you wrote for Lab 5, write a GraphicsProgram that creates a stoplight and three buttons labeled Red, Yellow, and Green, as shown in the sample run below. Clicking on a button should send a message to the stoplight to change its state accordingly. GStoplightGUI Red Yellow Green import acm.program.; // for GraphicsProgram import java.awt.event.; // for ActionListener import javax.swing.; // for JButtons public class TestStopLight extends GraphicsProgram { public static final int APPLICATION_WIDTH = 250; public static final int APPLICATION_HEIGHT = 475; public static final int RED = 1; public static final int YELLOW = 2; public static final int GREEN = 3; public static final int X = 20, Y = 20; // 3 JButton instance vars to be added along south control strip private JButton red,green,yellow; // instance variable...the StopLight private StopLight stopLight;*

Solution: Interactive Stoplight

main method not shown public void init() { this.stopLight = new StopLight(X,Y); this.stopLight.add(this); this.red this.add(this.red, = new JButton SOUTH);(" Red "); this.green = new JButton("Green "); this.add(this.green,SOUTH); this.yellow = new JButton("Yellow"); this.add(this.yellow,SOUTH); this.addActionListeners(); } // end run method public void actionPerformed(ActionEvent e) { if (e.getSource().equals(this.red)) { stopLight.setLight(RED); } else if (e.getSource().equals(this.yellow)) { stopLight.setLight(YELLOW); } else if (e.getSource().equals(this.green)) { }^ stopLight.setLight(GREEN); } //end actionPerformed method

Solution: Interactive Stoplight

The JToggleButton Class

  • The JToggleButton class is another type of button that is similar to JButton but maintains an on/off state. On the screen, a JToggleButton looks just like a JButton except for the fact that it stays on after you release the mouse button.
  • As its name suggests, a JToggleButton toggles back and forth between on and off when it is clicked. Clicking the first time turns it from off to on; clicking a second time turns it off. Toggle
  • You can determine whether a JToggleButton is on by calling isSelected , which returns true if the button is on.
  • The JToggleButton class itself is not used as much as two of its subclasses, JCheckBox and JRadioButton , which are described on the next two slides.

The JCheckBox Class

  • The JCheckBox class is a subclass of JToggleButton and therefore inherits its behavior.
  • In terms of its operation, a JCheckBox works exactly like an instance of its parent class. The only difference is in what the button looks like on the screen. In a JCheckBox , the button label appears to the right of a small square that either contains or does not contain a check mark, like this:
  • Because a JCheckBox is a JToggleButton , you can call the isSelected method to determine its state.
  • Like a JButton , a JCheckBox generates action events when it is clicked. Both of these classes inherit this behavior from AbstractButton , which is their common superclass. CheckBox

The JRadioButton Class

  • The JRadioButton class also extends JToggleButton and behaves in much the same way. In this case, the button is displayed as a circle that is tinted and marked with a dot when it is selected, as follows:
  • Radio buttons are ordinarily not used individually but instead as a set. If you create a ButtonGroup object and then add several radio buttons to it, the Swing libraries make sure that only one of those buttons is selected at a time.
  • Grouped radio buttons are used to allow the user to choose among several mutually exclusive options. As an example, the text extends the DrawStarMap program to allow the user to choose the size of the star by selecting a radio button: Radio button Small Medium Large

The JSlider Class

  • In many applications, you want to let the user adjust a value over a wide range instead of selecting among a set of options.
  • The simplest form of the JSlider constructor looks like this: new JSlider( min , max , value ) where min and max are integers giving the minimum and maximum values of the slider and value is the initial value.
  • You can retrieve the current value by calling getValue.
  • The Swing libraries include several different interactors that allow the user to adjust a parameter. The text uses the JSlider class, which appears on the screen like this: The user can adjust a JSlider by dragging the slider knob.

The JLabel Class

  • The interactors you display on the screen sometimes don’t provide the user with enough information. In such cases, it is useful to include JLabel objects, which appear as text strings in the user interface but do not respond to any events. DrawStarMap Small Large
  • As an example, if you wanted to label a slider so that it was clear it controlled size, you could use the following code to produce the control strip shown at the bottom of the screen: this.add(new JLabel("Small"), SOUTH); this.add(sizeSlider, SOUTH); this.add(new JLabel("Large"), SOUTH);

The JTextField Class

  • There are some situations in which keyboard input is necessary in a GUI.
  • You can accept keyboard input in a user interface by using the JTextField class, which provides the user with an area in which it is possible to enter a single line of text. HelloGUI Name Hello, Hello, world.Eric.
  • The HelloGUI program on the next slide illustrates the use of the JTextField class in a ConsoleProgram that prints a greeting each time a name is entered in the text field. worldEric

The HelloGUI Program

import acm.program.; import java.awt.event.; import javax.swing.; /* This class displays a greeting whenever a name is entered / public class HelloGUI extends ConsoleProgram { public void init() { this.nameField = new JTextField(10); this.add(new JLabel("Name"), SOUTH); this.add(nameField, SOUTH); nameField.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == this.nameField) { this.println("Hello, " + this.nameField.getText()); this.nameField.setText(""); } } / Private instance variables / private JTextField nameField; }* main method not shown

Notes on the JTextField Class

  • The constructor for the JTextField class has the form new JTextField( columns ) where columns is the number of text columns assigned to the field. The space often appears larger than one might expect, because Java reserves space for the widest characters.
  • A JTextField generates an action event if the user presses the ENTER key in the field. If you want your program to respond to that action event, you need to register the program as an action listener for the field. In the HelloGUI example, the action listener is enabled by the statement nameField.addActionListener(this);
  • You can get and set the string entered in a JTextField by calling the getText and setText methods.