Search code examples
javaswingjtextfieldcaret

How can I draw a cursor in a custom JTextField?


I have created a rounded JTextField, which overwrites the paintComponent(g: Graphics) method. The shape and the text are properly painting, but I have not implemented anything that shows a cursor.

How can I achieve that?

Edit: super.paintComponent(...) is NOT the solution. If I use that, then you can see the edges of the other painted component.

This is the code so far (as described nothing to render the cursor!)

@Override
protected void paintComponent(Graphics g) {

    //TODO entfernen
    //super.paintComponent(g);

    if(g instanceof Graphics2D) {
        Graphics2D graphics = (Graphics2D) g;
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //Draw button background
        graphics.setColor(getBackground());
        graphics.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, arcRadius, arcRadius);

        this.paintText(graphics);

    }
}

protected final void paintText(@NotNull Graphics2D g) {
    //Draw font
    g.setColor(getForeground());
    if (this.getFont() != null && this.getText() != null) {
        FontMetrics fm = getFontMetrics(getFont());
        g.setColor(this.getForeground());
        g.drawString(this.getText(), ((this.getWidth() / 2) - (fm.stringWidth(this.getText()) / 2)),
                ((this.getHeight() / 2) + fm.getMaxDescent()));
    }
}

Edit 2: Here is the result, when I call super.paintComponent(...):

super component visible

As you can see, the super component is visible. That is why, I do not call the super method.

Does anybody have experience with Carets? Pretty sure that this is the right way to go...


Solution

  • Well, I figured it out myself and it is really easy:

    Just add

    this.getCaret().paint(g);
    

    to the paintComponent method and the cursor will then be automatically painted.