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 t
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 JFormattedTextField
is 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
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.
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.