Example usage for javax.swing JEditorPane getDocument

List of usage examples for javax.swing JEditorPane getDocument

Introduction

In this page you can find the example usage for javax.swing JEditorPane getDocument.

Prototype

public Document getDocument() 

Source Link

Document

Fetches the model associated with the editor.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    JEditorPane edPane = new JEditorPane();
    edPane.setContentType("text/html");

    HTMLEditorKit hek = new HTMLEditorKit();

    edPane.setEditorKit(hek);/*  w ww  . j av  a  2s.  c  o  m*/

    HTMLDocument doc = (HTMLDocument) edPane.getDocument();

    doc.insertString(0, "Test testing", null);

    Element[] roots = doc.getRootElements();
    Element body = null;
    for (int i = 0; i < roots[0].getElementCount(); i++) {
        Element element = roots[0].getElement(i);
        if (element.getAttributes().getAttribute(StyleConstants.NameAttribute) == HTML.Tag.BODY) {
            body = element;
            break;
        }
    }

    doc.insertAfterEnd(body, "<img src=" + ClassLoader.getSystemResource("thumbnail.png").toString() + ">");
    frame.add(edPane);

    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame fr = new JFrame();
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JEditorPane pane = new JEditorPane();
    pane.setEditorKit(new NewEditorKit());
    pane.setText(/*  ww  w.  j a  v a  2 s  .  c o  m*/
            "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");

    StyledDocument doc = (StyledDocument) pane.getDocument();
    MutableAttributeSet attr = new SimpleAttributeSet();
    attr.addAttribute("strike-color", Color.red);
    doc.setCharacterAttributes(0, 9, attr, false);

    attr.addAttribute("strike-color", Color.blue);
    doc.setCharacterAttributes(10, 19, attr, false);
    JScrollPane sp = new JScrollPane(pane);

    fr.getContentPane().add(sp);
    fr.setSize(300, 300);
    fr.setLocationRelativeTo(null);
    fr.setVisible(true);
}

From source file:ReplaceReader.java

public static void main(String[] args) {
    try {//www.  j a  va  2  s  .com
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new JFrame("JEditorPane with Custom Reader");
    JEditorPane ep = new JEditorPane();
    f.getContentPane().add(new JScrollPane(ep));
    f.setSize(400, 300);
    f.setVisible(true);

    HTMLEditorKit kit = new HTMLEditorKit() {
        public Document createDefaultDocument() {
            HTMLDocument doc = new CustomHTMLDocument(getStyleSheet());
            doc.setAsynchronousLoadPriority(4);
            doc.setTokenThreshold(100);
            return doc;
        }
    };
    ep.setEditorKit(kit);

    try {
        Document doc = ep.getDocument();
        doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
        kit.read(new FileReader(args[0]), doc, 0);
    } catch (Exception e) {
        System.out.println("Exception while reading HTML " + e);
    }
}

From source file:com.rapidminer.gui.flow.processrendering.annotations.AnnotationDrawUtils.java

/**
 * Returns plain text from the editor.//  w w  w  .  jav  a  2s . c  o  m
 *
 * @param editor
 *            the editor from which to take the text.
 * @param onlySelected
 *            if {@code true} will only return the selected text
 * @return the text of the editor converted to plain text
 * @throws BadLocationException
 * @throws IOException
 */
public static String getPlaintextFromEditor(final JEditorPane editor, final boolean onlySelected)
        throws IOException, BadLocationException {
    if (editor == null) {
        throw new IllegalArgumentException("editor must not be null!");
    }
    HTMLDocument document = (HTMLDocument) editor.getDocument();
    StringWriter writer = new StringWriter();
    int start = 0;
    int length = document.getLength();
    if (onlySelected) {
        start = editor.getSelectionStart();
        length = editor.getSelectionEnd() - start;
    }
    editor.getEditorKit().write(writer, document, start, length);
    String text = writer.toString();
    text = AnnotationDrawUtils.removeStyleFromComment(text);
    // switch <br> and <br/> to actual newline (current system)
    text = text.replaceAll("<br.*?>", System.lineSeparator());
    // kill all other html tags
    text = text.replaceAll("\\<.*?>", "");
    text = StringEscapeUtils.unescapeHtml(text);
    return text;
}

From source file:net.sf.texprinter.utils.UIUtils.java

/**
 * Set the label font to the editor. When the content type
 * is set to 'text/html', the plain visualization is very ugly, so this
 * method will set the default JLabel font to a JEditorPane.
 *
 * @param editor The editor. The CSS stylesheet will be added to it.
 * @param justify A flag representing full justification. If true, the
 * text will be fully justified.//from ww w .jav  a  2  s.  c  om
 */
public static void setDefaultFontToEditorPane(JEditorPane editor, boolean justify) {

    // get the system font
    Font font = UIManager.getFont("Label.font");

    // set the body rule
    String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize()
            + "pt; margin-left: 0px; margin-top: 0px; " + (justify ? "text-align: justify;" : "") + " }";

    // set the list rule
    String listRule = "ol { margin-left: 20px; list-style-type: square; }";

    // add the body rule
    ((HTMLDocument) editor.getDocument()).getStyleSheet().addRule(bodyRule);

    // add the list rule
    ((HTMLDocument) editor.getDocument()).getStyleSheet().addRule(listRule);
}

From source file:com.mirth.connect.plugins.rtfviewer.RTFViewer.java

@Override
public void viewAttachments(List<String> attachmentIds) {
    // do viewing code

    Frame frame = new Frame("RTF Viewer");

    frame.setLayout(new BorderLayout());

    try {//  ww  w .j  ava 2s .c  o m

        Attachment attachment = parent.mirthClient.getAttachment(attachmentIds.get(0));
        byte[] rawRTF = Base64.decodeBase64(attachment.getData());
        JEditorPane jEditorPane = new JEditorPane("text/rtf", new String(rawRTF));

        if (jEditorPane.getDocument().getLength() == 0) {
            // decoded when it should not have been.  i.e.) the attachment data was not encoded.
            jEditorPane.setText(new String(attachment.getData()));
        }

        jEditorPane.setEditable(false);
        JScrollPane scrollPane = new javax.swing.JScrollPane();
        scrollPane.setViewportView(jEditorPane);
        frame.add(scrollPane);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

        frame.setSize(600, 800);

        Dimension dlgSize = frame.getSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            frame.setLocationRelativeTo(null);
        } else {
            frame.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        frame.setVisible(true);
    } catch (Exception e) {
        parent.alertException(parent, e.getStackTrace(), e.getMessage());
    }
}

From source file:com.mirth.connect.plugins.textviewer.TextViewer.java

@Override
public void viewAttachments(String channelId, Long messageId, String attachmentId) {
    // do viewing code
    Frame frame = new Frame("Text Viewer");
    frame.setLayout(new BorderLayout());

    try {//from  w  w  w . j  a  v  a 2 s .c o m
        Attachment attachment = parent.mirthClient.getAttachment(channelId, messageId, attachmentId);
        byte[] content = Base64.decodeBase64(attachment.getContent());

        boolean isRTF = attachment.getType().toLowerCase().contains("rtf");
        //TODO set character encoding
        JEditorPane jEditorPane = new JEditorPane(isRTF ? "text/rtf" : "text/plain", new String(content));

        if (jEditorPane.getDocument().getLength() == 0) {
            // decoded when it should not have been.  i.e.) the attachment data was not encoded.
            jEditorPane.setText(new String(attachment.getContent()));
        }

        jEditorPane.setEditable(false);
        JScrollPane scrollPane = new javax.swing.JScrollPane();
        scrollPane.setViewportView(jEditorPane);
        frame.add(scrollPane);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                e.getWindow().dispose();
            }
        });

        frame.setSize(600, 800);

        Dimension dlgSize = frame.getSize();
        Dimension frmSize = parent.getSize();
        Point loc = parent.getLocation();

        if ((frmSize.width == 0 && frmSize.height == 0) || (loc.x == 0 && loc.y == 0)) {
            frame.setLocationRelativeTo(null);
        } else {
            frame.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
        }

        frame.setVisible(true);
    } catch (Exception e) {
        parent.alertThrowable(parent, e);
    }
}

