Java AWT KeyListener not working - java

I have been playing around with Java and I added a KeyListener. When I type a key it prints "0" and I would like it to print the key code.
Key.java
import java.awt.event.*;
public class Key implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + Integer.toString(e.getKeyCode()));
}
}
Main.java
public void init() {
addKeyListener(new Key());
addMouseListener(new Mouse());
this.setBackground(new Color(100, 100, 255));
this.setSize(screen);
}
Thanks for all the help!

Just read the doc :
void keyTyped(KeyEvent e)
Invoked when a key has been typed. See the class description for
KeyEvent for a definition of a key typed event.
So go through the description :
public int getKeyCode()
Returns the integer keyCode associated with the key in this event.
Returns: the integer code for an actual key on the keyboard. (For
KEY_TYPED events, the keyCode is VK_UNDEFINED.)
And the constant VK_UNDEFINED is :
public static final int VK_UNDEFINED = 0;
So that's totally normal you only get 0.
You should use :
public void keyTyped(KeyEvent e) {
System.out.println("TYPED: " + e.getKeyChar());
}
Here's an example using the three methods.

For KEY_TYPED event, the Key Code is undefined. Check the java docs:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()
Use getKeyChar() instead.

Related

Get caret position when key pressed using KeyboardFocusManager

I'm trying to get the current caret position when the "<" character is typed, using a KeyboardFocusManager. Code below. If the text field is empty when they character is typed I would expect the caret position to be 0. However, the result I actually get is this: 0 0 1. Could anyone explain why this is happening?
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TextEditor {
#SuppressWarnings("serial")
public static class TextClass extends JTextArea {
static int startpos = 0;
public boolean checkKeyTyped (KeyEvent e) {
String keystr = Character.toString(e.getKeyChar());
switch (keystr) {
case "<":
startpos = getSelectionStart();
System.out.print(" " + startpos);
}
return false;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
final JTextArea textArea = new TextClass();
frame.add(textArea);
frame.setVisible(true);
// Add keyboard listener
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
return ((TextClass) textArea).checkKeyTyped(e);
}
});
}
}
You are using a general Key Event dispatcher. The possible events are KEY_PRESSED, KEY_TYPED and KEY_RELEASED. Based on what you say, you need KEY_TYPED. So filter for that:
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEY_TYPED) {
return ((TextClass) textArea).checkKeyTyped(e);
}
}
});
It is not how you are supposed to do it, you are supposed to implement a KeyListener and add it to your JTextArea using addKeyListener(KeyListener), as next:
final JTextArea textArea = new TextClass();
...
textArea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(final KeyEvent e) {
char key = e.getKeyChar();
switch (key) {
case '<':
System.out.print(" " + textArea.getSelectionStart());
}
}
#Override
public void keyPressed(final KeyEvent e) {
}
#Override
public void keyReleased(final KeyEvent e) {
}
});
Up to now, you get it printed 3 times because your method is called for each type of KeyEvent that is triggered whenever you type on a key:
KEY_TYPED
The "key typed" event. This event is generated when a character is
entered. In the simplest case, it is produced by a single key press.
Often, however, characters are produced by series of key presses, and
the mapping from key pressed events to key typed events may be
many-to-one or many-to-many.
KEY_PRESSED
The "key pressed" event. This event is generated when a key is pushed
down.
KEY_RELEASED
The "key released" event. This event is generated when a key is let
up.

How can i get unique key code for character key

The default listner has only character value for character keys, and code for all of them is VK_UNDEFINED, but this make difference between characters and system keys processing.
How to handle all keys with one method, independently of its type?
This is a problem, because I try to save key in a text file, so I need to check if there is a code or a character to parse this file back.
It works for me:
import java.awt.event.*;
import javax.swing.*;
class TestKeyCode implements KeyListener {
public void keyPressed(KeyEvent e)
{
System.out.println("keyPressed(KeyEvent e)");
int code= e.getKeyCode();
System.out.println("code = " + code);
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setSize(800, 800);
TestKeyCode tkc = new TestKeyCode();
jf.addKeyListener(tkc);
jf.setVisible(true);
}
}

