Example usage for javax.swing JTextPane getDocument

List of usage examples for javax.swing JTextPane getDocument

Introduction

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

Prototype

public Document getDocument() 

Source Link

Document

Fetches the model associated with the editor.

Usage

From source file:UndoEditor.java

public UndoEditor() {
    setLayout(new BorderLayout());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane editor = new JTextPane();
    editor.getDocument().addUndoableEditListener(new UndoListener());

    JScrollPane scroller = new JScrollPane(editor);
    menuBar.add(editMenu);//from   w  w w .j  av  a  2 s  .c om
    editMenu.add(undoAction);
    editMenu.add(redoAction);
    this.setJMenuBar(menuBar);
    add(scroller);
    setSize(400, 300);
    setVisible(true);
}

From source file:UndoStyleFrame.java

public UndoStyleFrame() {
    super();// w  w  w  .java  2  s  .  c om
    setTitle("UndoStyleFrame");
    JTextPane textPane = new JTextPane();

    textPane.getDocument().addUndoableEditListener(undoAction);
    textPane.getDocument().addUndoableEditListener(redoAction);

    JMenu editMenu = new JMenu("Edit");
    editMenu.add(new JMenuItem(undoAction));
    editMenu.add(new JMenuItem(redoAction));

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(editMenu);

    setJMenuBar(menuBar);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(new JButton(undoAction));
    buttonPanel.add(new JButton(redoAction));

    getContentPane().add(textPane, "Center");
    getContentPane().add(buttonPanel, "South");
}

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  w w .j a  va2 s  . c o m
        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:de.unentscheidbar.validation.swing.trigger.DocumentChangeTriggerTest.java

@Override
protected void onSetUp() {

    JEditorPane text2 = new JEditorPane();
    JTextPane text3 = new JTextPane();

    text2.setDocument(text3.getDocument());

    gui.add(text2Key, text2);/*from   w  w  w . j a  v a  2  s. c o m*/
    gui.add(text3Key, text3);
}

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);/*  ww w.j  ava  2s  .  c  om*/
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);
}

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

private void setupLogAppender(final JTextPane textPane) {
    Logger.getRootLogger().addAppender(new AppenderSkeleton() {
        @Override/*w w w .  j a  v a  2  s  .  co  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 . j a  v a 2 s.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.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);/*  w ww . j ava  2  s  .c o m*/
    tp.setCharacterAttributes(aset, false);
    tp.replaceSelection(msg);

}

From source file:de.ailis.xadrian.components.ComplexEditor.java

/**
 * Prints the complex data/*from w w w .  j a  va2 s  .com*/
 */
public void print() {
    // Prepare model
    final Map<String, Object> model = new HashMap<String, Object>();
    model.put("complex", this.complex);
    model.put("print", true);
    model.put("config", Config.getInstance());

    // Generate content
    final String content = TemplateFactory.processTemplate(template, model);

    // Put content into a text pane component
    final JTextPane printPane = new JTextPane();
    printPane.setContentType("text/html");
    ((HTMLDocument) printPane.getDocument()).setBase(Main.class.getResource("templates/"));
    printPane.setText(content);

    // Print the text pane
    try {
        printPane.print(null, null, true, null, Config.getInstance().getPrintAttributes(), true);
    } catch (final PrinterException e) {
        JOptionPane.showMessageDialog(null, I18N.getString("error.cantPrint"), I18N.getString("error.title"),
                JOptionPane.ERROR_MESSAGE);
        log.error("Unable to print complex: " + e, e);
    }
}

From source file:org.geopublishing.atlasViewer.GpCoreUtil.java

public static void setTabs(final JTextPane textPane, final int charactersPerTab) {
    final FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
    final int charWidth = fm.charWidth('w');
    final int tabWidth = charWidth * charactersPerTab;

    final TabStop[] tabs = new TabStop[10];

    for (int j = 0; j < tabs.length; j++) {
        final int tab = j + 1;
        tabs[j] = new TabStop(tab * tabWidth);
    }/*from   www.  j  a va 2 s.  c  om*/

    final TabSet tabSet = new TabSet(tabs);
    final SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setTabSet(attributes, tabSet);
    final int length = textPane.getDocument().getLength();
    textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
}