Example usage for javax.swing.text StyledDocument insertString

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

Introduction

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

Prototype

public void insertString(int offset, String str, AttributeSet a) throws BadLocationException;

Source Link

Document

Inserts a string of content.

Usage

From source file:TextSamplerDemo.java

private JTextPane createTextPane() {
    String[] initString = { "This is an editable JTextPane, ", //regular
            "another ", //italic
            "styled ", //bold
            "text ", //small
            "component, ", //large
            "which supports embedded components..." + newline, //regular
            " " + newline, //button
            "...and embedded icons..." + newline, //regular
            " ", //icon
            newline + "JTextPane is a subclass of JEditorPane that "
                    + "uses a StyledEditorKit and StyledDocument, and provides "
                    + "cover methods for interacting with those objects." };

    String[] initStyles = { "regular", "italic", "bold", "small", "large", "regular", "button", "regular",
            "icon", "regular" };

    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);//from   ww w . j a  va 2 s.  co  m

    try {
        for (int i = 0; i < initString.length; i++) {
            doc.insertString(doc.getLength(), initString[i], doc.getStyle(initStyles[i]));
        }
    } catch (BadLocationException ble) {
        System.err.println("Couldn't insert initial text into text pane.");
    }

    return textPane;
}

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 {/* ww  w.  ja  v  a  2  s  . com*/
        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.tor.tribes.ui.wiz.ref.SupportRefillCalculationPanel.java

public void notifyStatusUpdate(String pMessage) {
    try {// w ww.  j  a va2s .  c om
        StyledDocument doc = jTextPane1.getStyledDocument();
        doc.insertString(doc.getLength(),
                "(" + dateFormat.format(new Date(System.currentTimeMillis())) + ") " + pMessage + "\n",
                doc.getStyle("Info"));
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                scroll();
            }
        });
    } catch (BadLocationException ignored) {
    }
}

From source file:com.junichi11.netbeans.php.enhancements.ui.actions.ConvertToAction.java

