我刚刚创建了一个java tic-tac-toe游戏我想弄清楚如何在某个条件下按下回车键时运行一个方法,例如下面的一个例子......
if(/*condition is met*/){
//keyListener
}
答案 0 :(得分:6)
根据您要捕获“enter”键的位置,您可以使用ActionListener
(在文本组件或按钮等组件上)或将key binding附加到组件
public class MyPanel extends JPanel {
public MyPanel() {
InputMap im = getInputMap(WHEN_FOCUSED);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");
am.put("onEnter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Enter pressed
}
});
}
}
这将依赖于所关注的组件。
答案 1 :(得分:3)
一种方法是实现KeyListener
接口及其关键事件方法。例如,
public class MyClass implements KeyListener {
public void keyTyped(KeyEvent e) {
// Invoked when a key has been typed.
}
public void keyPressed(KeyEvent e) {
// Invoked when a key has been pressed.
if (e.getKeyCode() == KeyEvent.VK_ENTER && yourOtherCondition) {
myMethod();
}
}
public void keyReleased(KeyEvent e) {
// Invoked when a key has been released.
}
}
然后使用
添加此侦听器myComponent.addKeyListener(new MyClass());
或者,如果您愿意,
myComponent.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) { /* ... */ }
public void keyReleased(KeyEvent e) { /* ... */ }
public void keyTyped(KeyEvent e) { /* ... */ }
});
See this了解详情。
答案 2 :(得分:1)