Example usage for javax.swing JTextPane scrollRectToVisible

List of usage examples for javax.swing JTextPane scrollRectToVisible

Introduction

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

Prototype

public void scrollRectToVisible(Rectangle aRect) 

Source Link

Document

Forwards the scrollRectToVisible() message to the JComponent's parent.

Usage

From source file:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    JTextPane textPane = new JTextPane();
    JTextField tf = new JTextField("is");
    String word = "";
    Highlighter highlighter = new UnderlineHighlighter(null);

    textPane.setHighlighter(highlighter);
    textPane.setText("This is a test");
    panel.setLayout(new BorderLayout());
    panel.add(new JLabel("Enter word, then press ENTER key: "), "West");
    panel.add(tf, "Center");

    final WordSearcher searcher = new WordSearcher(textPane);
    tf.addActionListener(e -> {//from  ww  w .  ja va 2s  .  c  om
        String w = tf.getText().trim();
        int offset = searcher.search(w);
        if (offset == -1) {
            return;
        }
        try {
            textPane.scrollRectToVisible(textPane.modelToView(offset));
        } catch (BadLocationException ex) {
        }

    });
    textPane.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent evt) {
            searcher.search(word);
        }

        @Override
        public void removeUpdate(DocumentEvent evt) {
            searcher.search(word);
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
        }
    });
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(panel, "South");
    f.add(new JScrollPane(textPane), "Center");
    f.setSize(400, 400);
    f.setVisible(true);
}