Inconsistency calling TextField text in setOnKeyTyped

落花浮王杯 提交于 2019-12-25 07:39:55

问题


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();
    });

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


回答1:


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

To get your KeyCode

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

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

equality checks

if(kc == KeyCode.BACK_SPACE) //checking for your backspace

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

also you can make use of these methods

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



来源:https://stackoverflow.com/questions/33455527/inconsistency-calling-textfield-text-in-setonkeytyped

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!