Example usage for javax.swing JTextPane setCaretPosition

List of usage examples for javax.swing JTextPane setCaretPosition

Introduction

In this page you can find the example usage for javax.swing JTextPane setCaretPosition.

Prototype

@BeanProperty(bound = false, description = "the caret position")
public void setCaretPosition(int position) 

Source Link

Document

Sets the position of the text insertion caret for the TextComponent.

Usage

From source file:Main.java

private static void appendToPane(JTextPane tp, String msg, Color f, Color b) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, f);
    aset = sc.addAttribute(aset, StyleConstants.Background, b);

    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);/*w w  w. j a  v  a  2 s .  co  m*/
}

From source file:Main.java

/** 
 * Affect a stylised text into an instance of JTextPane. 
 * @param textPane Instance of JTextPane to affect.
 * @param textArray Array of strings.//from w w w  .  j a  v  a2 s.com
 * @param styleArray Array of styles.  Must match the textArray.
 */
public static void setText(JTextPane textPane, String[] textArray, String[] styleArray) {
    StyledDocument doc = textPane.getStyledDocument();
    try {
        doc.remove(0, doc.getLength()); // Erase all the previous text.
        for (int i = 0; i < textArray.length; i++) {
            int offset = doc.getLength();
            javax.swing.text.Style style = textPane.getStyle(styleArray[i]);
            doc.insertString(offset, textArray[i], style);
            doc.setParagraphAttributes(offset, textArray[i].length(), style, true);
        }
        textPane.setCaretPosition(0);
    } catch (BadLocationException ignore) {
        ignore.printStackTrace();
    }
}

From source file:Main.java

private void appendToPane(JTextPane tp, String msg, Color c) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);/*from  ww  w .java 2s . c  o  m*/
}

From source file:esmska.gui.AboutFrame.java

private void creditsButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_creditsButtonActionPerformed
    //show credits
    try {/*from w w w.ja v  a2s.  c  om*/
        logger.fine("Showing credits...");
        String credits = IOUtils.toString(getClass().getResourceAsStream(RES + "credits.html"), "UTF-8");
        String translators = l10n.getString("Translators");
        if ("translator-credits".equals(translators)) {
            //there are no translators mentioned
            translators = "";
        } else {
            translators = translators.replaceAll("\n", "<br>\n").replaceAll("\n  ", "\n&nbsp;&nbsp;");
            //add hyperlinks to the Launchpad URLs
            translators = translators.replaceAll("(https://[^<]*)", "<a href=\"$1\">$1</a>");
        }

        String document = MessageFormat.format(credits, l10n.getString("Credits.authors"),
                l10n.getString("Credits.contributors"), l10n.getString("Credits.graphics"),
                l10n.getString("Credits.sponsors"), l10n.getString("Credits.translators"), translators,
                Links.DONATORS, l10n.getString("Credits.moreDonators"),
                MessageFormat.format(l10n.getString("Credits.packagers"), Links.DOWNLOAD));

        JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText(document);
        tp.setEditable(false);
        tp.setPreferredSize(new Dimension(450, 400));
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && Desktop.isDesktopSupported()) {
                    try {
                        logger.fine("Browsing URL: " + e.getURL());
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    } catch (Exception ex) {
                        logger.log(Level.SEVERE, "Can't browse hyperlink: " + e.getURL(), ex);
                    }
                }
            }
        });

        String option = l10n.getString("AboutFrame.Thank_you");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.Credits"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Could not show credits", e);
    }
}

From source file:esmska.gui.AboutFrame.java

private void licenseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_licenseButtonActionPerformed
    //show licence
    try {/*w w w.  j  a  va  2 s.  c  o  m*/
        logger.fine("Showing license...");
        String license = IOUtils.toString(getClass().getResourceAsStream(RES + "license.txt"), "UTF-8");
        final String agpl = IOUtils.toString(getClass().getResourceAsStream(RES + "gnu-agpl.txt"), "UTF-8");
        license = MiscUtils.escapeHtml(license);
        license = license.replaceAll("GNU Affero General Public License",
                "<a href=\"agpl\">GNU Affero General Public License</a>");

        final JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText("<html><pre>" + license + "</pre></html>");
        tp.setEditable(false);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        tp.setPreferredSize(new Dimension((int) d.getWidth() / 2, (int) d.getHeight() / 2)); //reasonable size
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    logger.fine("Showing GNU AGPL...");
                    tp.setText(null);
                    tp.setContentType("text/plain");
                    tp.setText(agpl);
                    tp.setCaretPosition(0);
                }
            }
        });

        String option = l10n.getString("AboutFrame.Acknowledge");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.License"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Could not show license", ex);
    }
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Displays help window/*from w ww  .  j  a  va2 s . co  m*/
 */
