I’m writing an editor with syntax highlighting. What I want to do is getting the current line and just parse it instead of the whole document. The problem is that I’m probably doing it wrong but I don’t know why.
Here’s what I’m doing:
public void keyReleased(KeyEvent e) {
System.out.println(e);
try {
int inizio = Utilities.getRowStart(ta, ta.getCaretPosition());
int fine = Utilities.getRowEnd(ta, ta.getCaretPosition());
System.out.println("Inizio: " + inizio + " - Fine: " + fine);
Element root = ta.getDocument().getDefaultRootElement();
if(inizio == fine) System.out.println("Mi trovo ad inizio riga");
else {
int linea = RXTextUtilities.getLineAtCaret(ta);
System.out.println("Linea: " + linea);
Element child = root.getElement(linea-1);
System.out.println("Testo corrente: " + child.getDocument().getLength() );
}
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My understaing of using javax.swing.text.Element was that I can get just the line I want (the child) and than work on that but child.getDocument.getLength() gives me the length of the whole document. What am I doing wrong?
edit #1:
child.getDocument.getLength() gives me the length form the start of the document, I would expect the current line length. See: I got my line number using int linea = RXTextUtilities.getLineAtCaret(ta); than I extract the line using root.getElement(linea-1) so I would expect that child.getDocument().getLength() would give me the length of the current line.
RXTextUtilities link: http://www.camick.com/java/source/RXTextUtilities.java
For your specific case you get the length of the whole document, because
child.getDocument()actually returns the document in which the child is embedded.You can use
child.getStartOffset()andchild.getEndOffset()to determine start and end within the document and then cut out the text from the whole document.Please note that text then also contains a EOL delimiter.