@Override
public void actionPerformed(ActionEvent ev) {
    try {/* ww  w.  ja va 2 s .  c om*/
        JTextComponent editor = EditorRegistry.lastFocusedComponent();
        if (editor == null) {
            return;
        }
        final StyledDocument document = context.openDocument();
        if (editor.getDocument() != document) {
            return;
        }

        final String selectedText = editor.getSelectedText();
        if (selectedText == null || selectedText.isEmpty()) {
            return;
        }

        final String convertedString = convert(selectedText);
        if (selectedText.equals(convertedString)) {
            return;
        }

        final int selectionStartPosition = editor.getSelectionStart();
        NbDocument.runAtomic(document, new Runnable() {

            @Override
            public void run() {
                try {
                    document.remove(selectionStartPosition, selectedText.length());
                    document.insertString(selectionStartPosition, convertedString, null);
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        });
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Make sure the data in the table is valid. This checks to make sure that for
 * all rows, all columns that contain numeric data are actually set, or none
 * of these columns are set in a row. This avoids the case of partial data.
 * This method is fail fast in that it will display a dialog box on the first
 * error it finds./*from   w  ww  .  j  av  a  2  s. c  o m*/
 * 
 * @return true if everything is ok
 */
@SuppressFBWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON", justification = "Static inner class to replace anonomous listener isn't worth the confusion of finding the class definition")
private boolean validateData() {
    stopCellEditors();

    final List<String> warnings = new LinkedList<String>();
    for (final ScoreCategory subjectiveCategory : getChallengeDescription().getSubjectiveCategories()) {
        final String category = subjectiveCategory.getName();
        final String categoryTitle = subjectiveCategory.getTitle();

        final List<AbstractGoal> goals = subjectiveCategory.getGoals();
        final List<Element> scoreElements = SubjectiveTableModel.getScoreElements(_scoreDocument, category);
        for (final Element scoreElement : scoreElements) {
            int numValues = 0;
            for (final AbstractGoal goal : goals) {
                final String goalName = goal.getName();

                final Element subEle = SubjectiveUtils.getSubscoreElement(scoreElement, goalName);
                if (null != subEle) {
                    final String value = subEle.getAttribute("value");
                    if (!value.isEmpty()) {
                        numValues++;
                    }
                }
            }
            if (numValues != goals.size() && numValues != 0) {
                warnings.add(categoryTitle + ": " + scoreElement.getAttribute("teamNumber")
                        + " has too few scores (needs all or none): " + numValues);
            }

        }
    }

    if (!warnings.isEmpty()) {
        // join the warnings with carriage returns and display them
        final StyledDocument doc = new DefaultStyledDocument();
        for (final String warning : warnings) {
            try {
                doc.insertString(doc.getLength(), warning + "\n", null);
            } catch (final BadLocationException ble) {
                throw new RuntimeException(ble);
            }
        }
        final JDialog dialog = new JDialog(this, "Warnings");
        final Container cpane = dialog.getContentPane();
        cpane.setLayout(new BorderLayout());
        final JButton okButton = new JButton("Ok");
        cpane.add(okButton, BorderLayout.SOUTH);
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent ae) {
                dialog.setVisible(false);
                dialog.dispose();
            }
        });
        cpane.add(new JTextPane(doc), BorderLayout.CENTER);
        dialog.pack();
        dialog.setVisible(true);
        return false;
    } else {
        return true;
    }
}

From source file:me.mayo.telnetkek.MainPanel.java

private void writeToConsoleImmediately(final ConsoleMessage message, final boolean isTelnetError) {
    SwingUtilities.invokeLater(() -> {
        if (isTelnetError && chkIgnoreErrors.isSelected()) {
            return;
        }//from   w w w  .j a  v a 2 s . co m

        final StyledDocument styledDocument = mainOutput.getStyledDocument();

        int startLength = styledDocument.getLength();

        try {
            styledDocument.insertString(styledDocument.getLength(),
                    message.getMessage() + System.lineSeparator(),
                    StyleContext.getDefaultStyleContext().addAttribute(SimpleAttributeSet.EMPTY,
                            StyleConstants.Foreground, message.getColor()));
        } catch (BadLocationException ex) {
            throw new RuntimeException(ex);
        }

        if (MainPanel.this.chkAutoScroll.isSelected() && MainPanel.this.mainOutput.getSelectedText() == null) {
            final JScrollBar vScroll = mainOutputScoll.getVerticalScrollBar();

            if (!vScroll.getValueIsAdjusting()) {
                if (vScroll.getValue() + vScroll.getModel().getExtent() >= (vScroll.getMaximum() - 50)) {
                    MainPanel.this.mainOutput.setCaretPosition(startLength);

                    final Timer timer = new Timer(10, (ActionEvent ae) -> {
                        vScroll.setValue(vScroll.getMaximum());
                    });
                    timer.setRepeats(false);
                    timer.start();
                }
            }
        }
    });
}

From source file:eu.ggnet.dwoss.redtape.document.DocumentUpdateView.java

/**
 * Refreshes the Areas contant if changes occur.
 *///from  w w  w  .  ja v  a2  s  .c om
public final void refreshAddressArea() {
    addressesArea.setText("");
    StyledDocument doc = addressesArea.getStyledDocument();
    Style boldStyle = addressesArea.addStyle("bold", null);
    StyleConstants.setBold(boldStyle, true);
    try {
        if (document.getInvoiceAddress().getDescription()
                .equals(document.getShippingAddress().getDescription())) {
            doc.insertString(doc.getLength(), "Rechnungs und Lieferadresse:\n", boldStyle);
            doc.insertString(doc.getLength(), document.getInvoiceAddress().getDescription(), null);
        } else {
            doc.insertString(doc.getLength(), "Rechnungsadresse:\n", boldStyle);
            doc.insertString(doc.getLength(), document.getInvoiceAddress().getDescription(), null);
            doc.insertString(doc.getLength(), "\n\nLieferadresse:\n", boldStyle);
            doc.insertString(doc.getLength(), document.getShippingAddress().getDescription(), null);
        }
    } catch (BadLocationException ex) {
        addressesArea.setText("Rechnungsadresse:\n" + document.getInvoiceAddress().getDescription()
                + "\n\nLieferAdresse:\n" + document.getShippingAddress().getDescription());
    }
}

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 ww  . ja v a  2  s  .  c  om*/
        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:dataviewer.DataViewer.java

private void cb_tableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_tableActionPerformed
    try {//w ww.  ja v  a2s. c  o m
        table = cb_table.getSelectedItem().toString();
        DB db = new DB("./db/" + table + ".db");
        db.open();
        String[] cols = db.get_table_columns(table);
        db.close();

        DefaultTableModel model = new DefaultTableModel();
        //model.addColumn("Column Index");
        model.addColumn("Field");
        int i = 1;

        StyleContext sc = StyleContext.getDefaultStyleContext();
        TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) });
        AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs);
        tp_sql.setParagraphAttributes(paraSet, false);

        StyledDocument doc = tp_sql.getStyledDocument();

        doc.remove(0, doc.getLength());

        doc.insertString(doc.getLength(), "SELECT", null);
        doc.insertString(doc.getLength(), "\n", null);

        for (int j = 1; j < cols.length; ++j) {
            String s = cols[j];
            //model.addRow(new Object[]{i++, s});
            model.addRow(new Object[] { s });
            doc.insertString(doc.getLength(), "\t", null);
            doc.insertString(doc.getLength(), s, null);
            if (j < cols.length - 1) {
                doc.insertString(doc.getLength(), ",", null);
            }
            doc.insertString(doc.getLength(), "\n", null);
        }

        doc.insertString(doc.getLength(), "FROM", null);
        doc.insertString(doc.getLength(), "\n", null);
        doc.insertString(doc.getLength(), "\t", null);
        doc.insertString(doc.getLength(), table, null);
        /*doc.insertString(doc.getLength(), "\n", null);
         doc.insertString(doc.getLength(), "WHERE", null);
         doc.insertString(doc.getLength(), "\n", null);
         doc.insertString(doc.getLength(), "\t", null);
         doc.insertString(doc.getLength(), "_N_ <= " + N, null);
         doc.insertString(doc.getLength(), ";", null);*/

        tb_columns.setModel(model);

        TableRowSorter trs = new TableRowSorter(model);
        trs.setComparator(0, new IntComparator());
        tb_columns.setRowSorter(trs);

        //highline();
    } catch (Exception e) {
        txt_count.setText(e.getMessage());
    }
}

From source file:dylemator.DylematorUI.java

private void displayCenteredText(String text) {
    textArea.setText("");
    text = "\n\n\n" + text;
    SimpleAttributeSet attribs = new SimpleAttributeSet();
    if (sd == null)
        sd = new SettingsDialog(this, true);
    float fnt = sd.getFontSize();
    StyledDocument doc = (StyledDocument) textArea.getDocument();
    Style style = doc.getStyle(StyleContext.DEFAULT_STYLE);//doc.addStyle("MyStyle",null);
    StyleConstants.setFontSize(style, (int) fnt);
    StyleConstants.setLineSpacing(attribs, 0.5f);
    StyleConstants.setFontFamily(style, "Segoe UI");
    StyleConstants.setAlignment(attribs, StyleConstants.ALIGN_CENTER);
    textArea.setParagraphAttributes(attribs, true);

    try {/*from  w w  w  . j a va2 s . c  o m*/
        doc.insertString(doc.getLength(), text, style);
        doc.setParagraphAttributes(0, doc.getLength() - 1, attribs, false);
    } catch (BadLocationException ex) {
        Logger.getLogger(DylematorUI.class.getName()).log(Level.SEVERE, null, ex);
    }

}