Poll for pressed buttons in Java - java

I have a WorldWind application build based on the Java SDK. It has a great event handler for detecting when you click on objects, but I've run into a snag. While I can click on and select individual objects, I can't determine if the user is pressing the control key while they click (if they want to select multiple objects). I can implement event handlers for both the mouse and the keyboard, but I can't for the life of me figure out how to tie the two together. How could I make my mouse listener poll the system for a list of currently depressed keys?

You can call getModifiers() and bitwise compare to see if the control key (or shift key was depressed during the event.
public void mouseClicked( MouseEvent e ) {
if( ( e.getModifiers() & ActionEvent.CTRL_MASK ) > 0 ) {
// Control key depressed
}
}

For a MouseEvent , you could just call the getModifiers() to get a mask of modifier keys(shift/control/alt etc.) keys that are pressed .
For the general case, use a variable to tie them together ?
Your keyhandler sets/clears the variable when it registers a keypress, your mouselistener checks that variable.
If you need to decople these a bit more, just create a instance that both your key listener and mouselistener accesses.
public class Pressedkeys {
private boolean shiftPressed = false;
private boolean controlPressed = false;
public void setShiftPressed(boolean pressed) {
this.shiftPressed = pressed;
}
public void setControlPressed (boolean pressed) {
this.shiftPressed = pressed;
}
public boolean isControlPresed() {
return controlPressed ;
}
...
}
Pressedkeys k = new PressedKeys();
MyMouseThing t = new MyMouseThing(k);
//your mousething mouse handler would check k.isControlPressed();
MyKeyboardThing t = new MyKeyboardThing (k);
//your KeyBoardThing - which has a key handler would set k.setControlPressed(..);

Related

ImageJ actionmap [duplicate]

I'm using KeyListeners in my code (game or otherwise) as the way for my on-screen objects to react to user key input. Here is my code:
public class MyGame extends JFrame {
static int up = KeyEvent.VK_UP;
static int right = KeyEvent.VK_RIGHT;
static int down = KeyEvent.VK_DOWN;
static int left = KeyEvent.VK_LEFT;
static int fire = KeyEvent.VK_Q;
public MyGame() {
// Do all the layout management and what not...
JLabel obj1 = new JLabel();
JLabel obj2 = new JLabel();
obj1.addKeyListener(new MyKeyListener());
obj2.addKeyListener(new MyKeyListener());
add(obj1);
add(obj2);
// Do other GUI things...
}
static void move(int direction, Object source) {
// do something
}
static void fire(Object source) {
// do something
}
static void rebindKey(int newKey, String oldKey) {
// Depends on your GUI implementation.
// Detecting the new key by a KeyListener is the way to go this time.
if (oldKey.equals("up"))
up = newKey;
if (oldKey.equals("down"))
down = newKey;
// ...
}
public static void main(String[] args) {
new MyGame();
}
private static class MyKeyListener extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
Object source = e.getSource();
int action = e.getExtendedKeyCode();
/* Will not work if you want to allow rebinding keys since case variables must be constants.
switch (action) {
case up:
move(1, source);
case right:
move(2, source);
case down:
move(3, source);
case left:
move(4, source);
case fire:
fire(source);
...
}
*/
if (action == up)
move(1, source);
else if (action == right)
move(2, source);
else if (action == down)
move(3, source);
else if (action == left)
move(4, source);
else if (action == fire)
fire(source);
}
}
}
I have problems with the responsiveness:
I need to click on the object for it to work.
The response I get for pressing one of the keys is not how I wanted it to work - too responsive or too unresponsive.
Why does this happen and how do I fix this?
This answer explains and demonstrates how to use key bindings instead of key listeners for educational purpose. It is not
How to write a game in Java.
How good code writing should look like (e.g. visibility).
The most efficient (performance- or code-wise) way to implement key bindings.
It is
What I would post as an answer to anyone who is having trouble with key listeners.
Answer; Read the Swing tutorial on key bindings.
I don't want to read manuals, tell me why I would want to use key bindings instead of the beautiful code I have already!
Well, the Swing tutorial explains that
Key bindings don't require you to click the component (to give it focus):
Removes unexpected behavior from the user's point of view.
If you have 2 objects, they can't move simultaneously as only 1 of the objects can have the focus at a given time (even if you bind them to different keys).
Key bindings are easier to maintain and manipulate:
Disabling, rebinding, re-assigning user actions is much easier.
The code is easier to read.
OK, you convinced me to try it out. How does it work?
The tutorial has a good section about it. Key bindings involve 2 objects InputMap and ActionMap. InputMap maps a user input to an action name, ActionMap maps an action name to an Action. When the user presses a key, the input map is searched for the key and finds an action name, then the action map is searched for the action name and executes the action.
Looks cumbersome. Why not bind the user input to directly to the action and get rid of the action name? Then you need only one map and not two.
Good question! You will see that this is one of the things that make key bindings more manageable (disable, rebind etc.).
I want you to give me a full working code of this.
No (the Swing tutorial has working examples).
You suck! I hate you!
Here is how to make a single key binding:
myComponent.getInputMap().put("userInput", "myAction");
myComponent.getActionMap().put("myAction", action);
Note that there are 3 InputMaps reacting to different focus states:
myComponent.getInputMap(JComponent.WHEN_FOCUSED);
myComponent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
WHEN_FOCUSED, which is also the one used when no argument is supplied, is used when the component has focus. This is similar to the key listener case.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT is used when a focused component is inside a component which is registered to receive the action. If you have many crew members inside a spaceship and you want the spaceship to continue receiving input while any of the crew members has focus, use this.
WHEN_IN_FOCUSED_WINDOW is used when a component which is registered to receive the action is inside a focused component. If you have many tanks in a focused window and you want all of them to receive input at the same time, use this.
The code presented in the question will look something like this assuming both objects are to be controlled at the same time:
public class MyGame extends JFrame {
private static final int IFW = JComponent.WHEN_IN_FOCUSED_WINDOW;
private static final String MOVE_UP = "move up";
private static final String MOVE_DOWN = "move down";
private static final String FIRE = "move fire";
static JLabel obj1 = new JLabel();
static JLabel obj2 = new JLabel();
public MyGame() {
// Do all the layout management and what not...
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("UP"), MOVE_UP);
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);
// ...
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("control CONTROL"), FIRE);
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("W"), MOVE_UP);
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("S"), MOVE_DOWN);
// ...
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("T"), FIRE);
obj1.getActionMap().put(MOVE_UP, new MoveAction(1, 1));
obj1.getActionMap().put(MOVE_DOWN, new MoveAction(2, 1));
// ...
obj1.getActionMap().put(FIRE, new FireAction(1));
obj2.getActionMap().put(MOVE_UP, new MoveAction(1, 2));
obj2.getActionMap().put(MOVE_DOWN, new MoveAction(2, 2));
// ...
obj2.getActionMap().put(FIRE, new FireAction(2));
// In practice you would probably create your own objects instead of the JLabels.
// Then you can create a convenience method obj.inputMapPut(String ks, String a)
// equivalent to obj.getInputMap(IFW).put(KeyStroke.getKeyStroke(ks), a);
// and something similar for the action map.
add(obj1);
add(obj2);
// Do other GUI things...
}
static void rebindKey(KeyEvent ke, String oldKey) {
// Depends on your GUI implementation.
// Detecting the new key by a KeyListener is the way to go this time.
obj1.getInputMap(IFW).remove(KeyStroke.getKeyStroke(oldKey));
// Removing can also be done by assigning the action name "none".
obj1.getInputMap(IFW).put(KeyStroke.getKeyStrokeForEvent(ke),
obj1.getInputMap(IFW).get(KeyStroke.getKeyStroke(oldKey)));
// You can drop the remove action if you want a secondary key for the action.
}
public static void main(String[] args) {
new MyGame();
}
private class MoveAction extends AbstractAction {
int direction;
int player;
MoveAction(int direction, int player) {
this.direction = direction;
this.player = player;
}
#Override
public void actionPerformed(ActionEvent e) {
// Same as the move method in the question code.
// Player can be detected by e.getSource() instead and call its own move method.
}
}
private class FireAction extends AbstractAction {
int player;
FireAction(int player) {
this.player = player;
}
#Override
public void actionPerformed(ActionEvent e) {
// Same as the fire method in the question code.
// Player can be detected by e.getSource() instead, and call its own fire method.
// If so then remove the constructor.
}
}
}
You can see that separating the input map from the action map allow reusable code and better control of bindings. In addition, you can also control an Action directly if you need the functionality. For example:
FireAction p1Fire = new FireAction(1);
p1Fire.setEnabled(false); // Disable the action (for both players in this case).
See the Action tutorial for more information.
I see that you used 1 action, move, for 4 keys (directions) and 1 action, fire, for 1 key. Why not give each key its own action, or give all keys the same action and sort out what to do inside the action (like in the move case)?
Good point. Technically you can do both, but you have to think what makes sense and what allows for easy management and reusable code. Here I assumed moving is similar for all directions and firing is different, so I chose this approach.
I see a lot of KeyStrokes used, what are those? Are they like a KeyEvent?
Yes, they have a similar function, but are more appropriate for use here. See their API for info and on how to create them.
Questions? Improvements? Suggestions? Leave a comment.
Have a better answer? Post it.
Note: this is not an answer, just a comment with too much code :-)
Getting keyStrokes via getKeyStroke(String) is the correct way - but needs careful reading of the api doc:
modifiers := shift | control | ctrl | meta | alt | altGraph
typedID := typed <typedKey>
typedKey := string of length 1 giving Unicode character.
pressedReleasedID := (pressed | released) key
key := KeyEvent key code name, i.e. the name following "VK_".
The last line should better be exact name, that is case matters: for the down key the exact key code name is VK_DOWN, so the parameter must be "DOWN" (not "Down" or any other variation of upper/lower case letters)
Not entirely intuitive (read: had to dig a bit myself) is getting a KeyStroke to a modifier key. Even with proper spelling, the following will not work:
KeyStroke control = getKeyStroke("CONTROL");
Deeper down in the awt event queue, a keyEvent for a single modifier key is created with itself as modifier. To bind to the control key, you need the stroke:
KeyStroke control = getKeyStroke("ctrl CONTROL");
Here is an easyway that would not require you to read hundreds of lines of code just learn a few lines long trick.
declare a new JLabel and add it to your JFrame (I didn't test it in other components)
private static JLabel listener= new JLabel();
The focus needs to stay on this for the keys to work though.
In constructor :
add(listener);
Use this method:
OLD METHOD:
private void setKeyBinding(String keyString, AbstractAction action) {
listener.getInputMap().put(KeyStroke.getKeyStroke(keyString), keyString);
listener.getActionMap().put(keyString, action);
}
KeyString must be written properly. It is not typesafe and you must consult the official list to learn what is the keyString(it is not an official term) for each button.
NEW METHOD
private void setKeyBinding(int keyCode, AbstractAction action) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_CONTROL:
modifier = InputEvent.CTRL_DOWN_MASK;
break;
case KeyEvent.VK_SHIFT:
modifier = InputEvent.SHIFT_DOWN_MASK;
break;
case KeyEvent.VK_ALT:
modifier = InputEvent.ALT_DOWN_MASK;
break;
}
listener.getInputMap().put(KeyStroke.getKeyStroke(keyCode, modifier), keyCode);
listener.getActionMap().put(keyCode, action);
}
In this new method you can simply set it using KeyEvent.VK_WHATEVER
EXAMPLE CALL:
setKeyBinding(KeyEvent.VK_CONTROL, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ctrl pressed");
}
});
Send an anonymous class (or use subclass) of AbstractAction. Override its public void actionPerformed(ActionEvent e) and make it do whatever you want the key to do.
PROBLEM:
I couldn't get it running for VK_ALT_GRAPH.
case KeyEvent.VK_ALT_GRAPH:
modifier = InputEvent.ALT_GRAPH_DOWN_MASK;
break;
does not make it work for me for some reason.
Here is an example of how to get key bindings working.
(Inside JFrame subclass using extends, which is called by the constructor)
// Create key bindings for controls
private void createKeyBindings(JPanel p) {
InputMap im = p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = p.getActionMap();
im.put(KeyStroke.getKeyStroke("W"), MoveAction.Action.MOVE_UP);
im.put(KeyStroke.getKeyStroke("S"), MoveAction.Action.MOVE_DOWN);
im.put(KeyStroke.getKeyStroke("A"), MoveAction.Action.MOVE_LEFT);
im.put(KeyStroke.getKeyStroke("D"), MoveAction.Action.MOVE_RIGHT);
am.put(MoveAction.Action.MOVE_UP, new MoveAction(this, MoveAction.Action.MOVE_UP));
am.put(MoveAction.Action.MOVE_DOWN, new MoveAction(this, MoveAction.Action.MOVE_DOWN));
am.put(MoveAction.Action.MOVE_LEFT, new MoveAction(this, MoveAction.Action.MOVE_LEFT));
am.put(MoveAction.Action.MOVE_RIGHT, new MoveAction(this, MoveAction.Action.MOVE_RIGHT));
}
Separate class to handle those key bindings created above (where Window is the class that extends from JFrame)
// Handles the key bindings
class MoveAction extends AbstractAction {
enum Action {
MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT;
}
private static final long serialVersionUID = /* Some ID */;
Window window;
Action action;
public MoveAction(Window window, Action action) {
this.window = window;
this.action = action;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (action) {
case MOVE_UP:
/* ... */
break;
case MOVE_DOWN:
/* ... */
break;
case MOVE_LEFT:
/* ... */
break;
case MOVE_RIGHT:
/* ... */
break;
}
}
}

