文本已更改事件在JTextArea?如何? [英] Text Changed event in JTextArea? How to?

查看:303
本文介绍了文本已更改事件在JTextArea?如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图为我的 JTextArea 制作一个文字改变事件处理机制。为了出于我的目的,当 JTextArea 的文本发生变化时,事件必须被触发。我尝试使用 KeyListener 接口,这里是我的代码。

  txtArea.addKeyListener(new KeyListener(){

@Override
public void keyTyped(KeyEvent arg0){

}

@覆盖
public void keyReleased(KeyEvent arg0){
// TODO自动生成的方法存根

}

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

}
});

当文本区域的文本与硬编码文本匹配时,没有任何事情发生。

这个目标可以通过一个 PropertyChangedListener 来实现吗?我可以通过 getDocument()

获取JTextArea的文档。 code>(实际上是PlainDocument),并使用 DocumentListener 听取变更。这样,您可以从关键笔画以及复制/粘贴/剪切事件中捕获更改。


I have been trying to make a text changed event handling mechanism for my JTextArea. 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.

这篇关于文本已更改事件在JTextArea?如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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