I am trying to simulate the movement of a debugging cursor using java. I am having problem to get the viewable area of the JScrollPane to the right position.
Here is
I don't think the line numbers should be part of the text. For example you have a horizontal scrollbar. If you scroll to the right you will lose the line numbers.
Instead you should use a row header to display the line numbers.
See Text Component Line Number. It contains a class that does custom painting of the line number for you. You can use add this component to the row header.
The painting code in that class will highlight the current line number. If you want to add an arrow then you will need to modify the painting code. In the paintComponent(...) method you can add the following:
g.drawString(lineNumber, x, y);
// Code to paint an arrow
if (isCurrentLine(rowStartOffset))
{
int height = fontMetrics.getAscent() - fontMetrics.getDescent();
Polygon triangle = new Polygon();
triangle.addPoint(borderGap, y);
triangle.addPoint(borderGap, y - height);
triangle.addPoint(borderGap + 10, y - height / 2);
Graphics2D g2d = (Graphics2D)g.create();
g2d.fill( triangle );
g2d.dispose();
}
One more change to make. Since we are now painting an arrow we will need to increase the width of the components. So in the setPreferredWidth(...) method you will need to make the following change:
//int preferredWidth = insets.left + insets.right + width;
int preferredWidth = insets.left + insets.right + width + 15;
I want to scroll only if the line I want to jump it is not visible.
Here is some code to do this:
public static void gotoStartOfLine(JTextComponent component, int line)
{
Element root = component.getDocument().getDefaultRootElement();
line = Math.max(line, 1);
line = Math.min(line, root.getElementCount());
int startOfLineOffset = root.getElement( line - 1 ).getStartOffset();
component.setCaretPosition( startOfLineOffset );
}
I took the above code from Text Utilities which may have other methods of interest (if not now, in the future).
You can also use the Line Painter if you want to highlight the entire line in the text pane.