Example usage for javax.swing JEditorPane getEditorKit

List of usage examples for javax.swing JEditorPane getEditorKit

Introduction

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

Prototype

public EditorKit getEditorKit() 

Source Link

Document

Fetches the currently installed kit for handling content.

Usage

From source file:Main.java

public static void main(final String args[]) {
    JFrame frame = new JFrame("EditorPane Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    try {//from   w  ww  . j a va 2 s  . c om
        JEditorPane editorPane = new JEditorPane("http://www.java2s.com");
        editorPane.setEditable(false);
        EditorKit kit = editorPane.getEditorKit();

        JScrollPane scrollPane = new JScrollPane(editorPane);
        frame.add(scrollPane);
    } catch (IOException e) {
        System.err.println("Unable to load: " + e);
    }

    frame.setSize(640, 480);
    frame.setVisible(true);
}

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

/**
 * Returns plain text from the editor.//from  w  ww  .ja  v  a  2s.c  om
 *
 * @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:Main.java

public JComponent makeEditorPane(String bullet) {
    JEditorPane pane = new JEditorPane();
    pane.setContentType("text/html");
    pane.setEditable(false);//from  www  . jav  a 2s  .  co  m
    if (bullet != null) {
        HTMLEditorKit htmlEditorKit = (HTMLEditorKit) pane.getEditorKit();
        StyleSheet styleSheet = htmlEditorKit.getStyleSheet();
        String u = "http://i.stack.imgur.com/jV29K.png";
        styleSheet.addRule(String.format("ul{list-style-image:url(%s);margin:0px 20px;", u));
        // styleSheet.addRule("ul{list-style-type:disc;margin:0px 20px;}");

    }
    pane.setText("<html><h1>Heading</h1>Text<ul><li>Bullet point</li></ul></html>");
    return pane;
}

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 {/*from w  ww. j a  v  a 2s .  com*/
            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:org.docx4all.ui.menu.FileMenu.java

@Action
public void printPreview() {
    WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
    JEditorPane editor = wmlEditor.getCurrentEditor();

    WordMLEditorKit kit = (WordMLEditorKit) editor.getEditorKit();
    kit.saveCaretText();/*www. ja  va  2 s .  com*/

    Document doc = editor.getDocument();
    String filePath = (String) doc.getProperty(WordMLDocument.FILE_PATH_PROPERTY);
    DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
    DocumentML rootML = (DocumentML) elem.getElementML();

    //Do not include the last paragraph when saving or printing.
    //we'll put it back when the job is done.
    elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
    ElementML paraML = elem.getElementML();
    ElementML bodyML = paraML.getParent();
    paraML.delete();

    try {
        WordprocessingMLPackage wordMLPackage = rootML.getWordprocessingMLPackage();

        //         XmlPackage worker = new XmlPackage(wordMLPackage);         
        //         org.docx4j.xmlPackage.Package result = worker.get();         
        //         boolean suppressDeclaration = true;
        //         boolean prettyprint = true;         
        //         System.out.println( 
        //               org.docx4j.XmlUtils.
        //                  marshaltoString(result, suppressDeclaration, prettyprint, 
        //                        org.docx4j.jaxb.Context.jcXmlPackage) );

        //Create temporary .pdf file.
        //Remember that filePath is in Commons-VFS format which
        //uses '/' as separator char.
        String tmpName = filePath.substring(filePath.lastIndexOf("/"), filePath.lastIndexOf(Constants.DOT));
        File tmpFile = File.createTempFile(tmpName + ".tmp", ".pdf");
        // Delete the temporary file when program exits.
        tmpFile.deleteOnExit();

        OutputStream os = new java.io.FileOutputStream(tmpFile);

        // Could write to a ByteBuffer and avoid the temp file if:
        // 1. com.sun.pdfview.PDFViewer had an appropriate open method
        // 2. We knew how big to make the buffer
        // java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(15000);
        // //15kb
        // OutputStream os = newOutputStream(buf);

        PdfConversion c = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
        // can change from viaHTML to viaIText or viaXSLFO
        PdfSettings settings = new PdfSettings();
        c.output(os, settings);

        os.close();

        PDFViewer pv = new PDFViewer(true);
        // pv.openFile(buf, "some name"); // requires modified
        // com.sun.pdfview.PDFViewer
        pv.openFile(tmpFile);

    } catch (Exception exc) {
        exc.printStackTrace();
        ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
        String title = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.text");
        String message = rm.getString(PRINT_PREVIEW_ACTION_NAME + ".Action.errorMessage") + "\n"
                + VFSUtils.getFriendlyName(filePath);
        wmlEditor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);

    } finally {
        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);
    }

}

