The other answers here show how to remove the transparency sliders from an instance of JColorChooser, but the main way to use JColorChooser is the static showDialog
method, in which case you don't get access to an instance. Therefore I present two methods, one which hides the controls from an instance of JColorChooser, and a drop-in replacement method for showDialog
that has showTransparencyControls
as a extra parameter:
import java.awt.*;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.swing.*;
import javax.swing.colorchooser.AbstractColorChooserPanel;
class SwingUtil {
/**
* Hides controls for configuring color transparency on the specified
* color chooser.
*/
public static void hideTransparencyControls(JColorChooser cc) {
AbstractColorChooserPanel[] colorPanels = cc.getChooserPanels();
for (int i = 0; i < colorPanels.length; i++) {
AbstractColorChooserPanel cp = colorPanels[i];
try {
Field f = cp.getClass().getDeclaredField("panel");
f.setAccessible(true);
Object colorPanel = f.get(cp);
Field f2 = colorPanel.getClass().getDeclaredField("spinners");
f2.setAccessible(true);
Object sliders = f2.get(colorPanel);
Object transparencySlider = java.lang.reflect.Array.get(sliders, 3);
if (i == colorPanels.length - 1)
transparencySlider = java.lang.reflect.Array.get(sliders, 4);
Method setVisible = transparencySlider.getClass().getDeclaredMethod(
"setVisible", boolean.class);
setVisible.setAccessible(true);
setVisible.invoke(transparencySlider, false);
} catch (Throwable t) {}
}
}
/**
* Shows a modal color chooser dialog and blocks until the dialog is
* closed.
*
* @param component the parent component for the dialog; may be null
* @param title the dialog's title
* @param initialColor the initial color set when the dialog is shown
* @param showTransparencyControls whether to show controls for
* configuring the color's transparency
* @return the chosen color or null if the user canceled the dialog
*/
public static Color showColorChooserDialog(Component component,
String title, Color initialColor, boolean showTransparencyControls) {
JColorChooser pane = new JColorChooser(
initialColor != null ? initialColor : Color.white);
if (!showTransparencyControls) hideTransparencyControls(pane);
Color[] result = new Color[1];
ActionListener okListener = e -> result[0] = pane.getColor();
JDialog dialog = pane.createDialog(component, title, true, pane, okListener, null);
dialog.setVisible(true);
dialog.dispose();
return result[0];
}
}