Hello,
Part of an app I am working on includes a log file viewer, with a find text function, which calls a pattern matcher on JTextField#getText()
, like so:
Matcher m = somePattern.matcher(textField.getText());
m.find(startPosn);
System.out.println("startPosn: " + m.start());
System.out.println("endPosn: " + m.end());
where textField is a JTextField, and
startPosn is set to the current caret position of the text field
However the start and end positions returned by this return incorrect start and end caret positions, only in Windows.
Both the start and end positions are X more than they should be, where X = the number of times a new line is encountered in textField up to startPosn.
As this does not appear in Linux, I think it may be to do with a difference in the way in which new lines (\r\n
and \n
) are handled.
Am I doing something wrong; and how do I work arounhd this?
Impl. solution:
Modified using example in TFA linked by camickr.
Matcher m = somePattern.matcher(textField.getDocument().getText(0, textField.getDocument().getLength()));
m.find(startPosn);
System.out.println("startPosn: " + m.start());
System.out.println("endPosn: " + m.end());
Note: only first line changed.
This was able to give me the right output in both Linux and Windows.