Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mouse Events and Keyboard Events

Similar presentations


Presentation on theme: "Mouse Events and Keyboard Events"— Presentation transcript:

1 Mouse Events and Keyboard Events
Events are central to programming for a graphical user interface. The GUI program must be prepared to respond to various kinds of events that can happen at unpredictable times and in an order that the program doesn’t control The most basic kinds of events are generated by the mouse and keyboard. In Java, events are represented by objects. Different types of events are represented by objects belonging to different classes. For a mouse event, an object belonging to a class called MouseEvent is constructed. For a keyboard event, an object belonging to a class called KeyEvent is constructed. After the event object is constructed, it is passed as a parameter to a designated subroutine. For a GUI program like Applet, although there is no main() routine there, there is still a sort of main routine running somewhere that executes a loop to response the events. This loop is called an event loop. It’s part of “the system”.

2 “Listen” for the events
For an event to have any effect, a program must detect the event and react to it. Listening for events is done by an object called an event listener. This object must contain instance methods for handling the events for which it listens. The methods that are required in a mouse event listener are specified in an interface named MouseListerner. An interface in Java is just a list of instance methods. A class can "implement" an interface by doing two things. First, the class must be declared to implement the interface, as in "class MyListerner implements MouseListener" or "class RandomStrings extends Applet implements MouseListener". Second, the class must include a definition for each instance method specified in the interface. Every event in Java is associated with a GUI component. Before a listener object can “hear” events associated with a given component, the listener object must be registered with the component. If you have a component object called comp, you can register in the following way to listen the mouse event: comp.addMouseListener(Mylistener)

3 MouseEvent and MouseListener
The MouseListener interface specifies five different instance methods: public void mousePressed(MouseEvent evt); public void mouseReleased(MouseEvent evt); public void mouseClicked(MouseEvent evt); public void mouseEntered(MouseEvent evt); public void mouseExited(MouseEvent evt); User can hold down certain modifier keys while using the mouse. The possible modifier keys include: the shift key, the control key, the ALT key. The boolean-valued instance methods can be used are: evt.isShiftDown(), evt.isControlDown(), evt.isAltDown() evt.isMetaDown()

