Text Component Line Number
Posted by Rob Camick on May 23, 2009
Over the years I’ve seen many requests in the forums for the ability to display line numbers in a text component. I’ve probably seen just as many solutions as well. I even posted my own solution years ago. It was my first attempt at doing custom painting so I figured now was a good time to revisit that code to see if I could improve on it.
The approach I took was to create a separate component that could be added to a scroll pane along with the related text component. The main reason for this was to allow for horizontal scrolling of the text component, while having the line numbers remain fixed at the left of the scroll pane. It will support a JTextArea or JTextPane. Typically, a single font will be used by the component so the line heights are all the same size. However, in the case of a JTextPane, it will also support the usage of multiple fonts and font sizes.
The result is the TextLineNumber component. The main features of the TextLineNumber are the added support for:
- wrapped lines – the first line will show the line number and the wrapped lines will show nothing
- current line number highllighting – the line number for the current line (the line with the caret) will be painted a different color
Sample code for using the TextLineNumber would be as follows:
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
TextLineNumber tln = new TextLineNumber(textPane);
scrollPane.setRowHeaderView( tln );
TextLineNumber extends JComponent so you can easily customize the foreground, background or border. The font defaults to the related text components font. It can be changed, but you are responsible for ensuring the font size is reasonable. It also supports a couple of methods to allow for further customization:
- setBorderGap – a convenience method to adjust the left and right insets of the Border, while retaining the outer MatteBorder
- setCurrentLineForeground – the Color of the current line number
- setDigitAlignment – align the line numbers to the LEFT, CENTER or RIGHT
- setMinimumDisplayDigits – controls the minimum width of the component. The width will increase automatically as necessary.
- setUpdateFont – enables the automatic updating of the Font when the Font of the related text component changes.