java - JTextPane Syntax Highlighting Offsets Are Incorrect -
i creating text editor syntax highlighting in java using jtextpane. when run program, output: https://www.dropbox.com/s/kkce9xvtriujizy/output.jpg?dl=0
i want every html tag highlighted pink, after few tags begins highlight wrong areas.
here highlighting code:
private void htmlhighlight() { string texttoscan; texttoscan = txtredit.gettext(); styleddocument doc = txtredit.getstyleddocument(); simpleattributeset sas = new simpleattributeset(); while(texttoscan.contains(">")) { styleconstants.setforeground(sas, new color(0xeb13b1)); styleconstants.setbold(sas, true); doc.setcharacterattributes(texttoscan.indexof('<'), texttoscan.indexof('>'), sas, false); styleconstants.setforeground(sas, color.black); styleconstants.setbold(sas, false); texttoscan = texttoscan.substring(texttoscan.indexof('>') + 1, texttoscan.length()); } }
thanks in advance!
the second argument of setcharacterattributes length, not end index.
this gives us:
private void htmlhighlight() { string texttoscan; texttoscan = txtredit.gettext(); styleddocument doc = txtredit.getstyleddocument(); simpleattributeset sas = new simpleattributeset(); while(texttoscan.contains(">")) { styleconstants.setforeground(sas, new color(0xeb13b1)); styleconstants.setbold(sas, true); int start = texttoscan.indexof('<'); int end = texttoscan.indexof('>')+1; doc.setcharacterattributes(start, end-start, sas, false); texttoscan = texttoscan.substring(texttoscan.indexof('>') + 1, texttoscan.length()); } }
update:
the substring problem, without it, there still offset, perhaps due end of lines. solution have found recreate new document:
try { string texttoscan; texttoscan = txtredit.gettext(); styleddocument doc = new defaultstyleddocument(); simpleattributeset sas = new simpleattributeset(); styleconstants.setforeground(sas, new color(0xeb13b1)); styleconstants.setbold(sas, true); int end = 0; while (true) { int start = texttoscan.indexof('<', end); if (start < 0) { doc.insertstring(end, texttoscan.substring(end), null); break; } doc.insertstring(end, texttoscan.substring(end, start), null); end = texttoscan.indexof('>', start+1); if (end < 0) { doc.insertstring(start, texttoscan.substring(start), sas); break; } ++end; doc.insertstring(start, texttoscan.substring(start, end), sas); } txtredit.setstyleddocument(doc); } catch (badlocationexception ex) { logger.getlogger(mydialog.class.getname()).log(level.severe, null, ex); }
Comments
Post a Comment