Add mouse event to JMapViewer mapMarker

How can I add mouseListener to a MapMarker (MepMarkerDot or MapMarkerCircle) that makes it like button?
I tried this soloution but it makes whole map clickable (mouse Event works on all the map).
You're on the right path to start with TrashGod's MouseListener solution, but you need to add a little more code, the key part being, that you need to get the Point location of where the user pressed, something the MouseEvent#getPoint() method will tell you, and then based on that information, and the bounds of the "active" area of the component decide whether to respond. Something like:
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint(); // this is where the user pressed
if (isPointValid(p)) {
// do something
}
System.out.println(map.getPosition(e.getPoint()));
}
private boolean isPointValid(Point p) {
// here you have code to decide if the point was pressed in the area of interest.
}
Note that if your code uses Shape derived objects, such as Ellipse2D or Rectangle2D, you can use their contains(Point p) method to easily tell you if the point press was within the Shape or not. Or if there are several locations that you want to check, you may have a collection of Shapes, iterate through them within your mousePressed or (if you have it) isPointValid method, and check containment within the for loop.
I found this nice example:
https://www.programcreek.com/java-api-examples/index.php?source_dir=netention-old1-master/swing/automenta/netention/swing/map/Map2DPanel.java
It has an interface MarkerClickable and its own LabeledMarker which implements MapMarker and MarkerClickable:
public boolean onClick(final Coordinate p, final MouseEvent e) {
for (final MapMarker x : getMap().getMapMarkerList()) {
if (x instanceof MarkerClickable) {
final MarkerClickable mc = (MarkerClickable)x;
final Rectangle a = mc.getClickableArea();
if (a == null)
continue;
if (a.contains(e.getPoint())) {
mc.onClicked(e.getPoint(), e.getButton());
return false;
}
}
}
return true;
}

