[英]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: 这给了我以下输出:
While pressing the button I usually get: 当按下按钮时,我通常会得到:
But when I change the LaF to Nimbus, this won't happen. 但是,当我将LaF更改为Nimbus时,这不会发生。
Is there any possibility to configure Nimbus to darken the icon while pressing a button ? 是否可以将Nimbus配置为在按下按钮时使图标变暗?
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... 但是我不确定如何编写CustomPainter
类,或者这是否可以解决所有问题……
Solved the problem by having a look at the source code of the Aqua LaF ( GitHub ) 通过查看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: 这为我提供了一种通用的方式来使图像变暗,就像Aqua LaF默认将其变暗一样:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.