Example usage for javax.swing.text StyledDocument getCharacterElement

List of usage examples for javax.swing.text StyledDocument getCharacterElement

Introduction

In this page you can find the example usage for javax.swing.text StyledDocument getCharacterElement.

Prototype

public Element getCharacterElement(int pos);

Source Link

Document

Gets the element that represents the character that is at the given offset within the document.

Usage

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();//ww  w  .  java2  s.  c  o 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:Main.java

private static AttributeSet getAttributes(MouseEvent e) {
    JTextPane text = (JTextPane) e.getSource();
    Point mouseLocation = new Point(e.getX(), e.getY());
    int pos = text.viewToModel(mouseLocation);

    if (pos >= 0) {
        try {/*from w  w  w.  jav a2 s.  c o  m*/
            Rectangle rect = text.modelToView(pos);
            int lowerCorner = rect.y + rect.height;
            if (e.getX() < rect.x && e.getY() < lowerCorner && pos > 0) {
                pos--;
            }
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
        StyledDocument doc = text.getStyledDocument();
        Element element = doc.getCharacterElement(pos);
        return element.getAttributes();
    }
    return null;
}

From source file:Main.java

private void changeStyle() {
    StyledDocument doc = (StyledDocument) textPane.getDocument();
    int selectionEnd = textPane.getSelectionEnd();
    int selectionStart = textPane.getSelectionStart();
    if (selectionStart == selectionEnd) {
        return;/*from w ww. j av a2  s  .  c  o m*/
    }
    Element element = doc.getCharacterElement(selectionStart);
    AttributeSet as = element.getAttributes();

    MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
    StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
    doc.setCharacterAttributes(selectionStart, textPane.getSelectedText().length(), asNew, true);
    String text = (StyleConstants.isBold(as) ? "Cancel Bold" : "Bold");
    btnStyle.setText(text);
}

From source file:MainClass.java

public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);

    if (editor == null) {
        JOptionPane.showMessageDialog(null,
                "You need to select the editor pane before you can change the color.", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;/*from   w w w .  ja  va  2  s .c  o m*/
    }
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    fg = StyleConstants.getForeground(as);
    if (fg == null) {
        fg = Color.BLACK;
    }
    colorChooser.setColor(fg);

    JButton accept = new JButton("OK");
    accept.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            fg = colorChooser.getColor();
            dialog.dispose();
        }
    });

    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            cancelled = true;
            dialog.dispose();
        }
    });

    JButton none = new JButton("None");
    none.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            noChange = true;
            dialog.dispose();
        }
    });

    JPanel buttons = new JPanel();
    buttons.add(accept);
    buttons.add(none);
    buttons.add(cancel);

    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
    dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
    dialog.setModal(true);
    dialog.pack();
    dialog.setVisible(true);

    if (!cancelled) {

        MutableAttributeSet attr = null;
        if (editor != null) {
            if (fg != null && !noChange) {
                attr = new SimpleAttributeSet();
                StyleConstants.setForeground(attr, fg);
                setCharacterAttributes(editor, attr, false);
            }
        }
    } // end if color != null
    noChange = false;
    cancelled = false;
}

From source file:MainClass.java

public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();

    family = StyleConstants.getFontFamily(as);
    fontSize = StyleConstants.getFontSize(as);

    formatText = new JDialog(new JFrame(), "Font and Size", true);
    formatText.getContentPane().setLayout(new BorderLayout());

    JPanel choosers = new JPanel();
    choosers.setLayout(new GridLayout(2, 1));

    JPanel fontFamilyPanel = new JPanel();
    fontFamilyPanel.add(new JLabel("Font"));

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();

    fontFamilyChooser = new JComboBox();
    for (int i = 0; i < fontNames.length; i++) {
        fontFamilyChooser.addItem(fontNames[i]);
    }//from  w  ww .  ja  v  a 2  s .  c  o m
    fontFamilyChooser.setSelectedItem(family);
    fontFamilyPanel.add(fontFamilyChooser);
    choosers.add(fontFamilyPanel);

    JPanel fontSizePanel = new JPanel();
    fontSizePanel.add(new JLabel("Size"));
    fontSizeChooser = new JComboBox();
    fontSizeChooser.setEditable(true);
    fontSizeChooser.addItem(new Float(4));
    fontSizeChooser.addItem(new Float(8));
    fontSizeChooser.addItem(new Float(12));
    fontSizeChooser.addItem(new Float(16));
    fontSizeChooser.addItem(new Float(20));
    fontSizeChooser.addItem(new Float(24));
    fontSizeChooser.setSelectedItem(new Float(fontSize));
    fontSizePanel.add(fontSizeChooser);
    choosers.add(fontSizePanel);

    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            accept = true;
            formatText.dispose();
            family = (String) fontFamilyChooser.getSelectedItem();
            fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
        }
    });

    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            formatText.dispose();
        }
    });

    JPanel buttons = new JPanel();
    buttons.add(ok);
    buttons.add(cancel);
    formatText.getContentPane().add(choosers, BorderLayout.CENTER);
    formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
    formatText.pack();
    formatText.setVisible(true);

    MutableAttributeSet attr = null;
    if (editor != null && accept) {
        attr = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attr, family);
        StyleConstants.setFontSize(attr, (int) fontSize);
        setCharacterAttributes(editor, attr, false);
    }

}

