开发者

Text Changed event in JTextArea? How to?

开发者 https://www.devze.com 2023-04-12 06:42 出处:网络
I have been trying to make a text changed event handling mechanism for my JT开发者_Go百科extArea. For my purposes an event has to be fired whenever there is a change in the text of the JTextArea. I tr

I have been trying to make a text changed event handling mechanism for my JT开发者_Go百科extArea. For my purposes an event has to be fired whenever there is a change in the text of the JTextArea. I tried using the KeyListener interface and here is my code for that.

txtArea.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent arg0) {

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        currentText = text.getText();
        if (currentText == textString)
            JOptionPane.showMessageDialog(null, "Correct");

    }
});

Nothing happened when the textarea's text matched the hardcoded text. How can an event changed event be made for this.

Can this objective be achieved with a PropertyChangedListener? If it can, then how?


I would get the JTextArea's Document via getDocument() (a PlainDocument actually) and use a DocumentListener to listen for changes. This way you'd capture changes from key strokes and also from copy/paste/cut events.


Not the JTextArea, but the contained document receives updates, so you need:

jTextArea.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {

        }

        @Override
        public void insertUpdate(DocumentEvent e) {

        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {

        }
    });


You are comparing strings with ==

if (currentText == textString)

This will never be true. This compares if the strings are the same String object. You should use equals.

if (currentText.equals( textString) )

You might also want to check out DocumentListeners. See also this How do I compare strings in Java?

0

精彩评论

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

关注公众号