40
CHAPTER 10 EVENT HANDLING

CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Embed Size (px)

Citation preview

Page 1: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

CHAPTER 10

EVENT HANDLING

Page 2: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

CHAPTER GOALS

• To understand the Java event model

• To install mouse and action listeners

• To accept mouse and text input

• To display frame windows  

• To show text output in a text area with a

scroll bar

Page 3: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Event Classes• Event source: Generates events and manages

listenersExample: applet

• Listener: Notified when event happensExample: MouseListener

• Event class: Describes eventExample: MouseEvent

Page 4: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

The MouseListener Interface public interface MouseListener

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

}

Page 5: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File MouseSpy.java1 import java.awt.event.MouseEvent;

2 import java.awt.event.MouseListener;

3

4 /**

5 This listener simply prints out the listener method name

6 and the x- and y-coordinate of the mouse position.

7 */

8 public class MouseSpy implements MouseListener

9 {

10 public void mousePressed(MouseEvent event)

11 {

12 System.out.println("Mouse pressed. x = "

13 + event.getX() + " y = " + event.getY());

14 }

15

16 public void mouseReleased(MouseEvent event)

17 {

18 System.out.println("Mouse released. x = "

Page 6: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

19 + event.getX() + " y = " + event.getY());

20 }

21

22 public void mouseClicked(MouseEvent event)

23 {

24 System.out.println("Mouse clicked. x = "

25 + event.getX() + " y = " + event.getY());

26 }

27

28 public void mouseEntered(MouseEvent event)

29 {

30 System.out.println("Mouse entered. x = "

31 + event.getX() + " y = " + event.getY());

32 }

33

34 public void mouseExited(MouseEvent event)

35 {

36 System.out.println("Mouse exited. x = "

37 + event.getX() + " y = " + event.getY());

38 }

39 }

Page 7: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File MouseSpyApplet.java1 import java.applet.Applet;

2

3 /**

4 This applet installs a mouse spy. Try generating the

5 five mouse event types by moving and clicking the mouse.

6 */

7 public class MouseSpyApplet extends Applet

8 {

9 public MouseSpyApplet()

10 {

11 MouseSpy listener = new MouseSpy();

12 addMouseListener(listener);

13 }

14 }

15

Page 8: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Spying on Mouse Events

Page 9: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Mouse Listener that Moves a Rectangle

public MouseApplet()

{ ... //add mouse press listener class MousePressListener implements MouseListener { public void mousePressed(MouseEvent event) {

int x = event.getX(); int y = event.getY(); box.setLocation(x,y); repaint();

}

Page 10: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

//do-nothing methods public void mouseReleased(MouseEvent event){}

public void mouseClicked(MouseEvent event){}

public void mouseEntered(MouseEvent event){}

public void mouseExited(MouseEvent event){} } MouseListener listener = new MousePressListener(); addMouseListener(listener);

}

Page 11: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Mouse Listener that Moves a Rectangle

• Gets mouse position from event object • Accesses box instance field of outer class • Invokes repaint method on outer class • repaint triggers paint method • You should always call repaint to trigger painting

Don't call paint directly

Page 12: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

The Mouse Applet

Page 13: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

The Mouse Applet

Page 14: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

An Applet with a Control Panel

Page 15: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Control Panel Components

• Use Swing package javax.swing • Class names start with J

• JTextField xField = new JTextField(width); • JLabel xLabel = new JLabel("x = "); • Icon buttonIcon = new ImageIcon("hand.gif");• moveButton = new JButton("Move",buttonIcon);

Page 16: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Button Listener• Moves rectangle when button is clicked • Reads xField, yField variables from enclosing scope public ButtonApplet() { ... class MoveButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { int x =Integer.parseInt(xField.getText()); int y =Integer.parseInt(yField.getText()); box.setLocation(x,y); repaint(); } }; ActionListener listener = new MoveButtonListener(); moveButton.addActionListener(listener); ... }

Page 17: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Placing Components in a Panel •JPanel is container for components • Add components to panelJPanel panel = new JPanel();panel.add(xLabel);panel.add(xField);. . .

• Place panel inside frameJFrame frame = new JFrame();frame.setContentPane(panel);

• Pack frame: size it to just contain the componentsframe.pack();frame.show();

Page 18: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File ButtonApplet.java 1 import java.applet.Applet;

2 import java.awt.Graphics;

3 import java.awt.Graphics2D;

4 import java.awt.Rectangle;

5 import java.awt.event.ActionEvent;

6 import java.awt.event.ActionListener;

7 import javax.swing.ImageIcon;

8 import javax.swing.JButton;

9 import javax.swing.JFrame;

10 import javax.swing.JLabel;

11 import javax.swing.JPanel;

12 import javax.swing.JTextField;

13

