Java getInputMap() for the enter key on numpad - java

So in my calculator program, I would like to set up the equals operation where it the mathematical problem could be computed by pressing the enter key (on the main keyboard) or by pressing the enter key (on the numpad). I know the numbers are VK_NUMPAD0 - VK_NUMPAD9, VK_ADD, VK_SUBTRACT, VK_MULTIPLY, VK_DIVIDE. However I can't seem to find one for the enter key. VK_ENTER is for the keyboards enter key. I also looked at KeyEvent.KEY_LOCATION_NUMPAD, but not sure how to add it to my code to get it to work. I have a method called SetupKeyInput() that takes some parameters that adds the key bindings for the inputmap and actionmap.
private void SetupKeyInput(JButton component, int keyStroke, int mask) {
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyStroke, mask), "hmm");
component.getActionMap().put("hmm", new MyButtonEvents(component));
}
So, I can call the function like this
SetupKeyInput(buttonEquals, KeyEvent.VK_ENTER, 0); // Only works for keyboard enter
What am i missing for the numpad enter? I also tried this
SetupKeyInput(buttonEquals, KeyEvent.VK_ENTER, KeyEvent.KEY_LOCATION_NUMPAD);

Related

Java Swing: KeyBinding for KEY_TYPED event

I've been trying to learn keybinds by rewriting problems from my book that I've previously solved using KeyListener. The problem that I'm struggling to solve using keybinds requires me to record a message that's been typed and to display it on the panel.
The way it was solved using KeyListener is simply by recording characters with unicodes using the keyTyped() method and reading modifier/non-Unicode keys with keyPressed. If KeyEvent.VK_ENTER matches the keycode from the keyevent, then it displays the string on the panel.
~~~~~~~~
I thought that it can be solved in a similar way with KeyBinds. It says in the KeyEvent docs that KeyEvent.KEY_TYPED is fired every time a character is entered. I assumed that it meant every character with a corresponding Unicode being typed like how it works in KeyListener.
Later on, I realized that I have no idea how to retrieve the character since the Oracle tutorial on KeyBinds says that the KeyEvent is consumed when actionPerformed() is invoked.
This is the code that I THOUGHT would enable me to record typed keys to a StringBuilder using KeyBindings:
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.KEY_TYPED, 0), "recordTypedKey");
getActionMap().put("recordTypedKey", addCharToString);
Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?
Is there a way to obtain the characters that would invoke KeyListener's keyTyped() method besides adding a key to every one of them and using a separate Action event to record them?
I do not believe there is a global KeyStroke you can pass to the InputMap that will work similar to a KeyListener, as KeyBindings work on an individual key basis. You can however create a single Action and bind keys to it by looping over the char values you wish to process - in the ActionListener implementation you can obtain the value of the key via getActionCommand. For example to deal with a-z:
AbstractAction action = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
//loop over the ascii char values
for ( char a = 'A'; a <= 'Z'; a++ ){
panel.getInputMap().put(KeyStroke.getKeyStroke(Character.toString(a)), "recordTypedKey");
}
panel.getActionMap().put("recordTypedKey", action);
You can add modifiers if needed...for example to deal with the shift key (eg upper case),
panel.getInputMap().put(KeyStroke.getKeyStroke("shift " + Character.toString(a)), "recordTypedKey");

Key listener java - number limitation

I've got an app in JFrame. Here is part of the code:
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = text.getText();
int number = Integer.parseInt(text.getText());
if(number>0)
{
for(int i=0; i<liczba; i++)
{
new NewWindow();
}
}
}
});
This action creates new windows in app where number of windows depend on number we've inputted. I need to make sure it IS a number (not a letter or something). I also know the key listener must be used and the symbol inputted has to be between some values of ASCII which represent numbers. But I don't know how to do this exackly. Any solutions?
I also know the key listener must be used
No a KeyListener does not need to be used. That is probably the oldest solution and was used in AWT. Swing has newer and better API's which you should be using.
You could use a JSpinner, JFormattedTextField or a DocumentFilter.
Read the Swing Tutorial. You should check out sections on:
How to Use a Spinner
How to use Formatted Text Fields
How to Write a DocumentFilter
Any one of the above is a better solution than using a KeyListener.

Checking JTextField Characters

I have a program I've written for my kids to practice basic arithmetic. There is a JTextField on a JFrame where the student keys in the answer to a given math problem (like 8+8, they key in 16, Enter). This field accepts only integer values as entries by way of a DocumentFilter.
That part works just fine. What I want to do with this is to avoid having the user have to hit the enter key. Ideally, when the user keys in the first number (1), a check is done to see if 1 == 16. If not, nothing happens. When they subsequently type the 6, the text field displays the number 16. I want to run a check to verify if 16 == 16, and then handle the entry as if the user had also hit the Enter key.
txtAnswer.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
respondToAnswer(isTimed);
} else {
/* Check if the correct answer has been entered */
System.out.println(txtAnswer.getText());
//int userAnswer = Integer.parseInt(txtAnswer.getText());
//if (userAnswer == correctAnswer {
// respondToAnswer(isTimed);
//}
}
};
});
This code isn't quite working. It's as if it is one character behind. What I mean by that is when the user hits the '1' key (in my 8+8=16 example), the console output is an empty string. When they hit the '6' key, the output is '1'. If they then hit another integer key, the output is '16'. It's always one digit behind. Because of this, I cannot capture the entire contents of the text field to see if it matches the correct answer.
Anyone see what I am missing?
Thanks!
Use a DocumentListener for that instead of a KeyListener. In all three events, you will have access to the actual text content.
To listen for the Enter on JTextField, us an ActionListener
Side note: you should almost never need a KeyListener. On JTextComponent, always rely on a DocumentListener. For all the others, use appropriate Swing Key bindings. KeyListener is really a low level API.
You should use DocumentListener for this purpose. keyPressed is probably fired before the text in the field is updated.
See How to Write a Document Listener for details and examples.

Get string of the keyboard key

Is there any way to get the String text representation of a keyboard key?
Examples:
Input: User presses Shift
Output: "Shift"
Input: User presses F1
Output: "F1"
Input: User presses Left arrow key
Output: "Left Arrow"
Im using a keylistener in order to get the key strokes by the way
Closest to this is KeyEvent.getKeyText: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html#getKeyText(int)
I say closest to because there are some platform-specific differences in implementation on certain keys

Java/AWT/Swing: how to distinguish the pressed enter or return key

It looks like native applications behave differently if the user presses the Return key (right to the characters) or the Enter key (number key pad) - one time a new line character is inserted, the other time the default button is activated.
How I can distinguish both key presses from Java/AWT/Swing?
keyEvent.getKeyLocation() == KeyEvent.KEY_LOCATION_NUMPAD

Categories

Resources