Clarification on modifying a Document's contents from a DocumentListener

后端 未结 3 481

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

相关标签:
3条回答
  • 2020-12-21 22:52

    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

    0 讨论(0)
  • 2020-12-21 22:52

    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.

    0 讨论(0)
  • 2020-12-21 23:03

    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.

    0 讨论(0)
提交回复
热议问题