不久:
如何使用Swing读取ESC,ENTER,CTRL,ALT等不同的键?
答案 0 :(得分:1)
这是一个演示,可帮助您捕获键盘的按键(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...
}
}
答案 1 :(得分:1)
好吧,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
我希望这会有所帮助,而且我明白了“阅读不同的密钥”的含义
答案 2 :(得分:0)
您需要阅读key bindings上的Sun教程。