Example usage for javax.swing.text Document getLength

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

Introduction

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

Prototype

public int getLength();

Source Link

Document

Returns number of characters of content currently in the document.

Usage

From source file:Main.java

public TestPane() {
    setLayout(new BorderLayout());
    JPanel searchPane = new JPanel();
    searchPane.add(new JLabel("Find: "));

    searchPane.add(findText);//from w w  w  . j  a  va 2s.c o m

    add(searchPane, BorderLayout.NORTH);
    add(new JScrollPane(ta));

    try (BufferedReader reader = new BufferedReader(new FileReader(new File("c:/Java_Dev/run.bat")))) {
        ta.read(reader, "Text");
    } catch (Exception e) {
        e.printStackTrace();
    }
    ta.setCaretPosition(0);

    keyTimer = new Timer(250, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String find = findText.getText();
            Document document = ta.getDocument();
            try {
                for (int index = 0; index + find.length() < document.getLength(); index++) {
                    String match = document.getText(index, find.length());
                    if (find.equals(match)) {
                        DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(
                                Color.YELLOW);
                        ta.getHighlighter().addHighlight(index, index + find.length(), highlightPainter);
                    }
                }
            } catch (BadLocationException exp) {
                exp.printStackTrace();
            }
        }
    });
    keyTimer.setRepeats(false);

    findText.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            keyTimer.restart();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            keyTimer.restart();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            keyTimer.restart();
        }
    });
}

From source file:Main.java

public int search(String word) {
    int firstOffset = -1;
    Highlighter highlighter = comp.getHighlighter();
    Highlighter.Highlight[] highlights = highlighter.getHighlights();
    for (int i = 0; i < highlights.length; i++) {
        Highlighter.Highlight h = highlights[i];
        if (h.getPainter() instanceof UnderlineHighlightPainter) {
            highlighter.removeHighlight(h);
        }// www  . ja va  2 s  .  c o  m
    }
    if (word == null || word.equals("")) {
        return -1;
    }
    String content = null;
    try {
        Document d = comp.getDocument();
        content = d.getText(0, d.getLength()).toLowerCase();
    } catch (BadLocationException e) {
        return -1;
    }
    word = word.toLowerCase();
    int lastIndex = 0;
    int wordSize = word.length();
    while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
        int endIndex = lastIndex + wordSize;
        try {
            highlighter.addHighlight(lastIndex, endIndex, painter);
        } catch (BadLocationException e) {
        }
        if (firstOffset == -1) {
            firstOffset = lastIndex;
        }
        lastIndex = endIndex;
    }
    return firstOffset;
}

From source file:MyDocumentListener.java

public void updateLog(DocumentEvent e, String action) {
    Document doc = (Document) e.getDocument();
    int changeLength = e.getLength();
    System.out.println(changeLength + " character" + ((changeLength == 1) ? " " : "s ") + action + " "
            + doc.getProperty("name") + "." + newline + "  Text length = " + doc.getLength() + newline);
}

From source file:com.ansorgit.plugins.bash.editor.inspections.inspections.FixShebangInspection.java

private void updateShebangLines(DocumentEvent documentEvent) {
    validShebangCommands.clear();//from w  ww  .ja v a  2 s.c  o  m
    try {
        Document doc = documentEvent.getDocument();
        for (String item : doc.getText(0, doc.getLength()).split("\n")) {
            if (item.trim().length() != 0) {
                validShebangCommands.add(item);
            }
        }
    } catch (BadLocationException e) {
        throw new RuntimeException("Could not save shebang inspection settings input", e);
    }
}

From source file:com.croer.javaorange.diviner.SimpleOrangeTextPane.java

protected void fireText(DocumentEvent e) {
    Document document = e.getDocument();
    String text = "";
    try {//w w  w . j a v  a 2 s  .  co  m
        text = document.getText(0, document.getLength());
    } catch (BadLocationException ex) {
        Logger.getLogger(SimpleOrangeTextPane.class.getName()).log(Level.SEVERE, null, ex);
    }
    firePropertyChange("text", null, text);
}

From source file:de.unentscheidbar.validation.swing.trigger.DocumentChangeTriggerTest.java

@Override
protected void provokeTrigger(Iterable<JTextComponent> components) {

    for (final JTextComponent c : components) {
        runInEdt(new Callable<Void>() {

            @Override/*from   w  ww  . j a v  a2s  . c o  m*/
            public Void call() throws Exception {

                Document doc = c.getDocument();
                switch (rnd.nextInt(3)) {
                case 0:
                    doc.remove(doc.getStartPosition().getOffset(), doc.getLength() / 2);
                    break;
                case 1:
                    doc.insertString(rnd.nextInt(Math.max(1, doc.getStartPosition().getOffset())),
                            RandomStringUtils.randomAlphanumeric(1 + rnd.nextInt(10)), null);
                    break;
                case 2:
                    c.setText(UUID.randomUUID().toString());
                    break;
                default:
                    Assert.fail();
                }
                return null;
            }
        });

    }
    drainEventQueue();
}

From source file:com.adito.upgrade.GUIUpgrader.java

void appendString(String message, Color c) {
    Document doc = console.getDocument();
    if (doc.getLength() != 0) {
        message = "\n" + message;
    }//from  w w w .  ja v  a  2 s  .  c o m
    SimpleAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, c);
    try {
        doc.insertString(doc.getLength(), message, attr);
    } catch (Exception e) {
    }
    console.setCaretPosition(doc.getLength());
    console.scrollRectToVisible(console.getVisibleRect());
}

From source file:EditorPaneExample6.java