14 /**

15 This applet lets the user move a rectangle by specifying

16 the x- and y-position of the top left corner.

17 */

Page 19: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

18 public class ButtonApplet extends Applet

19 {

20 public ButtonApplet()

21 {

22 // the rectangle that the paint method draws

23 box = new Rectangle(BOX_X, BOX_Y,

24 BOX_WIDTH, BOX_HEIGHT);

25

26 // the text fields for entering the x- and y-coordinates

27 final JTextField xField = new JTextField(5);

28 final JTextField yField = new JTextField(5);;

29

30 // the button to move the rectangle

31 JButton moveButton = new JButton("Move",

32 new ImageIcon("hand.gif"));

33

34 class MoveButtonListener implements ActionListener

35 {

36 public void actionPerformed(ActionEvent event)

37 {

Page 20: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

38 int x = Integer.parseInt(xField.getText());

39 int y = Integer.parseInt(yField.getText());

40 box.setLocation(x, y);

41 repaint();

42 }

43 };

44

45 ActionListener listener = new MoveButtonListener();

46 moveButton.addActionListener(listener);

47

48 // the labels for labeling the text fields

49 JLabel xLabel = new JLabel("x = ");

50 JLabel yLabel = new JLabel("y = ");

51

52 // the panel for holding the user interface components

53 JPanel panel = new JPanel();

54

55 panel.add(xLabel);

56 panel.add(xField);

57 panel.add(yLabel);

58 panel.add(yField);

Page 21: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

59 panel.add(moveButton);

60

61 // the frame for holding the component panel

62 JFrame frame = new JFrame();

63 frame.setContentPane(panel);

64 frame.pack();

65 frame.show();

66 }

67

68 public void paint(Graphics g)

69 {

70 Graphics2D g2 = (Graphics2D)g;

71 g2.draw(box);

72 }

73

74 private Rectangle box;

75 private static final int BOX_X = 100;

76 private static final int BOX_Y = 100;

77 private static final int BOX_WIDTH = 20;

78 private static final int BOX_HEIGHT = 30;

79 }

Page 22: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Multiple Buttons with Similar Behavior

• Don't want to write separate code for similar listeners

• Remedy: Write method that attaches the listener

• Make variable parts into final method parameters • Local listener class can access final parameters

Page 23: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

An Applet with Multiple Buttons

Page 24: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Method for Attaching Listenerpublic JButton makeButton(String label, final int dx,final int dy) { JButton button = new JButton(label); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { box.translate(dx, dy); repaint(); } };

ButtonListener listener = new ButtonListener(); button.addActionListener(listener); return button; }

Page 25: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Method for Attaching Listener

• Call multiple times

panel.add(makeButton("Left",-BOX_WIDTH,0)); panel.add(makeButton("Right",BOX_WIDTH,0)); panel.add(makeButton("Up",0,-BOX_HEIGHT)); panel.add(makeButton("Down",0,BOX_HEIGHT));

Page 26: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File ButtonApplet.java 1 import java.applet.Applet;

2 import java.awt.Graphics;

3 import java.awt.Graphics2D;

4 import java.awt.Rectangle;

5 import java.awt.event.ActionEvent;

6 import java.awt.event.ActionListener;

7 import javax.swing.JButton;

8 import javax.swing.JFrame;

9 import javax.swing.JPanel;

10

11 /**

12 This applet lets the user move a rectangle by clicking

13 on buttons labeled "Left", "Right", "Up", and "Down".

14 */

15 public class ButtonApplet extends Applet

16 {

17 public ButtonApplet()

Page 27: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

18 {

19 // the rectangle that the paint method draws

20 box = new Rectangle(BOX_X, BOX_Y,

21 BOX_WIDTH, BOX_HEIGHT);

22

23 // the panel for holding the user interface components

24 JPanel panel = new JPanel();

25

26 panel.add(makeButton("Left", -BOX_WIDTH, 0));

27 panel.add(makeButton("Right", BOX_WIDTH, 0));

28 panel.add(makeButton("Up", 0, -BOX_HEIGHT));

29 panel.add(makeButton("Down", 0, BOX_HEIGHT));

30

31 // the frame for holding the component panel

32 JFrame frame = new JFrame();

33 frame.setContentPane(panel);

34 frame.pack();

35 frame.show();

36 }

37

Page 28: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

38 public void paint(Graphics g)

39 {

40 Graphics2D g2 = (Graphics2D)g;

41 g2.draw(box);

42 }

43

44 /**

45 Makes a button that moves the box.

46 @param label the label to show on the button

47 @param dx the amount by which to move the box in x-direction

48 when the button is clicked

49 @param dy the amount by which to move the box in y-direction

50 when the button is clicked

51 @return the button

52 */

53 public JButton makeButton(String label, final int dx,

54 final int dy)

55 {

56 JButton button = new JButton(label);

57

Page 29: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

58 class ButtonListener implements ActionListener

59 {

60 public void actionPerformed(ActionEvent event)

61 {

62 box.translate(dx, dy);

63 repaint();

64 }

65 };

66

67 ButtonListener listener = new ButtonListener();

68 button.addActionListener(listener);

69 return button;

70 }

71

72 private Rectangle box;

73 private static final int BOX_X = 100;

74 private static final int BOX_Y = 100;

75 private static final int BOX_WIDTH = 20;

76 private static final int BOX_HEIGHT = 30;

77 }

