我在名为对话框的弹出窗口中有多个 TextField
对象(类型:Stage
)。
我正在尝试为他们定义一个操作处理程序,旨在在单击键盘上的退出按钮后关闭舞台。
这是我的舞台关闭功能:
public void escapeKeyPressed(KeyCode keyCode , Stage dialog){
if (keyCode == KeyCode.ESCAPE ){
dialog.close();
System.out.println("escape got called");
}
}
以下是我的称呼:
textUsername.setOnAction((event) -> {escapeKeyPressed(KeyCode.ESCAPE ,dialog );});
textAddress.setOnAction((event) -> {escapeKeyPressed(KeyCode.ESCAPE ,dialog );});
textwp.setOnAction((event) -> {escapeKeyPressed(KeyCode.ESCAPE ,dialog );});
textState.setOnAction((event) -> {escapeKeyPressed(KeyCode.ESCAPE ,dialog );});
textloginName.setOnAction((event) -> {escapeKeyPressed(KeyCode.ESCAPE ,dialog );});
问题是函数没有被调用。
知道如何解决这个问题吗?值得一提的是,如果我从 setOnAction();
最佳答案
setOnAction
TextField
的文档说明:
The action handler associated with this text field, or null if no action handler is assigned. The action handler is normally called when the user types the ENTER key.
因此,escapeKeyPressed
将在 Enter
键按下时执行。现在会发生什么:如果您按下 Enter 键,它将使用 KeyCode.ESCAPE
调用此方法,因此它将关闭对话框。
使用setOnKeyPressed
而不是 setOnAction
:
Defines a function to be called when this Node or its child Node has input focus and a key has been pressed.
不是传递 KeyCode.ESCAPE
,而是传递 KeyEvent
的 KeyCode
使用 getCode()
可以获得什么:
textUsername.setOnKeyPressed(event -> escapeKeyPressed(event.getCode(), dialog));
关于java - 在 JavaFX 中为 TextField 设置 KeyPressed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39328375/