Example usage for javax.swing JTextPane setEditorKit

List of usage examples for javax.swing JTextPane setEditorKit

Introduction

In this page you can find the example usage for javax.swing JTextPane setEditorKit.

Prototype

public final void setEditorKit(EditorKit kit) 

Source Link

Document

Sets the currently installed kit for handling content.

Usage

From source file:Main.java

public static void main(String[] args) {
    JFrame jframe = new JFrame();
    jframe.setSize(500, 200);//  w w  w.  ja v  a2 s  .co m
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane jTextPane = new JTextPane();
    jTextPane.setEditorKit(new HTMLEditorKit());
    JButton btn = new JButton("Print");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                jTextPane.setContentType("text/html");
                boolean done = jTextPane.print();
                if (done) {
                    System.out.println("Printing is done");
                } else {
                    System.out.println("Error while printing");
                }
            } catch (Exception pex) {
                pex.printStackTrace();
            }
        }
    });
    jframe.add(btn, BorderLayout.SOUTH);
    jframe.add(jTextPane);
    jframe.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(200, 200);//from  w  ww .j  ava  2 s .c  om
    f.getContentPane().setLayout(new BorderLayout());
    JTextPane jtp = new JTextPane();
    jtp.setEditorKit(new WrapEditorKit());
    JScrollPane jsp = new JScrollPane(jtp);
    jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    f.getContentPane().add(jsp, BorderLayout.CENTER);
    jtp.setText("thisIsATestThisisAtestthisIsATestThisisAtestthisIsATestThisisAtest");
    f.setVisible(true);
}

From source file:Main.java

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

    JTextPane pane = new JTextPane();
    pane.setEditorKit(new CustomEditorKit());
    pane.setText("Underline With Different Color");

    StyledDocument doc = (StyledDocument) pane.getDocument();
    MutableAttributeSet attrs = new SimpleAttributeSet();
    attrs.addAttribute("Underline-Color", Color.red);
    doc.setCharacterAttributes(0, doc.getLength() - 1, attrs, true);

    JScrollPane sp = new JScrollPane(pane);
    frame.setContentPane(sp);// w  w  w  . jav a2  s  .  c o  m
    frame.setPreferredSize(new Dimension(400, 300));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String args[]) throws BadLocationException {
    JTextPane textPane1 = new JTextPane();

    MutableAttributeSet black = new SimpleAttributeSet();
    MutableAttributeSet red = new SimpleAttributeSet();

    StyleConstants.setForeground(black, Color.black);
    StyleConstants.setForeground(red, Color.red);
    textPane1.setEditorKit(new StyledEditorKit());
    doc1 = textPane1.getDocument();/*  w  w w . j  a  v  a  2s. co  m*/

    append1("This is a Test!\n");

    attribute = red;
    append1("Hello world! Hello Stackoverflow\n");

    attribute = black;
    append1("the text is black again\n");

    StyledDocument styledDocument = textPane1.getStyledDocument();
    Element element;

    JTextPane textPane2 = new JTextPane();
    textPane2.setEditorKit(new StyledEditorKit());

    doc2 = textPane2.getDocument();
    for (int i = 0; i < styledDocument.getLength(); i++) {
        element = styledDocument.getCharacterElement(i);
        AttributeSet attributeNew = element.getAttributes();
        System.out.println(i);
        append2(styledDocument.getText(i, 1), attributeNew);
    }

    JFrame frame1 = new JFrame();
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setSize(400, 300);
    frame1.getContentPane().add(new JScrollPane(textPane1), BorderLayout.CENTER);
    frame1.setVisible(true);

    JFrame frame2 = new JFrame();
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame2.setSize(400, 300);
    frame2.setLocation(300, 0);
    frame2.getContentPane().add(new JScrollPane(textPane2), BorderLayout.CENTER);
    frame2.setVisible(true);
}

From source file:ExtendedParagraphExample.java

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

    JFrame f = new JFrame("Extended Paragraph Example");

    // Create the StyleContext, the document and the pane
    final StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    final JTextPane pane = new JTextPane(doc);
    pane.setEditorKit(new ExtendedStyledEditorKit());

    try {
        // Add the text and apply the styles
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                // Build the styles
                createDocumentStyles(sc);

                // Add the text
                addText(pane, sc, sc.getStyle(mainStyleName), content);
            }
        });
    } catch (Exception e) {
        System.out.println("Exception when constructing document: " + e);
        System.exit(1);
    }

    f.getContentPane().add(new JScrollPane(pane));
    f.setSize(400, 300);
    f.setVisible(true);
}

From source file:com.hp.alm.ali.idea.ui.editor.field.HTMLAreaField.java

