Swing component flickering when updated a lot

前端 未结 2 1823
悲&欢浪女
悲&欢浪女 2020-12-21 06:50

I\'ve got a couple thousand lines of code somewhere and I\'ve noticed that my JTextPane flickers when I update it too much.. I wrote a simplified version here:



        
相关标签:
2条回答
  • 2020-12-21 07:28

    Not sure if this will work, but you could try using the insertString() method of the text pane's Document instance. I would try having a single space at the end of the document and keeping the caret positioned after that space; but when you insert a string, insert it before the space. That way the caret position will remain at the end of the document automatically.

    I'm thinking that the text pane might be getting redrawn twice, once when you call setText() and once when you call setCaretPosition(), and that might be contributing to the flickering. Not sure, though (it's been a while since I worked with Swing).

    0 讨论(0)
  • 2020-12-21 07:29

    Part of your error is that you are accessing a Swing component from outside the event thread! Yes, setText() is thread-safe, but Swing methods are not Thread-safe unless they are explicitly declared as such. Thus, setCaretPosition() is not Thread-safe and must be accessed from the event thread. This is almost certainly why your application eventually freezes.

    NOTE: JTextPane inherits its setText() method from JEditorPane and its setCaretPosition method from JTextComponent, which explains the links in the previous paragraph not going to the JTextPane JavaDoc page.

    To be Thread-safe, you really need to at least call setCaretPosition() from within the event thread, which you can do with code like this:

    SwingUtilities.invokeAndWait(new Runnable() {
      public void run() {
        a.setText(b.toString());
        a.setCaretPosition(b.length());
      }
    }
    

    And since you have to call setCaretPosition() from within the event thread, you might as well also call setText() from the same place.

    It's possible that you may not need to manually set the caret position. Check out the section "Caret Changes" in the JavaDoc for JTextComponent.

    Finally, you may want to check out a series of two articles:

    • Faster JTextPane Text Insertion (Part I)
    • Faster JTextPane Text Insertion (Part II)
    0 讨论(0)
提交回复
热议问题