Page 30: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Frame Windows• Application program, not applet

• Construct and show frameJFrame frame = new JFrame();. . .frame.show();

• Set the default close operationframe.setDefaultCloseOperation(EXIT_ON_CLOSE);

• Add components to a panel, then set the panel as content paneJPanel panel = new JPanel();panel.add(. . .);panel.add(. . .)frame.setContentPane(panel);

Page 31: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

A Frame with Two Labels

Page 32: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File FrameTest.java1 import javax.swing.ImageIcon;

2 import javax.swing.JFrame;

3 import javax.swing.JLabel;

4 import javax.swing.JPanel;

5

6 /**

7 This program displays a frame with an image and a text label.

8 */

9 public class FrameTest

10 {

11 public static void main(String[] args)

12 {

13 JFrame frame = new JFrame();

14 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

15

16 JLabel iconLabel = new JLabel(new ImageIcon("world.gif"));

17 JLabel textLabel = new JLabel("Hello, World!");

Page 33: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

18

19 JPanel panel = new JPanel();

20 panel.add(iconLabel);

21 panel.add(textLabel);

22 frame.setContentPane(panel);

23

24 frame.pack();

25 frame.show();

26 }

27 }

Page 34: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

Text Components • JTextField holds a single line of text • JTextArea holds multiple lines

• Construct with new JTextArea(rows, columns)

• textArea.append(aString) appends text

• Use textArea.setEditable(false) to use for display only

• To add scroll bars, useJScrollPane scrollPane = new JScrollPane(textArea);

textArea.setContentPane(scrollPane);

Page 35: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

A Text Area with Scroll Bars

Page 36: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

The Control Panel for Adding Interest

Page 37: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

File TextAreaTest.java1 import java.awt.event.ActionEvent;

2 import java.awt.event.ActionListener;

3 import javax.swing.JButton;

4 import javax.swing.JFrame;

5 import javax.swing.JLabel;

6 import javax.swing.JPanel;

7 import javax.swing.JScrollPane;

8 import javax.swing.JTextArea;

9 import javax.swing.JTextField;

10

11 /**

12 This program shows a frame with a text area that displays

13 the growth of an investment. A second frame holds a text

14 field to specify the interest rate.

15 */

16 public class TextAreaTest

17 {

Page 38: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

18 public static void main(String[] args)

19 {

20 // the application adds interest to this bank account

21 final BankAccount account = new BankAccount(INITIAL_BALANCE);

22 // the text area for displaying the results

23 final JTextArea textArea = new JTextArea(10, 30);

24 textArea.setEditable(false);

25 JScrollPane scrollPane = new JScrollPane(textArea);

26

27 // construct the frame for displaying the text area

28 JFrame frame = new JFrame();

29 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

30 frame.setContentPane(scrollPane);

31 frame.pack();

32 frame.show();

33

34 // the label and text field for entering the interest rate

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

36

37 final JTextField rateField = new JTextField(10);

Page 39: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

38 rateField.setText("" + DEFAULT_RATE);

39

40 // the button to trigger the calculation

41 JButton calculateButton = new JButton("Add Interest");

42

43 class CalculateListener implements ActionListener

44 {

45 public void actionPerformed(ActionEvent event)

46 {

47 double rate = Double.parseDouble(

48 rateField.getText());

49 double interest = account.getBalance()

50 * rate / 100;

51 account.deposit(interest);

52 textArea.append(account.getBalance() + "\n");

53 }

54 }

55

56 ActionListener listener = new CalculateListener();

57 calculateButton.addActionListener(listener);

Page 40: CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display

58

59 // the control panel that holds the input components

60 JPanel controlPanel = new JPanel();

61 controlPanel.add(rateLabel);

62 controlPanel.add(rateField);

63 controlPanel.add(calculateButton);

64

65 // the frame to hold the control panel

66 JFrame controlFrame = new JFrame();

67 controlFrame.setContentPane(controlPanel);

68 controlFrame.pack();

69 controlFrame.show();

70 }

71

72 private static final double DEFAULT_RATE = 10;

73 private static final double INITIAL_BALANCE = 1000;

74 }