Question

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.

 21  62727  21
1 Jan 1970

Solution

 34

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) {
            }
        });
2011-05-11

Solution

 13

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.

2011-05-11