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:org.openmicroscopy.shoola.util.ui.UIUtilities.java

/**
 * Formats the text and displays it in a {@link JTextPane}.
 * /* w  w w.j  a va 2s .c  o m*/
 * @param text          The text to display.
 * @param foreground   The foreground color.
 * @return See above.
 */
public static JTextPane buildTextPane(String text, Color foreground) {
    if (text == null)
        text = "";
    StyleContext context = new StyleContext();
    StyledDocument document = new DefaultStyledDocument(context);

    Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setAlignment(style, StyleConstants.ALIGN_LEFT);
    if (foreground != null)
        StyleConstants.setForeground(style, foreground);
    try {
        document.insertString(document.getLength(), text, style);
    } catch (BadLocationException e) {
    }

    JTextPane textPane = new JTextPane(document);
    textPane.setOpaque(false);
    textPane.setEditable(false);
    textPane.setFocusable(false);
    return textPane;
}

From source file:org.optaplanner.benchmark.impl.aggregator.swingui.BenchmarkAggregatorFrame.java

private JComponent createNoPlannerFoundTextField() {
    String infoMessage = "No planner benchmarks have been found in the benchmarkDirectory ("
            + benchmarkAggregator.getBenchmarkDirectory() + ").";
    JTextPane textPane = new JTextPane();

    textPane.setEditable(false);/*from ww w  .  j a v  a  2 s  .  c  o  m*/
    textPane.setText(infoMessage);

    // center info message
    StyledDocument styledDocument = textPane.getStyledDocument();
    SimpleAttributeSet center = new SimpleAttributeSet();
    StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
    StyleConstants.setBold(center, true);
    styledDocument.setParagraphAttributes(0, styledDocument.getLength(), center, false);
    return textPane;
}

From source file:org.quackbot.gui.GUIConsoleAppender.java

/**
 * Used by Log4j to write something from the LoggingEvent. This simply points to
 * WriteOutput which writes to the the GUI or to the console
 * @param event/*w ww  .  ja  v  a 2 s. c o  m*/
 */
@Override
public void append(final ILoggingEvent event) {
    if (!inited)
        synchronized (initMessageQueue) {
            if (!inited) {
                initMessageQueue.add(event);
                return;
            }
        }

    //Grab bot info off of MDC
    final String botId = MDC.get("pircbotx.id");
    final String botServer = MDC.get("pircbotx.server");
    final String botPort = MDC.get("pircbotx.port");

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                //Figure out where this is going
                JTextPane textPane = (StringUtils.isBlank(botId)) ? gui.CerrorLog : gui.BerrorLog;
                JScrollPane scrollPane = (StringUtils.isBlank(botId)) ? gui.CerrorScroll : gui.BerrorScroll;

                //Configure stle
                StyledDocument doc = textPane.getStyledDocument();
                Style msgStyle = event.getLevel().isGreaterOrEqual(Level.WARN) ? doc.getStyle("Error")
                        : doc.getStyle("Normal");

                doc.insertString(doc.getLength(), "\n", doc.getStyle("Normal"));
                int prevLength = doc.getLength();
                doc.insertString(doc.getLength(), "[" + dateFormatter.format(event.getTimeStamp()) + "] ",
                        doc.getStyle("Normal")); //time
                //doc.insertString(doc.getLength(), "["+event.getThreadName()+"] ", doc.getStyle("Thread")); //thread name
                doc.insertString(doc.getLength(), event.getLevel().toString() + " ", doc.getStyle("Level")); //Logging level
                doc.insertString(doc.getLength(), event.getLoggerName() + " ", doc.getStyle("Class"));
                if (StringUtils.isNotBlank(botId)) {
                    String port = !botPort.equals("6667") ? ":" + botPort : "";
                    doc.insertString(doc.getLength(), "<" + botId + ":" + botServer + port + "> ",
                            doc.getStyle("Server"));
                }
                doc.insertString(doc.getLength(), messageLayout.doLayout(event).trim(), msgStyle);

                //Only autoscroll if the scrollbar is at the bottom
                //JScrollBar scrollBar = scroll.getVerticalScrollBar();
                //if (scrollBar.getVisibleAmount() != scrollBar.getMaximum() && scrollBar.getValue() + scrollBar.getVisibleAmount() == scrollBar.getMaximum())
                textPane.setCaretPosition(prevLength);
            } catch (Exception e) {
                addError("Exception encountered when logging", e);
            }
        }
    });
}

