简体   繁体   中英

Java - getting/setting line height of JTextPane with content type “text/html”

I have a JTextPane with content type "text/html". It is integrated in a JScrollPane .

The user can scroll down in this JTextPane and hits a button. At this moment I want to compute the topmost actual visible line of the JTextPane !

What I found in another post here where these lines:

public Integer getActualDisplayedRows() {
    int y1 = jtextpane.getVisibleRect().y;
    int lineHeight = jtextpane.getFontMetrics(jtextpane.getFont()).getHeight();
    int topMostRow = (int) Math.ceil((double) y1 / lineHeight);
    return topMostRow;
}

But this does not compute correct.. The number in lineHeight is too small. So, if I scroll to the 20th row -for example- the method returns more then 20..

I tried to set the height of the line via stylesheet (like here ):

StyleSheet sh = editorKit.getStyleSheet();
sh.addRule("body {line-height: 50px}");

But doesn't matter what pixel number I set there, the resulting JTextPane has always the same height (and I am using the body tag)..

Do you have any suggestions??

Thank you very much for your help!

If I understand your requirement you just want to know the line number at the top of the viewport?

Here is some code for getting the line at the caret position:

public static int getLineAtCaret(JTextComponent component)
{
    int caretPosition = component.getCaretPosition();
    Element root = component.getDocument().getDefaultRootElement();

    return root.getElementIndex( caretPosition ) + 1;
}

Don't know if this will work for HTML with all kinds of weird tags with images and tables etc. In this case I'm not sure what the meaning of "line" would be.

Now obviously the caret will not be at the top of the viewport, so you need to modify the logic to get an "offset" of the text at the top of the viewport.

So you should be able to use the viewToModel(...) method of the text pane. Something like:

int y = textPane.getVisibleRect().y;
Point p = new Point(5, y);
int offset = textPane.viewToModel( p );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM