Enabling word wrap in a JTextPane with HTMLDocument

可紊 提交于 2019-12-04 07:46:17

Use this as example to implement custom wrap (whatever you need) http://java-sl.com/tip_html_letter_wrap.html

http://java-sl.com/wrap.html

There are several duplicates of this question, and many answers, but none that I have found have a single-component solution to the problem. This class is based on one of Stanislav's solutions to a similar problem with plain-text wrapping, with a few changes. This solution is tested with Java 1.7.0_55.

import javax.swing.text.Element;
import javax.swing.text.LabelView;
import javax.swing.text.StyleConstants;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

public class WrappedHtmlEditorKit extends HTMLEditorKit
{
    private static final long serialVersionUID = 1L;

    private ViewFactory viewFactory = null;

    public WrappedHtmlEditorKit()
    {
        super();
        this.viewFactory = new WrappedHtmlFactory();
        return;
    }

    @Override
    public ViewFactory getViewFactory()
    {
        return this.viewFactory;
    }

    private class WrappedHtmlFactory extends HTMLEditorKit.HTMLFactory
    {
        @Override
        public View create(Element elem)
        {
            View v = super.create(elem);

            if (v instanceof LabelView)
            {
                Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);

                if ((o instanceof HTML.Tag) && (o == HTML.Tag.BR))
                {
                    return v;
                }

                return new WrapLabelView(elem);
            }

            return v;
        }

        private class WrapLabelView extends LabelView
        {
            public WrapLabelView(Element elem)
            {
                super(elem);
                return;
            }

            @Override
            public float getMinimumSpan(int axis)
            {
                switch (axis)
                {
                    case View.X_AXIS:
                    {
                        return 0;
                    }
                    case View.Y_AXIS:
                    {
                        return super.getMinimumSpan(axis);
                    }
                    default:
                    {
                        throw new IllegalArgumentException("Invalid axis: " + axis);
                    }
                }
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!