开发者

What listener should I use for a JTextField in a typing game?

Here is my situation: I am developing a java typing game, and I need to find the best listener for my JTextField.

JTextField typeBox;

The listener should be able to detect the user's input, send the text inside the box to the main game part for processing, and if the ending of a word is reached, the type box MUST BE CLEARED (so the user can type one 开发者_如何学编程word at a time, like in usual typing games). I have tried KeyListener

    public class TypeBoxListener implements KeyListener
    {
        @Override
        public void keyPressed(KeyEvent arg0) {
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            if (arg0.getKeyChar() == arg0.CHAR_UNDEFINED) return;
            String typedText = typeBox.getText();
            thisGUI.processUserInput(typedText);
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
        }   
    }

The problem of this is when the user reaches the ending of a word without RELEASING a key, and immediately type another key, that new key is lost.

I also tried DocumentListener

public class TypeBoxListener implements DocumentListener
{
    @Override
    public void changedUpdate(DocumentEvent arg0) {
    }

    @Override
    public void insertUpdate(DocumentEvent arg0) {
        String typedText = paragraphPanel.typeBox.getText();
        thisGUI.processUserInput(typedText);
    }

    @Override
    public void removeUpdate(DocumentEvent arg0) {
        String typedText = paragraphPanel.typeBox.getText();
        thisGUI.processUserInput(typedText);
    }
}

This method is much more responsive than using keyReleased, however, I can't clear the text box using this method, because I'll get an IllegalStateException trying to modify the document inside a DocumentListener.


You could try to define your textbox-clearing code as a Runnable and execute it via SwingUtilities.html.invokeLater to get around the IllegalStateException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