Sat Feb 09, 2013 1:21 pm
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);
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.