Hi there,
I'm currently trying to receive key events during a drag and drop, but it seems to me that the focus is taken away while dragging so that I can't listen to any key events.
I'm dragging a JComponent subclass that implements KeyListener and requests the focus in the DragSourceListener's dragEnter method, but my assumption is that the focus is taken away from it afterwards.
Now, who's got the focus and how can I take it away back to my JComponent. Or is there a different approach that is more suitable for dnd?
Thank you in advance.
UPDATE:
It's a lot of code necessary to make this work so I'm only going to post some snippets to show you what I'm trying to do:
public class Stone extends JComponent implements Serializable, KeyListener {
public Stone(...) {
//...
setFocusable(true);
addKeyListener(this);
this.dragSource = DragSource.getDefaultDragSource();
this.dgListener = new StoneDGListener();
this.dsListener = new StoneDSListener();
this.dragSource.createDefaultDragGestureRecognizer(
this,
DnDConstants.ACTION_MOVE,
this.dgListener
);
//...
}
//...
public void keyPressed(KeyEvent e) {
System.out.println("Stone: "+e.getKeyCode());
}
//...
public class StoneDSListener implements DragSourceListener, Serializable {
//...
@Override
public void dragEnter(DragSourceDragEvent dsde) {
//...
Stone.this.requestFocus();
addKeyListener(Stone.this);
}
//...
}
}
What happens is that before I'm dragging the Stone
component my JPanel has the focus so it receives any keys I'm pressing.
During the drag I can't listen to any pressed keys(so I don't know who's got the focus) even though I'm requesting it when in dragEnter()
and after I release the Stone
any key events are send to the Stone
.
It's probably not important for the question but to illustrate what I'm doing here's a screenshot:
(Here I'm dragging the Stone
from the collection below to the game field on the top). In this state I don't know how to find out what keys are pressed. I need to figure this out in order to be able to rotate the Stone
.