Search code examples
javaswinguser-interfacejtextpanecaret

Change caret height in JTextPane


How do I alter the caret height in JTextPane, and how do I shift it vertically (make the caret appear to be e.g. 2px lower than normal without moving anything else?

BTW: This won't work. It makes the caret stop blinking.


Solution

  • The only problem with your previous example was that the blink rate wasn't set...

    JTextPane editor = new JTextPane();
    DefaultCaret dc = new DefaultCaret() {
        @Override
        public void paint(Graphics g) {
    
            if (isVisible()) {
    
                JTextComponent comp = getComponent();
                if (comp == null) {
                    return;
                }
    
                Rectangle r = null;
                try {
                    r = comp.modelToView(getDot());
                    if (r == null) {
                        return;
                    }
                } catch (BadLocationException e) {
                    return;
                }
                if (isVisible()) {
                    g.fillRect(r.x, r.y + 2, 1, r.height - 2);
                }
            }
        }
    };
    dc.setBlinkRate(500);
    editor.setCaret(dc);
    

    There is a blink rate property which you should probably use to keep it in sync, but I'll let you figure that out as you need...