简体   繁体   English

JTextField和\\ r \\ n问题

[英]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: 我正在处理的应用程序的一部分包括一个日志文件查看器,带有一个查找文本函数,它在JTextField#getText()上调用模式匹配器,如下所示:

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 其中textField是一个JTextField,和
startPosn is set to the current caret position of the text field startPosn设置为文本字段的当前插入符号位置

However the start and end positions returned by this return incorrect start and end caret positions, only in Windows . 但是,由此返回的开始和结束位置仅在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. 开始位置和结束位置都比它们应该多X,其中X =在textField到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. 由于这在Linux中没有出现,我认为这可能与处理新行( \\r\\n\\n )的方式有所不同。

Am I doing something wrong; 难道我做错了什么; and how do I work arounhd this? 我如何工作arounhd这个?

Impl. IMPL。 solution: 解:

Modified using example in TFA linked by camickr. 使用camickr链接的TFA中的示例进行了修改。

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. 这能够在Linux和Windows中为我提供正确的输出。

I think it may be to do with a difference in the way in which new lines (\\r\\n and \\n) are handled. 我认为这可能与处理新行(\\ r \\ n和\\ n)的方式有所不同。

Yes, that is a problem in Windows. 是的,这是Windows中的一个问题。

But, I doubt that you will have a problem with a JTextField since they don't contain new lines strings. 但是,我怀疑你有一个JTextField的问题,因为它们不包含新的行字符串。

I suggest you read Text and New Lines which will explain how to handle this for JTextArea and JTextPane. 我建议你阅读Text和New Lines ,它们将解释如何为JTextArea和JTextPane处理这个问题。

If you need more help post your SSCCE that shows the problem. 如果您需要更多帮助,请发布显示问题的SSCCE

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. 在上面的代码中,您可以将“\\ n”替换为适合您需要的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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