Deepak Chaudhry
Deepak Chaudhry

Reputation: 219

Fading a portion of Graphics in Java Swing

I am trying to implement the fade in/fade out animation in swing. I am using a JPanel which does not have any components in it. It is completely drawn by paintComponent() method.

Now in one of the portion of this JPanel, I want to implement the fade in/fade-out animation. When I tried using AlphaComposite, the animation is being triggered for whole JPanel.

Can I limit this animation in a small clipped region in that panel?

Graphics2D g2d = (Graphics2D) g;
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.XOR, alpha));

Upvotes: 1

Views: 371

Answers (3)

StanislavL
StanislavL

Reputation: 57421

You can use setClip() before painting to restrict the fading area. Suppose you want a small fading rectangle. Using Area class create 2 Shapes. Intersection of original clip and fading rect and subtraction (subtract the fading rectangle from the original clip).

Call super.paintComponent() twice with 2 different clips. For the second paint you can set your alpha filter.

Upvotes: 1

Nate
Nate

Reputation: 557

Perhaps, but that may be more difficult to achieve than what it's worth. Create a JComponent of the size you want to animate (or fade), add it to your JPanel, and have repaint() called on your smaller component during animation instead of the larger JPanel.

Upvotes: 1

Byron Voorbach
Byron Voorbach

Reputation: 4495

Have you tried using an Graphics object (like rectangle, circle etc..) for your fade in/out? That way it won't be triggered for the complete panel.

Good luck!

Upvotes: 1

Related Questions