How to use Key Bindings instead of Key Listeners

I'm using KeyListeners in my code (game or otherwise) as the way for my on-screen objects to react to user key input. Here is my code:
public class MyGame extends JFrame {
static int up = KeyEvent.VK_UP;
static int right = KeyEvent.VK_RIGHT;
static int down = KeyEvent.VK_DOWN;
static int left = KeyEvent.VK_LEFT;
static int fire = KeyEvent.VK_Q;
public MyGame() {
// Do all the layout management and what not...
JLabel obj1 = new JLabel();
JLabel obj2 = new JLabel();
obj1.addKeyListener(new MyKeyListener());
obj2.addKeyListener(new MyKeyListener());
add(obj1);
add(obj2);
// Do other GUI things...
}
static void move(int direction, Object source) {
// do something
}
static void fire(Object source) {
// do something
}
static void rebindKey(int newKey, String oldKey) {
// Depends on your GUI implementation.
// Detecting the new key by a KeyListener is the way to go this time.
if (oldKey.equals("up"))
up = newKey;
if (oldKey.equals("down"))
down = newKey;
// ...
}
public static void main(String[] args) {
new MyGame();
}
private static class MyKeyListener extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
Object source = e.getSource();
int action = e.getExtendedKeyCode();
/* Will not work if you want to allow rebinding keys since case variables must be constants.
switch (action) {
case up:
move(1, source);
case right:
move(2, source);
case down:
move(3, source);
case left:
move(4, source);
case fire:
fire(source);
...
}
*/
if (action == up)
move(1, source);
else if (action == right)
move(2, source);
else if (action == down)
move(3, source);
else if (action == left)
move(4, source);
else if (action == fire)
fire(source);
}
}
}
I have problems with the responsiveness:
I need to click on the object for it to work.
The response I get for pressing one of the keys is not how I wanted it to work - too responsive or too unresponsive.
Why does this happen and how do I fix this?
This answer explains and demonstrates how to use key bindings instead of key listeners for educational purpose. It is not
How to write a game in Java.
How good code writing should look like (e.g. visibility).
The most efficient (performance- or code-wise) way to implement key bindings.
It is
What I would post as an answer to anyone who is having trouble with key listeners.
Answer; Read the Swing tutorial on key bindings.
I don't want to read manuals, tell me why I would want to use key bindings instead of the beautiful code I have already!
Well, the Swing tutorial explains that
Key bindings don't require you to click the component (to give it focus):
Removes unexpected behavior from the user's point of view.
If you have 2 objects, they can't move simultaneously as only 1 of the objects can have the focus at a given time (even if you bind them to different keys).
Key bindings are easier to maintain and manipulate:
Disabling, rebinding, re-assigning user actions is much easier.
The code is easier to read.
OK, you convinced me to try it out. How does it work?
The tutorial has a good section about it. Key bindings involve 2 objects InputMap and ActionMap. InputMap maps a user input to an action name, ActionMap maps an action name to an Action. When the user presses a key, the input map is searched for the key and finds an action name, then the action map is searched for the action name and executes the action.
Looks cumbersome. Why not bind the user input to directly to the action and get rid of the action name? Then you need only one map and not two.
Good question! You will see that this is one of the things that make key bindings more manageable (disable, rebind etc.).
I want you to give me a full working code of this.
No (the Swing tutorial has working examples).
You suck! I hate you!
Here is how to make a single key binding:
myComponent.getInputMap().put("userInput", "myAction");
myComponent.getActionMap().put("myAction", action);
Note that there are 3 InputMaps reacting to different focus states:
myComponent.getInputMap(JComponent.WHEN_FOCUSED);
myComponent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
myComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
WHEN_FOCUSED, which is also the one used when no argument is supplied, is used when the component has focus. This is similar to the key listener case.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT is used when a focused component is inside a component which is registered to receive the action. If you have many crew members inside a spaceship and you want the spaceship to continue receiving input while any of the crew members has focus, use this.
WHEN_IN_FOCUSED_WINDOW is used when a component which is registered to receive the action is inside a focused component. If you have many tanks in a focused window and you want all of them to receive input at the same time, use this.
The code presented in the question will look something like this assuming both objects are to be controlled at the same time:
public class MyGame extends JFrame {
private static final int IFW = JComponent.WHEN_IN_FOCUSED_WINDOW;
private static final String MOVE_UP = "move up";
private static final String MOVE_DOWN = "move down";
private static final String FIRE = "move fire";
static JLabel obj1 = new JLabel();
static JLabel obj2 = new JLabel();
public MyGame() {
// Do all the layout management and what not...
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("UP"), MOVE_UP);
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("DOWN"), MOVE_DOWN);
// ...
obj1.getInputMap(IFW).put(KeyStroke.getKeyStroke("control CONTROL"), FIRE);
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("W"), MOVE_UP);
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("S"), MOVE_DOWN);
// ...
obj2.getInputMap(IFW).put(KeyStroke.getKeyStroke("T"), FIRE);
obj1.getActionMap().put(MOVE_UP, new MoveAction(1, 1));
obj1.getActionMap().put(MOVE_DOWN, new MoveAction(2, 1));
// ...
obj1.getActionMap().put(FIRE, new FireAction(1));
obj2.getActionMap().put(MOVE_UP, new MoveAction(1, 2));
obj2.getActionMap().put(MOVE_DOWN, new MoveAction(2, 2));
// ...
obj2.getActionMap().put(FIRE, new FireAction(2));
// In practice you would probably create your own objects instead of the JLabels.
// Then you can create a convenience method obj.inputMapPut(String ks, String a)
// equivalent to obj.getInputMap(IFW).put(KeyStroke.getKeyStroke(ks), a);
// and something similar for the action map.
add(obj1);
add(obj2);
// Do other GUI things...
}
static void rebindKey(KeyEvent ke, String oldKey) {
// Depends on your GUI implementation.
// Detecting the new key by a KeyListener is the way to go this time.
obj1.getInputMap(IFW).remove(KeyStroke.getKeyStroke(oldKey));
// Removing can also be done by assigning the action name "none".
obj1.getInputMap(IFW).put(KeyStroke.getKeyStrokeForEvent(ke),
obj1.getInputMap(IFW).get(KeyStroke.getKeyStroke(oldKey)));
// You can drop the remove action if you want a secondary key for the action.
}
public static void main(String[] args) {
new MyGame();
}
private class MoveAction extends AbstractAction {
int direction;
int player;
MoveAction(int direction, int player) {
this.direction = direction;
this.player = player;
}
#Override
public void actionPerformed(ActionEvent e) {
// Same as the move method in the question code.
// Player can be detected by e.getSource() instead and call its own move method.
}
}
private class FireAction extends AbstractAction {
int player;
FireAction(int player) {
this.player = player;
}
#Override
public void actionPerformed(ActionEvent e) {
// Same as the fire method in the question code.
// Player can be detected by e.getSource() instead, and call its own fire method.
// If so then remove the constructor.
}
}
}
You can see that separating the input map from the action map allow reusable code and better control of bindings. In addition, you can also control an Action directly if you need the functionality. For example:
FireAction p1Fire = new FireAction(1);
p1Fire.setEnabled(false); // Disable the action (for both players in this case).
See the Action tutorial for more information.
I see that you used 1 action, move, for 4 keys (directions) and 1 action, fire, for 1 key. Why not give each key its own action, or give all keys the same action and sort out what to do inside the action (like in the move case)?
Good point. Technically you can do both, but you have to think what makes sense and what allows for easy management and reusable code. Here I assumed moving is similar for all directions and firing is different, so I chose this approach.
I see a lot of KeyStrokes used, what are those? Are they like a KeyEvent?
Yes, they have a similar function, but are more appropriate for use here. See their API for info and on how to create them.
Questions? Improvements? Suggestions? Leave a comment.
Have a better answer? Post it.
Note: this is not an answer, just a comment with too much code :-)
Getting keyStrokes via getKeyStroke(String) is the correct way - but needs careful reading of the api doc:
modifiers := shift | control | ctrl | meta | alt | altGraph
typedID := typed <typedKey>
typedKey := string of length 1 giving Unicode character.
pressedReleasedID := (pressed | released) key
key := KeyEvent key code name, i.e. the name following "VK_".
The last line should better be exact name, that is case matters: for the down key the exact key code name is VK_DOWN, so the parameter must be "DOWN" (not "Down" or any other variation of upper/lower case letters)
Not entirely intuitive (read: had to dig a bit myself) is getting a KeyStroke to a modifier key. Even with proper spelling, the following will not work:
KeyStroke control = getKeyStroke("CONTROL");
Deeper down in the awt event queue, a keyEvent for a single modifier key is created with itself as modifier. To bind to the control key, you need the stroke:
KeyStroke control = getKeyStroke("ctrl CONTROL");
Here is an easyway that would not require you to read hundreds of lines of code just learn a few lines long trick.
declare a new JLabel and add it to your JFrame (I didn't test it in other components)
private static JLabel listener= new JLabel();
The focus needs to stay on this for the keys to work though.
In constructor :
add(listener);
Use this method:
OLD METHOD:
private void setKeyBinding(String keyString, AbstractAction action) {
listener.getInputMap().put(KeyStroke.getKeyStroke(keyString), keyString);
listener.getActionMap().put(keyString, action);
}
KeyString must be written properly. It is not typesafe and you must consult the official list to learn what is the keyString(it is not an official term) for each button.
NEW METHOD
private void setKeyBinding(int keyCode, AbstractAction action) {
int modifier = 0;
switch (keyCode) {
case KeyEvent.VK_CONTROL:
modifier = InputEvent.CTRL_DOWN_MASK;
break;
case KeyEvent.VK_SHIFT:
modifier = InputEvent.SHIFT_DOWN_MASK;
break;
case KeyEvent.VK_ALT:
modifier = InputEvent.ALT_DOWN_MASK;
break;
}
listener.getInputMap().put(KeyStroke.getKeyStroke(keyCode, modifier), keyCode);
listener.getActionMap().put(keyCode, action);
}
In this new method you can simply set it using KeyEvent.VK_WHATEVER
EXAMPLE CALL:
setKeyBinding(KeyEvent.VK_CONTROL, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ctrl pressed");
}
});
Send an anonymous class (or use subclass) of AbstractAction. Override its public void actionPerformed(ActionEvent e) and make it do whatever you want the key to do.
PROBLEM:
I couldn't get it running for VK_ALT_GRAPH.
case KeyEvent.VK_ALT_GRAPH:
modifier = InputEvent.ALT_GRAPH_DOWN_MASK;
break;
does not make it work for me for some reason.
Here is an example of how to get key bindings working.
(Inside JFrame subclass using extends, which is called by the constructor)
// Create key bindings for controls
private void createKeyBindings(JPanel p) {
InputMap im = p.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = p.getActionMap();
im.put(KeyStroke.getKeyStroke("W"), MoveAction.Action.MOVE_UP);
im.put(KeyStroke.getKeyStroke("S"), MoveAction.Action.MOVE_DOWN);
im.put(KeyStroke.getKeyStroke("A"), MoveAction.Action.MOVE_LEFT);
im.put(KeyStroke.getKeyStroke("D"), MoveAction.Action.MOVE_RIGHT);
am.put(MoveAction.Action.MOVE_UP, new MoveAction(this, MoveAction.Action.MOVE_UP));
am.put(MoveAction.Action.MOVE_DOWN, new MoveAction(this, MoveAction.Action.MOVE_DOWN));
am.put(MoveAction.Action.MOVE_LEFT, new MoveAction(this, MoveAction.Action.MOVE_LEFT));
am.put(MoveAction.Action.MOVE_RIGHT, new MoveAction(this, MoveAction.Action.MOVE_RIGHT));
}
Separate class to handle those key bindings created above (where Window is the class that extends from JFrame)
// Handles the key bindings
class MoveAction extends AbstractAction {
enum Action {
MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT;
}
private static final long serialVersionUID = /* Some ID */;
Window window;
Action action;
public MoveAction(Window window, Action action) {
this.window = window;
this.action = action;
}
#Override
public void actionPerformed(ActionEvent e) {
switch (action) {
case MOVE_UP:
/* ... */
break;
case MOVE_DOWN:
/* ... */
break;
case MOVE_LEFT:
/* ... */
break;
case MOVE_RIGHT:
/* ... */
break;
}
}
}

