【问题标题】:Adding text to a JTextPane from another class从另一个类向 JTextPane 添加文本
【发布时间】:2013-10-10 15:27:48
【问题描述】:

我正在尝试将字符串从另一个类添加到 JTextPane,但它不会更新 JTextPane。我尝试过线程,现在我一直倾向于使用文档侦听器或文档过滤器。显然 DocumentFilter 用于更新 JTextPane Docs,但是是否可以从另一个类执行此操作并在我添加字符串时更新它? 我尝试过类似的东西:

textPane.insertString(FilterBypass fb, int offs,String str, AttributeSet a) 

但 NetBeans 无法识别参数。感谢您的帮助。

*一些澄清,通过更新我的意思是它实际上显示了 JTextPane 上的更改。

【问题讨论】:

    标签: java swing user-interface jtextpane documentfilter


    【解决方案1】:

    我一直倾向于使用文档侦听器或文档过滤器

    DocumentListner 会在对 Document 进行更改时通知您。 DocumentFilter 允许您在更改文档之前过滤文本。

    我尝试过类似的方法:

    textPane.insertString(FilterBypass fb, int offs,String str, AttributeSet a) 
    

    您不应该直接访问 DocumentFilter。当您在 Document 上调用 insertString() 方法时,DocumentFilter 将访问 Document。

    您应该只调用 Document 的 insertString() 方法:

    textPane.getDocument().insertString(int offs,String str, AttributeSet a) 
    

    【讨论】:

    • 所以如果我调用文档的 insertString() 方法,这是否会在文档中添加一个字符串并同时更新 JTextPane?谢谢
    【解决方案2】:

    如果你是从不同的线程做的,你需要使用 SwingUtilities 中的 invokeLater

    public void updateTextPane(final String text){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              updateTextPane(text);
            }
        });
    }
    

    记得将文本定义为final,顺便说一句,String 是不可变的不是问题

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      相关资源
      最近更新 更多