Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

[an error occurred while processing this directive]

Java Notes

Example - KeyDemo

This program doesn't do anything useful, but it does illustrate handling regular characters, virtual, and modifier keys.

See Keyboard.

A standard main program

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
// KeyDemo.java - Demonstrates handling three kinds of keys:
import javax.swing.*;
/** Demonstrates handling of different types of keys:
    virtual keys (arrows), modifiers (shift), and characters.
    @author Fred Swartz
    @version 2004-05-06
*/
public class KeyDemo extends JFrame {
    public static void main(String[] args) {
        JFrame window = new KeyDemoGUI();
        window.setDefaultCloseOperation(EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}//endclass KeyDemo

A standard subclass of JFrame to build the GUI

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
// KeyDemoGUI.java - JFrame subclass
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//////////////////////////////////////////////////////////////// KeyDemoGUI
/** JFrame subclass for KeyDemo GUI.
    virtual keys (arrows), and characters.
    @author Fred Swartz
    @version 2004-05-06
*/
public class KeyDemoGUI extends JFrame {
    MovingTextPanel drawing;

    //==========================================================constructor
    public KeyDemoGUI() {
        drawing = new MovingTextPanel();
        this.getContentPane().setLayout(new BorderLayout());
        JLabel instructions = new JLabel("<html><ul><li>Type text.</li>"
                    + "<li>Use arrow keys to move text.</li>"
                    + "<li>Press shift arrows to move faster.</li></html>");
        this.getContentPane().add(instructions, BorderLayout.NORTH);
        this.getContentPane().add(drawing, BorderLayout.CENTER);
        
        this.setTitle("KeyDemo");
        this.pack();
        
        drawing.requestFocus();      // Give the panel focus.
    }//end constructor
}//endclass KeyDemoGUI

A subclass of JPanel that has a KeyListener

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
 61 
 62 
 63 
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 
 76 
 77 
 78 
 79 
 80 
 81 
 82 
// MovingTextPanel.java - Demonstrates handling three kinds of keys:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

///////////////////////////////////////////////////////// class DrawingPanel
/** Define a new panel to draw on, therefore it has a paintComponent method.
    This class implements KeyListener, altho the listeners don't really 
    have to be inside this class.
    This class displays any characters that are typed, and handles
    virtual keys (arrows) and modifiers (shift) to move the text.
    @author Fred Swartz
    @version 2004-05-06
*/
class MovingTextPanel extends JPanel implements KeyListener {
    //===================================================== field variables
    String display = ""; // Initial string to display
    private int x = 50;  // Initial coordinates of string
    private int y = 50;
    
    private Font biggerFont = new Font("sansserif", Font.PLAIN, 24);
    private int speed = 2; // number of pixels to move
    
    //========================================================= constructor
    public MovingTextPanel() {
        this.setBackground(Color.white);
        this.setFont(biggerFont);
        this.setPreferredSize(new Dimension(300, 200));
        this.addKeyListener(this);  // This class has its own key listeners.
        this.setFocusable(true);    // Allow panel to get focus
    }//endconstructor

    //======================================================= paintComponent
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString(display, x, y);
    }//endmethod paintComponent

    //==================================================== keyTyped listener
    /** This listener is called for character keys. */
    public void keyTyped(KeyEvent kevt) {
        //System.out.println("keyTyped");
        char c = kevt.getKeyChar();
        if (c == '\b') { // if this is a backspace
            if (display.length() > 0) {  // remove last character
                display = display.substring(0, display.length()-1);
            }
        } else {
            display += c;
        }
        this.repaint();
    }//endmethod keyTyped

    //================================================== keyPressed listener
    /** This listener is called for both character and non-character keys. */
    public void keyPressed(KeyEvent e) {
        // Check the shift key, and do 10x the movement if the
        // shift key is down when the arrow keys are pressed.
        // Altho keyPressed is called for normal characters, they
        // are ignored here and handled in keyTyped.
        if (e.isShiftDown()) {
            speed = 10;
        } else {
            speed = 2;
        }        
        
        //-- Process arrow "virtual" keys
        switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT : x -= speed; x = Math.max(x, 0);   break;
            case KeyEvent.VK_RIGHT: x += speed; x = Math.min(x, 300); break;
            case KeyEvent.VK_UP   : y -= speed; y = Math.max(y, 0);   break;
            case KeyEvent.VK_DOWN : y += speed; y = Math.min(y, 200); break;
        }
        
        speed = 2;       // Restore speed to its default value
            
        this.repaint();  // Display the changes.
    }//endmethod keyPressed

    //------------------------------------------------- keyReleased listener
    public void keyReleased(KeyEvent ke) {}  // Ignore.
}//endclass MovingTextPanel

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (
post your own) View All Comments Latest 10 Comments:
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.