我正在尝试使用swingx中的ShadowRenderer为面板创建阴影。这是我到目前为止所做的:
在面板构造函数中创建一次阴影渲染器。
public CustomPanel() {
super();
renderer = new ShadowRenderer(20, 0.5f, Color.RED);
}
每次调整面板大小时,我都会重新计算新阴影。
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
shadow = renderer.createShadow(GraphicsUtilities.createCompatibleTranslucentImage(width, height));
}
然后我覆盖我的面板的paintComponent
方法来绘制生成的图像:
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.drawImage(shadow, 0, 0, null);
//super.paintComponent(g);
}
但shadow
图片从未显示过。为什么?我阅读了this和我除了我的代码以绘制阴影渲染器生成的一种“阴影”图像。
答案 0 :(得分:4)
这里是shortened example of DropShadowDemo
JXPanel panel = new JXPanel() {
int shadowSize = 40;
ShadowRenderer renderer = new ShadowRenderer(shadowSize/ 2, 0.5f, Color.RED);
BufferedImage imageA =
XTestUtils.loadDefaultImage("moon.jpg");
BufferedImage shadow;
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
// not really needed here - the base image size is fixed
shadow = renderer.createShadow(imageA);
}
@Override
protected void paintComponent(Graphics g) {
int x = (getWidth() - imageA.getWidth()) / 2;
int y = (getHeight() - imageA.getHeight()) / 2;
Graphics2D g2 = (Graphics2D) g;
Composite c = g2.getComposite();
g2.setComposite(AlphaComposite.SrcOver.derive(renderer.getOpacity()));
g.drawImage(shadow, x - shadowSize / 2, y - shadowSize / 2, null);
g2.setComposite(c);
g.drawImage(imageA, x, y, null);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(imageA.getWidth() + shadowSize, imageA.getHeight()+ shadowSize);
}
};
panel.setOpaque(false);