Чтение "альтернативных" ключей с помощью Java Swing - PullRequest
1 голос
/ 02 января 2011

Коротко:

Как я могу читать различные клавиши, такие как ESC, ENTER, CTRL, ALT, используя Swing?

Ответы [ 3 ]

1 голос
/ 02 января 2011

Вот демонстрация, которая поможет вам захватить нажатую клавишу клавиатуры ( веб-сайт Oracle ):

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...
    }
}
1 голос
/ 02 января 2011

Ну, KeyStroke идентифицирует действия на клавиатуре, это позволит вам воздействовать на различные ключевые события.

Что вам нужно сделать, это сопоставить действия с каждым ключом, например:

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

Действие будет вызвано после нажатия клавиши.

Также может быть полезно прочитать о KeyStroke по адресу: http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/KeyStroke.html

Надеюсь, это поможет, и я понял, что вы имели в виду под «читать разные ключи»

0 голосов
/ 02 января 2011

Вам необходимо прочитать учебник Sun по привязкам клавиш .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...