4 A MouseEvent example (SimpleStamper.java)
import java.awt.*; import java.awt.event.*; import java.applet.*; public class SimpleStamper extends Applet implements MouseListener { public void init() { // When the applet is created, set its background color // to black, and register the applet to listen to mouse // events on itself. setBackground(Color.black); addMouseListener(this); }

5 public void mousePressed(MouseEvent evt) {
// This method will be called when the user clicks the // mouse on the applet. if ( evt.isShiftDown() ) { // The user was holding down the Shift key. Just // repaint the applet, which will fill it with its // background color, black. repaint(); return; } int x = evt.getX(); // x-coordinate where user clicked. int y = evt.getY(); // y-coordinate where user clicked. Graphics g = getGraphics(); // Graphics context // for drawing on the applet. if ( evt.isMetaDown() ) { // User right-clicked at the point (x,y). // Draw a blue oval centered at the point (x,y). // A black outline around the oval will make it more // distinct when ovals and rects overlap. g.setColor(Color.blue); g.fillOval( x - 25, y - 15, 60, 30 ); g.setColor(Color.black); g.drawOval( x - 25, y - 15, 60, 30 ); }

6 } // end class SimpleStamper
else { // Draw a red rectangle centered at the point (x,y). g.setColor(Color.red); g.fillRect( x - 25, y - 15, 60, 30 ); g.setColor(Color.black); g.drawRect( x - 25, y - 15, 60, 30 ); } g.dispose(); // We are finished with the graphics context, // so dispose of it. } // end mousePressed() // The following empty routines are required by the // MouseListener interface: public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } } // end class SimpleStamper

7

8 What you need to notice from the previous example
Put the import specification "import java.awt.event.*;" at the beginning of your source code; Declare that some class implements the appropriate listener interface, such as MouseListener; Provide definitions in the class for the subroutines from that interface; Register the listener object with the applet or other component.

9 MouseMotionListeners and Dragging
Whenever the mouse is moved, it generates events The methods for responding to mouse motion events are defined in interface named MouseMotionListner. This interface specifies two event-handling methods: public void mouseDragged(MouseEvent evt) Mouse moving while a button on the mouse is pressed public void mouseMoved(MouseEvent evt) Mouse moving while no muse button is down

10 Example to listen the mouse move events
import java.awt.*; import java.awt.event.*; import java.applet.*; public class Mouser extends Applet implements MouseListener, MouseMotionListener { public void init() { // set up the applet addMouseListener(this); addMouseMotionListener(this); . . . // other initializations } . . // Define the seven MouseListener and . // MouseMotionListener methods. Also, there . // can be other variables and methods.

11 Keyboard Events Keyboard event objects belong to a class called KeyEvent. The methods for responding to KeyEvent are defined in interface named KeyListener. This interface specifies three event-handling methods: public void keyPressed(KeyEvent evt); public void keyReleased(KeyEvent evt); public void keyTyped(KeyEvent evt); The KeyListener object must be registered with a component by calling the component’s addKeyListener() method.

12 Focus Events In Java, objects are notified abut changes of input focus by events of type FocusEvent. An object that wants to be notified of changes in focus can implement the FocusListener interface. This interface declares two methods: public void focusGained(FocusEvent evt); public void focusLost(FocusEvent evt);

13 Example about KeyEvents and Fous Events (KeyboardAndFocusDemo.java)
import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class KeyboardAndFocusDemo extends Applet implements KeyListener, FocusListener, MouseListener { static final int SQUARE_SIZE = 40; // Length of a side of the square. Color squareColor; // The color of the square. int squareTop, squareLeft; // Coordinates of top-left corner of square. boolean focussed = false; // True when this applet has input focus. public void init() { setBackground(Color.white); squareTop = getSize().height / 2 - SQUARE_SIZE / 2; squareLeft = getSize().width / 2 - SQUARE_SIZE / 2; squareColor = Color.red; addFocusListener(this); addKeyListener(this); addMouseListener(this); }

14 public void paint(Graphics g) {
/* Draw a 3-pixel border, colored cyan if the applet has the keyboard focus, or in light gray if it does not. */ if (focussed) g.setColor(Color.cyan); else g.setColor(Color.lightGray); int width = getSize().width; // Width of the applet. int height = getSize().height; // Height of the applet. g.drawRect(0,0,width-1,height-1); g.drawRect(1,1,width-3,height-3); g.drawRect(2,2,width-5,height-5); /* Draw the square. */ g.setColor(squareColor); g.fillRect(squareLeft, squareTop, SQUARE_SIZE, SQUARE_SIZE); /* If the applet does not have input focus, print a message. */ if (!focussed) { g.setColor(Color.magenta); g.drawString("Click to activate",7,20); } } // end paint()

15 public void focusGained(FocusEvent evt) {
// The applet now has the input focus. focussed = true; repaint(); // redraw with cyan border } public void focusLost(FocusEvent evt) { // The applet has now lost the input focus. focussed = false; repaint(); // redraw without cyan border

16 public void keyTyped(KeyEvent evt) {
char ch = evt.getKeyChar(); // The character typed. if (ch == 'B' || ch == 'b') { squareColor = Color.blue; repaint(); } else if (ch == 'G' || ch == 'g') { squareColor = Color.green; } else if (ch == 'R' || ch == 'r') { squareColor = Color.red; } else if (ch == 'K' || ch == 'k') { squareColor = Color.black; } } // end keyTyped()

17 public void keyPressed(KeyEvent evt) {
// Called when the user has pressed a key, which can be // a special key such as an arrow key. If the key pressed // was one of the arrow keys, move the square (but make sure // that it doesn't move off the edge, allowing for a // 3-pixel border all around the applet). int key = evt.getKeyCode(); // keyboard code for the key that was pressed if (key == KeyEvent.VK_LEFT) { squareLeft -= 8; if (squareLeft < 3) squareLeft = 3; repaint(); } else if (key == KeyEvent.VK_RIGHT) { squareLeft += 8; if (squareLeft > getSize().width SQUARE_SIZE) squareLeft = getSize().width SQUARE_SIZE; else if (key == KeyEvent.VK_UP) { squareTop -= 8; if (squareTop < 3) squareTop = 3; else if (key == KeyEvent.VK_DOWN) { squareTop += 8; if (squareTop > getSize().height SQUARE_SIZE) squareTop = getSize().height SQUARE_SIZE; } // end keyPressed()

18 public void keyReleased(KeyEvent evt) {
// empty method, required by the KeyListener Interface } public void mousePressed(MouseEvent evt) { // Request the input focus when the user clicks on the applet. requestFocus(); public void mouseEntered(MouseEvent evt) { } // Required by the public void mouseExited(MouseEvent evt) { } // MouseListener public void mouseReleased(MouseEvent evt) { } // interface. public void mouseClicked(MouseEvent evt) { } } // end class KeyboardAndFocusDemo


Download ppt "Mouse Events and Keyboard Events"

Similar presentations


Ads by Google