我有一个非常简单的KeyEvent:
@Override
public void start(Stage stage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root);
Canvas canvas = new Canvas( 900, 700 );
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
switch (ke.getCode()) {
case UP:
System.out.println("UP");
break;
case DOWN:
System.out.println("DOWN");
break;
case LEFT:
System.out.println("LEFT");
break;
case RIGHT:
System.out.println("RIGHT");
break;
case ENTER:
//ke.consume();
break;
default:
break;
}
}});
我想达到的目标: 我开始运行该程序,如果我按向上,向下,向左,向右输出写回我UP,DOWN,LEFT,RIGHT(它没有问题)。 但!如果按下输入,如果我按下向上,向下,向左,向右,输入或其他按键不要将输出向上,向下,向左,向右写回。
所以我想停止KeyEvent&#34;运行&#34;当我按下ENTER按钮。
答案 0 :(得分:1)
你有几个机会,这两个是我的第一个想法。
1)将您的关键事件的监听器存储为您的班级成员,然后在ENTER上取消注册。
private EventHandler<KeyEvent> keyHandler;
@Override
public void start(Stage stage) {
final Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(450);
stage.setHeight(500);
keyHandler = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
switch (ke.getCode()) {
case ENTER:
scene.removeEventHandler(KeyEvent.KEY_PRESSED, keyHandler);
break;
case UP:
System.out.println("UP");
break;
case DOWN:
System.out.println("DOWN");
break;
case LEFT:
System.out.println("LEFT");
break;
case RIGHT:
System.out.println("RIGHT");
break;
default:
break;
}
}};
scane.addEventHandler(KeyEvent.KEY_PRESSED, keyHandler);
2)在ENTER按下,将布尔值存储到成员,如果设置了此成员,则使用该事件。
private Boolean enterPressed = false;
@Override
public void start(Stage stage) {
final Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(450);
stage.setHeight(500);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent ke) {
if(enterPressed){
ke.consume();
return;
}
switch (ke.getCode()) {
case ENTER:
enterPressed = true;
break;
case UP:
System.out.println("UP");
break;
case DOWN:
System.out.println("DOWN");
break;
case LEFT:
System.out.println("LEFT");
break;
case RIGHT:
System.out.println("RIGHT");
break;
default:
break;
}
}});
两者都在工作,选择你喜欢的任何东西。