在JTextPane中找到字符串的偏移量 [英] Find the offset to a String in a JTextPane

查看:237
本文介绍了在JTextPane中找到字符串的偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在JTextPane中查找字符串并在那里更改样式的快速方法,因此它会突出显示.我目前拥有的是这样的东西(tpOutput是有问题的JTextPane,strSearch要搜索的字符串.. duh):

I'm looking for a quick way to find a String in a JTextPane and change the style there, so it gets highlighted. What I currently have is something like this (tpOutput is the JTextPane in question, strSearch the String to be searched.. duh):

int index = tpOutput.getText().indexOf(strSearch);
StyledDocument doc = tpOutput.getStyledDocument();
doc.setCharacterAttributes(i, strSearch.length(), doc.getStyle("exampleStyle") , false);

但是,如果它能工作得那么漂亮,那么它在换行符上就算错了,所以如果我在其中搜索文本"foobar"

However, as beautiful as that would be if it worked, it counts wrong on newline characters, so if I search the text "foobar" in

foobarTTT
abcd123
abcd123

它将在第一行中正确突出显示"foobar".但是,在

it would highlight "foobar" in the first line correctly. However, in

abcd123
abcd123
foobarTTT

它将突出显示"obarTT"(以及以下两个空白,如果它们存在的话)

it would highlight "obarTT" (and the following 2 whitespaces if they exist)

我可能整个事情做错了,试图仅使用文本来轻松获得偏移量.有人知道这样做的正确方法吗?

I'm probably doing the whole thing wrong, trying to get the offset easy using just the text. Anyone know the proper way to do this?

推荐答案

您还可以使用Highlighter,在

You can also use a Highlighter, discussed in How to Use Text Fields: Another Example: TextFieldDemo.

这篇关于在JTextPane中找到字符串的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