Pressed button as a hotkey - java

I'm trying to make something like hotkey textbox. User presses F11 / Caps lock / any key and it appears in the box.
I did it this way:
#Override
public void keyPressed(KeyEvent e) {
textField_1.setText(String.valueOf(e.getKeyChar()));
}
but it doesn't work for the Fs, caps lock etc. (what is obvious, because those aren't chars).
How can I deal with this problem?

You can use:
event.getKeyCode();
But in general you should probably use Key Bindings.
As Agusti-N states in his answer:
The interface KeyListener contain three methods:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
If you use keyPressed and you are using event.getKeyChar() 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.
As stated in the javadoc.

You probably want to use e.getKeyText() instead of e.getKeyChar() that will return F1 if the F1 key is presed. Here is the API description:
getKeyText
public static String getKeyText(int keyCode)
Returns a String describing the keyCode, such as "HOME", "F1" or "A".
These strings can be localized by changing the awt.properties file.
Returns: a string containing a text description for a physical key, identified by its keyCode
-- http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyText(int)
Alternatively:
You could also use e.getKeyCode that will give you the key codes for the various key events identified their corresponding constant values. For instance, e.getKeyCode will return 112 as the value for a key press for F1, which can be accessed by the constant VK_F1. Following is the API Description:
getKeyCode
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.)
-- http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyCode()
And here are the listings for the Key Constants: http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.awt.event.KeyEvent.CHAR_UNDEFINED

Related

Distinguishing left and right shift keys in Processing 3

Alright, I'll say in advance I'm aware this isn't a new concept... But no matter what I research nothing seems to work. Basically, I want to be able to sense every key on my keyboard including the different shift/ctrl/alt/enter keys. Every key besides these returns a unique keyCode which is good, but I can't seem to distinguish these duplicates.
Without any modifications, the void keyPressed () will work just fine. I'm told that to distinguish the duplicate keys I can import java.awt.event.KeyEvent; and then use
void keyPressed (KeyEvent e) {
if (keyCode == SHIFT) {
int location = e.getKeyLocation ();
if (location == KEY_LOCATION_RIGHT) {
RShift = true;
}
if (location == KEY_LOCATION_LEFT) {
LShift = true;
}
}
}
However, some problems arise with this:
If I import the library, keyPressed () never gets called at all.
If I import the library but take out the KeyEvent parameter in keyPressed () it works as long as I comment out any reference to the nonexistent KeyEvent e.
If I DON'T import it and leave the parameter it just complains that getKeyLocation () doesn't exist, but that's it.
Do I need like a reverse override or something?? Help is much appreciated!
P.S. Another related question, how can I distinguish more than left, center, and right mouse buttons? I can get these and the scrollwheel but any other button just returns a mouseButton code of 0. Suggestions? Thanks!
https://processing.org/reference/keyPressed_.html
The keyPressed() function is called once every time a key is pressed. The key that was pressed is stored in the key variable.
if you want to override keyPressed you must use the same signature so no parameters, in the method you can reference the key variable of the PApplet
like this i believe
void keyPressed ()
**int location = key
edit: int location = keyEvent

How do I check if the left angle bracket key is pressed?

In Java, I have checked the list of Virtual Key Codes, and there is not a VK for '<'. I have tried "VK_LESS" with my program (which sounds like it could be '<'), but that did not work either.
I am wondering if I have to check to see if the Shift key is pressed down, and then check to see if the Comma key is also pressed down, but I am not sure how to do that in a KeyHandler class, using a switch statement for the keyPressed method.
The KeyHandler keyPressed method will receive a KeyEvent. You can call isShiftDown() on that KeyEvent to see if the shift key is currently pressed.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_COMMA && e.isShiftDown()) {
// do your thing!
}
}
You could also try doing:
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '<') {
...
}
}
Note the use of keyTyped rather than keyPressed. keyTyped triggers only when a key press outputs a character, rather than on every key press. This method would be more likely to work for other types of keyboard. But I haven't tried it, so I don't know if it would work at all.
I believe you'd want to use VK_LESS and VK_GREATER for "<" and ">", respectively.
You can use KeyEvents.getKeyChar() method
public void keyPressed(KeyEvent e) {
if (evt.getKeyChar().equals("<")) {
/*your code*/
}
}

