不一致调用setOnKeyTyped中的TextField文本 [英] Inconsistency calling TextField text in setOnKeyTyped

查看:185
本文介绍了不一致调用setOnKeyTyped中的TextField文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaFX在Java中进行打字测试。我想将TextField中输入的文本与定义的随机单词进行比较。但是,TextField仅更新时有时输入的字母而不是所有时间。以下代码是发生此问题的地方。

I am making a typing test in Java with JavaFX. I want to compare the text that is being typed in a TextField to the defined random words. However, the TextField only updates with the letter just typed sometimes and not all the times. The following code is where this problem is occurring.

    field.setOnKeyTyped(e -> {

        String typingWord = field.getText();

        if(     typingWord.isEmpty()          && 
                e.getCharacter().charAt(0) == '\b' && 
                !(typedWords.size() == 0)          &&
                typingWord.equals(previousWord)){

            field.setText(typedWords.get(typedWords.size() - 1));
            typedWords.remove(typedWords.size() - 1);
            field.positionCaret(typingWord.length());
            index--;
        }

        //compare random words to typed words

        if (Character.isWhitespace(e.getCharacter().charAt(0))) {

            typedWords.set(index, typingWord);
            field.clear();
            e.consume();
            index++;
        }

        previousWord = field.getText();
    });

这纯粹是由于我的电脑速度还是只是JavaFX中的一个错误?

Is this purely due to the speed of my computer or is it just a bug in JavaFX?

推荐答案

先生我不知道你想做什么,但我想提供帮助,所以在你的 onKeyPressed( ) onKeyReleased(),它提供 KeyEvent e 在您的情况下,您可以使用它来代替 Character.isWhitespace()& e.getCharacter()。charAt(0)以及 / b

Sir i do not know what you want to do but i want to help, so in your onKeyPressed() or onKeyReleased(), it gives a KeyEvent that is e in your case, you can use that in place of Character.isWhitespace() & e.getCharacter().charAt(0) and also /b

获取 KeyCode

field.setOnKeyTyped(e -> {
      KeyCode kc = e.getCode(); // your keycode here is the character you just pressed

现在使用KeyCode可以检查很多好东西,而不会落入角色

now with the KeyCode you can check for a whole lot of goodies,without falling to character

等式检查

if(kc == KeyCode.BACK_SPACE) //检查退格

if(kc.isWhitespaceKey()) //你的输入,制表符,空格等

if(kc.isWhitespaceKey()) // your enter, tabs, space etc

你也可以制作使用这些方法

also you can make use of these methods

TextField.deletePreviousChar(); TextField.deleteNextChar() ; 可能会在清算之前为您节省所有选择。如果您想清除其中的10个然后循环10次

TextField.deletePreviousChar();,TextField.deleteNextChar(); that might save you all the selection before clearing. if you want to clear like 10 of them then loop it 10 times

最后为什么这样做你检查空虚,然后检查它是否为空

lastly why do you check for emptiness & later check if its not empty

这篇关于不一致调用setOnKeyTyped中的TextField文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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