Example usage for javax.swing JTextPane modelToView

List of usage examples for javax.swing JTextPane modelToView

Introduction

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

Prototype

@Deprecated(since = "9")
public Rectangle modelToView(int pos) throws BadLocationException 

Source Link

Document

Converts the given location in the model to a place in the view coordinate system.

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  . j  av  a 2  s . c  o m*/
        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);
}

From source file:Main.java

private static AttributeSet getAttributes(MouseEvent e) {
    JTextPane text = (JTextPane) e.getSource();
    Point mouseLocation = new Point(e.getX(), e.getY());
    int pos = text.viewToModel(mouseLocation);

    if (pos >= 0) {
        try {//from  w  w  w.  ja  v a  2s  . c o  m
            Rectangle rect = text.modelToView(pos);
            int lowerCorner = rect.y + rect.height;
            if (e.getX() < rect.x && e.getY() < lowerCorner && pos > 0) {
                pos--;
            }
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
        StyledDocument doc = text.getStyledDocument();
        Element element = doc.getCharacterElement(pos);
        return element.getAttributes();
    }
    return null;
}