Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 323


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Java Notes: Keyboard

Go to all tips in Java Notes by Fred Swartz

Not normally used. You don't normally need to capture the low-level keyboard events because components (eg, JTextField) handle them for you. One of the few cases where you might want to handle them is in a subclass of JPanel that is being used for graphics where key strokes need to be interpreted, eg, to move an image, fill in a crossword cell, etc.

There are three types of characters, each of which is handled differently, altho they all generated pressed and released events.

  1. Characters (a, A, #, ...) - handled in the keyTyped() listener.
  2. Virtual keys (arrow keys, function keys, etc) - handled with keyPressed() listener.
  3. Modifier keys (shift, alt, control, ...) - Usually their status (up/down) is tested by calls in one of the other listeners, rather than in keyPressed().

Warning: This was written for Java 1.2. In more recent versions (1.3+) javax.swing.InputMap should be used in preference to KeyListener for getting characters. Eventually I'll rewrite these notes.

Listener Classes and Interfaces

The java.awt.event.KeyListener interface and java.awt.event.KeyEvent class are all imported by:

import java.awt.event.*;

KeyTyped() versus KeyPressed() and KeyReleased()

Three methods must be defined in a class that implements KeyListener:

keyTyped(KeyEvent e)
The KeyTyped() listener method is called when a character is typed, but is not useful for virtual keys (arrow keys, function keys, etc). Modifier key (shift, control, etc) status (up/down) can be tested with method calls in the listener.
keyPressed(KeyEvent e) and keyReleased(KeyEvent e)
These methods are called whenever any key is pressed or released. Regular character keys also produce calls to these listeners, but are usually handled by the keyTyped() listener and may be ignored in this listener. Modifier keys (shift, control) also generate calls to these listeners, but are typically tested with method calls in the listener. For example, if you type an uppercase 'J', there are five events, which call these methods:
  1. KeyPressed for pressing the shift key.
  2. KeyPressed for pressing the j key.
  3. KeyTyped for the character J.
  4. KeyReleased for releasing the j key.
  5. KeyReleased for releasing the shift key.

Focus - Which component gets KeyEvents? -- The one with Focus

The key listener for your JPanel is called only if the JPanel has focus. Only one component has focus at a time, not all components can get focus, and key events are directed to the component with focus.

Make your panel focusable, then request focus.

Not all components can get focus, eg labels do not get focus. To ensure that your JPanel subclass can get focus, call setFocusable() in the constructor (note: it can only help, altho I've written programs where it didn't appear to be necessary.).

this.setFocusable(true);   //  In panel constructor.

After you have build the graphical user interface, give the panel p focus with:

p.requestFocus();

When your window is active, all key events will be given to the listeners for your panel p.

Example - Key listeners in a JPanel subclass

You can place a key listener in your JPanel subclass. For example

class MyPanel extends JPanel implements KeyListener {
    . . .
    //=================================== constructor
    public MyPanel() {
       this.setFocusable(true);   // Allow this panel to get focus.
       this.addKeyListener(this); // listen to our own key events.
       . . .
    }
    
    //-- Define one or more of these to handle keyboard events
    public void keyPressed(KeyEvent e) {. . .}
    public void keyReleased(KeyEvent e){. . .}
    public void keyTyped(KeyEvent e)   {. . .}
}

Example - To get a character that is typed

You need to add a key listener to your panel. A key listener has three methods for handling events, but you only need to do something in the keyTyped method if you want to get the character that was typed. Here is a listener that adds all characters that are typed to the string s.

public void keyTyped(KeyEvent e) {
    s = s + e.getKeyChar();
}

Virtual Keys

Many keys do not generate characters, for example, the shift, arrow, or function keys. These keys generate a virtual key code that you can check in the keyPressed() (but not keyTyped()) listener.

Use keyPressed(...) or keyReleased(...), not keyTyped(...)

There is no character for many keys, so you can not use the KeyTyped() listener method. You must write the KeyPressed(...) or KeyReleased(...) listener methods to find out when these keys are used.

To get the virtual key code

se the KeyEvent.getKeyCode() method to get the virtual key code. For example,

public void keyPressed(KeyEvent ke) {
    switch (ke.getKeyCode()) {
    case KeyEvent.VK_LEFT:  // move x coordinate left
        x -= dx;
        x = Math.max(x, 0);
        break;
    case KeyEvent.VK_RIGHT: // move x coordinate right
        x += dx;
        x = Math.min(x, 100);
    }
    drawing.repaint();
}

Virtual Key Codes

The KeyEvent class defines a large number of virtual key codes that correspond keys on the keyboard. This list may expand as new keyboards are supported. See the java.awt.event.KeyEvent documentation for a list of these. Below are some of the most common codes. You can probably figure out the key from the name.

Alphanumeric keys
VK_0, VK_1, ..., VK_9, VK_A, VK_B, ..., VK_Z
Control keys
VK_ENTER, VK_BACKSPACE, VK_TAB, VK_ESCAPE
Function keys
VK_F1, VK_F2, VK_F3, VK_F4 VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12,
VK_SCROLL_LOCK, VK_PRINTSCREEN, VK_PAUSE,
VK_DELETE, VK_INSERT,
VK_PAGE_UP, VK_PAGE_DOWN, VK_HOME, VK_END
Arrow keys
VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN

Testing Modifier Keys

Certain keys are used as modifier keys to change another action. For example, holding the ALT key down while clicking on the mouse may alter the action you want to perform. The event object has methods which may be called to find the status (up/down) for these modifier keys. MouseEvent and KeyEvent are both subsets of java.awt.event.InputEvent, so either can use these methods for determining which modifier keys are pressed.

Testing Modifier Keys from an Event Object

The following methods are available for KeyEvent and MouseEvent objects (e), and would normally be used inside of a mouse or key listener.

e.isAltDown()true if the ALT key was down when this event happened.
e.isControlDown()true if the CTRL key was down when this event happened.
e.isShiftDown()true if the SHIFT key was down when this event happened.
e.isMetaDown()true if the META key was down when this event happened.
e.isAltGraphDown()true if the ALT-GRAPH key was down when this event happened.
e.getModifiers() This method returns an int bit mask which identifies the keys and mouse buttons which are down at the time of the event. Many constants are defined to test these. Some of the more common are:
InputEvent.ALT_MASK ALT key is down.
InputEvent.CTRL_MASK CTRL key is down.
InputEvent.SHIFT_MASK SHIFT key is down.
InputEvent.ALT_GRAPH_MASKALT-GRAPH key is down.
InputEvent.META_MASK META key is down.
InputEvent.BUTTON1_MASK Mouse button 1 is down.
InputEvent.BUTTON2_MASK Mouse button 2 is down.
InputEvent.BUTTON3_MASK Mouse button 3 is down.

Examples



6 comments | Printer Friendly Page  Send to a Friend | Score: 0
Posted by jalex on Friday, March 18, 2005 (00:00:00) (4494 reads)

The Java Lesson 36: Mouse event processing

Go to all tips in Java Lessons by Jon Huhtala
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 36 by Jon Huhtala: Mouse event processing


Overview

Features for detecting and processing mouse events are part of the java.awt and java.awt.event packages. Any windows program or applet may easily incorporate mouse event processing.

The MouseEvent class

  • Is part of the java.awt.event package

  • Is used to construct MouseEvent objects. Such objects are automatically fired when a mouse action occurs within a component. These actions are categorized as either simple mouse events or mouse motion events as follows:

Simple mouse events:

A mouse button is pressed
A mouse button is released
A mouse button is clicked
The mouse enters a component
The mouse exits a component

Mouse motion events:

The mouse is moved
The mouse is dragged

In order to receive and process simple mouse events, a component must register a MouseListener. To receive and process mouse motion events, a component must register a MouseMotionListener. For example, if myCanvas is a Canvas object, the statements

myCanvas.addMouseListener(this);
myCanvas.addMouseMotionListener(this);

will register listeners for all mouse events that may be fired by the myCanvas component. All that remains is to implement the two interfaces and their required methods. This will be covered shortly.

  • Has many methods. The two most frequently used are:

Method

Usage

getX()

Returns the x-axis coordinate of the event relative to the top-left corner of the component

getY()

Returns the y-axis coordinate of the event relative to the top-left corner of the component


The MouseListener interface

  • Is part of the java.awt.event package

  • Is a listener interface for receiving simple mouse events

  • May be implemented by any class that has Component as an ancestor. The implementation is specified in the class header. For example,

    public class MyApplet extends Applet implements MouseListener

    begins the definition of an Applet class extension (MyApplet) that implements the MouseListener interface. Components that wish to be notified of simple mouse events must register their MouseListener. For example, if x is the reference of some component, you may register the current object as a MouseListener by coding:

x.addMouseListener(this);

When a simple mouse event occurs within component x, a MouseEvent object will be automatically fired to the relevant method within the listener object.

  • Has five required methods that MUST be defined by the implementing class. The methods are:

Method

Usage

mouseClicked()

Invoked when the mouse has been clicked on a component

mouseEntered()

Invoked when the mouse enters a component

mouseExited()

Invoked when the mouse exits a component

mousePressed()

Invoked when a mouse button has been pressed on a component

mouseReleased()

Invoked when a mouse button has been released on a component

Each of the above methods receives a MouseEvent object as a parameter and returns no value (is void). Consult the Java API for more details.

The MouseMotionListener interface

  • Is part of the java.awt.event package

  • Is a listener interface for receiving mouse motion events

  • May be implemented by any class that has Component as an ancestor. The implementation is specified in the class header. For example,

    public class MyApplet extends Applet implements MouseMotionListener

    begins the definition of an Applet class extension (MyApplet) that implements the MouseMotionListener interface. Components that wish to be notified of mouse motion events must register their MouseMotionListener. For example, if x is the reference of some component, you may register the current object as a MouseMotionListener by coding:

x.addMouseMotionListener(this);

When a mouse motion event occurs within component x, a MouseEvent object will be automatically fired to the relevant method within the listener object.

  • Has two required methods that MUST be defined by the implementing class. The methods are:

Method

Usage

mouseDragged()

Invoked when a mouse button is pressed on a component and the mouse is moved with the button down

mouseMoved()

Invoked when the mouse has been moved on a component with no buttons down

Each of the above methods receives a MouseEvent object as a parameter and returns no value (is void). Consult the Java API for more details.

The MouseAdapter and the MouseMotionAdapter classes

Rather than implement the MouseListener or MouseMotionListener interfaces, a class may choose to extend the MouseAdapter or the MouseMotionAdapter class. These classes contain definitions for all required interface methods so that only the methods of interest must be coded to override those inherited.

The technique is most often used when registering and defining an inner listener. For example, if x is the reference of some component, you may register and define its listener for handling mouse movement by coding:

x.addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
custom code goes here...
}
}
);