Adding double-click expansion to the Tree Viewer in SWT

Double-Clicking tree items works completely fine, but when I press CTRL + M on the keyboard then the tree items expand\collapse, can someone please tell me the reason behind this? Is this a bug in Eclipse or why does this double-click functionality get triggered when I press CTRL+M.
Thanks.
Use TreeViewer.addDoubleClickListener to listen for tree double clicks not a mouse listener. You could use something like this:
private class DoubleClickListener implements IDoubleClickListener
{
#Override
public void doubleClick(final DoubleClickEvent event)
{
final IStructuredSelection selection = (IStructuredSelection)event.getSelection();
if (selection == null || selection.isEmpty())
return;
final Object sel = selection.getFirstElement();
final ITreeContentProvider provider = (ITreeContentProvider)treeViewer.getContentProvider();
if (!provider.hasChildren(sel))
return;
if (treeViewer.getExpandedState(sel))
treeViewer.collapseToLevel(sel, AbstractTreeViewer.ALL_LEVELS);
else
treeViewer.expandToLevel(sel, 1);
}
}
Update:
Using TreeViewer.addDoubleClickListener is the preferred way to do double click handling for all classes derived from StructuredViewer.
Each double click listener is run using SafeRunnable which deals with any exceptions that the listener may throw, this safeguards the rest of the code for errors in the listeners.
The DoubleClickEvent provides direct access to the model object data so it is not necessary to deal with Tree or TreeItem objects to work out selections.
The double click code in the TreeViewer interfaces correctly with the OpenStrategy single / double click to open code.
I think the following code will be better , cause it will not cause the tree item to reload children and will keep the original state of other tree items.
_treeViewer.addDoubleClickListener( new IDoubleClickListener()
{
#Override
public void doubleClick( DoubleClickEvent event )
{
ISelection selection = event.getSelection();
if( selection instanceof ITreeSelection )
{
TreePath[] paths= ((ITreeSelection)selection).getPathsFor(selectedItem);
for (int i= 0; i < paths.length; i++)
{
_treeViewer.setExpandedState(paths[i], !_treeViewer.getExpandedState(paths[i]));
}
}
}
}
} );

