简体   繁体   中英

JTextField and \r\n problems

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM