Tuesday, October 6, 2015

GlyphView: Stale view: javax.swing.text.BadLocationException: Length must be positive


In this article I will show you, how you can get rid of the "GlyphView: Stale view: javax.swing.text.BadLocationException: Length must be positive" exception in JAVA Swing's JTextPane

If you are trying to develop your own cool text editor based on the JTextPane component, you probably have seen the message, which actually tells you, that you are trying to work with some incorrect offset/length combination.

The cause of the situation may be on your side and you should be sure for example, that you do modify the JTextPane's content only from the Dispatch thread (SwingUtilities.invokeLater is your friend).

If you are "pretty sure", that you do everything in the right way and your program keeps to fail with the BadLocationException, you can try the following workaround:

You will need your own implementations of the JTextPane, EditorKit and StyledDocument. You can put them all to one single class.
public class SCADTextPane extends JTextPane {

  private class Document extends DefaultStyledDocument {

    @Override
    public void getText(int _offset, int _length, Segment _txt) {
      if(_length<0){
        System.out.println("Getting rid of negative length "+_length);
       }
      try {
        super.getText(_offset, Math.max(_length, 0), _txt);
      } catch (Exception _e) {
        Logger.logError(new Exception("Offset/length/text: " + _offset + "/" + _length));
        Logger.logError(_e);
      }
    }
  }

  private class Kit extends StyledEditorKit {

    @Override
    public Document createDefaultDocument() {
      return new Document();
    }
  }

  @Override
  public EditorKit createDefaultEditorKit() {
    return new Kit();
  }
}


You can easily see, what makes the magic. You just grab the _length parameter of the getText() method and make sure that it's value is positive. You can of course do the similar with the _offset parameter.

Hope this will help you.