In GWT, how to known from a SelectionEvent in a Tree if the Shift button is pressed

I try in GWT to create a Tree with multiple selection for the nodes and ran into a problem similar to this question Shift Key in GWT?.
When a selectionEvent is raised from the Tree, I would like to know if the Shift key is pressed or not.
SelectionHandler<TreeItem> getSelectionHandler() {
return new SelectionHandler<TreeItem>(){
#Override
public void onSelection(SelectionEvent<TreeItem> event) {
// is shift key pressed ?
}
};
}
The solution in the question above cannot apply in this case as the SelectionHandler class does not inherit from DOMEvent and then does not have a getNativeEvent() function.
I tried a dirty solution by adding keyDownEventHandler and keyUpEventHandler to the Tree with a boolean flag but the handlers are only called when the focus is on the tree so this doesn't work.
Is there a simple solution (or just a solution even if it's not simple) ? Thanks.
Edit on aem response :
The solution can work by enclosing the components in a FocusPanel with a keyUp/DownHandler but then I can't add any component needing keyboard input such as TextArea as the "global" handler takes the priority... So it don't really solve my problem.
My suggestion is to create a custom Tree class that temporary store the event and store this event by overriding the onBrowseEvent method. Then you can, in your onSelection method, check if the shift key was pressed by checking this stored event. Since JavaScript is not concurrent it should be no problem using the private variable. The code would be something like this:
public class MyTree extends Tree {
private Event currentEvent;
... constructors...
// Call this method from within the onSelection method to determine if the shift key
// was pressed.
public boolean isShiftPressed() {
return currentEvent != null ? currentEvent.getShiftKey() : false;
}
#Override
public void onBrowserEvent(Event event) {
currentEvent = event;
super.onBrowserEvent(event);
currentEvent = null;
}
}
I'm not sure whether this will work, but it's worth a try:
What about adding key handlers to the root panel containing the Tree, and have them set a boolean indicating whether the Shift key is down? Then the tree's SelectionHandler can check that boolean.
The trouble with this is that the page might contain other widgets that capture the key events, which would make this behavior seem flaky to the user.

Categories