I created a simple JavaFX application that receives input from the user in a TextField. I attached the KeyTyped event from SceneBuilder to the controller. My function looks like this:
#FXML private void keyTyped(KeyEvent event) {
System.out.println(event.getCode().equals(KeyCode.ENTER));
}
This function always prints out UNDEFINED when I type the enter key. Any ideas on how to fix this? Other letters I type seem to have the same problem as well.
KeyTyped is a special event. It doesn't have KeyCode but has character set instead.
See example for letter 'a':
KeyEvent [source = TextField[id=null, styleClass=text-input text-field],
target = TextField[id=null, styleClass=text-input text-field], eventType = KEY_TYPED, consumed = false,
character = a, text = , code = UNDEFINED]
and javadoc: http://docs.oracle.com/javafx/2/api/javafx/scene/input/KeyEvent.html#getCode()
The key code associated with the key in this key pressed or key
released event. For key typed events, code is always
KeyCode.UNDEFINED.
Related
The following is code block, where i have been trying to validate jFormatedTextFeild. When a key is typed (any key) code block does seem to execute for the first key typed. But works fine for second key typed ! Please help me :(
private void jFormattedTextField_ByingPriceKeyTyped(KeyEvent evt) {
System.out.println("key typed action ");
String checking = jFormattedTextField_ByingPrice.getText();
Pattern ptrn = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher match = ptrn.matcher(checking);
if(match.find()){
txtPriceMessage.setVisible(true);
//text field which contains the message does not appears
//for first key typed only it appears when second key is typed.
} else {
txtPriceMessage.setVisible(false);
}
}
Use a DocumentFilter to filter the values going to a text component in real time, that's what it's design for. Take a look at these examples, there's even a PatternFilter for using with regular expressions...
For post validation, use a InputVerifier
I have a piece of code that allows me to capture keystroke and print them with a System.out.println. My problem is that when I try to use it with ctrl (e.g. ctrl + m) it removes the KeyChar attribute of the m key. Does anyone know why this happen and how I can solve it?
public TestForm() {
initComponents();
KeyEventDispatcher keyEventDispatcher = new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(final KeyEvent e)
{
if (e.getID() == KeyEvent.KEY_PRESSED && e.isAltDown())
{
System.out.println("ALT + "+e.getKeyChar());
}
else if (e.getID() == KeyEvent.KEY_PRESSED && e.isShiftDown())
{
System.out.println("SHIFT + "+e.getKeyChar());
}
else if (e.getID() == KeyEvent.KEY_PRESSED && e.isControlDown())
{
System.out.println("CTRL + "+e.getKeyChar()/*+"\n"+e*/);
}
else
{
System.out.println(e);
}
return true;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatcher)
;
}
I'm quite new to java so it might be something simple im missing. Thanks in advance
There is an important difference between key code and key char. A key code represents a key on a keyboard. A key char represents a letter in some alphabet. There is a ctrl key on your keyboard but there is no letter in any alphabet (e.g. no unicode character) for ctrl. So when the ctrl key is pressed you get a KEY_PRESSED event with a key code but no key char.
Not all hope is lost though. It looks like you are trying to detect when CTRL and some character is pressed (e.g. if I type ctrl+A instead of just A). The problem is that you are looking at KEY_PRESSED events. In Java there is an important distinction between the KEY_PRESSED event and the KEY_TYPED event.
For exmaple, if I were to press Ctrl+A on my keyboard I would first press down the Ctrl key, then press down the A key, then release them more or less at the same time. In my mind I think of this as one action, but it's not. What happens in Java is you get:
KEY_PRESSED (keyCode = VK_CTRL, keyChar = CHAR_UNDEFINED) //I press down Ctrl key
KEY_PRESSED (keyCode = VK_A, keyChar = CHAR_UNDEFINED) //I press down the a key
KEY_TYPED (keyCode = VK_UNDEFINED, keyChar = 'A') //The 'typing' of the letter 'A'
//some key released events that are not relevant to this discussion
As you can see, a KEY_PRESSED event has a key code but no key char (this is fired when a key on the keyboard is pressed down). A KEY_TYPED event has a key char but not key code (this represents the completion of a key sequence resulting in a letter).
All of this is documented in detail on the javadocs for the KeyEvent page.
I have field in which only Alphanumeric values are allowed. I need to check a scenario where user could enter capital letter using "shift" key (OKAY)
SHIFT+a =A
Also a possibility junk characters can be entered using "shift" key (NOT OKAY), like
SHIFT+1 = !
How do I put a validation in a way that only characters are allowed if "SHIFT" key is pressed?
if(NativeEvent.getShiftKey()){
...........
}
If you want to detect pressed keys, you can use a KeyUpHandler or KeyDownHandler.
TextBox t = new TextBox();
t.addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
int pressedKey = event.getNativeKeyCode();
}
});
You can use the "pressedKey" integer to see what key code user pressed. Also interesting is KeyCodes, which has the codes for special keys.
If you want to validate user input instead, the easiest way is with HTML5 form validation. To implement that method, you can set up your field like this:
TextBox t = new TextBox();
t.getElement().setAttribute("required", "required");
t.getElement().setAttribute("pattern", "[a-zA-Z0-9]+");
Here's another resource for HTML5 form validation. And another.
I'm trying to use the Robot class in Java and type some text. Unfortunately I'm having problems finding the key codes of the square brackets, this symbol | and this symbol `. I can't find them in the KeyEvent constants. I want to use them, because the text i'm typing is in cyrillic and these symbols represent characters in the alphabet. Thanks in advance.
It's in the JavaDoc for KeyEvent
KeyEvent.VK_OPEN_BRACKET
and
KeyEvent.VK_CLOSE_BRACKET
Edit
From the KeyEvent JavaDoc
This low-level event is generated by a component object (such as a
text field) when a key is pressed, released, or typed.
So on a US 101-key keyboard, the ` and ~ will produce the same keycode, although ~ will have a SHIFT modifier. Also notice that KeyEvent.VK_BACK_SLASH traps the | (pipe) keystroke too.
Try adding the following sample KeyAdapter to your project to see this in action.
new KeyAdapter()
{
public void keyPressed(final KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_BACK_QUOTE)
{
e.toString();
}
if (e.getKeyCode() == KeyEvent.VK_BACK_SLASH)
{
e.toString();
}
if (e.getKeyCode() == KeyEvent.VK_OPEN_BRACKET)
{
e.toString();
}
}
}
The general solution is to call KeyEvent.getExtendedKeyCodeForChar(int c). If the unicode codepoint c has a VK_ constant that will be returned. Otherwise a "unique integer" is returned.
I think that '`' is KeyEvent.VK_BACK_QUOTE ...
I am facing a problem in implementing Input method for Virtual Keyboard. Currently I am using robot class for sending input to any application from virtual keyboard. But for that I need to create mapping of key-code and unicode, which is not consistent on different keyboard layout, can I directly pass the UNICODE to any application using Input method without worry about mapping between keycode and unicode.
Any useful link or sample code will be useful.
It is a simple Java program which is always on top of any application and work as onscreen keyboard. Using a mouse while you press any button (key) of the keyboard, the corresponding character will be typed in the application running below. This is working perfectly for English Alphabets. I am facing problem while I am doing for unicode.
find the code snippet below
public static void simulateKeyEvent(char key){
try{
AWTKeyStroke awtKS = AWTKeyStroke.getAWTKeyStroke(key);
int key_code = awtKS.getKeyCode();
System.out.println("key = "+key+" keyCode = "+key_code);
robot.keyPress(key_code);
robot.keyRelease(key_code);
}catch(Exception e){
e.printStackTrace();
}
}
How I sovled it:
//on startup: override the SystemEventQueue
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
final OwnEventQueue newEventQueue = new OwnEventQueue();
eventQueue.push(newEventQueue);
//because dispatchEvent is protected
public class OwnEventQueue {
private final static OwnEventQueue instance;
static{
instance = new OwnEventQueue();
}
#Override
public void dispatchEvent(AWTEvent event) {
super.dispatchEvent(event);
}
public static OwnEventQueue getInstance() {
return instance;
}
}
//then onpress of keyboard button
Character character = getCharacter();
int[] events = {KeyEvent.KEY_PRESSED, KeyEvent.KEY_RELEASED, KeyEvent.KEY_TYPED};
for (int i = 0; i < events.length; i++) {
KeyEvent pressKeyEvent = new KeyEvent(focusComponent, events[i], System.currentTimeMillis(), 0, 0, character.charValue());
OwnEventQueue.getInstance().dispatchEvent(pressKeyEvent);
}
robotKeystrokeSender.keyPress(KeyEvent.VK_RIGHT);
robotKeystrokeSender.delay(10);
robotKeystrokeSender.keyRelease(KeyEvent.VK_RIGHT);
Is your virtual keyboard used as a device by your OS ?
Or, in other words, have you tried considering it as a "real" keyboard ?
According to Java hardware abstraction, were your virtual keyboard to be considered as a driver, it should simply work like a real keyboard.
EDIT : according to comment, this is not a virtual device, but a Java application, as a consequence, probleme is different.
According to Javadoc, Robot can send key strokes given as int. To create those key strokes from characters, I would recommand you create them using getKeystroke(char) before to transform them into integer values using getKeycode(). This way, you would have integer values associatesd your unicode characters, whichever they are.
EDIT 2 : once again, a modification ;-)
it seems like getKeyStroke(String) "should" handle unicode characters.