From source file:Main.java

private void initComponents() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane textPane = new JTextPane();
    ((AbstractDocument) textPane.getDocument()).addDocumentListener(new DocumentListener() {
        @Override/*w  w w  .j av a2 s.com*/
        public void insertUpdate(final DocumentEvent de) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        StyledDocument doc = (StyledDocument) de.getDocument();
                        int start = Utilities.getRowStart(textPane, Math.max(0, de.getOffset() - 1));
                        int end = Utilities.getWordStart(textPane, de.getOffset() + de.getLength());

                        String text = doc.getText(start, end - start);

                        for (String emoticon : imageTokens) {
                            int i = text.indexOf(emoticon);
                            while (i >= 0) {
                                final SimpleAttributeSet attrs = new SimpleAttributeSet(
                                        doc.getCharacterElement(start + i).getAttributes());
                                if (StyleConstants.getIcon(attrs) == null) {
                                    switch (emoticon) {
                                    case imageToken:
                                        StyleConstants.setIcon(attrs, anImage);
                                        break;
                                    }
                                    doc.remove(start + i, emoticon.length());
                                    doc.insertString(start + i, emoticon, attrs);
                                }
                                i = text.indexOf(emoticon, i + emoticon.length());
                            }
                        }
                    } catch (BadLocationException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });

    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setPreferredSize(new Dimension(300, 300));
    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);
}

From source file:plugin.notes.gui.NotesView.java

/**
 *  Updates Editing buttons based on the location of the cursor
 *
 *@param  textPane  text pane to update buttons base on
 *@param  pos       current text position
 */// w w w .ja  v a2  s .c  o  m
private void updateButtons(JTextPane textPane, int pos) {
    StyledDocument doc = textPane.getStyledDocument();
    AttributeSet set = doc.getCharacterElement(pos - 1).getAttributes();
    AttributeSet set1 = doc.getCharacterElement(pos).getAttributes();

    if (StyleConstants.isBold(set) && StyleConstants.isBold(set1)) {
        highlightButton(boldButton);
    } else {
        stdButton(boldButton);
    }

    if (StyleConstants.isItalic(set) && StyleConstants.isItalic(set1)) {
        highlightButton(italicButton);
    } else {
        stdButton(italicButton);
    }

    if (StyleConstants.isUnderline(set) && StyleConstants.isUnderline(set1)) {
        highlightButton(underlineButton);
    } else {
        stdButton(underlineButton);
    }

    int align = StyleConstants.getAlignment(set);
    stdButton(leftJustifyButton);
    stdButton(rightJustifyButton);
    stdButton(centerJustifyButton);

    if (align == StyleConstants.ALIGN_LEFT) {
        highlightButton(leftJustifyButton);
    } else if (align == StyleConstants.ALIGN_RIGHT) {
        highlightButton(rightJustifyButton);
    } else if (align == StyleConstants.ALIGN_CENTER) {
        highlightButton(centerJustifyButton);
    }

    int fontSize = StyleConstants.getFontSize(set);

    for (int i = 0; i < sizeCB.getItemCount(); i++) {
        String value = (String) sizeCB.getItemAt(i);

        if (value.equals(Integer.toString(fontSize))) {
            sizeCB.setSelectedItem(value);

            break;
        }
    }
}

From source file:plugin.notes.gui.NotesView.java

private void handleBackspace() {
    // TODO: This sucks, clean it up
    Element elem;//from w  w w .ja va  2  s. c o m
    int pos = editor.getCaretPosition();
    StyledDocument htmlDoc = editor.getStyledDocument();

    try {
        if (pos > 0) {
            if ((editor.getSelectedText()) != null) {
                ExtendedHTMLEditorKit.delete(editor);
                return;
            }

            int sOffset = htmlDoc.getParagraphElement(pos).getStartOffset();

            if (sOffset == editor.getSelectionStart()) {

                if (ExtendedHTMLEditorKit
                        .checkParentsTag(htmlDoc.getParagraphElement(editor.getCaretPosition()), HTML.Tag.LI)) {
                    elem = ExtendedHTMLEditorKit
                            .getListItemParent(htmlDoc.getCharacterElement(editor.getCaretPosition()));
                    boolean content = false;
                    int so = elem.getStartOffset();
                    int eo = elem.getEndOffset();

                    if ((so + 1) < eo) {
                        char[] temp = editor.getText(so, eo - so).toCharArray();
                        for (char aTemp : temp) {
                            if (!Character.isWhitespace(aTemp)) {
                                content = true;
                            }
                        }
                    }

                    if (!content) {
                        elem.getParentElement();
                        ExtendedHTMLEditorKit.removeTag(editor, elem);
                        editor.setCaretPosition(sOffset - 1);
                        return;
                    }
                    editor.setCaretPosition(editor.getCaretPosition() - 1);
                    editor.moveCaretPosition(editor.getCaretPosition() - 2);
                    editor.replaceSelection("");
                    return;
                }
            }

            editor.replaceSelection("");
        }
    } catch (BadLocationException ble) {
        Logging.errorPrint(ble.getMessage(), ble);
    }
}