我在我的程序中调用了一个新阶段,我希望在按下escape时关闭它。我这样做了,它给了我一个NullPointerException:
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
KeyCode key = t.getCode();
if (key == KeyCode.ESCAPE){
stage.close();
}
}
});
答案 0 :(得分:12)
试试这个..
scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>
() {
@Override
public void handle(KeyEvent t) {
if(t.getCode()==KeyCode.ESCAPE)
{
System.out.println("click on escape");
Stage sb = (Stage)label.getScene().getWindow();//use any one object
sb.close();
}
}
});
答案 1 :(得分:8)
将事件处理程序添加到要在ESC上关闭的舞台/窗口。
JavaFX 8风格:
stage.addEventHandler(KeyEvent.KEY_RELEASED, (KeyEvent event) -> {
if (KeyCode.ESCAPE == event.getCode()) {
stage.close();
}
});
答案 2 :(得分:0)
为什么你不向我们展示你的更多代码?但是,试试这个:
public class Login extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("JavaFX Welcome");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("Welcome");
scenetitle.setId("welcome-text");
grid.add(scenetitle, 0, 0, 2, 1);
Label userName = new Label("User Name:");
grid.add(userName, 0, 1);
TextField userTextField = new TextField();
grid.add(userTextField, 1, 1);
Label pw = new Label("Password:");
grid.add(pw, 0, 2);
PasswordField pwBox = new PasswordField();
grid.add(pwBox, 1, 2);
Button btn = new Button("Sign in");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(btn);
grid.add(hbBtn, 1, 4);
Scene scene = new Scene(grid, 660, 300);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
if (ke.getCode() == KeyCode.ESCAPE) {
System.out.println("Key Pressed: " + ke.getCode());
primaryStage.close();
}
}
});
//primaryStage.setFullScreen(true);
primaryStage.setScene(scene);
primaryStage.show();
}
}
完成。
答案 3 :(得分:0)
希望导入的Eventhandler包不是JavaFX。
尝试使用,
import javafx.event.EventHandler;
注意:由于命名约定相同,但只有swig和JavaFX之间的包名称不同,因此NetBeans / Eclipse可能会自动导入不同的包,因此请确保它。