From source file:org.docx4all.ui.menu.FileMenu.java

/**
 * Saves editor documents to a file./*from  w w  w  .ja  v a  2s  .co m*/
 * 
 * Internal frame may have two editors for presenting two different views
 * to user namely editor view and source view. WordMLTextPane is used for 
 * editor view and JEditorPane for source view.
 * The contents of these two editors are synchronized when user switches
 * from one view to the other. Therefore, there will be ONLY ONE editor 
 * that is dirty and has to be saved by this method.
 * 
 * @param iframe
 * @param saveAsFilePath
 * @param callerActionName
 * @return
 */
public boolean save(JInternalFrame iframe, String saveAsFilePath, String callerActionName) {
    boolean success = true;

    if (saveAsFilePath == null) {
        saveAsFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);
    }

    if (log.isDebugEnabled()) {
        log.debug("save(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));
    }

    WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe);
    JEditorPane sourceView = SwingUtil.getSourceEditor(iframe);

    if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG))
            .booleanValue()) {
        //signifies that Source View is not synchronised with Editor View yet.
        //Therefore, it is dirty and has to be saved.
        if (editorView != null && editorView.getWordMLEditorKit().getPlutextClient() != null) {
            //Document has to be saved from editor view 
            //by committing local edits
            success = false;
        } else {
            EditorKit kit = sourceView.getEditorKit();
            Document doc = sourceView.getDocument();
            WordprocessingMLPackage wmlPackage = (WordprocessingMLPackage) doc
                    .getProperty(WordMLDocument.WML_PACKAGE_PROPERTY);

            DocUtil.write(kit, doc, wmlPackage);
            success = save(wmlPackage, saveAsFilePath, callerActionName);

            if (success) {
                if (saveAsFilePath.endsWith(Constants.DOCX_STRING)
                        || saveAsFilePath.endsWith(Constants.FLAT_OPC_STRING)) {
                    doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                    iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                }
            }
        }
        return success;
    }
    sourceView = null;

    if (editorView == null) {
        ;//pass

    } else if (editorView.getWordMLEditorKit().getPlutextClient() != null) {
        if (saveAsFilePath.equals(editorView.getDocument().getProperty(WordMLDocument.FILE_PATH_PROPERTY))) {
            success = commitLocalChanges(editorView, callerActionName);

        } else {
            //TODO: Enable saving Plutext document as a new file.
            WordMLEditor wmlEditor = WordMLEditor.getInstance(WordMLEditor.class);
            ResourceMap rm = wmlEditor.getContext().getResourceMap(getClass());
            String title = rm.getString(callerActionName + ".Action.text");
            StringBuilder message = new StringBuilder();
            message.append("File ");
            message.append(saveAsFilePath);
            message.append(Constants.NEWLINE);
            message.append(rm.getString(callerActionName + ".Action.wrong.fileName.infoMessage"));
            wmlEditor.showMessageDialog(title, message.toString(), JOptionPane.INFORMATION_MESSAGE);

            success = false;
        }
    } else {
        WordMLEditorKit kit = (WordMLEditorKit) editorView.getEditorKit();
        kit.saveCaretText();

        Document doc = editorView.getDocument();
        DocumentElement elem = (DocumentElement) doc.getDefaultRootElement();
        DocumentML rootML = (DocumentML) elem.getElementML();

        //Do not include the last paragraph when saving.
        //After saving we put it back.
        elem = (DocumentElement) elem.getElement(elem.getElementCount() - 1);
        ElementML paraML = elem.getElementML();
        ElementML bodyML = paraML.getParent();
        paraML.delete();

        success = save(rootML.getWordprocessingMLPackage(), saveAsFilePath, callerActionName);

        //Remember to put 'paraML' as last paragraph
        bodyML.addChild(paraML);

        if (success) {
            if (saveAsFilePath.endsWith(Constants.DOCX_STRING)) {
                doc.putProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
                iframe.putClientProperty(WordMLDocument.FILE_PATH_PROPERTY, saveAsFilePath);
            }
        }
    }

    return success;
}

From source file:org.docx4all.ui.menu.FileMenu.java