When the mouse is moved within component x, a MouseEvent object will be automatically fired to the custom code defined within this inner listener.

A sample applet that uses mouse events

This applet can be used to draw small blue dots. To draw a dot, just click the mouse anywhere within the central portion of the applet's panel. A button at the bottom of the applet panel can be clicked to clear the dots already drawn.

The applet's code is as follows:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class App extends Applet implements ActionListener,
MouseListener, MouseMotionListener {

Button surprise = new Button("Click here to win $1 Million!");
Button clear = new Button("Clear");
Canvas canvas = new Canvas();

public void init() {
resize(400, 400);
setLayout(new BorderLayout());
surprise.setFont(new Font("SanSerif", Font.BOLD, 1Cool);
surprise.addMouseListener(this);
add(surprise, BorderLayout.NORTH);
canvas.setForeground(Color.blue);
canvas.setFont(new Font("SanSerif", Font.PLAIN, 10));
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
add(canvas);
clear.addActionListener(this);
add(clear, BorderLayout.SOUTH);
}

// Method required by the ActionListener interface.

public void actionPerformed(ActionEvent e) {
Graphics g = canvas.getGraphics();
g.setColor(canvas.getBackground());
g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
}

// Methods required by the MouseListener interface.

public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(canvas)) {
int originX = e.getX() - 10;
int originY = e.getY() - 10;
Graphics g = canvas.getGraphics();
g.fillOval(originX, originY, 20, 20);
}
}
public void mouseEntered(MouseEvent e) {
if (e.getSource().equals(surprise))
surprise.setVisible(false);
else
surprise.setVisible(true);
}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

