Синхронизация позиции каретки с текстом в соответствующей строке
Я нахожусь в процессе добавления некоторых функций форматирования на основе HTML в JTextPane. Идея состоит в том, что пользователь будет выбирать текст в JTextPane, а затем нажимать кнопку (полужирный, курсив и т. Д.), Чтобы вставить теги html в соответствующие места. Я могу сделать это без труда, используя методы JTextPane.getSelectionStart() и.getSelectionEnd().
Моя проблема в том, что я также хочу сканировать каждый символ в JTextPane, чтобы индексировать все местоположения html-тегов - это так, чтобы программа могла определить, где находится курсор JTextPane по отношению к html-тегам. Эта информация затем используется, если пользователь хочет удалить теги форматирования. У меня возникают трудности при синхронизации этого индекса символов с позицией каретки в JTextPane. Вот код, который я использовал:
public void scanHTML(){
try {
boolean blnDocStartFlag = false;
alTagRecords = new ArrayList(25);
alTextOnlyIndex = new ArrayList();
String strTagBuild = "";
int intTagIndex = 0; // The index for a tag pair record in alTagRecords.
int intTextOnlyCount = 0; // Counts each text character, ignoring all html tags.
// Loop through HTMLDoc character array:
for (int i = 0; i <= strHTMLDoc.length() -1; i ++){
// Look for the "<" angle bracket enclosing the tag keyword ...
if (strHTMLDoc.charAt(i) == '<'){// It is a html tag ...
int intTagStartLocation = i; // this value will go into alTagFields(?,0) later ...
while (strHTMLDoc.charAt(i) != '>'){
strTagBuild += strHTMLDoc.charAt(i);
i ++; // continue incrementing the iterator whilst in this sub loop ...
}
strTagBuild += '>'; // makes sure the closing tag is not missed from the string
if (!strTagBuild.startsWith("</")){
// Create new tag record:
ArrayList<Integer> alTagFields = new ArrayList(3);
alTagFields.add(0, intTagStartLocation); // Tag start location index ...
alTagFields.add(1, -1); // Tag end not known at this stage ...
alTagFields.add(2, getTagType(strTagBuild));
alTagRecords.add(intTagIndex, alTagFields); // Tag Type
System.out.println("Tag: " + strTagBuild);
intTagIndex ++; // Increment the tag records index ...
} else { // find corresponding start tag and store its location in the appropriate field of alTagFields:
int intManipulatedTagIndex = getMyOpeningTag(getTagType(strTagBuild));
ArrayList<Integer> alManipulateTagFields = alTagRecords.get(intManipulatedTagIndex);
alManipulateTagFields.set(1, (intTagStartLocation + strTagBuild.length() -1) ); // store the position of the end angled bracket of the closing tag ...
alTagRecords.set(intManipulatedTagIndex, alManipulateTagFields);
System.out.println("Tag: " + strTagBuild);
}
strTagBuild = "";
} else {
// Create the text index:
if (blnDocStartFlag == false){
int intAscii = (int) strHTMLDoc.charAt(i);
if (intAscii >= 33){ // Ascii character 33 is an exclamation mark(!). It is the first character after a space.
blnDocStartFlag = true;
}
}
// Has the first non space text character has been reached? ...
if (blnDocStartFlag == true){ // Index the character if it has ...
alTextOnlyIndex.add(i);
intTextOnlyCount ++;
}
}
}
} catch (Exception ex){
System.err.println("Error at HTMLTagIndexer.scanHTML: " + ex);
}
}
Проблема с приведенным выше кодом заключается в том, что строковая переменная strHTMLDoc получается с использованием JTextPane.getText, и, похоже, в строку вставлены некоторые дополнительные символы пробела. Следовательно, это вывело его из синхронизации с соответствующей позицией каретки в текстовой панели.
Кто-нибудь может предложить альтернативный способ сделать то, что я пытаюсь достичь?
Большое спасибо