开发者

Reading "alternative" keys with Java Swing

Shortly:

How can I read different keys like E开发者_Python百科SC, ENTER, CTRL, ALT using Swing?


Well, KeyStroke identifies actions on the keyboard, it will allow you to act on different key events.

What you need to do is map actions to each key, like so:

// Create key stoke and bind the key stroke to an action
component.getInputMap().put(KeyStroke.getKeyStroke("alt"), "actionName");

// Add the action to the component
component.getActionMap().put("actionName",
    new AbstractAction("actionName") {
        public void actionPerformed(ActionEvent evt) {
            //do something here
        }
    }
);

The action will be invoked once the key stroke is pressed.

Also it may be helpful to read about KeyStroke at: http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/KeyStroke.html

I hope this helps and that I understood what you meant by 'read different keys'


Here is a demo to help you capturing the keyboard's pressed key (Oracle website):

public class KeyEventDemo ...  implements KeyListener ... {
    ...//where initialization occurs:
    typingArea = new JTextField(20);
    typingArea.addKeyListener(this);

        //Uncomment this if you wish to turn off focus
        //traversal.  The focus subsystem consumes
        //focus traversal keys, such as Tab and Shift Tab.
        //If you uncomment the following line of code, this
        //disables focus traversal and the Tab events 
        //become available to the key event listener.
        //typingArea.setFocusTraversalKeysEnabled(false);
    ...
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
    }

    /** Handle the key-pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
    }

    /** Handle the key-released event from the text field. */
    public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
    }
    ...
    private void displayInfo(KeyEvent e, String keyStatus){

        //You should only rely on the key char if the event
        //is a key typed event.
        int id = e.getID();
        String keyString;
        if (id == KeyEvent.KEY_TYPED) {
            char c = e.getKeyChar();
            keyString = "key character = '" + c + "'";
        } else {
            int keyCode = e.getKeyCode();
            keyString = "key code = " + keyCode
                    + " ("
                    + KeyEvent.getKeyText(keyCode)
                    + ")";
        }


        ...//Display information about the KeyEvent...
    }
}


You need to read the Sun tutorial on key bindings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