Java examples for Swing:JTextComponent
Gets the line index which contains specified offset in JTextComponent.
//package com.java2s; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.JTextComponent; public class Main { /**//ww w. j av a 2 s .c o m * Gets the line index which contains specified offset. * @param comp * @param offset * @return * @throws BadLocationException */ public static int getLineOfOffset(JTextComponent comp, int offset) throws BadLocationException { Document doc = comp.getDocument(); if (offset < 0) { throw new BadLocationException( "Can't translate offset to line", -1); } else if (offset > doc.getLength()) { throw new BadLocationException( "Can't translate offset to line", doc.getLength() + 1); } else { Element map = doc.getDefaultRootElement(); return map.getElementIndex(offset); } } }