// Methods required by the MouseMotionListener interface.

public void mouseMoved(MouseEvent e) {
showPosition(e);
}
public void mouseDragged(MouseEvent e) {
showPosition(e);
}

// Custom method to display the current mouse position within the
// canvas component.

private void showPosition(MouseEvent e) {
Graphics g = canvas.getGraphics();
String currentPosition =
new String("x = " + e.getX() + ", y = " + e.getY());
g.clearRect(2, canvas.getHeight()-17, 80, 17);
g.setColor(Color.black);
g.drawString(currentPosition, 2, canvas.getHeight()-2);
}
}

Notes:

  1. In order to handle all kinds of mouse events, the applet implements both the MouseListener and MouseMotionListener interfaces.

  2. The applet has two Button components (surprise and clear) and a Canvas component (canvas).

  3. No, you're NEVER going to get that $1 million. The surprise button has a registered MouseListener and the MouseEntered() method hides the button every time you enter it and makes it reappear every time you enter some other component having a registered MouseListener interface (canvas). Sorry...

  4. Drawing of dots occurs within the Canvas object (canvas). It has a registered MouseListener, so a mouse click within the component fires a MouseEvent object to the mouseClicked() method. The method determines the location of the click, obtains the context of the component, and draws a blue dot at that location.

  5. Whenever the mouse is moved or dragged within canvas, its position is displayed at the bottom-right corner of the component. The registered MouseMotionListener makes this possible by firing a MouseEvent object to either the mouseMoved() or the mouseDragged() method. These methods pass the object along to a custom method of the applet's class named showPosition() which builds a text string representing the current mouse position and displays it via the component's context.

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. Which of the following statements are true of what will happen when the user moves the mouse to touch a component? (choose two)

  1. a MouseMotionEvent object will be fired

  1. a MouseEvent object will be fired

  2. if the component has registered an ActionListener, its actionPerformed() method will be called

  3. if the component has registered a MouseListener, its mouseEntered() method will be called

  4. if the component has registered a MouseListener, its mouseMoved() method will be called

  1. Which of the following methods are defined within the MouseMotionListener interface?

  1. mouseMoved()

  1. mouseDragged()

  2. both mouseMoved() and mouseDragged()

  3. neither mouseMoved() or mouseDragged()

  1. Which one of the following is not a method required by the MouseListener interface?

    1. mouseExited()

    1. mouseReleased()

    2. mouseClicked()

    3. mousePressed()

    4. mouseMoved()

  1. If e is the reference of a MouseEvent object, which one of the following statements is true?

  1. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the screen

  2. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the component

  3. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the screen

  4. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the component

  5. none of the above


21831 bytes more | 4 comments | Printer Friendly Page  Send to a Friend | Score: 4
Posted by jalex on Thursday, March 17, 2005 (00:00:00) (12625 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324|
323
| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy