简体   繁体   English

Java-获取/设置内容类型为“ text / html”的JTextPane的行高

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

I have a JTextPane with content type "text/html". 我有一个内容类型为“ text / html”的JTextPane It is integrated in a JScrollPane . 它集成在JScrollPane

The user can scroll down in this JTextPane and hits a button. 用户可以在此JTextPane向下滚动并单击一个按钮。 At this moment I want to compute the topmost actual visible line of the JTextPane ! 现在,我想计算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. 但这不能正确计算lineHeight的数字太小。 So, if I scroll to the 20th row -for example- the method returns more then 20.. 因此,例如,如果我滚动到第20行,则该方法返回的值将大于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).. 但是,不管我在此处设置什么像素数,生成的JTextPane始终具有相同的高度(并且我正在使用body标签)。

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. 不知道这是否适用于带有图像和表格等各种奇怪标记的HTML。在这种情况下,我不确定“ line”的含义是什么。

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. 因此,您应该能够使用文本窗格的viewToModel(...)方法。 Something like: 就像是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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