From source file:org.smart.migrate.ui.ImportThread.java

@Override
public void log(String level, String msg) {
    if (logger != null) {
        StyledDocument doc = logger.getStyledDocument();
        try {/*from   w  w  w .j  a  va 2 s  . co m*/
            doc.insertString(doc.getLength(), new SimpleDateFormat("MM-dd hh:mm:ss ").format(new Date()),
                    doc.getStyle("gray"));
            doc.insertString(doc.getLength(), msg + "\n", doc.getStyle(level.toLowerCase()));
            logger.setCaretPosition(logger.getDocument().getLength());
            //logger.append(   + ", level:" + level+", message: " + msg+"\n");
        } catch (BadLocationException ex) {
            Logger.getLogger(ImportThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:pl.otros.logview.gui.actions.search.SearchAction.java

private void scrollToSearchResult(ArrayList<String> toHighlight, JTextPane textPane) {
    if (toHighlight.size() == 0) {
        return;/*from  w w  w. ja v  a2 s .c o  m*/
    }
    try {
        StyledDocument logDetailsDocument = textPane.getStyledDocument();
        String text = logDetailsDocument.getText(0, logDetailsDocument.getLength());
        String string = toHighlight.get(0);
        textPane.setCaretPosition(Math.max(text.indexOf(string), 0));
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

From source file:pl.otros.logview.gui.message.update.MessageUpdateUtils.java

public static void highlightSearchResult(OtrosJTextWithRulerScrollPane<JTextPane> otrosJTextWithRulerScrollPane,
        PluginableElementsContainer<MessageColorizer> colorizersContainer) {
    MessageUpdateUtils messageUpdateUtils = new MessageUpdateUtils();
    StyledDocument styledDocument = otrosJTextWithRulerScrollPane.getjTextComponent().getStyledDocument();
    String text;/*from  w  w  w .  j  ava 2  s . c om*/
    try {
        text = styledDocument.getText(0, styledDocument.getLength());
    } catch (BadLocationException e) {
        LOGGER.log(Level.SEVERE, "Cant get document text for log details view: ", e);
        return;
    }
    MessageColorizer messageColorizer = colorizersContainer.getElement(SearchResultColorizer.class.getName());
    List<MessageFragmentStyle> messageFragmentStyles = new ArrayList<MessageFragmentStyle>();
    if (messageColorizer != null) {
        messageFragmentStyles
                .addAll(messageUpdateUtils.colorizeMessageWithTimeLimit(text, 0, messageColorizer, 10));
    }
    markSearchResult(messageFragmentStyles, otrosJTextWithRulerScrollPane);
}

From source file:pl.otros.logview.gui.MessageDetailListener.java

public void updateInfo() {
    Collection<MessageFormatter> formatters = formattersContainer.getElements();
    Collection<MessageColorizer> colorizers = colorizersContainer.getElements();
    int row = table.getSelectedRow();
    if (row >= 0 && row < table.getRowCount()) {
        logDetailTextArea.setText("");
        int rowConverted = table.convertRowIndexToModel(row);
        LogData ld = dataTableModel.getLogData(rowConverted);
        StyledDocument document = logDetailTextArea.getStyledDocument();
        synchronized (document) {
            try {
                document.remove(0, document.getLength());
                String s1 = "Date:    " + dateFormat.format(ld.getDate()) + "\n";
                document.insertString(0, s1, mainStyle);
                s1 = "Class:   " + ld.getClazz() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Method:  " + ld.getMethod() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Level:   ";
                document.insertString(document.getLength(), s1, classMethodStyle);
                Icon levelIcon = LevelRenderer.getIconByLevel(ld.getLevel());
                if (levelIcon != null) {
                    logDetailTextArea.insertIcon(levelIcon);
                }//from   w  w  w .  j  a  v a2s  . c om
                s1 = " " + ld.getLevel().getName() + "\n";
                document.insertString(document.getLength(), s1, classMethodStyle);
                s1 = "Message: ";
                document.insertString(document.getLength(), s1, mainStyle);
                int beforeMessage = document.getLength();
                s1 = ld.getMessage();
                if (s1.length() > maximumMessageSize) {
                    int removedCharsSize = s1.length() - maximumMessageSize;
                    s1 = StringUtils.left(s1, maximumMessageSize)
                            + String.format("%n...%n...(+%,d chars)", removedCharsSize);
                }

                for (MessageFormatter messageFormatter : formatters) {
                    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                    try {
                        Thread.currentThread()
                                .setContextClassLoader(messageFormatter.getClass().getClassLoader());
                        if (messageFormatter.formattingNeeded(s1)) {
                            s1 = messageFormatter.format(s1);
                        }
                    } catch (Throwable e) {
                        LOGGER.severe(String.format("Error occured when using message formatter %s: %s",
                                messageFormatter.getName(), e.getMessage()));
                        LOGGER.fine(String.format(
                                "Error occured when using message formatter %s with message\"%s\"",
                                messageFormatter.getName(), s1));
                    } finally {
                        Thread.currentThread().setContextClassLoader(contextClassLoader);
                    }

                }
                document.insertString(document.getLength(), s1, mainStyle);
                searchResultMessageColorizer = null;
                for (MessageColorizer messageColorizer : colorizers) {
                    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                    try {
                        Thread.currentThread()
                                .setContextClassLoader(messageColorizer.getClass().getClassLoader());
                        if (messageColorizer.colorizingNeeded(s1)) {
                            messageColorizer.colorize(document, beforeMessage,
                                    document.getLength() - beforeMessage);
                        }
                    } catch (Throwable e) {
                        LOGGER.severe(String.format("Error occured when using message colorizer %s: %s",
                                messageColorizer.getName(), e.getMessage()));
                        LOGGER.fine(String.format(
                                "Error occured when using message colorizer %s with message\"%s\"",
                                messageColorizer.getName(), s1));
                    } finally {
                        Thread.currentThread().setContextClassLoader(contextClassLoader);
                    }

                    if (messageColorizer.getPluginableId().equals(SearchResultColorizer.class.getName())) {
                        searchResultMessageColorizer = messageColorizer;
                    }

                }
                if (searchResultMessageColorizer != null && searchResultMessageColorizer.colorizingNeeded(s1)) {
                    searchResultMessageColorizer.colorize(document, beforeMessage,
                            document.getLength() - beforeMessage);
                }
                document.insertString(document.getLength(), "\n", mainStyle);
                if (ld.getProperties() != null && ld.getProperties().size() > 0) {
                    document.insertString(document.getLength(), "\nProperties:\n", noteStyle);
                    String prop = Joiner.on("\n").withKeyValueSeparator("=").join(ld.getProperties());
                    document.insertString(document.getLength(), prop, noteStyle);
                    document.insertString(document.getLength(), "\n", noteStyle);
                }
                Note note = dataTableModel.getNote(rowConverted);
                if (note != null && note.getNote() != null && note.getNote().length() > 0) {
                    s1 = "\nNote: " + note.getNote();
                    document.insertString(document.getLength(), s1, noteStyle);
                }
            } catch (BadLocationException e) {
                LOGGER.warning("Cant set message details: " + e.getMessage());
            }
        }
    } else {
        StyledDocument document = logDetailTextArea.getStyledDocument();
        synchronized (document) {
            try {
                document.remove(0, document.getLength());
                document.insertString(0, "No event selected", mainStyle);
            } catch (BadLocationException e) {
                LOGGER.warning("Cant set message details: " + e.getMessage());
            }
        }
    }
    logDetailTextArea.setCaretPosition(0);
}

From source file:uk.ac.kcl.texthunter.core.AnnotationEditor.java

private void updateProjectSummary() {
    try {/* w w  w  .  j a v  a  2  s  .c o  m*/
        projectXML.updateProjectSummary(con, targetTableName);
    } catch (java.sql.SQLException ex) {
        updateProjectStatus("Annotation table not ready");
    }
    StyledDocument doc;
    doc = projectSummaryTextPane.getStyledDocument();
    SimpleAttributeSet newString = new SimpleAttributeSet();
    StyleConstants.setForeground(newString, Color.BLACK);
    StyleConstants.setBold(newString, true);

    StringBuilder newText = new StringBuilder("\n");
    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    Date date = new Date();

    newText.append("------ results updated on ").append(dateFormat.format(date)).append(" ------\n\n");
    newText.append("current project annotations:\n");
    newText = newText.append("Gold Standard Positive Annotations = ").append(projectXML.getGsPos())
            .append("\n");
    newText = newText.append("Gold Standard Negative Annotations = ").append(projectXML.getGsneg())
            .append("\n");
    newText = newText.append("Gold Standard Unknown Annotations = ").append(projectXML.getGsunk()).append("\n");
    newText = newText.append("Gold Standard Form Annotations = ").append(projectXML.getGsform()).append("\n");
    newText = newText.append("Seed positive Annotations = ").append(projectXML.getSeedpos()).append("\n");
    newText = newText.append("Seed Negative Annotations = ").append(projectXML.getSeedneg()).append("\n");
    newText = newText.append("Seed Unknown Annotations = ").append(projectXML.getSeedunk()).append("\n");
    newText = newText.append("Seed Form Annotations = ").append(projectXML.getSeedform()).append("\n");
    newText = newText.append("AL Positive Annotations = ").append(projectXML.getAlpos()).append("\n");
    newText = newText.append("AL Negative Annotations = ").append(projectXML.getAlneg()).append("\n");
    newText = newText.append("AL Form Annotations = ").append(projectXML.getAlform()).append("\n");
    newText = newText.append("AL Unknown Annotations = ").append(projectXML.getAlunk()).append("\n\n");

    newText = newText.append("Last Pipeline run results:\n");
    newText = newText.append("P = ").append(projectXML.getPrecision()).append("\n");
    newText = newText.append("R = ").append(projectXML.getRecall()).append("\n");
    newText = newText.append("F1 = ").append(projectXML.getF1()).append("\n");

    try {
        doc.insertString(doc.getLength(), "\n" + newText, newString);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:uk.ac.kcl.texthunter.core.AnnotationEditor.java

private void updateInfoTextPane(String newText) {
    StyledDocument doc;
    doc = infoTextPane.getStyledDocument();

    //  Define a keyword attribute

    SimpleAttributeSet newString = new SimpleAttributeSet();
    StyleConstants.setForeground(newString, Color.RED);
    StyleConstants.setBold(newString, true);

    SimpleAttributeSet oldString = new SimpleAttributeSet();
    StyleConstants.setForeground(oldString, Color.BLACK);
    StyleConstants.setBold(oldString, false);

    //  Add some text

    try {//from  ww w  . j av  a 2s . co  m
        doc.setCharacterAttributes(0, doc.getLength(), oldString, true);
        doc.insertString(doc.getLength(), "\n" + newText, newString);
    } catch (Exception e) {
        System.out.println(e);
    }
}