Java TextField getText() 返回先前的字符串值 [英] Java TextField getText() returns previous string value

查看:52
本文介绍了Java TextField getText() 返回先前的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Java Textfield 的问题,即当我覆盖 JTextField 中的所有文本并立即将新文本(不要通过退格键)输入到 JTextField 中时,然后我使用函数 getText() 我得到的是前一个字符串而不是当前字符串.请帮助一些解决方案.提前致谢.

I have a problem with Java Textfield that is when I cover all text in the JTextField and input new text immediately(do not pass backspace) into the JTextField, then I use function getText() I get the previous string not current string. Please help for some solutions. Thanks in advance.

推荐答案

我刚刚通过向 JTextField 添加 keyListener 并将 getText() 方法的返回值打印到控制台来测试您描述的问题.

I just tested the problem you described by adding a keyListener to a JTextField and printing the getText() method's return value to the console.

我发现如果你想在 keyTyped 或 keyPressed 事件中使用 getText() 方法,它总是落后一个字符(我不知道这一点,因为我通常只使用一个按钮来确认我'm 完成输入文本并将 KeyEvent 绑定到 Return 键以触发按钮(如果用户想按回车键确认)

What I found out is that it is always one character behind if you want to use the getText() method right in the keyTyped or keyPressed event (I didn't know this because I usually just use a button to confirm I'm done entering the text and bind a KeyEvent to the Return key to trigger the button if a user wants to confirm by hitting enter)

我认为这是由于在事件发生后 textField 更新了其文本值.

I think this is due to the textField updating its text value AFTER the event is shot.

我认为这是您所做的,因为您没有提供示例代码,所以如果没有,我将删除此答案.

I assume this is what you did since you didn't provide sample code, so I'll delete this answer if it's not.

解决此问题的方法是在 keyReleased 方法中实现您想要执行的操作.

The work around to this is to implement what you want to do in the keyReleased method instead.

public void keyReleased(Event e)
{
  System.out.println(myTextField.getText());
}

这篇关于Java TextField getText() 返回先前的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