Example usage for javax.swing.text StyledDocument setCharacterAttributes

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

Introduction

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

Prototype

public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace);

Source Link

Document

Changes the content element attributes used for the given range of existing content in the document.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();

    // Set text in the range [5, 7) red
    doc.setCharacterAttributes(5, 2, textPane.getStyle("Red"), 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(/*from  w  w  w  .jav a2  s  .co  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: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);//www. ja v  a 2s.co  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) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JTextPane textPane = new JTextPane();

    JButton button = new JButton("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel.setLayout(new BorderLayout());
    panel.setPreferredSize(new Dimension(200, 200));

    panel.add(textPane, BorderLayout.CENTER);
    panel.add(button, BorderLayout.SOUTH);
    textPane.addStyle("myStyle", null);

    button.addActionListener(e -> {/*w  ww .  j  ava 2  s .  c  o  m*/
        StyledDocument doc = textPane.getStyledDocument();
        int start = textPane.getSelectionStart();
        int end = textPane.getSelectionEnd();
        if (start == end) {
            return;
        }
        if (start > end) {
            int life = start;
            start = end;
            end = life;
        }
        Style style = textPane.getStyle("myStyle");

        if (StyleConstants.isBold(style)) {
            StyleConstants.setBold(style, false);
        } else {
            StyleConstants.setBold(style, true);
        }
        doc.setCharacterAttributes(start, end - start, style, false);
    });

    frame.add(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:Main.java

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

    StyledDocument doc = new DefaultStyledDocument();
    JTextPane textPane = new JTextPane(doc);
    textPane.setText("this is a test.");

    Random random = new Random();
    for (int i = 0; i < textPane.getDocument().getLength(); i++) {
        SimpleAttributeSet set = new SimpleAttributeSet();
        StyleConstants.setForeground(set,
                new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        StyleConstants.setFontSize(set, random.nextInt(12) + 12);
        StyleConstants.setBold(set, random.nextBoolean());
        StyleConstants.setItalic(set, random.nextBoolean());
        StyleConstants.setUnderline(set, random.nextBoolean());

        doc.setCharacterAttributes(i, 1, set, true);
    }//from  ww w . ja  v  a 2 s .  co  m

    frame.add(new JScrollPane(textPane));
    frame.setSize(500, 400);
    frame.setVisible(true);
}

From source file:DocumentModel.java

public static void main(String[] args) {
    final StyledDocument doc;
    final JTextPane textpane;

    JFrame f = new JFrame();

    f.setTitle("Document Model");

    JToolBar toolbar = new JToolBar();
    JButton boldb = new JButton("bold");
    JButton italb = new JButton("italic");
    JButton strib = new JButton("strike");
    JButton undeb = new JButton("underline");

    toolbar.add(boldb);/* w  ww .ja  v  a 2s .c o  m*/
    toolbar.add(italb);
    toolbar.add(strib);
    toolbar.add(undeb);

    f.add(toolbar, BorderLayout.NORTH);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    JScrollPane pane = new JScrollPane();
    textpane = new JTextPane();
    textpane.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

    doc = textpane.getStyledDocument();

    Style style = textpane.addStyle("Bold", null);
    StyleConstants.setBold(style, true);

    style = textpane.addStyle("Italic", null);
    StyleConstants.setItalic(style, true);

    style = textpane.addStyle("Underline", null);
    StyleConstants.setUnderline(style, true);

    style = textpane.addStyle("Strike", null);
    StyleConstants.setStrikeThrough(style, true);

    boldb.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            doc.setCharacterAttributes(textpane.getSelectionStart(),
                    textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Bold"),
                    false);
        }
    });

    italb.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            doc.setCharacterAttributes(textpane.getSelectionStart(),
                    textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Italic"),
                    false);
        }

    });

    strib.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            doc.setCharacterAttributes(textpane.getSelectionStart(),
                    textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Strike"),
                    false);
        }

    });

    undeb.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            doc.setCharacterAttributes(textpane.getSelectionStart(),
                    textpane.getSelectionEnd() - textpane.getSelectionStart(), textpane.getStyle("Underline"),
                    false);
        }
    });

    pane.getViewport().add(textpane);
    panel.add(pane);

    f.add(panel);

    f.setSize(new Dimension(380, 320));
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

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;//w ww . j  a va  2  s. co  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:Main.java

