Chapter 10

Event Handling


Chapter Goals

Event Classes

The MouseListener Interface

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

File MouseSpy.java

1import java.awt.event.MouseEvent;
2import 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*/
8public 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 = " 
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}

File MouseSpyApplet.java

1import 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*/
7public class MouseSpyApplet extends Applet
8{  
9   public MouseSpyApplet()
10   {  
11      MouseSpy listener = new MouseSpy();
12      addMouseListener(listener);
13   }
14}
15

Spying on Mouse Events


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();

}
//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);
}

Mouse Listener that Moves a Rectangle

The Mouse Applet


MouseApplet.java

An Applet with a Control Panel


Control Panel Components

Button Listener

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);
...
}

Placing Components in a Panel

File ButtonApplet.java

1import java.applet.Applet;
2import java.awt.Graphics;
3import java.awt.Graphics2D;
4import java.awt.Rectangle;
5import java.awt.event.ActionEvent;
6import java.awt.event.ActionListener;
7import javax.swing.ImageIcon;
8import javax.swing.JButton;
9import javax.swing.JFrame;
10import javax.swing.JLabel;
11import javax.swing.JPanel;
12import 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*/
18public 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         {
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);
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}

Multiple Buttons with Similar Behavior

An Applet with Multiple Buttons


Method for Attaching Listener

public 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;
}

Method for Attaching Listener

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));

File ButtonApplet.java

1import java.applet.Applet;
2import java.awt.Graphics;
3import java.awt.Graphics2D;
4import java.awt.Rectangle;
5import java.awt.event.ActionEvent;
6import java.awt.event.ActionListener;
7import javax.swing.JButton;
8import javax.swing.JFrame;
9import 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*/
15public class ButtonApplet extends Applet
16{  
17   public ButtonApplet()
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
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
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}

Frame Windows

A Frame with Two Labels


File FrameTest.java

1import javax.swing.ImageIcon;
2import javax.swing.JFrame;
3import javax.swing.JLabel;
4import javax.swing.JPanel;
5
6/**
7   This program displays a frame with an image and a text label.
8*/
9public 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!");
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}

Text Components

A Text Area with Scroll Bars


The Control Panel for Adding Interest


File TextAreaTest.java

1import java.awt.event.ActionEvent;
2import java.awt.event.ActionListener;
3import javax.swing.JButton;
4import javax.swing.JFrame;
5import javax.swing.JLabel;
6import javax.swing.JPanel;
7import javax.swing.JScrollPane;
8import javax.swing.JTextArea;
9import 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*/
16public class TextAreaTest
17{  
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);
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);
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}