开发者

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, 开发者_Go百科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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