Search code examples
javaswingjtextarea

JTextArea - count selected rows


I'm creating a text editor, and I want to count selected lines, as in image below.

This is the interface that I created until now.

enter image description here

For example if those two lines are selected, I need a way to store number of selected lines (2 in this case) into a variable. Is there a way to do that?

If you need any piece of code to see, I will add.


Solution

  • Check out the getLineAtCaret() method found in Text Utilities. This will get the line number at the caret (which won't help here).

    So, you will need to modify the code to receive an offset as a parameter. Then you can pass in the getSelectionStart() and getSelectionEnd() values of the text component and use these values to return the line number. Then once you know the line number of each you can subtract the starting line number from the ending line number to give you the number of rows selected.

    You can also check out the Text Component Line Number blog entry for a line number component to use for you editor.