views:

210

answers:

2

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.

+1  A: 

You may use something like this:

String text = textField.getText();
text.replaceAll(System.getProperty("line.separator"), "\n");

Then do your stuff. In the above code you can replace "\n" with something that suits your need.

Suraj Chandran
I actually want to avoid using a replace function before doing the pattern match. However, if all else fails, I guess this'll be an OK workaround.
bguiz
Instead of replace, why not just trim()?
Amir Afghani
No, I think trim wont work. Because trim will remove whitespaces only from the very begining and very end. What if the whitespaces lie in between!!:)
Suraj Chandran
@bguiz, don't i deserve an upvote;)
Suraj Chandran
Can you comment on why you want to avoid using replaceAll?
Amir Afghani
I wanted to avoid it because 1) There may already be an overlooked API that does it; 2) If 1 is true, I am duplicating code, possbily introducing errors.As it turns out, 1 is true, see camickr's answer, and my implemented soln.
bguiz
there you go Suraj, +1 for you
bguiz
+2  A: 

I think it may be to do with a difference in the way in which new lines (\r\n and \n) are handled.

Yes, that is a problem in Windows.

But, I doubt that you will have a problem with a JTextField since they don't contain new lines strings.

I suggest you read Text and New Lines which will explain how to handle this for JTextArea and JTextPane.

If you need more help post your SSCCE that shows the problem.

camickr
Thank you. This is what I was lookign for. See my impl. solution (edit).
bguiz