javaswingjscrollpanejeditorpane

Changing view of JScrollPane so that a certain part of JEditorPane is visible


How do I make a certain line of text in a jEditorPane visible when it is in a JScrollPane?

private JEditorPane myEditorPane = new JEditorPane();
private JScrollPane myScrollPane = new JScrollPane(myEditorPane);

myEditorPane.setContentType("text/html");
myEditorPane.setText("<html>" + getMyString(x) + "</html>");
myEditorPane.repaint();

getMyString gets a long String with many lines, separated by \n. The programme has 2 panels. The programme then goes down the lines in the above panel and for each one underlines the text in that line and displays a related image in another panel. Each is viewed for 1 second then moves on to underline the next line of text and show the next image. I've got it going down and underlining them in turn, displaying the relevant images for each underlined line of text. But the scrollpane jumps to the start every time.

I think I've got to use scrollRectToVisible on the viewport, but how do I find out what the rectangle is for part of the string in the JEditorPAne?


Solution

  • I've been able to manipulate scroll bar position by directly calling setValue on the scroll bar.

    myScrollPane.getVerticalScrollBar().setValue()
    

    The question is, what value to set? Can you assume that the lines of text are the same? If they wrap, things are going to get complicated. I'm going to assume they don't, and that the height of each line is the same because the font and size is the same. Then you'll need to know what index the current displayed line is, and the total count of lines.

    Once you've got that, you convert the line index to editor Y position by multiplying the line index by editor height over line count and set accordingly.

    myScrollPane.getVerticalScrollBar().setValue( (int) indexOfCurrentLine * myEditorPane.getHeight() / countOfLines );
    

    Obviously haven't been able to test any of this without an SSCCE.