How to get key events while dragging and dropping?

I'm currently trying to get key events while dragging and dropping, but it seems to me that the focus is removed when dragging and dropping, so I can’t listen to any key events.

I am dragging a subclass of JComponent that implements KeyListener and requests focus in the dragEnter DragSourceListener method, but my assumption is that after that the focus is taken away from it.

Now, who got the focus and how can I pick it back to my JComponent. Or is there another approach that is more suitable for dnd?

Thanks in advance.

UPDATE

This is a lot of code needed to do this work, so I'm 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);
        }

        //...
    }
}

, , , Stone, JPanel , , . ( , ), , dragEnter(), , Stone, Stone.

, , , , :

, "" http://img685.imageshack.us/img685/1884/pico.png ( Stone ). , , . , Stone.

+3
1

, . KeyEventDispatcher Stone KeyboardFocusManager. JavaDoc:

KeyboardFocusManager FocusEvents, WindowEvents, , KeyEvents +.

+ .

KeyEvents, , .

, , ( ). - :

Public Stone(...) {
    // ...

    KeyboardFocusManager fm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    fm.addKeyEventDispatcher(
        new KeyEventDispatcher() {
            public boolean dispatchKeyEvent(KeyEvent e) {
                System.out.println("Key Press: " + e.getKeyChar());
                return false;
            }            
        } 
    );

   // ... 
}

, , .

, KeyboardFocusManager , ?

, , .

+3

Source: https://habr.com/ru/post/1725850/


All Articles