Articles Projects Tips Downloads Contacts About

JEditorPane/JTextPane's Document and Views structure viewer.
By Stanislav Lapitsky

 

From time to time I have to investigate how JEditorPane works inside to implement custom features. Itís important to know hierarchy and structure of Document (data model) and Views. The Views are especially complicated in e.g HTMLEditorKit and itís difficult to understand how small change of code changes all the content. I used to use debug info Ė all the variables values at some point of code but the info isnít available in SUNís classes and it could be cases when we just donít have place to set breakpoint.

To solve the problem I wrote a small tool which shows Document and Views structures trees and hope it will be useful for somebody else who will do the same. Thatís a picture which shows how it looks like.

Both Document tree and Views tree show tooltips over nodes with additions info such as start and end offsets, text, child count, and attributes. In the Views tree selection highlights appropriate viewís rectangle in the JEditorPane. To find view's bounds I used following code.

    protected static Shape getAllocation(View v, JEditorPane edit) {
        Insets ins=edit.getInsets();
        View vParent=v.getParent();
        int x=ins.left;
        int y=ins.top;
        while(vParent!=null) {
            int i=vParent.getViewIndex(v.getStartOffset(), Position.Bias.Forward);
            Shape alloc=vParent.getChildAllocation(i, new Rectangle(0,0, Short.MAX_VALUE, Short.MAX_VALUE));
            x+=alloc.getBounds().x;
            y+=alloc.getBounds().y;

            vParent=vParent.getParent();
        }

        if (v instanceof BoxView) {
            int ind=v.getParent().getViewIndex(v.getStartOffset(), Position.Bias.Forward);
            Rectangle r2=v.getParent().getChildAllocation(ind, new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE)).getBounds();

            return new Rectangle(x,y, r2.width, r2.height);
        }

        return new Rectangle(x,y, (int)v.getPreferredSpan(View.X_AXIS), (int)v.getPreferredSpan(View.Y_AXIS));
    }

If JEditorPaneís content was edited or size was changed Document and Views hierarchy may be changed so press ďRefreshĒ button to see actual state.

The structure.jar library contains the demo application shown above and full source code to extend and reuse.

Back to Table of Content