When using JColorChooser.showDialog
with colorTransparencySelectionEnabled=false
in Java 21 on macOS, RGB values in the range 0-64 are rounded down by 1 (e.g., 51/51/51/255
→ 50/50/50/255
), and values in 65-127 show inconsistent rounding (odd values match, even values are decremented by 1). This issue does not occur when colorTransparencySelectionEnabled=true
or when using JColorChooser.createDialog
with explicit JColorChooser
instance management and the sequence of setColorTransparencySelectionEnabled(false)
followed by setColor
.
This document describes the issue, provides steps to reproduce, and outlines a workaround.
- Java: 21.0.7 LTS
- OS: macOS
Use JColorChooser.showDialog
with colorTransparencySelectionEnabled=false
to set a color, such as 51/66/120/255
.
Look at the RGB panel or just click OK to confirm. You will see that the panel values are different or the standard output values are different from what you expected.
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import java.awt.Color;
public class Main {
public static void main(String[] args) {
Color c = new Color(51, 66, 120);
Color selected = JColorChooser.showDialog(new JFrame(), "Select Color", c, false);
if (selected != null) {
System.err.println(selected.getRed() + "/" +
selected.getGreen() + "/" +
selected.getBlue() + "/" +
selected.getAlpha());
}
}
}
51/66/120/255
50/64/119/255
When colorTransparencySelectionEnabled=true
, no rounding occurs, and all RGB values are returned correctly.
Using JColorChooser.createDialog
with explicit JColorChooser
instance management resolves the issue. The key is to call setColor
after setColorTransparencySelectionEnabled(false)
for each AbstractColorChooserPanel
.
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import java.awt.Color;
public class Main {
public static void main(String[] args) {
Color c = new Color(51, 66, 120);
JColorChooser colorChooser = new JColorChooser();
for (AbstractColorChooserPanel p : colorChooser.getChooserPanels()) {
p.setColorTransparencySelectionEnabled(false);
}
colorChooser.setColor(c);
JDialog d = JColorChooser.createDialog(new JFrame(), "Select Color", true, colorChooser, e -> {
Color selected = colorChooser.getColor();
if (selected != null) {
System.err.println(selected.getRed() + "/" +
selected.getGreen() + "/" +
selected.getBlue() + "/" +
selected.getAlpha());
}
}, e -> {
});
d.setVisible(true);
}
}
51/66/120/255
- Calling
setColor
aftersetColorTransparencySelectionEnabled(false)
ensures the color is set directly.