public EditorPaneExample6() {
    super("JEditorPane Example 6");

    pane = new JEditorPane();
    pane.setEditable(false); // Start read-only
    getContentPane().add(new JScrollPane(pane), "Center");

    // Build the panel of controls
    JPanel panel = new JPanel();

    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = 1;/*from  w  ww. ja v  a 2  s .  c o m*/
    c.gridheight = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    c.weighty = 0.0;

    JLabel urlLabel = new JLabel("File name: ", JLabel.RIGHT);
    panel.add(urlLabel, c);
    JLabel loadingLabel = new JLabel("State: ", JLabel.RIGHT);
    c.gridy = 1;
    panel.add(loadingLabel, c);
    JLabel typeLabel = new JLabel("Type: ", JLabel.RIGHT);
    c.gridy = 2;
    panel.add(typeLabel, c);

    c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 1;
    c.weightx = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;

    textField = new JTextField(32);
    panel.add(textField, c);
    loadingState = new JLabel(spaces, JLabel.LEFT);
    loadingState.setForeground(Color.black);
    c.gridy = 1;
    c.gridwidth = 2;
    panel.add(loadingState, c);
    loadedType = new JLabel(spaces, JLabel.LEFT);
    loadedType.setForeground(Color.black);
    c.gridy = 2;
    panel.add(loadedType, c);

    // Add a "Save" button
    saveButton = new JButton("Save");
    saveButton.setEnabled(false);
    c.gridwidth = 1;
    c.gridx = 2;
    c.gridy = 0;
    c.weightx = 0.0;
    panel.add(saveButton, c);

    getContentPane().add(panel, "South");

    // Change page based on text field
    textField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            String fileName = textField.getText().trim();
            file = new File(fileName);
            absolutePath = file.getAbsolutePath();
            String url = "file:///" + absolutePath;

            try {
                // Check if the new page and the old
                // page are the same.
                URL newURL = new URL(url);
                URL loadedURL = pane.getPage();
                if (loadedURL != null && loadedURL.sameFile(newURL)) {
                    return;
                }

                // Try to display the page
                textField.setEnabled(false); // Disable input
                textField.paintImmediately(0, 0, textField.getSize().width, textField.getSize().height);

                saveButton.setEnabled(false);
                saveButton.paintImmediately(0, 0, saveButton.getSize().width, saveButton.getSize().height);
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                // Busy cursor
                loadingState.setText("Loading...");
                loadingState.paintImmediately(0, 0, loadingState.getSize().width,
                        loadingState.getSize().height);
                loadedType.setText("");
                loadedType.paintImmediately(0, 0, loadedType.getSize().width, loadedType.getSize().height);
                pane.setEditable(false);
                pane.setPage(url);

                loadedType.setText(pane.getContentType());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(pane, new String[] { "Unable to open file", url },
                        "File Open Error", JOptionPane.ERROR_MESSAGE);
                loadingState.setText("Failed");
                textField.setEnabled(true);
                setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    // Listen for page load to complete
    pane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals("page")) {
                loadingState.setText("Page loaded.");

                textField.setEnabled(true); // Allow entry of new file name
                textField.requestFocus();
                setCursor(Cursor.getDefaultCursor());

                // Allow editing and saving if appropriate
                pane.setEditable(file.canWrite());
                saveButton.setEnabled(file.canWrite());
            }
        }
    });

    // Save button
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            try {
                String type = pane.getContentType();
                OutputStream os = new BufferedOutputStream(new FileOutputStream(file + ".save"));
                pane.setEditable(false);
                textField.setEnabled(false);
                saveButton.setEnabled(false);
                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                Document doc = pane.getDocument();
                int length = doc.getLength();
                if (type.endsWith("/rtf")) {
                    // Saving RTF - use the OutputStream
                    try {
                        pane.getEditorKit().write(os, doc, 0, length);
                        os.close();
                    } catch (BadLocationException ex) {
                    }
                } else {
                    // Not RTF - use a Writer.
                    Writer w = new OutputStreamWriter(os);
                    pane.write(w);
                    w.close();
                }
            } catch (IOException e) {
                JOptionPane.showMessageDialog(pane,
                        new String[] { "Unable to save file", file.getAbsolutePath(), }, "File Save Error",
                        JOptionPane.ERROR_MESSAGE);

            }
            pane.setEditable(file.canWrite());
            textField.setEnabled(true);
            saveButton.setEnabled(file.canWrite());
            setCursor(Cursor.getDefaultCursor());
        }
    });
}

From source file:com.mindcognition.mindraider.ui.swing.concept.annotation.renderer.AbstractTextAnnotationRenderer.java

/**
 * Search annotation from the current carret position.
 *///from  www. j  a  va  2s  . c o  m
public void searchAnnotation(String searchString, boolean again) {
    logger.debug("searchAnnotation() " + searchString); // {{debug}}
    JTextComponent textComponent;
    if (inViewMode()) {
        textComponent = viewer;
        logger.debug("Searching viewer..."); // {{debug}}
    } else {
        textComponent = editor;
        logger.debug("Searching editor..."); // {{debug}}
    }

    if (!again) {
        textComponent.setCaretPosition(0);
    }

    if (searchString != null && searchString.length() > 0) {
        Document document = textComponent.getDocument();
        try {
            int idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString,
                    textComponent.getCaretPosition());
            if (idx < 0) {
                // try it from the beginning
                idx = textComponent.getDocument().getText(0, document.getLength()).indexOf(searchString);
            } else if (idx > 0) {
                textComponent.setCaretPosition(idx);
                textComponent.requestFocus();
                textComponent.select(idx, idx + searchString.length());
            }
        } catch (Exception e) {
            // TODO no bundle!
            logger.debug(Messages.getString("ConceptJPanel.unableToSearch", e.getMessage()));
        }
    }
}

From source file:Console.java

void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {//from  w  w w.j av a2 s .c  o m
        synchronized (doc) {
            doc.getText(outputMark, len - outputMark, segment);
        }
    } catch (javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if (segment.count > 0) {
        history.addElement(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    synchronized (doc) {
        outputMark = doc.getLength();
    }
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}