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"!.

Java: Example - KeyDemo

JavaFAQ Home » Java Notes by Fred Swartz Go to all tips in Java Notes by Fred Swartz


Bookmark and Share

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

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("
  • Type text.
  • " + "
  • Use arrow keys to move text.
  • " + "
  • Press shift arrows to move faster.
  • "); 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 == '') { // 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

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



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