gpt4 book ai didi

java - 使用按键事件调用函数

转载 作者:行者123 更新时间:2023-12-02 12:58:59 26 4
gpt4 key购买 nike

我对按键事件不熟悉,正在尝试弄清楚如何在按下空格键时调用函数。我为我想要做的事情添加了一些伪代码。

public class scrap implements KeyListener {

jump() {
///////////
///code////
///////////
}

@Override
public void keyPressed(KeyEvent e) {
if(e == Space) {
jump()
}
}

@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}

@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}

最佳答案

您可以编写一个关键监听器:

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

int modifiersEx = e.getModifiersEx();
String modString = "extended modifiers = " + modifiersEx;
String tmpString = KeyEvent.getModifiersExText(modifiersEx);
if (tmpString.length() > 0) {
modString += " (" + tmpString + ")";
} else {
modString += " (no extended modifiers)";
}

String actionString = "action key? ";
if (e.isActionKey()) {
actionString += "YES";
} else {
actionString += "NO";
}

String locationString = "key location: ";
int location = e.getKeyLocation();
if (location == KeyEvent.KEY_LOCATION_STANDARD) {
locationString += "standard";
} else if (location == KeyEvent.KEY_LOCATION_LEFT) {
locationString += "left";
} else if (location == KeyEvent.KEY_LOCATION_RIGHT) {
locationString += "right";
} else if (location == KeyEvent.KEY_LOCATION_NUMPAD) {
locationString += "numpad";
} else { // (location == KeyEvent.KEY_LOCATION_UNKNOWN)
locationString += "unknown";
}

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

我发现这可能对您有帮助Complete Documentation

关于java - 使用按键事件调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com