Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text Changed event in JTextArea? How to?

Tags:

java

events

swing

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?

like image 794
prometheuspk Avatar asked Oct 12 '11 13:10

prometheuspk


People also ask

How do I add text to JTextArea?

Use textArea. append("text") , but I recomend JTextPane for more control like color, selection, etc.

How do I read text file into JTextArea?

Using the read(Reader in, Object desc) method inherited from the JTextComponent allow us to populate a JTextArea with text content from a file. This example will show you how to do it. In this example we use an InputStreamReader to read a file from our application resource.

How do I clear a JTextArea?

JTextArea0. selectAll(); JTextArea0. replaceSelection(""); This selects the entire textArea and then replaces it will a null string, effectively clearing the JTextArea.

Does JTextArea support HTML?

It has built in support for HTML. No how. Look for another component.


1 Answers

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.

like image 139
Hovercraft Full Of Eels Avatar answered Sep 19 '22 18:09

Hovercraft Full Of Eels