[英]JButton doesn't darken icon when pressed with Nimbus LaF
我创建了一些按钮,它们的图像仅可见:
public static JButton createImageButton(ImageIcon image) {
JButton btn = new JButton(image);
btn.setContentAreaFilled(false);
btn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
return btn;
}
这给了我以下输出:
当按下按钮时,我通常会得到:
但是,当我将LaF更改为Nimbus时,这不会发生。
是否可以将Nimbus配置为在按下按钮时使图标变暗?
我已经尝试过更改某些按钮默认值,例如:
UIManager.getLookAndFeelDefaults()
.put("Button[Pressed].backgroundPainter", new CustomPainter());
但是我不确定如何编写CustomPainter
类,或者这是否可以解决所有问题……
通过查看Aqua LaF的源代码( GitHub )解决了该问题
我找到了一个合适的方法,并基于此方法对源代码进行了如下修改:
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);
}
这为我提供了一种通用的方式来使图像变暗,就像Aqua LaF默认将其变暗一样:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.