Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java detect CTRL+X key combination on a jtree

I need an example how to add a keyboard handler that detect when Ctrl+C , Ctrl+X , Ctrl+C pressed on a JTree.

I were do this before with menu shortcut keys but with no success.

like image 228
ShirazITCo Avatar asked May 11 '11 21:05

ShirazITCo


4 Answers

You can add KeyListeners to any component (f)

        f.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if ((e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                    System.out.println("woot!");
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });
like image 136
MeBigFatGuy Avatar answered Oct 27 '22 18:10

MeBigFatGuy


Use KeyListener for example :

jTree1.addKeyListener(new java.awt.event.KeyAdapter() {

        public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_C) {

                JOptionPane.showMessageDialog(this, "ctrl + c");

            } else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_X) {

                JOptionPane.showMessageDialog(this, "ctrl + x");

            } else if (evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {

                JOptionPane.showMessageDialog(this, "ctrl + v");

            }
        }
    });

Hope that helps.

like image 39
MOHAMED FATHEI Avatar answered Oct 27 '22 17:10

MOHAMED FATHEI


Use Key Bindings.

like image 28
camickr Avatar answered Oct 27 '22 18:10

camickr


    initComponents();
      KeyboardFocusManager ky=KeyboardFocusManager.getCurrentKeyboardFocusManager();

    ky.addKeyEventDispatcher(new KeyEventDispatcher() {

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {

             if (e.getID()==KeyEvent.KEY_RELEASED && (e.getKeyCode() == KeyEvent.VK_C) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                System.out.println("Dhanushka Tharindu");
            }
             return  true;
        }
    });
like image 21
Dhanushka Tharindu Rathnayake Avatar answered Oct 27 '22 19:10

Dhanushka Tharindu Rathnayake