Search code examples
javaswingshadowswingx

Why i can't see shadow generated with this ShadowRenderer?


I'm trying to use the ShadowRenderer from swingx to create a shadow for a panel. Here is what i did so far:

  • Creating the shadow renderer one time in the panel constructor.

    public CustomPanel() {
        super();
        renderer = new ShadowRenderer(20, 0.5f, Color.RED);
    }
    
  • Each time the panel is resized, i recalculate the new shadow.

    @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));
    }
    
  • And then i override the paintComponent method of my panel to draw the generated image:

    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g.create();
    
        g2.drawImage(shadow, 0, 0, null);
        //super.paintComponent(g);
    }
    

But the shadow image is never shown. Why? I read this and i except my code to draw a kind of "shadowed" image generated by the shadow renderer.


Solution

  • Here's a 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);