предварительно обернуть в JEditorPane

Я использую JEditorPane для отображения стилизованного текста, а также использую тег <pre> для сохранения всех пробелов в тексте. Проблема в том, что я хочу, чтобы JEditorPane переносил текстовые строки, но HTMLEditorKit (или связанный с ним класс) не переносит текст внутри тега <pre>.

Я имею в виду, что я хочу, чтобы поведение было похоже на таблицу стилей «white-space: pre-wrap», которая, похоже, не поддерживается HTMLEditorKit.

Знаете ли вы, как заставить HTMLEditorKit оборачивать текст внутри <pre>, возможно, расширяя его.

Я сделал пример, чтобы показать, что я пытаюсь сделать.

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.text.*;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

public class PreWrapApp extends javax.swing.JFrame {

    public class PreWrapHTMLEditorKit extends HTMLEditorKit {

        ViewFactory viewFactory = new HTMLFactory() {

            @Override
            public View create(Element elem) {
                AttributeSet attrs = elem.getAttributes();
                Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
                Object o = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
                if (o instanceof HTML.Tag) {
                    HTML.Tag kind = (HTML.Tag) o;
                    if (kind == HTML.Tag.PRE) {
                        //View view = new javax.swing.text.html.ParagraphView(elem); // Not wrapping
                        View view = new javax.swing.text.html.ParagraphView(elem.getElement(0)); // Don't show everything
                        return view;
                    }
                }
                return super.create(elem);
            }
        };

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

    public PreWrapApp() {
        JEditorPane editorPane = new JEditorPane();
        JScrollPane scrollPane = new JScrollPane();

        this.setPreferredSize(new Dimension(300, 300));
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        //editorPane.setContentType("text/html");
        editorPane.setEditorKit(new PreWrapHTMLEditorKit());
        editorPane.setText(""
                + "<html>"
                + "<head>"
                + "<style type=\"text/css\">"
                + "pre.c1 { white-space: normal;}" // It is not wrapping
                + "pre.c2 { white-space: pre-wrap;}" // It is not wrapping
                + "p.c3 { white-space: pre;}" // It is not preserving white-spaces
                + "</style>"
                + "</head>"
                + "<body>"
                + "<pre class=\"c1\">long text line long text line long text line long text line (new line here!) \nlong text line long text line long text line long text line</pre>"
                + "<pre class=\"c2\">long text line long text line long text line long text line (new line here!) \nlong text line long text line long text line long text line</pre>"
                + "<p   class=\"c3\">long text line long text line long text line long text line (new line here!) \nlong text line long text line long text line long text line</p>"
                + "</body>"
                + "</html>");
        scrollPane.setViewportView(editorPane);
        getContentPane().add(scrollPane);
        pack();
    }

    public static void main(String args[]) {
        new PreWrapApp().setVisible(true);
    }
}

Спасибо.


person Braulio Horta    schedule 24.09.2010    source источник
comment
Не уверен, что это решит проблему, но этот проект выглядит очень интересно: cssbox.sourceforge.net/swingbox   -  person Paolo Fulgoni    schedule 17.06.2014


Ответы (2)


Я наконец сделал это!

Все, что вам нужно сделать, это предотвратить создание файла javax.swing.text.html.LineView. Это представление, которое не обертывается.

Ниже приведен полностью рабочий пример.

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.text.*;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

public class PreWrapApp extends javax.swing.JFrame {

    public static class PreWrapHTMLEditorKit extends HTMLEditorKit {

        ViewFactory viewFactory = new HTMLFactory() {

            @Override
            public View create(Element elem) {
                AttributeSet attrs = elem.getAttributes();
                Object elementName = attrs.getAttribute(AbstractDocument.ElementNameAttribute);
                Object o = (elementName != null) ? null : attrs.getAttribute(StyleConstants.NameAttribute);
                if (o instanceof HTML.Tag) {
                    HTML.Tag kind = (HTML.Tag) o;
                    if (kind == HTML.Tag.IMPLIED) {
                        return new javax.swing.text.html.ParagraphView(elem);
                    }
                }
                return super.create(elem);
            }
        };

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

    public PreWrapApp() {
        JEditorPane editorPane = new JEditorPane();
        JScrollPane scrollPane = new JScrollPane();

        this.setPreferredSize(new Dimension(300, 300));
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        editorPane.setEditorKit(new PreWrapHTMLEditorKit());
        editorPane.setText(""
                + "<html>"
                + "<head></head>"
                + "<body>"
                + "<pre>long text line long text line long text line long text line (two new lines here!)\n\n"
                + "long text line long text line long text line long text line long text line long text line</pre>"
                + "</body>"
                + "</html>");
        scrollPane.setViewportView(editorPane);
        getContentPane().add(scrollPane);
        pack();
    }

    public static void main(String args[]) {
        new PreWrapApp().setVisible(true);
    }
}
person Braulio Horta    schedule 28.09.2010

UPDATE2 (удален ошибочный ответ, который теперь отредактирован в вопросе)

Вам нужно найти замену HTMLEditorKit, совместимую с CSS2+. Вы можете ждать JWebPane вечно или просмотреть некоторые из этих ответов. Другой маршрут будет Браузер SWT, если у вас есть возможность немного отказаться от Swing.

person Geoffrey Zheng    schedule 24.09.2010
comment
Хорошо, но как я могу завернуть и вернуться? Какой подкласс javax.swing.text.View следует вернуть? - person Braulio Horta; 25.09.2010
comment
Видите ли, когда кто-то использует ‹pre›, он хочет сохранить формат, но наличие pre и wrap не так уж противоречит друг другу. На самом деле для этого есть таблица стилей white-space: pre-wrap. Но HTMLEditorKit не поддерживает его. :( Есть еще идеи? - person Braulio Horta; 25.09.2010
comment
Извините за мое невежество в CSS. pre-wrap довольно аккуратно, я буду продолжать искать удовлетворительное решение и отпишусь, если найду его. - person Geoffrey Zheng; 25.09.2010