ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在JavaFX中为TextField设置KeyPressed事件

2019-06-08 17:49:30  阅读:532  来源: 互联网

标签:java event-handling javafx stage


我在一个名为dialog的弹出窗口中有许多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()替换调用者,函数本身工作正常;

解决方法:

TextField的setOnAction文档说明:

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.

因此,将在按Enter键上执行escapeKeyPressed.现在会发生什么:如果按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,event-handling,javafx,stage
来源: https://codeday.me/bug/20190608/1199237.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有