private void help() {
    String msg = "";

    MutableDataSet options = new MutableDataSet();
    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();

    try {
        msg = IOUtils.toString(Main.getFile("Usage.md", this));
        Node document = parser.parse(msg);
        msg = renderer.render(document);
    } catch (IOException e) {
        e.printStackTrace();
    }

    JTextPane area = new JTextPane();
    area.setContentType("text/html");
    area.setText(msg);
    area.setCaretPosition(0);
    area.setEditable(false);

    JScrollPane scrollPane = new JScrollPane(area);
    scrollPane
            .setMaximumSize(new Dimension(GraphicsRunner.SCREEN_SIZE.width, GraphicsRunner.SCREEN_SIZE.height));
    scrollPane.setPreferredSize(
            new Dimension(GraphicsRunner.SCREEN_SIZE.width - 10, GraphicsRunner.SCREEN_SIZE.height - 10));
    scrollPane.scrollRectToVisible(new Rectangle());
    JOptionPane.showMessageDialog(this, scrollPane, "Help", JOptionPane.PLAIN_MESSAGE);
}

From source file:com.NewJFrame.java

private void appendToPane(JTextPane tp, String msg, Color c) {
    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

    //        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
    //        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
    int len = tp.getDocument().getLength();
    tp.setCaretPosition(len);
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);//from w  ww . j  av  a  2s .  c om

}

From source file:hr.fer.zemris.vhdllab.view.LogHistoryView.java

private void setupLogAppender(final JTextPane textPane) {
    Logger.getRootLogger().addAppender(new AppenderSkeleton() {
        @Override/*from   w  w  w . ja va  2  s.c  o m*/
        protected void append(LoggingEvent event) {
            if (!event.getLevel().equals(Level.INFO)) {
                return;
            }

            StringBuilder sb = new StringBuilder();
            String time = DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(event.timeStamp);
            sb.append(time).append("  ").append(event.getMessage());

            Document document = textPane.getDocument();
            int documentLength = document.getLength();
            try {
                document.insertString(documentLength, sb.toString() + "\n", null);
            } catch (BadLocationException e) {
                throw new IllegalStateException(e);
            }
            // scroll to end of document
            textPane.setCaretPosition(documentLength);
        }

        @Override
        public boolean requiresLayout() {
            return false;
        }

        @Override
        public void close() {
        }
    });
}

From source file:de.huxhorn.lilith.swing.preferences.PreferencesDialog.java

public void editDetailsFormatter() {
    Console console = new Console();
    File messageViewRoot = applicationPreferences.getDetailsViewRoot();
    File messageViewGroovyFile = new File(messageViewRoot, ApplicationPreferences.DETAILS_VIEW_GROOVY_FILENAME);

    EventWrapper<LoggingEvent> eventWrapper = new EventWrapper<>(
            new SourceIdentifier("identifier", "secondaryIdentifier"), 17, new LoggingEvent());
    console.setVariable("eventWrapper", eventWrapper);

    console.setCurrentFileChooserDir(messageViewRoot);
    String text = "";
    if (!messageViewGroovyFile.isFile()) {
        applicationPreferences.initDetailsViewRoot(true);
    }//  w  w w  .  ja va  2s  . c  o  m
    if (messageViewGroovyFile.isFile()) {
        InputStream is;
        try {
            is = new FileInputStream(messageViewGroovyFile);
            List lines = IOUtils.readLines(is, StandardCharsets.UTF_8);
            boolean isFirst = true;
            StringBuilder textBuffer = new StringBuilder();
            for (Object o : lines) {
                String s = (String) o;
                if (isFirst) {
                    isFirst = false;
                } else {
                    textBuffer.append("\n");
                }
                textBuffer.append(s);
            }
            text = textBuffer.toString();
        } catch (IOException e) {
            if (logger.isInfoEnabled()) {
                logger.info("Exception while reading '" + messageViewGroovyFile.getAbsolutePath() + "'.", e);
            }
        }
    } else {
        if (logger.isWarnEnabled())
            logger.warn("Failed to initialize detailsView file '{}'!", messageViewGroovyFile.getAbsolutePath());
    }
    console.run(); // initializes everything

    console.setScriptFile(messageViewGroovyFile);
    JTextPane inputArea = console.getInputArea();
    //inputArea.setText(text);
    Document doc = inputArea.getDocument();
    try {
        doc.remove(0, doc.getLength());
        doc.insertString(0, text, null);
    } catch (BadLocationException e) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while setting source!", e);
    }
    console.setDirty(false);
    inputArea.setCaretPosition(0);
    inputArea.requestFocusInWindow();
}

From source file:com.vgi.mafscaling.LogView.java

private void createUsageTab() {
    JTextPane usageTextArea = new JTextPane();
    usageTextArea.setMargin(new Insets(10, 10, 10, 10));
    usageTextArea.setContentType("text/html");
    usageTextArea.setText(usage());//w ww.jav  a 2 s  . co m
    usageTextArea.setEditable(false);
    usageTextArea.setCaretPosition(0);

    JScrollPane textScrollPane = new JScrollPane(usageTextArea);
    textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    textScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    add(textScrollPane, "<html><div style='text-align: center;'>U<br>s<br>a<br>g<br>e</div></html>");
}