Search code examples
javaswingjbuttonimageiconnimbus

JButton doesn't darken icon when pressed with Nimbus LaF


I create some buttons with only their image visible:

public static JButton createImageButton(ImageIcon image) {
    JButton btn = new JButton(image);
    btn.setContentAreaFilled(false);
    btn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    return btn;
}

This gives me the following output:

enter image description here

While pressing the button I usually get:

enter image description here

But when I change the LaF to Nimbus, this won't happen.

Is there any possibility to configure Nimbus to darken the icon while pressing a button ?

I've already tried to change some of the button defaults like this:

UIManager.getLookAndFeelDefaults()
.put("Button[Pressed].backgroundPainter", new CustomPainter());

But I'm not sure how to write a CustomPainter class or if this solves the problem at all...


Solution

  • Solved the problem by having a look at the source code of the Aqua LaF (GitHub)

    I found a suitable method and based on this method I adapted my source code as follows:

    public static JButton createImageButton(ImageIcon image) {
        JButton btn = new JButton(image);
        btn.setContentAreaFilled(false);
        btn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        btn.setPressedIcon(new ImageIcon(generatePressedDarkImage(image.getImage())));
        return btn;
    }
    
    private static Image generatePressedDarkImage(final Image image) {
        final ImageProducer prod = new FilteredImageSource(image.getSource(), new RGBImageFilter() {
    
            @Override
            public int filterRGB(int x, int y, int rgb) {
                final int red = (rgb >> 16) & 0xff;
                final int green = (rgb >> 8) & 0xff;
                final int blue = rgb & 0xff;
                final int gray = (int)((0.30 * red + 0.59 * green + 0.11 * blue) / 4);
    
                return (rgb & 0xff000000) | (grayTransform(red, gray) << 16) | (grayTransform(green, gray) << 8) | (grayTransform(blue, gray) << 0);
            }
    
             private int grayTransform(final int color, final int gray) {
                    int result = color - gray;
                    if (result < 0) result = 0;
                    if (result > 255) result = 255;
                    return result;
            }
        });
        return Toolkit.getDefaultToolkit().createImage(prod);
    }
    

    This provides me with a generic way to darken images in the same manner as the Aqua LaF would darken them by default:

    enter image description here