Switch to full style
Graphics and animation Java code examples
Post a reply

Handle Key event-keyboard-Get typed Character and its code

Sat Feb 09, 2013 1:21 pm

Handle Key event-keyboard-Get typed Character and its code in a text area.
java code
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class HandleKeysEvent extends Applet
implements KeyListener,
ActionListener {
TextArea textAreaObj;
TextField typingAreaObj;
String lineSeparator;

public void init() {
Button btnObj = new Button("Empty");
btnObj.addActionListener(this);

typingAreaObj = new TextField(20);
typingAreaObj.addKeyListener(this);

textAreaObj = new TextArea(5, 20);
textAreaObj.setEditable(false);
lineSeparator = System.getProperty("line.separator");
setLayout(new BorderLayout());
add("Center", textAreaObj);
add("North", btnObj);
add("South", typingAreaObj);



}

/** Handle key typed event */
public void keyTyped(KeyEvent e) {
sendToTextArea(e, "KEY TYPED: ");
}

/** Handle key pressed event */
public void keyPressed(KeyEvent e) {
sendToTextArea(e, "KEY PRESSED: ");
}

/** Handle key released event */
public void keyReleased(KeyEvent e) {
sendToTextArea(e, "KEY RELEASED: ");
}

/** Handle the button click. */
public void actionPerformed(ActionEvent e) {
//Empty the text area.
textAreaObj.setText("");
typingAreaObj.setText("");

//Request focus to typingArea.
typingAreaObj.requestFocus();
}

protected void sendToTextArea(KeyEvent e, String s){
String charString, keyCodeString, modString, tmpString;

char enteredChar = e.getKeyChar();
int keyCode = e.getKeyCode();
int modifiers = e.getModifiers();

// check if it is ISO control character
if (Character.isISOControl(enteredChar)) {
charString = "Character = (an unprintable control character)";
} else {
charString = "Character = '" + enteredChar + "'";
}

keyCodeString = "key code = " + keyCode
+ " ("
+ KeyEvent.getKeyText(keyCode)
+ ")";

modString = "modifiers = " + modifiers;
tmpString = KeyEvent.getKeyModifiersText(modifiers);
if (tmpString.length() > 0) {
modString += " (" + tmpString + ")";
} else {
modString += " (no modifiers)";
}

textAreaObj.append(s
+ lineSeparator + " "
+ charString
+ lineSeparator + " "
+ keyCodeString
+ lineSeparator + " "
+ modString
+ lineSeparator);
}
}




Post a reply
  Related Posts  to : Handle Key event-keyboard-Get typed Character and its code
 ANSI code value of character     -  
 relationship an event-listener interface & event handler     -  
 advantage of the event delegation model over event-inherit     -  
 check keyboard events using C++     -  
 Read two numbers from the keyboard and display larger number     -  
 What are exceptions and how to handle them!!!     -  
 Handle IsPostBack Condition     -  
 Handle Cookies using JQuery     -  
 How can a GUI component handle its own events     -  
 Character Operations     -  

Topic Tags

Java AWT, Java Applet