public TextPaneAttributes() {
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    MutableAttributeSet standard = new SimpleAttributeSet();

    StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, 0, standard, true);
    MutableAttributeSet keyWord = new SimpleAttributeSet();

    StyleConstants.setForeground(keyWord, Color.red);
    StyleConstants.setItalic(keyWord, true);

    textPane.setText("this is a test. \nthis is a four.");

    doc.setCharacterAttributes(0, 3, keyWord, false);
    doc.setCharacterAttributes(19, 4, keyWord, false);
    try {//from  www  .  j  av a 2s .  c o  m
        doc.insertString(0, "Start of text\n", null);
        doc.insertString(doc.getLength(), "End of text\n", keyWord);
    } catch (Exception e) {
    }
    MutableAttributeSet selWord = new SimpleAttributeSet();

    StyleConstants.setForeground(selWord, Color.RED);
    StyleConstants.setItalic(selWord, true);

    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setPreferredSize(new Dimension(200, 200));
    add(scrollPane);

    JButton toggleButton = new JButton("Find 'four'");
    toggleButton.addActionListener(e -> {
        int index = textPane.getText().indexOf("four");
        StyledDocument doc1 = textPane.getStyledDocument();
        doc1.setCharacterAttributes(index, 4, selWord, false);
    });
    add(toggleButton, BorderLayout.SOUTH);
}

From source file:de.codesourcery.jasm16.ide.ui.views.CPUView.java

private void internalRefreshDisplay() {
    if (emulator == null) {
        return;/* w w w.j a  v a2  s  . c  o m*/
    }
    final IReadOnlyCPU cpu = emulator.getCPU();

    final StringBuilder builder = new StringBuilder();
    final List<ITextRegion> redRegions = new ArrayList<ITextRegion>();

    Throwable lastError = emulator.getLastEmulationError();
    if (lastError != null) {
        final String msg = StringUtils.isBlank(lastError.getMessage()) ? lastError.getClass().getName()
                : lastError.getMessage();
        builder.append("Emulation stopped with an error: " + msg + "\n");
        redRegions.add(new TextRegion(0, builder.length()));
    }

    int itemsInLine = 0;
    for (int i = 0; i < ICPU.COMMON_REGISTER_NAMES.length; i++) {
        final int value = cpu.getRegisterValue(ICPU.COMMON_REGISTERS[i]);
        builder.append(ICPU.COMMON_REGISTER_NAMES[i] + ": " + Misc.toHexString(value) + "    ");

        Address address = Address.wordAddress(value);
        final byte[] data = MemUtils.getBytes(emulator.getMemory(), address, Size.words(4), true);

        builder.append(Misc.toHexDump(address, data, data.length, 4, true, false, true));
        builder.append("\n");
        itemsInLine++;
        if (itemsInLine == 4) {
            itemsInLine = 0;
            builder.append("\n");
        }
    }
    builder.append("\nPC: " + Misc.toHexString(cpu.getPC().getValue()));
    builder.append(" (elapsed cycles: " + cpu.getCurrentCycleCount()).append(")");
    builder.append("\n");

    builder.append("EX: " + Misc.toHexString(cpu.getEX())).append("\n");
    builder.append("IA: " + Misc.toHexString(cpu.getInterruptAddress())).append("\n");

    builder.append("IQ: Interrupt queueing is ");
    if (cpu.isQueueInterrupts()) {
        int start = builder.length();
        builder.append("ON");
        redRegions.add(new TextRegion(start, builder.length() - start));
    } else {
        builder.append("OFF");
    }
    builder.append("\n");
    builder.append("IRQs: " + StringUtils.join(cpu.getInterruptQueue(), ",")).append("\n");
    builder.append("SP: " + Misc.toHexString(cpu.getSP().getValue())).append("\n");

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            final StyledDocument doc = textArea.getStyledDocument();
            doc.putProperty(Document.StreamDescriptionProperty, null);

            textArea.setText(builder.toString());
            for (ITextRegion region : redRegions) {
                doc.setCharacterAttributes(region.getStartingOffset(), region.getLength(), errorStyle, true);
            }
        }
    });
}

From source file:ParenMatcher.java

public void run() {
    StyledDocument doc = getStyledDocument();
    String text = "";
    int len = doc.getLength();
    try {/* ww  w .  j av a  2 s.co m*/
        text = doc.getText(0, len);
    } catch (BadLocationException ble) {
    }
    java.util.Stack stack = new java.util.Stack();
    for (int j = 0; j < text.length(); j += 1) {
        char ch = text.charAt(j);
        if (ch == '(' || ch == '[' || ch == '{') {
            int depth = stack.size();
            stack.push("" + ch + j); // push a String containg the char and
            // the offset
            AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
            doc.setCharacterAttributes(j, 1, aset, false);
        }
        if (ch == ')' || ch == ']' || ch == '}') {
            String peek = stack.empty() ? "." : (String) stack.peek();
            if (matches(peek.charAt(0), ch)) { // does it match?
                stack.pop();
                int depth = stack.size();
                AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
                doc.setCharacterAttributes(j, 1, aset, false);
            } else { // mismatch
                doc.setCharacterAttributes(j, 1, badAttrSet, false);
            }
        }
    }

    while (!stack.empty()) { // anything left in the stack is a mismatch
        String pop = (String) stack.pop();
        int offset = Integer.parseInt(pop.substring(1));
        doc.setCharacterAttributes(offset, 1, badAttrSet, false);
    }
}