简体   繁体   中英

How to read last word or last line in DocumenListener

I implement DocumentListener for JEditorPane ( need help with method insertUpdate(DocumentEvent e) ). How to read last word or last line (lines are separated by '\\n' and words are separated by ' ' ) ?

Utilities class can be used with formatted content eg html

public static final int getWordStart(JTextComponent c, int offs) throws BadLocationException 
public static final int getWordEnd(JTextComponent c, int offs) throws BadLocationException 

To get the last line in your JEditorPane, split the text in the editor on \\n as shown below:

String text = editor.getText();
String[] lines = text.split("\n");
String lastLine = lines[lines.length-1];
System.out.println("Last line: " + lastLine);

Similarly, to get the last word, split the last line on space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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