Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand All @@ -25,6 +25,7 @@

package javax.swing.text;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Point;
Expand Down Expand Up @@ -690,7 +691,25 @@ public void paint(Graphics g) {
// semantics of damage we can't really get around this.
damage(r);
}
g.setColor(component.getCaretColor());
if (component.isEditable()) {
g.setColor(component.getCaretColor());
} else {
Color caretColor = component.getCaretColor();
if (caretColor == null) {
caretColor = g.getColor();
}
Color bg = component.getBackground();
if (bg == null) {
g.setColor(caretColor);
Comment on lines +702 to +703
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make sense to add alpha to the caret if background color is null?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a fallback which in theory should never happen because according to documentation it is impossible to set caret color to null, documentation for setCaretColor says:
Setting to null effectively restores the default color.
so i would leave it as is and instead looked at the Nimbus LaF to see why does it return null caret color for the disabled caret. Using the foreground color is a workaround to repeat the current behavior, not a proper solution. It might backfire on custom text component where user paints with some weird color something between text draw and caret painting.

} else {
int red = (caretColor.getRed() + bg.getRed()) / 2;
int green = (caretColor.getGreen() + bg.getGreen()) / 2;
int blue = (caretColor.getBlue() + bg.getBlue()) / 2;
int alpha = 127;
Color newCaretColor = new Color(red, green, blue, alpha);
g.setColor(newCaretColor);
}
}
int paintWidth = getCaretWidth(r.height);
r.x -= paintWidth >> 1;
g.fillRect(r.x, r.y, paintWidth, r.height);
Expand Down