From source file:net.sf.jabref.gui.fieldeditors.PreviewPanelTransferHandler.java

@Override
protected Transferable createTransferable(JComponent component) {
    if (component instanceof JEditorPane) {
        // this method should be called from the preview panel only

        // the default TransferHandler implementation is aware of HTML
        // and returns an appropriate Transferable
        // as textTransferHandler.createTransferable() is not available and
        // I don't know any other method, I do the HTML conversion by hand

        // First, get the HTML of the selected text
        JEditorPane editorPane = (JEditorPane) component;
        StringWriter stringWriter = new StringWriter();
        try {/* w  w w. j  a  v  a  2  s  . c om*/
            editorPane.getEditorKit().write(stringWriter, editorPane.getDocument(),
                    editorPane.getSelectionStart(), editorPane.getSelectionEnd());
        } catch (BadLocationException | IOException e) {
            LOGGER.warn("Cannot write preview", e);
        }

        // Second, return the HTML (and text as fallback)
        return new HtmlTransferable(stringWriter.toString(), editorPane.getSelectedText());
    } else {
        // if not called from the preview panel, return an error string
        return new StringSelection(Localization.lang("Operation not supported"));
    }
}

From source file:Main.java

public Main() throws Exception {
    setSize(400, 240);//  ww w.  j  ava  2 s  .  c  o m
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());
    getContentPane().add(topPanel, BorderLayout.CENTER);

    RTFEditorKit rtf = new RTFEditorKit();
    JEditorPane editor = new JEditorPane();
    editor.setEditorKit(rtf);

    JScrollPane scroller = new JScrollPane();
    scroller.getViewport().add(editor);
    topPanel.add(scroller, BorderLayout.CENTER);

    FileInputStream fi = new FileInputStream("test.rtf");
    rtf.read(fi, editor.getDocument(), 0);
}

From source file:net.sf.jasperreports.engine.util.JEditorPaneRtfMarkupProcessor.java

@Override
public String convert(String srcText) {
    JEditorPane editorPane = new JEditorPane("text/rtf", srcText);
    editorPane.setEditable(false);// ww w  .ja v  a 2s.  c o m

    List<Element> elements = new ArrayList<Element>();

    Document document = editorPane.getDocument();

    Element root = document.getDefaultRootElement();
    if (root != null) {
        addElements(elements, root);
    }

    String chunk = null;
    Element element = null;
    int startOffset = 0;
    int endOffset = 0;

    JRStyledText styledText = new JRStyledText();
    styledText.setGlobalAttributes(new HashMap<Attribute, Object>());
    for (int i = 0; i < elements.size(); i++) {
        if (chunk != null) {
            styledText.append(chunk);
            styledText.addRun(
                    new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
        }

        chunk = null;
        element = elements.get(i);
        startOffset = element.getStartOffset();
        endOffset = element.getEndOffset();

        try {
            chunk = document.getText(startOffset, endOffset - startOffset);
        } catch (BadLocationException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error converting markup.", e);
            }
        }

    }

    if (chunk != null && !"\n".equals(chunk)) {
        styledText.append(chunk);
        styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset));
    }

    return JRStyledTextParser.getInstance().write(styledText);
}