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
Related
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*/
}
}
I'm a beginner in Java programming & I am making an application requiring an object to move around a grid filled with squares.
The object should only move one square at a time and if the user wants to move into another square, they must press the key again. My move method is the following:
public void move() {
x += dx;
y += dy;
}
I am using the KeyListener interface to implement the keyPressed, keyTyped and keyReleased methods and I have conditions like the one in the fragment below inside KeyPressed
//KeyPressed
int c = e.getKeyCode();
if (c == KeyEvent.VK_UP) {
player.setDy(-5);
}
This allows the object to move freely. However, it will clearly continue to move as long as the UP arrow is pressed.
Is there any way to have to object move up by say -5 once and then stop even if the key is still pressed?
I am unsure whether I need to change my move method or the KeyListener methods to do this.
I hope that I have been clear enough as to what I'm asking and I'd highly appreciate any pointers.
first of all : you should use Synchronization if you call class-methods from within listeners like keyPressed or keyReleased - thats because your listener-method can be called from multiple threads so your class-method (player.setDy()) can (and will) be called in parallel - you will need to make sure that each call to setDy happens before the next one.
Also : keyTyped is much better in many cases : https://stackoverflow.com/a/7071810/351861
An example could look like this:
public void keyTyped(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_UP)
{
synchronized(player)
{
player.setDy(-5);
}
}
}
this will call setDy sequentially and reliably. Now all you need to do is to make sure that setDy works as intended, hence sets the position only once
easiest would be to add a boolean to indicate, that a moving key is pressed
class member : boolean movingKeyPressed = false
in key pressed :
if (movingKeyPressed) {
return;
} else {
// do stuff
movingKeyPressed = true;
}
in key released method :
movingKeyPressed = false;
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
I am trying to create a Tanks game but am still learning how to do graphics programming in Java. I had initially tried moving one of two images (which one depends on which player is going) with KeyListeners. I was told that Key Bindings might be a more effective way of going about this. Here is some of my code:
public class FrameMain extends JFrame{
...
public FrameMain(){
this.addBindings();
The addBindings() method:
protected void addBindings() {
InputMap inputMap = pnlPlay.getInputMap();
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.KEY_PRESS);
inputMap.put(key, pnlPlay.pnlGame.MoveTank(2, pnlPlay.nPlayer));
key = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.KEY_PRESS);
inputMap.put(key, pnlPlay.pnlGame.MoveTank(-2, pnlPlay.nPlayer));
}
The MoveTank method:
public int MoveTank(int xChange, int nPlayer){
System.out.println("move "+nPlayer);
if(nPlayer==0){
tank1.x+=xChange;
}else tank2.x+=xChange;
repaint();
return 1;
}
The problem I'm having is that, when I press either the right or left arrow key, I am not getting any kind of response. It should be printing "move #" but it's not. If anyone knows what I have done wrong or could point me in the direction of some code that does the same thing I would appreciate it. I learn best from seeing the code in working order and then playing around with it.
Two things with this code:
I do not see anything about the action map. The input map maps a key to an action identifier, and the action map is the link between the identifier and the actual action. So you normally have code like
InputMap inputMap = component.getInputMap( );
ActionMap actionMap = component.getActionMap();
Action actionToTrigger = ...;
actionMap.put( "myAction", actionToTrigger );
inputMap.put( key, "myAction" );
If putting your action in the action map with the correct identifier and it still does not work, you might have been using the wrong input map. There are 3 different input maps as explained in the Swing keybindings guide. Try with the others
Perhaps you should consult the Swing keybindings tutorial again as it explains all this in more detail + contains code examples
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