Chapter 12

Event Handling


Chapter Goals

Events, Event Sources, and Event Listeners

Events, Event Sources, and Event Listeners

File ClickListener.java

File ButtonTester.java

Output


Self Check

  1. Which objects are the event source and the event listener in the ButtonTester program?
  2. Why is it legal to assign a ClickListener object to a variable of type ActionListener?

Answers

  1. The button object is the event source. The listener object is the event listener.
  2. The ClickListener class implements the ActionListener interface.

Building Applications with Buttons

Building Applications with Buttons

File InvestmentViewer1.java

Self Check

  1. How do you place the "balance = . . ." message to the left of the "Add Interest" button?
  2. Why was it not necessary to declare the button variable as final?

Answers

  1. First add label to the panel, then add button.
  2. The actionPerformed method does not access that variable.

Processing Text Input

File InvestmentViewer2.java

Self Check

  1. What happens if you omit the first JLabel object?
  2. If a text field holds an integer, what expression do you use to read its contents?

Answers

  1. Then the text field is not labeled, and the user will not know its purpose.
  2. Integer.parseInt(textField.getText())

Mouse Events

Mouse Events

File RectangleComponent.java

Mouse Events

RectangleComponentViewer Program Output

File RectangleComponentViewer.java

Self Check

  1. What would happen if you omitted the call to repaint in the moveTo method?
  2. Why must the MousePressListener class supply five methods?

Answers

  1. The rectangle would only be painted at the new location when the component is repainted for some other reason, for example, when the frame is resized.
  2. It implements the MouseListener interface, which has five methods.