Example usage for javax.swing.text StyledDocument getLength

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

Introduction

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

Prototype

public int getLength();

Source Link

Document

Returns number of characters of content currently in the document.

Usage

From source file:eu.ggnet.dwoss.util.HtmlDialog.java

private void search() {
    try {//from ww  w.  j  av  a 2s .c  om
        Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);

        documentTextPane.getHighlighter().removeAllHighlights();
        StyledDocument styledDocument = documentTextPane.getStyledDocument();
        String text = styledDocument.getText(0, styledDocument.getLength());

        if (StringUtils.isBlank(text) || StringUtils.isBlank(searchField.getText()))
            return;
        int indexOf = text.indexOf(searchField.getText());

        if (indexOf == -1)
            JOptionPane.showMessageDialog(this, "Nichts gefunden.");
        while (indexOf != -1) {
            try {
                documentTextPane.getHighlighter().addHighlight(indexOf,
                        indexOf + searchField.getText().length(), painter);
                indexOf = text.indexOf(searchField.getText(), indexOf + 1);
            } catch (BadLocationException ex) {
                Logger.getLogger(HtmlDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (BadLocationException ex) {
        Logger.getLogger(HtmlDialog.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public JTextPane createJTextPane() {
    String newline = "\n";
    String[] description = { "PubChem XML Tool (Version: " + version + ")" + newline,
            "By: S. Canny (scanny@scripps.edu) and M. Southern (southern@scripps.edu)" + newline, "" + newline,
            "PubChem XML Tool main functions:" + newline,
            "1. Create a PubChem XML that can include Assay, Result TIDs, Xrefs, Panel, and Categorized Comments."
                    + newline,/* ww w  . j av  a  2 s . c o  m*/
            "2. Extract Assay, Result TID, Xref, Panel, and Categorized Comment information from a PubChem XML."
                    + newline,
            "3. Create a report from an Excel workbook or PubChem XMLs." + newline, "" + newline,
            "Other features:" + newline,
            "1. Automatically adds reference section to description of PubChem XML or a report if placeholder is used."
                    + newline,
            "2. Checks proteins, genes, omims, and taxonomies for connections when creating PubChem XML or a report."
                    + newline,
            "3. Can retrieve on-hold and newly deposited assays from deposition system to extract or create report."
                    + newline,
            "" + newline, "\t\t\t(c) 2010, The Scripps Research Institute- Florida" };
    String[] styles = { "bold", "regular", "regular", "regular", "regular", "regular", "regular", "regular",
            "regular", "regular", "regular", "regular", "regular", "regular", "right" };

    JTextPane jtp = new JTextPane();
    StyledDocument doc = jtp.getStyledDocument();
    addStylesToDocument(doc);

    try {
        for (int ii = 0; ii < description.length; ii++)
            doc.insertString(doc.getLength(), description[ii], doc.getStyle(styles[ii]));
    } catch (BadLocationException ble) {
        log.error(ble.getMessage(), ble);
    }
    jtp.setOpaque(false);
    jtp.setEditable(false);
    jtp.setPreferredSize(new Dimension(640, 230));

    return jtp;
}

From source file:io.github.jeddict.jcode.util.JavaSourceHelper.java

public static void reformat(DataObject dob) {
    try {//from w w w .  j a  va2 s  .  com
        EditorCookie ec = dob.getLookup().lookup(EditorCookie.class);
        if (ec == null) {
            return;
        }

        final StyledDocument doc = ec.openDocument();
        final Reformat reformat = Reformat.get(doc);

        reformat.lock();
        try {
            NbDocument.runAtomicAsUser(doc, () -> {
                try {
                    reformat.reformat(0, doc.getLength());
                } catch (BadLocationException ex) {
                    Exceptions.printStackTrace(ex);
                }
            });
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            reformat.unlock();
            ec.saveDocument();
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:Tela.java

/**
 * Creates new form Tela/*from   w w  w. ja va  2s .c  o  m*/
 */
public Tela() {
    initComponents();
    jPanel2.setLayout(new BorderLayout());
    exibeGrafico(new ArrayList<Double>());

    this.setVisible(true);

    StyledDocument doc = txtArtigos.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    doc.setParagraphAttributes(0, doc.getLength(), center, false);
}

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 v  a 2s .c  o  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:de.tor.tribes.ui.wiz.ref.SupportRefillCalculationPanel.java

public void notifyStatusUpdate(String pMessage) {
    try {/* www.  j av  a 2  s .co  m*/
        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: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 w  ww  . j  a  v a  2  s.  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: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  ava 2s .  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: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  w  w  .ja va2  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:eu.ggnet.dwoss.redtape.document.DocumentUpdateView.java

/**
 * Refreshes the Areas contant if changes occur.
 *//*from  w w  w.  j  ava 2 s  .  co  m*/
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());
    }
}