public static void enableCapability(final JTextPane desc, Project project, String value, boolean editable,
        boolean navigation) {
    value = removeSmallFont(value);//from  w w  w. ja  v  a2 s  .c o m
    HTMLEditorKit kit = new HTMLLetterWrappingEditorKit();
    desc.setEditorKit(kit);
    desc.setDocument(kit.createDefaultDocument());
    if (!editable && navigation) {
        value = NavigationDecorator.explodeHtml(project, value);
    }
    desc.setText(value);
    if (!editable) {
        desc.setCaret(new NonAdjustingCaret());
    }
    desc.addCaretListener(new BodyLimitCaretListener(desc));
    if (editable) {
        String element = checkElements(desc.getDocument().getDefaultRootElement());
        if (element != null) {
            desc.setToolTipText("Found unsupported element '" + element + "', editing is disabled.");
            editable = false;
        }
    }
    desc.setEditable(editable);

    if (editable && SpellCheckerManager.isAvailable()
            && ApplicationManager.getApplication().getComponent(AliConfiguration.class).spellChecker) {
        desc.getDocument().addDocumentListener(new SpellCheckDocumentListener(project, desc));
    }

    Font font = UIManager.getFont("Label.font");
    String bodyRule = "body { font-family: " + font.getFamily() + "; " + "font-size: " + font.getSize()
            + "pt; }";
    ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(bodyRule);

    // AGM uses plain "p" to create lines, we need to avoid excessive spacing this by default creates
    String paragraphRule = "p { margin-top: 0px; }";
    ((HTMLDocument) desc.getDocument()).getStyleSheet().addRule(paragraphRule);

    Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
    new AnAction() {
        public void actionPerformed(AnActionEvent e) {
            // following is needed to make copy work in the IDE
            try {
                StringSelection selection = new StringSelection(desc.getText(desc.getSelectionStart(),
                        desc.getSelectionEnd() - desc.getSelectionStart()));
                CopyPasteManager.getInstance().setContents(selection);
            } catch (Exception ex) {
                // no clipboard, so what
            }
        }
    }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_COPY)), desc);
    new AnAction() {
        public void actionPerformed(AnActionEvent e) {
            // avoid pasting non-supported HTML markup by always converting to plain text
            Transferable contents = CopyPasteManager.getInstance().getContents();
            try {
                desc.getActionMap().get(DefaultEditorKit.cutAction).actionPerformed(null);
                desc.getDocument().insertString(desc.getSelectionStart(),
                        (String) contents.getTransferData(DataFlavor.stringFlavor), null);
            } catch (Exception ex) {
                // no clipboard, so what
            }
        }
    }.registerCustomShortcutSet(new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_PASTE)), desc);
    installNavigationShortCuts(desc);

}

From source file:Main.java

