Java detect CTRL+X key combination on a jtree

主宰稳场 提交于 2019-11-27 06:37:33

问题


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.


回答1:


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



回答2:


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.




回答3:


Use Key Bindings.




回答4:


    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;
        }
    });



回答5:


But menu shortcut accelerators are the way to do this normally: myMenuItem.setAccelerator(KeyStroke.getKeyStroke("control C"));



来源:https://stackoverflow.com/questions/5970765/java-detect-ctrlx-key-combination-on-a-jtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!