Highlight current row in JTextPane

后端 未结 3 1588
别那么骄傲
别那么骄傲 2021-02-08 21:21

I\'m trying for more than 2 days to implement a specific requirement for a text editor window... unfortunately without success so far :(

The goal is to get a text editor

3条回答
  •  梦如初夏
    2021-02-08 21:23

    Below is the code to extract text from current line. You can use same logic to get required indexes and highlight text

        private String getCurrentEditLine() {
            int readBackChars = 100;
            int caretPosition = scriptEditor.getCaretPosition();
    
            if (caretPosition == 0) {
                return null;
            }
    
            StyledDocument doc = scriptEditor.getStyledDocument();
    
            int offset = caretPosition <= readBackChars ? 0 : caretPosition
                    - readBackChars;
    
            String text = null;
            try {
                text = doc.getText(offset, caretPosition);
            } catch (BadLocationException e) {
            }
    
            if (text != null) {
                int idx = text.lastIndexOf("\n");
                if(idx != -1) {
                    return text.substring(idx);
                }else {
                    return text;
                }
            }
    
            return null;
        }
    

提交回复
热议问题