Remove Enter key binding in JTable

What is the simplest and fastest way to remove the standard enter key bindings (pressing enter selects the next row) in a JTable?
That's what I tried
table.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), null);
But it doesn't work. I assume that we have to do that somehow for each cell and not the table itself.
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT and JComponent.WHEN_IN_FOCUSED_WINDOW have a value for the enter keystroke. So you want to get both of them
Correction: You need to get the InputMap for WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
InputMap iMap1 =
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
//InputMap iMap2 =
// table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
Then you want to set the value for the map to "none", instead of null, as described in How to Use Key Bindings.
To make a component ignore a key that it normally responds to, you can use the special action name "none". For example, the following code makes a component ignore the F2 key.
component.getInputMap().put(KeyStroke.getKeyStroke("F2"), "none");
So just do:
KeyStroke stroke = KeyStroke.getKeyStroke("ENTER");
iMap1.put(stroke, "none");
//iMap2.put(stroke, "none");
Also note when you just do getInputMap() without any arguments, it's basically the same thing as getInputMap(JComponent.WHEN_FOCUSED). And in the case of JTable, there's no value for the enter keystroke for that InputMap.
Read more at How to Use Key Bindings. You'll get a better explanation of the different InputMaps
UPDATE : Correction (corrections made above either struck through or // commented out)
You only to set it for the InputMap for JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
UPDATE per the OP comment: Yes in short
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.‌​getKeyStroke("ENTER"), "none");
This seems to be the most convenient way:
table.registerKeyboardAction(
null,
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
);
To assign an action replace null with ActionListener call or with e -> someMethod() for JDK 1.8
Update:
David Kroukamp solution:
private void createKeybindings(JTable table) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {}
});
}
And for you should be enough:
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter",null);
I dont know if it is possible to use null, you could use anonymous class instead...

Key Bindings Fire Multiple Times when Holding Key

I'm following this guide to get key binding to work in my application. So far, the key bindings fire successfully, when I press a key. What I expect to happen is when I bind one action to a key pressed event and another action to a key released event, it will fire the first action when the key is pressed down and the second action when the key is released. What actually happens when I hold down a key is both actions get called multiple times. What can I do to achieve my desired behavior?
Here's how I'm implementing the key bindings:
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("pressed UP"), "pressedUP");
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released UP"), "releasedUP");
Action pressedUpAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Pressed UP");
}
};
Action releasedUpAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Released UP");
}
};
component.getActionMap().put("pressedUP", pressedUpAction);
component.getActionMap().put("releasedUP", releasedUpAction);
When I run the program, the output I actually get when I hold down the up key is Pressed UP, a slight pause, and then multiple Pressed UP values. When I release the up key, I get a Released UP message. The entire output looks like this:
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Released UP
The really weird thing is if I replace UP with a keyboard letter key, such as P, everything works as I expect it to.
use Boolean value inside Swing Action when once times fired events then change Boolean from false to true or vice versa
I'm sorry nobody knows how did you implemented KeyBindings, post an SSCCE

Java Swing - KeyListener

How can I know when the key typed change my text? Or if the key is a char?
The interface KeyListener contain three methods:
void keyTyped(KeyEvent)
void keyPressed(KeyEvent)
void keyReleased(KeyEvent)
So, if you get the char in the KeyEvent object like:
if ("a".equals(KeyEvent.getKeyChar()))
System.out.println("It's a letter")
i guess you want to know wether typing a specific key actually prints a char or is some "invisible" control character or something:
in this case you can check the typed key in the KeyEvent which gets passed into the implemented methods of the KeyListener:
this quick example should work, although i didnt test it. It constructs a new String on the char returned by the KeyEvent, than invokes the length() method to chekc if the char created a readable character in the String. kinda hacky but i hope you get the gist of it
public void keyReleased(KeyEvent ke){
if (new String(ke.getKeyChar()).length() == 0){
// do something important...
}
}
alternativley you can use ke.getKeyCode() and check vs the static fields in KeyEvent (VK_F12,VK_ENTER...)
check here:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html
You need a document listener. See the oracle docs for more information: How to Write a Document Listener

Categories