public boolean export(JInternalFrame iframe, String saveAsFilePath, String callerActionName) {
    log.debug("export(): filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));

    WordprocessingMLPackage srcPackage = null;

    WordMLTextPane editorView = SwingUtil.getWordMLTextPane(iframe);
    JEditorPane sourceView = SwingUtil.getSourceEditor(iframe);

    if (sourceView != null && !((Boolean) sourceView.getClientProperty(Constants.LOCAL_VIEWS_SYNCHRONIZED_FLAG))
            .booleanValue()) {//from w ww .  j  ava  2 s  .  c o  m
        //signifies that Source View is not synchronised with Editor View yet.
        //Therefore, export from Source View.
        EditorKit kit = sourceView.getEditorKit();
        Document doc = sourceView.getDocument();
        srcPackage = DocUtil.write(kit, doc, null);
        editorView = null;
    }
    sourceView = null;

    if (editorView == null) {
        ;//pass
    } else {
        WordMLDocument doc = (WordMLDocument) editorView.getDocument();
        DocumentElement root = (DocumentElement) doc.getDefaultRootElement();
        DocumentML docML = (DocumentML) root.getElementML();
        srcPackage = docML.getWordprocessingMLPackage();
    }

    boolean success = save(XmlUtil.export(srcPackage), saveAsFilePath, callerActionName);

    log.debug("export(): success=" + success + " filePath=" + VFSUtils.getFriendlyName(saveAsFilePath));

    return success;
}

From source file:VASSAL.launch.ModuleManagerWindow.java

public ModuleManagerWindow() {
    setTitle("VASSAL");
    setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));

    ApplicationIcons.setFor(this);

    final AbstractAction shutDownAction = new AbstractAction() {
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            if (!AbstractLaunchAction.shutDown())
                return;

            final Prefs gl = Prefs.getGlobalPrefs();
            try {
                gl.write();//from w w w . j  a v  a 2  s  .  c  o m
                gl.close();
            } catch (IOException ex) {
                WriteErrorDialog.error(ex, gl.getFile());
            } finally {
                IOUtils.closeQuietly(gl);
            }

            logger.info("Exiting");
            System.exit(0);
        }
    };
    shutDownAction.putValue(Action.NAME, Resources.getString(Resources.QUIT));

    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            shutDownAction.actionPerformed(null);
        }
    });

    // setup menubar and actions
    final MenuManager mm = MenuManager.getInstance();
    final MenuBarProxy mb = mm.getMenuBarProxyFor(this);

    // file menu
    final MenuProxy fileMenu = new MenuProxy(Resources.getString("General.file"));
    fileMenu.setMnemonic(Resources.getString("General.file.shortcut").charAt(0));

    fileMenu.add(mm.addKey("Main.play_module"));
    fileMenu.add(mm.addKey("Main.edit_module"));
    fileMenu.add(mm.addKey("Main.new_module"));
    fileMenu.add(mm.addKey("Main.import_module"));
    fileMenu.addSeparator();

    if (!SystemUtils.IS_OS_MAC_OSX) {
        fileMenu.add(mm.addKey("Prefs.edit_preferences"));
        fileMenu.addSeparator();
        fileMenu.add(mm.addKey("General.quit"));
    }

    // tools menu
    final MenuProxy toolsMenu = new MenuProxy(Resources.getString("General.tools"));

    // Initialize Global Preferences
    Prefs.getGlobalPrefs().getEditor().initDialog(this);
    Prefs.initSharedGlobalPrefs();

    final BooleanConfigurer serverStatusConfig = new BooleanConfigurer(SHOW_STATUS_KEY, null, Boolean.FALSE);
    Prefs.getGlobalPrefs().addOption(null, serverStatusConfig);

    dividerLocationConfig = new IntConfigurer(DIVIDER_LOCATION_KEY, null, -10);
    Prefs.getGlobalPrefs().addOption(null, dividerLocationConfig);

    toolsMenu.add(new CheckBoxMenuItemProxy(new AbstractAction(Resources.getString("Chat.server_status")) {
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            serverStatusView.toggleVisibility();
            serverStatusConfig.setValue(serverStatusConfig.booleanValue() ? Boolean.FALSE : Boolean.TRUE);
            if (serverStatusView.isVisible()) {
                setDividerLocation(getPreferredDividerLocation());
            }
        }
    }, serverStatusConfig.booleanValue()));

    // help menu
    final MenuProxy helpMenu = new MenuProxy(Resources.getString("General.help"));
    helpMenu.setMnemonic(Resources.getString("General.help.shortcut").charAt(0));

    helpMenu.add(mm.addKey("General.help"));
    helpMenu.add(mm.addKey("Main.tour"));
    helpMenu.addSeparator();
    helpMenu.add(mm.addKey("UpdateCheckAction.update_check"));
    helpMenu.add(mm.addKey("Help.error_log"));

    if (!SystemUtils.IS_OS_MAC_OSX) {
        helpMenu.addSeparator();
        helpMenu.add(mm.addKey("AboutScreen.about_vassal"));
    }

    mb.add(fileMenu);
    mb.add(toolsMenu);
    mb.add(helpMenu);

    // add actions
    mm.addAction("Main.play_module", new Player.PromptLaunchAction(this));
    mm.addAction("Main.edit_module", new Editor.PromptLaunchAction(this));
    mm.addAction("Main.new_module", new Editor.NewModuleLaunchAction(this));
    mm.addAction("Main.import_module", new Editor.PromptImportLaunchAction(this));
    mm.addAction("Prefs.edit_preferences", Prefs.getGlobalPrefs().getEditor().getEditAction());
    mm.addAction("General.quit", shutDownAction);

    URL url = null;
    try {
        url = new File(Documentation.getDocumentationBaseDir(), "README.html").toURI().toURL();
    } catch (MalformedURLException e) {
        ErrorDialog.bug(e);
    }
    mm.addAction("General.help", new ShowHelpAction(url, null));

    mm.addAction("Main.tour", new LaunchTourAction(this));
    mm.addAction("AboutScreen.about_vassal", new AboutVASSALAction(this));
    mm.addAction("UpdateCheckAction.update_check", new UpdateCheckAction(this));
    mm.addAction("Help.error_log", new ShowErrorLogAction(this));

    setJMenuBar(mm.getMenuBarFor(this));

    // Load Icons
    moduleIcon = new ImageIcon(getClass().getResource("/images/mm-module.png"));
    activeExtensionIcon = new ImageIcon(getClass().getResource("/images/mm-extension-active.png"));
    inactiveExtensionIcon = new ImageIcon(getClass().getResource("/images/mm-extension-inactive.png"));
    openGameFolderIcon = new ImageIcon(getClass().getResource("/images/mm-gamefolder-open.png"));
    closedGameFolderIcon = new ImageIcon(getClass().getResource("/images/mm-gamefolder-closed.png"));
    fileIcon = new ImageIcon(getClass().getResource("/images/mm-file.png"));

    // build module controls
    final JPanel moduleControls = new JPanel(new BorderLayout());
    modulePanelLayout = new CardLayout();
    moduleView = new JPanel(modulePanelLayout);
    buildTree();
    final JScrollPane scroll = new JScrollPane(tree);
    moduleView.add(scroll, "modules");

    final JEditorPane l = new JEditorPane("text/html", Resources.getString("ModuleManager.quickstart"));
    l.setEditable(false);

    // Try to get background color and font from LookAndFeel;
    // otherwise, use dummy JLabel to get color and font.
    Color bg = UIManager.getColor("control");
    Font font = UIManager.getFont("Label.font");

    if (bg == null || font == null) {
        final JLabel dummy = new JLabel();
        if (bg == null)
            bg = dummy.getBackground();
        if (font == null)
            font = dummy.getFont();
    }

    l.setBackground(bg);
    ((HTMLEditorKit) l.getEditorKit()).getStyleSheet()
            .addRule("body { font: " + font.getFamily() + " " + font.getSize() + "pt }");

    l.addHyperlinkListener(BrowserSupport.getListener());

    // FIXME: use MigLayout for this!
    // this is necessary to get proper vertical alignment
    final JPanel p = new JPanel(new GridBagLayout());
    final GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    p.add(l, c);

    moduleView.add(p, "quickStart");
    modulePanelLayout.show(moduleView, getModuleCount() == 0 ? "quickStart" : "modules");
    moduleControls.add(moduleView, BorderLayout.CENTER);
    moduleControls.setBorder(new TitledBorder(Resources.getString("ModuleManager.recent_modules")));

    add(moduleControls);

    // build server status controls
    final ServerStatusView serverStatusControls = new ServerStatusView(new CgiServerStatus());
    serverStatusControls.setBorder(new TitledBorder(Resources.getString("Chat.server_status")));

    serverStatusView = new ComponentSplitter().splitRight(moduleControls, serverStatusControls, false);
    serverStatusView.revalidate();

    // show the server status controls according to the prefs
    if (serverStatusConfig.booleanValue()) {
        serverStatusView.showComponent();
    }

    setDividerLocation(getPreferredDividerLocation());
    serverStatusView.addPropertyChangeListener("dividerLocation", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            setPreferredDividerLocation((Integer) e.getNewValue());
        }
    });

    final Rectangle r = Info.getScreenBounds(this);
    serverStatusControls.setPreferredSize(new Dimension((int) (r.width / 3.5), 0));

    setSize(3 * r.width / 4, 3 * r.height / 4);

    // Save/load the window position and size in prefs
    final PositionOption option = new PositionOption(PositionOption.key + "ModuleManager", this);
    Prefs.getGlobalPrefs().addOption(option);
}