1

From the Swing tutorial on text components:

You may want to change the document's text within a document listener. However, you should never modify the contents of a text component from within a document listener. If you do, the program will likely deadlock. Instead, you can use a formatted text field or provide a document filter.

I am confused. So what is the correct way to change the text eg. as a result of a KeyEvent ?

3 Answers3

4

1) using DocumentListener for

  • output from JTextComponent to the GUI

  • HightLighter or Styled text

2) DocumentFilter for filtering of

  • unwanted chars,

  • chars sequence(s),

these filtered chars could be

  • replaced with another char (or with defined chars sequence)

  • removed (never will be displayed in the JTextComponent)

3) similair funcionality to provide JFormattedTextFieldis possible to input to the JTextComponent only chars 0 - 9, decimal separator, negative sing,

4) So what is the correct way to change the text eg. as a result of a KeyEvent ?

use DocumentFilter

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
3

A direct answer is using SwingUtilities.invokeLater() placing the Document modification code there. But mKorbel's answer (+1) covers most of the cases you can imagine.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • @StanislavL Thanks. It was exactly the concurrency issue I worried about and didn't find completely clear from the description in the tutorial. – Michael Ras Mar 19 '12 at 14:58
2

The text say's that you may want to use a document listener. Here is a example how to write one.

A Swing text component uses a Document to represent its content. Document events occur when the content of a document changes in any way.

So, always that your text component changes the document listener will fire, but the text says that you cannot change the value of the component in this listener.

In a KeyListener (that's not a document listener) you can change the value using setText().

Depending on what you want, i suggest you look DocumentFilter.