Java How to get ascii char from key code

I want to get ascii char from each key that user inputs into JComponent.
<JComponentName>.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char ch = getAsciiCharFromKeyCode(e.getKeyCode());
}
});
private char getAsciiCharFromKeyCode(int keyCode) {
// this implementation is what I'm interested in
}
When I press 'e' (English 'e') and 'у' (Cyrillic 'u'), I get the same key code (0x45 or KeyEvent.VK_E). Is there some way to implement getAsciiCharFromKeyCode function without writing my own hash map like this:
HashMap<Integer, Character> keyCodeToChar = new HashMap<Integer, Character>();
keyCodeToChar.put(KeyEvent.VK_E, 'e');
?
As Pshermo already mentioned the method you are looking for is e.getKeyChar() however, it is only meaningfull in the method keyTyped as explained here
Your code would modified look like this:
<JComponentName>.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char ch = e.getKeyChar();
}
});
Check out the tutorial Oracle: How to Write a Key Listener for more information on how to use KeyEvent to grab key info.
Oracle says:
For key-typed events you can obtain the key character value as well as any modifiers used.
Note:
You should not rely on the key character value returned from getKeyChar unless it is involved in a key-typed event.
You may need to set the locale to accept language specific keyboard characters.
class MyFrame extends JFrame {
private JTextArea txtara;
private JLabel lbl;
public MyFrame() {
super();
this.getContentPane().setLayout();
this.getInputContext().selectInputMethod(new Locale("ru")); // Russian
txtara = new JTextArea(5, 20);
lbl = new JLabel("Key: ");
txtara.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
lbl.setText("Key: " + e.getKeyChar()); // Show typed character
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
};
this.getContentPane().add(txtara, BorderLayout.CENTER);
this.getContentPane().add(lbl, BorderLayout.SOUTH);
}
}
Disclaimer: This code has not been compiled...

Java is not picking up keypresses?

I have a program which produces a JFrame and then a JPanel on top of it. For the program, I have tried implementing the KeyListener and then adding the methods (for both components), but the program does not pick any of my key strokes up. What am I doing wrong?
EDIT
This is my code. It is a part of the class which creates the JFrame. It still does not pick up the press of the ESC key.
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_ESCAPE){
System.out.println("Hi");
}else{
System.out.println("Hello");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
Without your code, all I can tell you is that usually when people ask this they don't know that the interface KeyListener contain three methods as Agusti-N states in their answer here:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
If you use keyTyped and you are using event.getKeyCode() to check for the character entered, this will not work. You should use getKeyChar() for keyTyped and getKeyCode() for keyPressed and keyReleased. Otherwise you'll get null.
You should only use this if you do not have any other alternative, in most cases you want to use Key Bindings.

JApplet - alphabet will not allowed

this is my code, which is written inside my applet
KeyListener keyListener = new KeyListener()
{
public void keyPressed(KeyEvent keyEvent)
{
validate valid=new validate();
valid.errorMessage(txt_district_id, keyEvent);
}
public void keyReleased(KeyEvent keyEvent)
{
}
public void keyTyped(KeyEvent keyEvent)
{
}
};
txt_district_id.addKeyListener(keyListener);
and code of validate class is
public class validate
{
public String errorMessage(KeyEvent keyEvent,JTextField txt)
{
int keyCode = keyEvent.getKeyCode();
String keyText = KeyEvent.getKeyText(keyCode);
//msg.setText(title + " : " + keyText + " / " + keyEvent.getKeyChar());
if(keyCode > 47 && keyCode < 58)
{
txt.setEditable(true);
}
else
{
txt.setEditable(false);
return "Only Numeric Value Accepted";
}
}
}
everything working properly, but the problem is whenever user input any alphabet the textfield will become disable, and that is my problem. I mean it should like, alphabet can not be entered and textfield should be enabled in any case. Thanks in advance.!!
Use DocumentListener for listening changes inside JTextComponents,
Don't use KeyListener, this Listener is designated for prehistoric AWT Components, for Swing JComponents (JApplet) use KeyBindings

Categories