public Main() {
    setSize(400, 400);/*from   w  w w  .ja va 2 s . c  o  m*/
    styleSheet.addRule(".someclass1 {color: blue;}");
    styleSheet.addRule(".someclass2 {color: green;}");

    htmlEditorKit.setStyleSheet(styleSheet);
    htmlDocument = (HTMLDocument) htmlEditorKit.createDefaultDocument();
    JTextPane jTextPane = new JTextPane();
    jTextPane.setEditorKit(htmlEditorKit);
    jTextPane.setDocument(htmlDocument);

    try {
        Element htmlElement = htmlDocument.getRootElements()[0];
        bodyElement = htmlElement.getElement(0);

        Container contentPane = getContentPane();
        contentPane.add(jTextPane, BorderLayout.CENTER);
        super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        addContent("<span class=someclass1>test 1</span><br>");
        addContent("<span class=someclass2>test 2</span><br>");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hp.alm.ali.idea.content.settings.SettingsPanel.java

public SettingsPanel(final Project prj, Color bgColor) {
    this.prj = prj;
    this.projectConf = prj.getComponent(AliProjectConfiguration.class);

    previewAndConnection = new JPanel(new GridBagLayout());
    previewAndConnection.setOpaque(false);
    GridBagConstraints c2 = new GridBagConstraints();
    c2.gridx = 0;//from w ww  .  j a va2s.  c  o  m
    c2.gridy = 1;
    c2.gridwidth = 2;
    c2.weighty = 1;
    c2.fill = GridBagConstraints.VERTICAL;
    JPanel filler = new JPanel();
    filler.setOpaque(false);
    previewAndConnection.add(filler, c2);

    passwordPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    passwordPanel.setBackground(bgColor);
    JLabel label = new JLabel("Password");
    label.setFont(label.getFont().deriveFont(Font.BOLD));
    passwordPanel.add(label);
    final JPasswordField password = new JPasswordField(24);
    passwordPanel.add(password);
    JButton connect = new JButton("Login");
    passwordPanel.add(connect);
    final JLabel message = new JLabel();
    passwordPanel.add(message);
    ActionListener connectionAction = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                checkConnection(projectConf.getLocation(), projectConf.getDomain(), projectConf.getProject(),
                        projectConf.getUsername(), password.getText());
            } catch (AuthenticationFailed e) {
                message.setText(e.getMessage());
                return;
            }
            projectConf.ALM_PASSWORD = password.getText();
            projectConf.fireChanged();
        }
    };
    password.addActionListener(connectionAction);
    connect.addActionListener(connectionAction);

    restService = prj.getComponent(RestService.class);
    restService.addServerTypeListener(this);

    location = createTextPane(bgColor);
    domain = createTextPane(bgColor);
    project = createTextPane(bgColor);
    username = createTextPane(bgColor);

    final JPanel panel = new JPanel(new BorderLayout());
    panel.setBackground(bgColor);
    panel.setBorder(new EmptyBorder(10, 10, 10, 10));

    final JTextPane textPane = new JTextPane();
    textPane.setEditorKit(new HTMLEditorKit());
    textPane.setText(
            "<html><body>HP ALM integration can be configured on <a href=\"ide\">IDE</a> and overridden on <a href=\"project\">project</a> level.</body></html>");
    textPane.setEditable(false);
    textPane.addHyperlinkListener(this);
    textPane.setBackground(bgColor);
    textPane.setCaret(new NonAdjustingCaret());
    panel.add(textPane, BorderLayout.CENTER);

    JPanel content = new JPanel(new BorderLayout());
    content.setBackground(bgColor);
    content.add(panel, BorderLayout.NORTH);
    content.add(previewAndConnection, BorderLayout.WEST);

    preview = new JPanel(new GridBagLayout()) {
        public Dimension getPreferredSize() {
            Dimension dim = super.getPreferredSize();
            // make enough room for the connection status message
            dim.width = Math.max(dim.width, 300);
            return dim;
        }

        public Dimension getMinimumSize() {
            return getPreferredSize();
        }
    };
    connectedTo(restService.getServerTypeIfAvailable());
    preview.setBackground(bgColor);

    final GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.anchor = GridBagConstraints.WEST;
    preview.add(location, c);
    c.gridwidth = 1;
    c.gridy++;
    preview.add(domain, c);
    c.gridy++;
    preview.add(project, c);
    c.gridy++;
    preview.add(username, c);
    c.gridx++;
    c.gridy--;
    c.gridheight = 2;
    c.weightx = 0;
    c.anchor = GridBagConstraints.SOUTHEAST;
    final LinkLabel reload = new LinkLabel("Reload", IconLoader.getIcon("/actions/sync.png"));
    reload.setListener(new LinkListener() {
        public void linkSelected(LinkLabel linkLabel, Object o) {
            projectConf.fireChanged();
        }
    }, null);
    preview.add(reload, c);

    JPanel previewNorth = new JPanel(new BorderLayout());
    previewNorth.setBackground(bgColor);
    previewNorth.add(preview, BorderLayout.NORTH);

    addToGridBagPanel(0, 0, previewAndConnection, previewNorth);

    setBackground(bgColor);
    setLayout(new BorderLayout());
    add(content, BorderLayout.CENTER);

    onChanged();
    ApplicationManager.getApplication().getComponent(AliConfiguration.class).addListener(this);
    projectConf.addListener(this);
}

From source file:com.diversityarrays.dal.server.SqlDialog.java

private void showHelp() {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.println("<html>");

    for (String line : HELP_LINES) {
        pw.println(line);//from   w  w w  . j  a v a 2  s .  co  m
    }
    pw.println("</html>");
    pw.close();

    JTextPane helpText = new JTextPane();
    helpText.setEditorKit(new HTMLEditorKit());
    helpText.setText(sw.toString());
    helpText.setEditable(false);

    addPanelToTabbedPane(new JScrollPane(helpText));
}

From source file:com.diversityarrays.dal.server.SqlDialog.java

private void processTaskResult(TaskResult taskResult) {
    if (taskResult.error == null) {
        if (taskResult.isQuery) {
            taskResult.showQueryResult();
        } else {/* w w w  . j a va  2  s .c  o  m*/
            taskResult.showUpdateResult();
        }
    } else {
        StringWriter ew = new StringWriter();
        PrintWriter ep = new PrintWriter(ew);
        taskResult.error.printStackTrace(ep);
        ep.close();
        JPanel panel = new JPanel(new BorderLayout());

        panel.add(BorderLayout.NORTH, GuiUtil.createLabelSeparator(taskResult.whyError));

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        pw.println("<html><body><h3>SQL:</h3><pre>");
        pw.println(DbUtil.htmlEscape(taskResult.sql));
        pw.println("</pre><hr/>");
        pw.println("<h3>Stacktrace</h3><pre>");
        pw.print(DbUtil.htmlEscape(ew.toString()));
        pw.println("</pre>");

        pw.println("</body></html>");
        pw.close();

        JTextPane text = new JTextPane();
        text.setEditorKit(new HTMLEditorKit());
        text.setEditable(false);
        ;
        text.setText(sw.toString());
        ;
        panel.add(BorderLayout.CENTER, new JScrollPane(text));

        addPanelToTabbedPane(panel);
    }
}